blob: 5582a96ac101644d997a41c42433566d29fdc7dc [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>
Riley Andrews06b01ad2014-12-18 12:10:08 -080032#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070033#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000034#include <binder/Functional.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080035#include <binder/IBinder.h>
36#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070038#include <binder/RpcServer.h>
39#include <binder/RpcSession.h>
Parth Sane81b4d5a2024-05-23 14:11:13 +000040#include <binder/Status.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;
Parth Sane81b4d5a2024-05-23 14:11:13 +000059using android::binder::Status;
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();
Parth Sane81b4d5a2024-05-23 14:11:13 +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
Parth Sane81b4d5a2024-05-23 14:11:13 +0000464TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
465 auto sm = defaultServiceManager();
466 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
467 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
468 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
469 virtual ~LocalRegistrationCallbackImpl() {}
470 };
471 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
472
473 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
474 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
475}
476
477TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
478 auto sm = defaultServiceManager();
479 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
480 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
481 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
482 virtual ~LocalRegistrationCallbackImpl() {}
483 };
484 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
485
486 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
487
488 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
489 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
490 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
491}
492
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500493TEST_F(BinderLibTest, WasParceled) {
494 auto binder = sp<BBinder>::make();
495 EXPECT_FALSE(binder->wasParceled());
496 Parcel data;
497 data.writeStrongBinder(binder);
498 EXPECT_TRUE(binder->wasParceled());
499}
500
Riley Andrews06b01ad2014-12-18 12:10:08 -0800501TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800502 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700503 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
504 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800505}
506
Steven Moreland80844f72020-12-12 02:06:08 +0000507TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000508 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700509 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
510 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000511}
512
Steven Morelandf183fdd2020-10-27 00:12:12 +0000513TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000514 Parcel data, reply;
515 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700516 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
517 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000518}
519
Marco Ballesio7ee17572020-09-08 10:30:03 -0700520TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700521 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700522 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700523
Li Li6f059292021-09-10 09:59:30 -0700524 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700525 if (freezer_file.fail()) {
526 GTEST_SKIP();
527 return;
528 }
529
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700530 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700531 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700532 for (int i = 0; i < 10; i++) {
533 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
534 }
Li Li6f059292021-09-10 09:59:30 -0700535
536 // Pass test on devices where BINDER_FREEZE ioctl is not supported
537 int ret = IPCThreadState::self()->freeze(pid, false, 0);
Alice Ryhl4634c902024-04-11 12:52:11 +0000538 if (ret == -EINVAL) {
Li Li6f059292021-09-10 09:59:30 -0700539 GTEST_SKIP();
540 return;
541 }
Alice Ryhl4634c902024-04-11 12:52:11 +0000542 EXPECT_EQ(NO_ERROR, ret);
Li Li6f059292021-09-10 09:59:30 -0700543
544 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000545
546 // b/268232063 - succeeds ~0.08% of the time
547 {
548 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
549 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
550 }
551
Li Li6f059292021-09-10 09:59:30 -0700552 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700553 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700554
Li Li4e678b92021-09-14 12:14:42 -0700555 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700556
557 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
558 &async_received));
559
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700560 EXPECT_EQ(sync_received, 1u);
561 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700562
Li Li4e678b92021-09-14 12:14:42 -0700563 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700564 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
565}
566
Riley Andrews06b01ad2014-12-18 12:10:08 -0800567TEST_F(BinderLibTest, SetError) {
568 int32_t testValue[] = { 0, -123, 123 };
569 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800570 Parcel data, reply;
571 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700572 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
573 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800574 }
575}
576
577TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700578 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800579}
580
581TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800582 int32_t ptrsize;
583 Parcel data, reply;
584 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700585 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700586 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
587 StatusEq(NO_ERROR));
588 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800589 RecordProperty("TestPtrSize", sizeof(void *));
590 RecordProperty("ServerPtrSize", sizeof(void *));
591}
592
593TEST_F(BinderLibTest, IndirectGetId2)
594{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800595 int32_t id;
596 int32_t count;
597 Parcel data, reply;
598 int32_t serverId[3];
599
600 data.writeInt32(ARRAY_SIZE(serverId));
601 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
602 sp<IBinder> server;
603 BinderLibTestBundle datai;
604
605 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700606 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800607 data.writeStrongBinder(server);
608 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
609 datai.appendTo(&data);
610 }
611
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700612 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
613 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800614
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700615 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800616 EXPECT_EQ(0, id);
617
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700618 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700619 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800620
621 for (size_t i = 0; i < (size_t)count; i++) {
622 BinderLibTestBundle replyi(&reply);
623 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700624 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800625 EXPECT_EQ(serverId[i], id);
626 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
627 }
628
629 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
630}
631
632TEST_F(BinderLibTest, IndirectGetId3)
633{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800634 int32_t id;
635 int32_t count;
636 Parcel data, reply;
637 int32_t serverId[3];
638
639 data.writeInt32(ARRAY_SIZE(serverId));
640 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
641 sp<IBinder> server;
642 BinderLibTestBundle datai;
643 BinderLibTestBundle datai2;
644
645 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700646 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800647 data.writeStrongBinder(server);
648 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
649
650 datai.writeInt32(1);
651 datai.writeStrongBinder(m_server);
652 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
653 datai2.appendTo(&datai);
654
655 datai.appendTo(&data);
656 }
657
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700658 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
659 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800660
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700661 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800662 EXPECT_EQ(0, id);
663
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700664 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700665 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800666
667 for (size_t i = 0; i < (size_t)count; i++) {
668 int32_t counti;
669
670 BinderLibTestBundle replyi(&reply);
671 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700672 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800673 EXPECT_EQ(serverId[i], id);
674
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700675 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800676 EXPECT_EQ(1, counti);
677
678 BinderLibTestBundle replyi2(&replyi);
679 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700680 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800681 EXPECT_EQ(0, id);
682 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
683
684 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
685 }
686
687 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
688}
689
690TEST_F(BinderLibTest, CallBack)
691{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800692 Parcel data, reply;
693 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
694 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700695 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
696 StatusEq(NO_ERROR));
697 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
698 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800699}
700
Steven Moreland35626652021-05-15 01:32:04 +0000701TEST_F(BinderLibTest, BinderCallContextGuard) {
702 sp<IBinder> binder = addServer();
703 Parcel data, reply;
704 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
705 StatusEq(DEAD_OBJECT));
706}
707
Riley Andrews06b01ad2014-12-18 12:10:08 -0800708TEST_F(BinderLibTest, AddServer)
709{
710 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700711 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800712}
713
Riley Andrews06b01ad2014-12-18 12:10:08 -0800714TEST_F(BinderLibTest, DeathNotificationStrongRef)
715{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800716 sp<IBinder> sbinder;
717
718 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
719
720 {
721 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700722 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700723 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800724 sbinder = binder;
725 }
726 {
727 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700728 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
729 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800730 }
731 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700732 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
733 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800734}
735
736TEST_F(BinderLibTest, DeathNotificationMultiple)
737{
738 status_t ret;
739 const int clientcount = 2;
740 sp<IBinder> target;
741 sp<IBinder> linkedclient[clientcount];
742 sp<BinderLibTestCallBack> callBack[clientcount];
743 sp<IBinder> passiveclient[clientcount];
744
745 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700746 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800747 for (int i = 0; i < clientcount; i++) {
748 {
749 Parcel data, reply;
750
751 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700752 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800753 callBack[i] = new BinderLibTestCallBack();
754 data.writeStrongBinder(target);
755 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700756 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
757 &reply, TF_ONE_WAY),
758 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800759 }
760 {
761 Parcel data, reply;
762
763 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700764 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800765 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700766 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
767 &reply, TF_ONE_WAY),
768 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800769 }
770 }
771 {
772 Parcel data, reply;
773 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
774 EXPECT_EQ(0, ret);
775 }
776
777 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700778 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
779 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800780 }
781}
782
Martijn Coenenf7100e42017-07-31 12:14:09 +0200783TEST_F(BinderLibTest, DeathNotificationThread)
784{
785 status_t ret;
786 sp<BinderLibTestCallBack> callback;
787 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700788 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200789 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700790 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200791
792 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
793
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700794 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200795
796 {
797 Parcel data, reply;
798 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
799 EXPECT_EQ(0, ret);
800 }
801
802 /* Make sure it's dead */
803 testDeathRecipient->waitEvent(5);
804
805 /* Now, pass the ref to another process and ask that process to
806 * call linkToDeath() on it, and wait for a response. This tests
807 * two things:
808 * 1) You still get death notifications when calling linkToDeath()
809 * on a ref that is already dead when it was passed to you.
810 * 2) That death notifications are not directly pushed to the thread
811 * registering them, but to the threadpool (proc workqueue) instead.
812 *
813 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
814 * is blocked on a condition variable waiting for the death notification to be
815 * called; therefore, that thread is not available for handling proc work.
816 * So, if the death notification was pushed to the thread workqueue, the callback
817 * would never be called, and the test would timeout and fail.
818 *
819 * Note that we can't do this part of the test from this thread itself, because
820 * the binder driver would only push death notifications to the thread if
821 * it is a looper thread, which this thread is not.
822 *
823 * See b/23525545 for details.
824 */
825 {
826 Parcel data, reply;
827
828 callback = new BinderLibTestCallBack();
829 data.writeStrongBinder(target);
830 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700831 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
832 TF_ONE_WAY),
833 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200834 }
835
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700836 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
837 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200838}
839
Riley Andrews06b01ad2014-12-18 12:10:08 -0800840TEST_F(BinderLibTest, PassFile) {
841 int ret;
842 int pipefd[2];
843 uint8_t buf[1] = { 0 };
844 uint8_t write_value = 123;
845
846 ret = pipe2(pipefd, O_NONBLOCK);
847 ASSERT_EQ(0, ret);
848
849 {
850 Parcel data, reply;
851 uint8_t writebuf[1] = { write_value };
852
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700853 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800854
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700855 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800856
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700857 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800858
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700859 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
860 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800861 }
862
863 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700864 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800865 EXPECT_EQ(write_value, buf[0]);
866
867 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
868
869 ret = read(pipefd[0], buf, sizeof(buf));
870 EXPECT_EQ(0, ret);
871
872 close(pipefd[0]);
873}
874
Ryo Hashimotobf551892018-05-31 16:58:35 +0900875TEST_F(BinderLibTest, PassParcelFileDescriptor) {
876 const int datasize = 123;
877 std::vector<uint8_t> writebuf(datasize);
878 for (size_t i = 0; i < writebuf.size(); ++i) {
879 writebuf[i] = i;
880 }
881
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700882 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +0900883 {
884 int pipefd[2];
885 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
886 read_end.reset(pipefd[0]);
887 write_end.reset(pipefd[1]);
888 }
889 {
890 Parcel data;
891 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
892 write_end.reset();
893 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
894 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
895
896 Parcel reply;
897 EXPECT_EQ(NO_ERROR,
898 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
899 &reply));
900 }
901 std::vector<uint8_t> readbuf(datasize);
902 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
903 EXPECT_EQ(writebuf, readbuf);
904
905 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
906
907 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
908}
909
Riley Andrews06b01ad2014-12-18 12:10:08 -0800910TEST_F(BinderLibTest, PromoteLocal) {
911 sp<IBinder> strong = new BBinder();
912 wp<IBinder> weak = strong;
913 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700914 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800915 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700916 strong = nullptr;
917 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800918 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700919 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800920}
921
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700922TEST_F(BinderLibTest, LocalGetExtension) {
923 sp<BBinder> binder = new BBinder();
924 sp<IBinder> ext = new BBinder();
925 binder->setExtension(ext);
926 EXPECT_EQ(ext, binder->getExtension());
927}
928
929TEST_F(BinderLibTest, RemoteGetExtension) {
930 sp<IBinder> server = addServer();
931 ASSERT_TRUE(server != nullptr);
932
933 sp<IBinder> extension;
934 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
935 ASSERT_NE(nullptr, extension.get());
936
937 EXPECT_EQ(NO_ERROR, extension->pingBinder());
938}
939
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700940TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700941 Parcel data, reply;
942
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700943 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
944 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700945
946 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700947 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800948 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
949 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
950 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
951 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700952}
953
Connor O'Brien52be2c92016-09-20 14:18:08 -0700954TEST_F(BinderLibTest, FreedBinder) {
955 status_t ret;
956
957 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700958 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700959
960 __u32 freedHandle;
961 wp<IBinder> keepFreedBinder;
962 {
963 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700964 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
965 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700966 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
967 freedHandle = freed->handle;
968 /* Add a weak ref to the freed binder so the driver does not
969 * delete its reference to it - otherwise the transaction
970 * fails regardless of whether the driver is fixed.
971 */
Steven Morelande171d622019-07-17 16:06:01 -0700972 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700973 }
Steven Morelande171d622019-07-17 16:06:01 -0700974 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700975 {
976 Parcel data, reply;
977 data.writeStrongBinder(server);
978 /* Replace original handle with handle to the freed binder */
979 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
980 __u32 oldHandle = strong->handle;
981 strong->handle = freedHandle;
982 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
983 /* Returns DEAD_OBJECT (-32) if target crashes and
984 * FAILED_TRANSACTION if the driver rejects the invalid
985 * object.
986 */
987 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
988 /* Restore original handle so parcel destructor does not use
989 * the wrong handle.
990 */
991 strong->handle = oldHandle;
992 }
993}
994
Sherry Yang336cdd32017-07-24 14:12:27 -0700995TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700996 Parcel data, reply;
997 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
998 for (int i = 0; i < 2; i++) {
999 BinderLibTestBundle datai;
1000 datai.appendFrom(&data, 0, data.dataSize());
1001
1002 data.freeData();
1003 data.writeInt32(1);
1004 data.writeStrongBinder(callBack);
1005 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1006
1007 datai.appendTo(&data);
1008 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001009 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1010 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -07001011}
1012
Martijn Coenen45b07b42017-08-09 12:07:45 +02001013TEST_F(BinderLibTest, OnewayQueueing)
1014{
Martijn Coenen45b07b42017-08-09 12:07:45 +02001015 Parcel data, data2;
1016
1017 sp<IBinder> pollServer = addPollServer();
1018
1019 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1020 data.writeStrongBinder(callBack);
1021 data.writeInt32(500000); // delay in us before calling back
1022
1023 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1024 data2.writeStrongBinder(callBack2);
1025 data2.writeInt32(0); // delay in us
1026
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001027 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1028 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001029
1030 // The delay ensures that this second transaction will end up on the async_todo list
1031 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001032 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1033 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001034
1035 // The server will ensure that the two transactions are handled in the expected order;
1036 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001037 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1038 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001039
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001040 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1041 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001042}
1043
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001044TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1045{
1046 status_t ret;
1047 Parcel data, reply;
1048 data.writeInterfaceToken(binderLibTestServiceName);
1049 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1050 EXPECT_EQ(-1, reply.readInt32());
1051 EXPECT_EQ(NO_ERROR, ret);
1052}
1053
1054TEST_F(BinderLibTest, WorkSourceSet)
1055{
1056 status_t ret;
1057 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001058 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001059 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001060 data.writeInterfaceToken(binderLibTestServiceName);
1061 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1062 EXPECT_EQ(100, reply.readInt32());
1063 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001064 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1065 EXPECT_EQ(NO_ERROR, ret);
1066}
1067
1068TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1069{
1070 status_t ret;
1071 Parcel data, reply;
1072
1073 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1074 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1075
1076 data.writeInterfaceToken(binderLibTestServiceName);
1077 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1078 EXPECT_EQ(-1, reply.readInt32());
1079 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001080 EXPECT_EQ(NO_ERROR, ret);
1081}
1082
1083TEST_F(BinderLibTest, WorkSourceCleared)
1084{
1085 status_t ret;
1086 Parcel data, reply;
1087
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001088 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001089 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1090 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001091 data.writeInterfaceToken(binderLibTestServiceName);
1092 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1093
1094 EXPECT_EQ(-1, reply.readInt32());
1095 EXPECT_EQ(100, previousWorkSource);
1096 EXPECT_EQ(NO_ERROR, ret);
1097}
1098
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001099TEST_F(BinderLibTest, WorkSourceRestored)
1100{
1101 status_t ret;
1102 Parcel data, reply;
1103
1104 IPCThreadState::self()->setCallingWorkSourceUid(100);
1105 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1106 IPCThreadState::self()->restoreCallingWorkSource(token);
1107
1108 data.writeInterfaceToken(binderLibTestServiceName);
1109 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1110
1111 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001112 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001113 EXPECT_EQ(NO_ERROR, ret);
1114}
1115
Olivier Gaillard91a04802018-11-14 17:32:41 +00001116TEST_F(BinderLibTest, PropagateFlagSet)
1117{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001118 IPCThreadState::self()->clearPropagateWorkSource();
1119 IPCThreadState::self()->setCallingWorkSourceUid(100);
1120 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1121}
1122
1123TEST_F(BinderLibTest, PropagateFlagCleared)
1124{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001125 IPCThreadState::self()->setCallingWorkSourceUid(100);
1126 IPCThreadState::self()->clearPropagateWorkSource();
1127 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1128}
1129
1130TEST_F(BinderLibTest, PropagateFlagRestored)
1131{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001132 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1133 IPCThreadState::self()->restoreCallingWorkSource(token);
1134
1135 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1136}
1137
1138TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1139{
1140 IPCThreadState::self()->setCallingWorkSourceUid(100);
1141
1142 Parcel data, reply;
1143 status_t ret;
1144 data.writeInterfaceToken(binderLibTestServiceName);
1145 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001146 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001147
1148 Parcel data2, reply2;
1149 status_t ret2;
1150 data2.writeInterfaceToken(binderLibTestServiceName);
1151 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1152 EXPECT_EQ(100, reply2.readInt32());
1153 EXPECT_EQ(NO_ERROR, ret2);
1154}
1155
Steven Morelandbf1915b2020-07-16 22:43:02 +00001156TEST_F(BinderLibTest, SchedPolicySet) {
1157 sp<IBinder> server = addServer();
1158 ASSERT_TRUE(server != nullptr);
1159
1160 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001161 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1162 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001163
1164 int policy = reply.readInt32();
1165 int priority = reply.readInt32();
1166
1167 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1168 EXPECT_EQ(kSchedPriority, priority);
1169}
1170
Steven Morelandcf03cf12020-12-04 02:58:40 +00001171TEST_F(BinderLibTest, InheritRt) {
1172 sp<IBinder> server = addServer();
1173 ASSERT_TRUE(server != nullptr);
1174
1175 const struct sched_param param {
1176 .sched_priority = kSchedPriorityMore,
1177 };
1178 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1179
1180 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001181 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1182 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001183
1184 int policy = reply.readInt32();
1185 int priority = reply.readInt32();
1186
1187 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1188 EXPECT_EQ(kSchedPriorityMore, priority);
1189}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001190
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001191TEST_F(BinderLibTest, VectorSent) {
1192 Parcel data, reply;
1193 sp<IBinder> server = addServer();
1194 ASSERT_TRUE(server != nullptr);
1195
1196 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1197 data.writeUint64Vector(testValue);
1198
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001199 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001200 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001201 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001202 EXPECT_EQ(readValue, testValue);
1203}
1204
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001205TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1206 sp<IBinder> server = addServer();
1207 ASSERT_TRUE(server != nullptr);
1208
1209 Parcel reply;
1210 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1211 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001212 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001213 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1214
1215 const int result = fcntl(fd.get(), F_GETFL);
1216 ASSERT_NE(result, -1);
1217 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1218}
1219
Steven Moreland59b84442022-07-12 18:32:44 +00001220// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1221// This value is not exposed, but some code in the framework relies on being able to use
1222// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001223constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001224constexpr size_t kSizeBytesOverFull = 1'050'000;
1225
1226TEST_F(BinderLibTest, GargantuanVectorSent) {
1227 sp<IBinder> server = addServer();
1228 ASSERT_TRUE(server != nullptr);
1229
1230 for (size_t i = 0; i < 10; i++) {
1231 // a slight variation in size is used to consider certain possible caching implementations
1232 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1233
1234 Parcel data, reply;
1235 data.writeUint64Vector(testValue);
1236 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1237 << i;
1238 std::vector<uint64_t> readValue;
1239 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1240 EXPECT_EQ(readValue, testValue);
1241 }
1242}
1243
1244TEST_F(BinderLibTest, LimitExceededVectorSent) {
1245 sp<IBinder> server = addServer();
1246 ASSERT_TRUE(server != nullptr);
1247 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1248
1249 Parcel data, reply;
1250 data.writeUint64Vector(testValue);
1251 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1252 StatusEq(FAILED_TRANSACTION));
1253}
1254
Martijn Coenen82c75312019-07-24 15:18:30 +02001255TEST_F(BinderLibTest, BufRejected) {
1256 Parcel data, reply;
1257 uint32_t buf;
1258 sp<IBinder> server = addServer();
1259 ASSERT_TRUE(server != nullptr);
1260
1261 binder_buffer_object obj {
1262 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001263 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001264 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1265 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001266 };
1267 data.setDataCapacity(1024);
1268 // Write a bogus object at offset 0 to get an entry in the offset table
1269 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001270 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001271 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1272 // And now, overwrite it with the buffer object
1273 memcpy(parcelData, &obj, sizeof(obj));
1274 data.setDataSize(sizeof(obj));
1275
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001276 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001277
Martijn Coenen82c75312019-07-24 15:18:30 +02001278 // Either the kernel should reject this transaction (if it's correct), but
1279 // if it's not, the server implementation should return an error if it
1280 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001281 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001282 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001283}
1284
Steven Morelandf2e0a952021-11-01 18:17:23 -07001285TEST_F(BinderLibTest, WeakRejected) {
1286 Parcel data, reply;
1287 sp<IBinder> server = addServer();
1288 ASSERT_TRUE(server != nullptr);
1289
1290 auto binder = sp<BBinder>::make();
1291 wp<BBinder> wpBinder(binder);
1292 flat_binder_object obj{
1293 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1294 .flags = 0,
1295 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1296 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1297 };
1298 data.setDataCapacity(1024);
1299 // Write a bogus object at offset 0 to get an entry in the offset table
1300 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001301 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001302 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1303 // And now, overwrite it with the weak binder
1304 memcpy(parcelData, &obj, sizeof(obj));
1305 data.setDataSize(sizeof(obj));
1306
1307 // a previous bug caused other objects to be released an extra time, so we
1308 // test with an object that libbinder will actually try to release
1309 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1310
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001311 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001312
1313 // send it many times, since previous error was memory corruption, make it
1314 // more likely that the server crashes
1315 for (size_t i = 0; i < 100; i++) {
1316 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1317 StatusEq(BAD_VALUE));
1318 }
1319
1320 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1321}
1322
Steven Moreland254e8ef2021-04-19 22:28:50 +00001323TEST_F(BinderLibTest, GotSid) {
1324 sp<IBinder> server = addServer();
1325
1326 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001327 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001328}
1329
Andrei Homescu1519b982022-06-09 02:04:44 +00001330struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1331 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1332
1333 // Flattenable protocol
1334 size_t getFlattenedSize() const {
1335 // Return a valid non-zero size here so we don't get an unintended
1336 // BAD_VALUE from Parcel::write
1337 return 16;
1338 }
1339 size_t getFdCount() const { return mFdCount; }
1340 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1341 for (size_t i = 0; i < count; i++) {
1342 fds[i] = STDIN_FILENO;
1343 }
1344 return NO_ERROR;
1345 }
1346 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1347 size_t & /*count*/) {
1348 /* This doesn't get called */
1349 return NO_ERROR;
1350 }
1351
1352 size_t mFdCount;
1353};
1354
1355TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1356 rlimit origNofile;
1357 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1358 ASSERT_EQ(0, ret);
1359
1360 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001361 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001362
1363 rlimit testNofile = {1024, 1024};
1364 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1365 ASSERT_EQ(0, ret);
1366
1367 Parcel parcel;
1368 // Try to write more file descriptors than supported by the OS
1369 TooManyFdsFlattenable tooManyFds1(1024);
1370 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1371
1372 // Try to write more file descriptors than the internal limit
1373 TooManyFdsFlattenable tooManyFds2(1025);
1374 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1375}
1376
Jayant Chowdhary30700942022-01-31 14:12:40 -08001377TEST(ServiceNotifications, Unregister) {
1378 auto sm = defaultServiceManager();
1379 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1380 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1381 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1382 virtual ~LocalRegistrationCallbackImpl() {}
1383 };
1384 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1385
1386 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1387 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1388}
1389
Elie Kheirallah47431c12022-04-21 23:46:17 +00001390TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1391 Parcel data, reply;
1392 sp<IBinder> server = addServer();
1393 ASSERT_TRUE(server != nullptr);
1394 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1395 StatusEq(NO_ERROR));
1396 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001397 // see getThreadPoolMaxTotalThreadCount for why there is a race
1398 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1399
Elie Kheirallah47431c12022-04-21 23:46:17 +00001400 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1401
1402 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001403 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1404 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1405 * started threads from setThreadPoolMaxThreadCount
1406 *
1407 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001408 */
1409 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001410 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001411 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001412 Parcel local_reply;
1413 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1414 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001415 }));
1416 }
1417
Steven Moreland3e9debc2023-06-15 00:35:29 +00001418 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1419 // the time, the below call will pre-empt them (presumably because we have the
1420 // scheduler timeslice already + scheduler hint).
1421 sleep(1);
1422
1423 data.writeInt32(1000);
1424 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001425 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1426
1427 for (auto &t : ts) {
1428 t.join();
1429 }
1430
1431 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1432 StatusEq(NO_ERROR));
1433 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001434 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001435}
1436
Devin Moore4354f712022-12-08 01:44:46 +00001437TEST_F(BinderLibTest, ThreadPoolStarted) {
1438 Parcel data, reply;
1439 sp<IBinder> server = addServer();
1440 ASSERT_TRUE(server != nullptr);
1441 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1442 EXPECT_TRUE(reply.readBool());
1443}
1444
Elie Kheirallah47431c12022-04-21 23:46:17 +00001445size_t epochMillis() {
1446 using std::chrono::duration_cast;
1447 using std::chrono::milliseconds;
1448 using std::chrono::seconds;
1449 using std::chrono::system_clock;
1450 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1451}
1452
1453TEST_F(BinderLibTest, HangingServices) {
1454 Parcel data, reply;
1455 sp<IBinder> server = addServer();
1456 ASSERT_TRUE(server != nullptr);
1457 int32_t delay = 1000; // ms
1458 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001459 // b/266537959 - must take before taking lock, since countdown is started in the remote
1460 // process there.
1461 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001462 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1463 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001464 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1465 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001466 Parcel local_reply;
1467 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1468 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001469 }));
1470 }
1471
1472 for (auto &t : ts) {
1473 t.join();
1474 }
1475 size_t epochMsAfter = epochMillis();
1476
1477 // deadlock occurred and threads only finished after 1s passed.
1478 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1479}
1480
Jing Jibbe9ae62023-10-07 15:26:02 -07001481TEST_F(BinderLibTest, BinderProxyCount) {
1482 Parcel data, reply;
1483 sp<IBinder> server = addServer();
1484 ASSERT_NE(server, nullptr);
1485
1486 uint32_t initialCount = BpBinder::getBinderProxyCount();
1487 size_t iterations = 100;
1488 {
1489 uint32_t count = initialCount;
1490 std::vector<sp<IBinder> > proxies;
1491 sp<IBinder> proxy;
1492 // Create binder proxies and verify the count.
1493 for (size_t i = 0; i < iterations; i++) {
1494 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1495 StatusEq(NO_ERROR));
1496 proxies.push_back(reply.readStrongBinder());
1497 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1498 }
1499 // Remove every other one and verify the count.
1500 auto it = proxies.begin();
1501 for (size_t i = 0; it != proxies.end(); i++) {
1502 if (i % 2 == 0) {
1503 it = proxies.erase(it);
1504 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1505 }
1506 }
1507 }
1508 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1509}
1510
Jing Jibdbe29a2023-10-03 00:03:28 -07001511static constexpr int kBpCountHighWatermark = 20;
1512static constexpr int kBpCountLowWatermark = 10;
1513static constexpr int kBpCountWarningWatermark = 15;
1514static constexpr int kInvalidUid = -1;
1515
1516TEST_F(BinderLibTest, BinderProxyCountCallback) {
1517 Parcel data, reply;
1518 sp<IBinder> server = addServer();
1519 ASSERT_NE(server, nullptr);
1520
1521 BpBinder::enableCountByUid();
1522 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1523 int32_t uid = reply.readInt32();
1524 ASSERT_NE(uid, kInvalidUid);
1525
1526 uint32_t initialCount = BpBinder::getBinderProxyCount();
1527 {
1528 uint32_t count = initialCount;
1529 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1530 kBpCountLowWatermark,
1531 kBpCountWarningWatermark);
1532 int limitCallbackUid = kInvalidUid;
1533 int warningCallbackUid = kInvalidUid;
1534 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1535 [&](int uid) { warningCallbackUid = uid; });
1536
1537 std::vector<sp<IBinder> > proxies;
1538 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1539 warningCallbackUid = limitCallbackUid = kInvalidUid;
1540 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1541 StatusEq(NO_ERROR));
1542 proxies.push_back(reply.readStrongBinder());
1543 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1544 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1545 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1546 };
1547 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1548 warningCallbackUid = limitCallbackUid = kInvalidUid;
1549 proxies.pop_back();
1550 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1551 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1552 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1553 };
1554
1555 // Test the increment/decrement of the binder proxies.
1556 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1557 createProxyOnce(kInvalidUid, kInvalidUid);
1558 }
1559 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1560 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1561 createProxyOnce(kInvalidUid, kInvalidUid);
1562 }
1563 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1564 createProxyOnce(kInvalidUid, kInvalidUid);
1565 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1566 removeProxyOnce(kInvalidUid, kInvalidUid);
1567 }
1568 createProxyOnce(kInvalidUid, kInvalidUid);
1569
1570 // Go down below the low watermark.
1571 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1572 removeProxyOnce(kInvalidUid, kInvalidUid);
1573 }
1574 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1575 createProxyOnce(kInvalidUid, kInvalidUid);
1576 }
1577 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1578 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1579 createProxyOnce(kInvalidUid, kInvalidUid);
1580 }
1581 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1582 createProxyOnce(kInvalidUid, kInvalidUid);
1583 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1584 removeProxyOnce(kInvalidUid, kInvalidUid);
1585 }
1586 createProxyOnce(kInvalidUid, kInvalidUid);
1587 }
1588 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1589}
1590
Yifan Hong84bedeb2021-04-21 21:37:17 -07001591class BinderLibRpcTestBase : public BinderLibTest {
1592public:
1593 void SetUp() override {
1594 if (!base::GetBoolProperty("ro.debuggable", false)) {
1595 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1596 "non-debuggable builds.";
1597 }
1598 BinderLibTest::SetUp();
1599 }
1600
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001601 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001602 auto rpcServer = RpcServer::make();
1603 EXPECT_NE(nullptr, rpcServer);
1604 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001605 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001606 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1607 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001608 return {};
1609 }
1610 return {rpcServer->releaseServer(), port};
1611 }
1612};
1613
Yifan Hong8b890852021-06-10 13:44:09 -07001614class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001615
Yifan Hongbd276552022-02-28 15:28:51 -08001616// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1617// If device is debuggable AND not on user builds, expects matcher.
1618// Otherwise expects INVALID_OPERATION.
1619// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1620static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1621 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1622 android::base::GetProperty("ro.build.type", "") != "user";
1623 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1624}
1625
Yifan Hong8b890852021-06-10 13:44:09 -07001626TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1627 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001628 ASSERT_TRUE(binder != nullptr);
1629 auto [socket, port] = CreateSocket();
1630 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001631 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1632 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001633}
1634
Yifan Hong8b890852021-06-10 13:44:09 -07001635// Tests for multiple RpcServer's on the same binder object.
1636TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1637 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001638 ASSERT_TRUE(binder != nullptr);
1639
1640 auto [socket1, port1] = CreateSocket();
1641 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001642 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001643 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1644 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001645
1646 auto [socket2, port2] = CreateSocket();
1647 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001648 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001649 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1650 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001651}
1652
Yifan Hong8b890852021-06-10 13:44:09 -07001653// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1654// local binders.
1655class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001656public:
1657 sp<IBinder> GetService() {
1658 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1659 }
1660 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1661 return info.param ? "remote" : "local";
1662 }
1663};
1664
Yifan Hong8b890852021-06-10 13:44:09 -07001665TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1666 auto binder = GetService();
1667 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001668 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001669 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001670}
1671
1672TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001673 auto binder = GetService();
1674 ASSERT_TRUE(binder != nullptr);
1675 auto [socket, port] = CreateSocket();
1676 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001677 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1678 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001679}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001680INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1681 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001682
Yifan Hong543edcd2021-05-18 19:47:30 -07001683class BinderLibTestService : public BBinder {
1684public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001685 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1686 : m_id(id),
1687 m_nextServerId(id + 1),
1688 m_serverStartRequested(false),
1689 m_callback(nullptr),
1690 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001691 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1692 pthread_cond_init(&m_serverWaitCond, nullptr);
1693 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001694 ~BinderLibTestService() {
1695 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1696 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001697
Yifan Hong543edcd2021-05-18 19:47:30 -07001698 void processPendingCall() {
1699 if (m_callback != nullptr) {
1700 Parcel data;
1701 data.writeInt32(NO_ERROR);
1702 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1703 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001704 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001705 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001706
Yifan Hong543edcd2021-05-18 19:47:30 -07001707 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1708 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001709 // TODO(b/182914638): also checks getCallingUid() for RPC
1710 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001711 return PERMISSION_DENIED;
1712 }
1713 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001714 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001715 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001716 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001717 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001718 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001719 return BAD_VALUE;
1720 }
1721
Yifan Hong543edcd2021-05-18 19:47:30 -07001722 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001723
1724 pthread_mutex_lock(&m_serverWaitMutex);
1725 if (m_serverStartRequested) {
1726 m_serverStartRequested = false;
1727 m_serverStarted = binder;
1728 pthread_cond_signal(&m_serverWaitCond);
1729 }
1730 pthread_mutex_unlock(&m_serverWaitMutex);
1731 return NO_ERROR;
1732 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001733 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001734 case BINDER_LIB_TEST_ADD_SERVER: {
1735 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001736 int serverid;
1737
1738 if (m_id != 0) {
1739 return INVALID_OPERATION;
1740 }
1741 pthread_mutex_lock(&m_serverWaitMutex);
1742 if (m_serverStartRequested) {
1743 ret = -EBUSY;
1744 } else {
1745 serverid = m_nextServerId++;
1746 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001747 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001748
1749 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001750 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001751 pthread_mutex_lock(&m_serverWaitMutex);
1752 }
1753 if (ret > 0) {
1754 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001755 struct timespec ts;
1756 clock_gettime(CLOCK_REALTIME, &ts);
1757 ts.tv_sec += 5;
1758 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001759 }
1760 if (m_serverStartRequested) {
1761 m_serverStartRequested = false;
1762 ret = -ETIMEDOUT;
1763 } else {
1764 reply->writeStrongBinder(m_serverStarted);
1765 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001766 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001767 ret = NO_ERROR;
1768 }
1769 } else if (ret >= 0) {
1770 m_serverStartRequested = false;
1771 ret = UNKNOWN_ERROR;
1772 }
1773 pthread_mutex_unlock(&m_serverWaitMutex);
1774 return ret;
1775 }
Steven Moreland35626652021-05-15 01:32:04 +00001776 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1777 IPCThreadState::SpGuard spGuard{
1778 .address = __builtin_frame_address(0),
1779 .context = "GuardInBinderTransaction",
1780 };
1781 const IPCThreadState::SpGuard *origGuard =
1782 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1783
1784 // if the guard works, this should abort
1785 (void)IPCThreadState::self()->getCallingPid();
1786
1787 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1788 return NO_ERROR;
1789 }
1790
Marco Ballesio7ee17572020-09-08 10:30:03 -07001791 case BINDER_LIB_TEST_GETPID:
1792 reply->writeInt32(getpid());
1793 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07001794 case BINDER_LIB_TEST_GETUID:
1795 reply->writeInt32(getuid());
1796 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07001797 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1798 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001799 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001800 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001801 // oneway error codes should be ignored
1802 if (flags & TF_ONE_WAY) {
1803 return UNKNOWN_ERROR;
1804 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001805 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001806 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1807 // Note: this transaction is only designed for use with a
1808 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001809 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001810 // A callback was already pending; this means that
1811 // we received a second call while still processing
1812 // the first one. Fail the test.
1813 sp<IBinder> callback = data.readStrongBinder();
1814 Parcel data2;
1815 data2.writeInt32(UNKNOWN_ERROR);
1816
Yi Kong91635562018-06-07 14:38:36 -07001817 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001818 } else {
1819 m_callback = data.readStrongBinder();
1820 int32_t delayUs = data.readInt32();
1821 /*
1822 * It's necessary that we sleep here, so the next
1823 * transaction the caller makes will be queued to
1824 * the async queue.
1825 */
1826 usleep(delayUs);
1827
1828 /*
1829 * Now when we return, libbinder will tell the kernel
1830 * we are done with this transaction, and the kernel
1831 * can move the queued transaction to either the
1832 * thread todo worklist (for kernels without the fix),
1833 * or the proc todo worklist. In case of the former,
1834 * the next outbound call will pick up the pending
1835 * transaction, which leads to undesired reentrant
1836 * behavior. This is caught in the if() branch above.
1837 */
1838 }
1839
1840 return NO_ERROR;
1841 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001842 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1843 Parcel data2, reply2;
1844 sp<IBinder> binder;
1845 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001846 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001847 return BAD_VALUE;
1848 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001849 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001850 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1851 return NO_ERROR;
1852 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001853 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1854 reply->writeStrongBinder(this);
1855 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001856 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1857 reply->writeInt32(m_id);
1858 return NO_ERROR;
1859 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1860 int32_t count;
1861 uint32_t indirect_code;
1862 sp<IBinder> binder;
1863
1864 count = data.readInt32();
1865 reply->writeInt32(m_id);
1866 reply->writeInt32(count);
1867 for (int i = 0; i < count; i++) {
1868 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001869 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001870 return BAD_VALUE;
1871 }
1872 indirect_code = data.readInt32();
1873 BinderLibTestBundle data2(&data);
1874 if (!data2.isValid()) {
1875 return BAD_VALUE;
1876 }
1877 BinderLibTestBundle reply2;
1878 binder->transact(indirect_code, data2, &reply2);
1879 reply2.appendTo(reply);
1880 }
1881 return NO_ERROR;
1882 }
1883 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1884 reply->setError(data.readInt32());
1885 return NO_ERROR;
1886 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1887 reply->writeInt32(sizeof(void *));
1888 return NO_ERROR;
1889 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1890 return NO_ERROR;
1891 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1892 m_strongRef = data.readStrongBinder();
1893 return NO_ERROR;
1894 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1895 int ret;
1896 Parcel data2, reply2;
1897 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1898 sp<IBinder> target;
1899 sp<IBinder> callback;
1900
1901 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001902 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001903 return BAD_VALUE;
1904 }
1905 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001906 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001907 return BAD_VALUE;
1908 }
1909 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001910 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001911 data2.writeInt32(ret);
1912 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1913 return NO_ERROR;
1914 }
1915 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1916 int ret;
1917 int32_t size;
1918 const void *buf;
1919 int fd;
1920
1921 fd = data.readFileDescriptor();
1922 if (fd < 0) {
1923 return BAD_VALUE;
1924 }
1925 ret = data.readInt32(&size);
1926 if (ret != NO_ERROR) {
1927 return ret;
1928 }
1929 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001930 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001931 return BAD_VALUE;
1932 }
1933 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001934 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001935 return NO_ERROR;
1936 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001937 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1938 int ret;
1939 int32_t size;
1940 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001941 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001942
1943 ret = data.readUniqueParcelFileDescriptor(&fd);
1944 if (ret != NO_ERROR) {
1945 return ret;
1946 }
1947 ret = data.readInt32(&size);
1948 if (ret != NO_ERROR) {
1949 return ret;
1950 }
1951 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001952 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001953 return BAD_VALUE;
1954 }
1955 ret = write(fd.get(), buf, size);
1956 if (ret != size) return UNKNOWN_ERROR;
1957 return NO_ERROR;
1958 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001959 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1960 alarm(10);
1961 return NO_ERROR;
1962 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001963 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001964 ;
1965 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001966 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001967 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001968 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001969 return NO_ERROR;
1970 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001971 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1972 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001973 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001974 return NO_ERROR;
1975 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001976 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1977 int policy = 0;
1978 sched_param param;
1979 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1980 return UNKNOWN_ERROR;
1981 }
1982 reply->writeInt32(policy);
1983 reply->writeInt32(param.sched_priority);
1984 return NO_ERROR;
1985 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001986 case BINDER_LIB_TEST_ECHO_VECTOR: {
1987 std::vector<uint64_t> vector;
1988 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001989 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001990 reply->writeUint64Vector(vector);
1991 return NO_ERROR;
1992 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001993 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1994 std::array<int, 2> sockets;
1995 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1996 if (!created) {
1997 ALOGE("Could not create socket pair");
1998 return UNKNOWN_ERROR;
1999 }
2000
2001 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2002 if (result != 0) {
2003 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2004 return UNKNOWN_ERROR;
2005 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002006 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002007 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2008 if (writeResult != NO_ERROR) {
2009 ALOGE("Could not write unique_fd");
2010 return writeResult;
2011 }
2012 close(sockets[1]); // we don't need the other side of the fd
2013 return NO_ERROR;
2014 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07002015 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02002016 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2017 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00002018 case BINDER_LIB_TEST_CAN_GET_SID: {
2019 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2020 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002021 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2022 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2023 return NO_ERROR;
2024 }
Devin Moore4354f712022-12-08 01:44:46 +00002025 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2026 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2027 return NO_ERROR;
2028 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002029 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002030 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002031 return NO_ERROR;
2032 }
2033 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002034 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002035 return NO_ERROR;
2036 }
2037 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2038 int32_t ms = data.readInt32();
2039 return unlockInMs(ms);
2040 }
2041 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002042 m_blockMutex.lock();
2043 sp<BinderLibTestService> thisService = this;
2044 int32_t value = data.readInt32();
2045 // start local thread to unlock in 1s
2046 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002047 t.detach();
2048 return NO_ERROR;
2049 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002050 default:
2051 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002052 };
2053 }
2054
Elie Kheirallah47431c12022-04-21 23:46:17 +00002055 status_t unlockInMs(int32_t ms) {
2056 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002057 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002058 return NO_ERROR;
2059 }
2060
Yifan Hong543edcd2021-05-18 19:47:30 -07002061private:
2062 int32_t m_id;
2063 int32_t m_nextServerId;
2064 pthread_mutex_t m_serverWaitMutex;
2065 pthread_cond_t m_serverWaitCond;
2066 bool m_serverStartRequested;
2067 sp<IBinder> m_serverStarted;
2068 sp<IBinder> m_strongRef;
2069 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002070 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002071 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002072};
2073
Martijn Coenen45b07b42017-08-09 12:07:45 +02002074int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002075{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002076 binderLibTestServiceName += String16(binderserversuffix);
2077
Steven Moreland35626652021-05-15 01:32:04 +00002078 // Testing to make sure that calls that we are serving can use getCallin*
2079 // even though we don't here.
2080 IPCThreadState::SpGuard spGuard{
2081 .address = __builtin_frame_address(0),
2082 .context = "main server thread",
2083 };
2084 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2085
Riley Andrews06b01ad2014-12-18 12:10:08 -08002086 status_t ret;
2087 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02002088 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002089 {
2090 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002091
Steven Morelandbf1915b2020-07-16 22:43:02 +00002092 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2093
Steven Morelandcf03cf12020-12-04 02:58:40 +00002094 testService->setInheritRt(true);
2095
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002096 /*
2097 * Normally would also contain functionality as well, but we are only
2098 * testing the extension mechanism.
2099 */
2100 testService->setExtension(new BBinder());
2101
Martijn Coenen82c75312019-07-24 15:18:30 +02002102 // Required for test "BufRejected'
2103 testService->setRequestingSid(true);
2104
Martijn Coenen45b07b42017-08-09 12:07:45 +02002105 /*
2106 * We need this below, but can't hold a sp<> because it prevents the
2107 * node from being cleaned up automatically. It's safe in this case
2108 * because of how the tests are written.
2109 */
2110 testServicePtr = testService.get();
2111
Riley Andrews06b01ad2014-12-18 12:10:08 -08002112 if (index == 0) {
2113 ret = sm->addService(binderLibTestServiceName, testService);
2114 } else {
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002115#pragma clang diagnostic push
2116#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -08002117 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002118#pragma clang diagnostic pop
Riley Andrews06b01ad2014-12-18 12:10:08 -08002119 Parcel data, reply;
2120 data.writeInt32(index);
2121 data.writeStrongBinder(testService);
2122
2123 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2124 }
2125 }
2126 write(readypipefd, &ret, sizeof(ret));
2127 close(readypipefd);
2128 //printf("%s: ret %d\n", __func__, ret);
2129 if (ret)
2130 return 1;
2131 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002132 if (usePoll) {
2133 int fd;
2134 struct epoll_event ev;
2135 int epoll_fd;
2136 IPCThreadState::self()->setupPolling(&fd);
2137 if (fd < 0) {
2138 return 1;
2139 }
2140 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2141
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002142 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002143 if (epoll_fd == -1) {
2144 return 1;
2145 }
2146
2147 ev.events = EPOLLIN;
2148 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2149 return 1;
2150 }
2151
2152 while (1) {
2153 /*
2154 * We simulate a single-threaded process using the binder poll
2155 * interface; besides handling binder commands, it can also
2156 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002157 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002158 *
2159 * processPendingCall() will then issue that transaction.
2160 */
2161 struct epoll_event events[1];
2162 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2163 if (numEvents < 0) {
2164 if (errno == EINTR) {
2165 continue;
2166 }
2167 return 1;
2168 }
2169 if (numEvents > 0) {
2170 IPCThreadState::self()->handlePolledCommands();
2171 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2172 testServicePtr->processPendingCall();
2173 }
2174 }
2175 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002176 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002177 ProcessState::self()->startThreadPool();
2178 IPCThreadState::self()->joinThreadPool();
2179 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002180 //printf("%s: joinThreadPool returned\n", __func__);
2181 return 1; /* joinThreadPool should not return */
2182}
2183
Steven Moreland68275d72023-04-21 22:12:45 +00002184int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002185 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002186 binderservername = argv[2];
2187 } else {
2188 binderservername = argv[0];
2189 }
2190
Martijn Coenen45b07b42017-08-09 12:07:45 +02002191 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2192 binderserversuffix = argv[5];
2193 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002194 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002195 binderserversuffix = new char[16];
2196 snprintf(binderserversuffix, 16, "%d", getpid());
2197 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002198
2199 ::testing::InitGoogleTest(&argc, argv);
2200 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2201 ProcessState::self()->startThreadPool();
2202 return RUN_ALL_TESTS();
2203}