blob: 2cea14f631679cf5486a664d92c5c5307d931a16 [file] [log] [blame]
Riley Andrews06b01ad2014-12-18 12:10:08 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080018#include <poll.h>
19#include <pthread.h>
20#include <stdio.h>
21#include <stdlib.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070022
23#include <chrono>
Yifan Hong8b890852021-06-10 13:44:09 -070024#include <fstream>
Steven Morelandd7088702021-01-13 00:27:00 +000025#include <thread>
Riley Andrews06b01ad2014-12-18 12:10:08 -080026
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070027#include <gmock/gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080028#include <gtest/gtest.h>
29
Yifan Hong84bedeb2021-04-21 21:37:17 -070030#include <android-base/properties.h>
Yifan Hong28d6c352021-06-04 17:27:35 -070031#include <android-base/result-gmock.h>
Yifan Hong8b890852021-06-10 13:44:09 -070032#include <android-base/strings.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080033#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070034#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000035#include <binder/Functional.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080036#include <binder/IBinder.h>
37#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070039#include <binder/RpcServer.h>
40#include <binder/RpcSession.h>
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070041#include <binder/unique_fd.h>
Tomasz Wasilczyk300aa132023-10-26 15:00:04 -070042#include <utils/Flattenable.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080043
Steven Morelandcf03cf12020-12-04 02:58:40 +000044#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020045#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080046#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070047#include <sys/socket.h>
48#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020049
Steven Moreland6ba5a252021-05-04 22:49:00 +000050#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070051
Riley Andrews06b01ad2014-12-18 12:10:08 -080052#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
53
54using namespace android;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000055using namespace android::binder::impl;
Yifan Hong84bedeb2021-04-21 21:37:17 -070056using namespace std::string_literals;
57using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070058using android::base::testing::HasValue;
Yifan Hong8b890852021-06-10 13:44:09 -070059using android::base::testing::Ok;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070060using android::binder::unique_fd;
Yifan Hong84bedeb2021-04-21 21:37:17 -070061using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080062using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070063using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070064using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070065
66// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
67MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
68 *result_listener << statusToString(arg);
69 return expected == arg;
70}
Riley Andrews06b01ad2014-12-18 12:10:08 -080071
Sherry Yang336cdd32017-07-24 14:12:27 -070072static ::testing::AssertionResult IsPageAligned(void *buf) {
Vilas Bhat04e28c72024-02-12 21:47:15 +000073 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
Sherry Yang336cdd32017-07-24 14:12:27 -070074 return ::testing::AssertionSuccess();
75 else
76 return ::testing::AssertionFailure() << buf << " is not page aligned";
77}
78
Riley Andrews06b01ad2014-12-18 12:10:08 -080079static testing::Environment* binder_env;
80static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070081static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080082static char binderserverarg[] = "--binderserver";
83
Steven Morelandbf1915b2020-07-16 22:43:02 +000084static constexpr int kSchedPolicy = SCHED_RR;
85static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000086static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000087static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000088
Riley Andrews06b01ad2014-12-18 12:10:08 -080089static String16 binderLibTestServiceName = String16("test.binderLib");
90
91enum BinderLibTestTranscationCode {
92 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
93 BINDER_LIB_TEST_REGISTER_SERVER,
94 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020095 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000096 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -080097 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -070098 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +020099 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800100 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700101 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800102 BINDER_LIB_TEST_GET_ID_TRANSACTION,
103 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
104 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
105 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
106 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
107 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
108 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900109 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800110 BINDER_LIB_TEST_EXIT_TRANSACTION,
111 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
112 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700113 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100114 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000115 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700116 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
117 BINDER_LIB_TEST_GETPID,
Jing Jibdbe29a2023-10-03 00:03:28 -0700118 BINDER_LIB_TEST_GETUID,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800119 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700120 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700121 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000122 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000123 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
124 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000125 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000126 BINDER_LIB_TEST_LOCK_UNLOCK,
127 BINDER_LIB_TEST_PROCESS_LOCK,
128 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
129 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800130};
131
Martijn Coenen45b07b42017-08-09 12:07:45 +0200132pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800133{
134 int ret;
135 pid_t pid;
136 status_t status;
137 int pipefd[2];
138 char stri[16];
139 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200140 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800141 char *childargv[] = {
142 binderservername,
143 binderserverarg,
144 stri,
145 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200146 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700147 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700148 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800149 };
150
151 ret = pipe(pipefd);
152 if (ret < 0)
153 return ret;
154
155 snprintf(stri, sizeof(stri), "%d", arg2);
156 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200157 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800158
159 pid = fork();
160 if (pid == -1)
161 return pid;
162 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800163 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800164 close(pipefd[0]);
165 execv(binderservername, childargv);
166 status = -errno;
167 write(pipefd[1], &status, sizeof(status));
168 fprintf(stderr, "execv failed, %s\n", strerror(errno));
169 _exit(EXIT_FAILURE);
170 }
171 close(pipefd[1]);
172 ret = read(pipefd[0], &status, sizeof(status));
173 //printf("pipe read returned %d, status %d\n", ret, status);
174 close(pipefd[0]);
175 if (ret == sizeof(status)) {
176 ret = status;
177 } else {
178 kill(pid, SIGKILL);
179 if (ret >= 0) {
180 ret = NO_INIT;
181 }
182 }
183 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700184 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800185 return ret;
186 }
187 return pid;
188}
189
Yifan Hong84bedeb2021-04-21 21:37:17 -0700190android::base::Result<int32_t> GetId(sp<IBinder> service) {
191 using android::base::Error;
192 Parcel data, reply;
193 data.markForBinder(service);
194 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
195 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
196 if (status != OK)
197 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
198 int32_t result = 0;
199 status = reply.readInt32(&result);
200 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
201 return result;
202}
203
Riley Andrews06b01ad2014-12-18 12:10:08 -0800204class BinderLibTestEnv : public ::testing::Environment {
205 public:
206 BinderLibTestEnv() {}
207 sp<IBinder> getServer(void) {
208 return m_server;
209 }
210
211 private:
212 virtual void SetUp() {
213 m_serverpid = start_server_process(0);
214 //printf("m_serverpid %d\n", m_serverpid);
215 ASSERT_GT(m_serverpid, 0);
216
217 sp<IServiceManager> sm = defaultServiceManager();
218 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000219#pragma clang diagnostic push
220#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -0800221 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000222#pragma clang diagnostic pop
Yi Kong91635562018-06-07 14:38:36 -0700223 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800224 //printf("%s: pid %d, get service done\n", __func__, m_pid);
225 }
226 virtual void TearDown() {
227 status_t ret;
228 Parcel data, reply;
229 int exitStatus;
230 pid_t pid;
231
232 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700233 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800234 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
235 EXPECT_EQ(0, ret);
236 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
237 EXPECT_EQ(0, ret);
238 }
239 if (m_serverpid > 0) {
240 //printf("wait for %d\n", m_pids[i]);
241 pid = wait(&exitStatus);
242 EXPECT_EQ(m_serverpid, pid);
243 EXPECT_TRUE(WIFEXITED(exitStatus));
244 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
245 }
246 }
247
248 pid_t m_serverpid;
249 sp<IBinder> m_server;
250};
251
252class BinderLibTest : public ::testing::Test {
253 public:
254 virtual void SetUp() {
255 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000256 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800257 }
258 virtual void TearDown() {
259 }
260 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200261 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800262 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800263 int32_t id;
264 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800265
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700266 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800267
Elie Kheirallahb7246642022-05-03 18:01:43 +0000268 sp<IBinder> binder = reply.readStrongBinder();
269 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700270 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800271 if (idPtr)
272 *idPtr = id;
273 return binder;
274 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200275
Yi Kong91635562018-06-07 14:38:36 -0700276 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200277 {
278 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
279 }
280
Yi Kong91635562018-06-07 14:38:36 -0700281 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200282 {
283 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
284 }
285
Riley Andrews06b01ad2014-12-18 12:10:08 -0800286 void waitForReadData(int fd, int timeout_ms) {
287 int ret;
288 pollfd pfd = pollfd();
289
290 pfd.fd = fd;
291 pfd.events = POLLIN;
292 ret = poll(&pfd, 1, timeout_ms);
293 EXPECT_EQ(1, ret);
294 }
295
296 sp<IBinder> m_server;
297};
298
299class BinderLibTestBundle : public Parcel
300{
301 public:
302 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800303 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800304 int32_t mark;
305 int32_t bundleLen;
306 size_t pos;
307
308 if (source->readInt32(&mark))
309 return;
310 if (mark != MARK_START)
311 return;
312 if (source->readInt32(&bundleLen))
313 return;
314 pos = source->dataPosition();
315 if (Parcel::appendFrom(source, pos, bundleLen))
316 return;
317 source->setDataPosition(pos + bundleLen);
318 if (source->readInt32(&mark))
319 return;
320 if (mark != MARK_END)
321 return;
322 m_isValid = true;
323 setDataPosition(0);
324 }
325 void appendTo(Parcel *dest) {
326 dest->writeInt32(MARK_START);
327 dest->writeInt32(dataSize());
328 dest->appendFrom(this, 0, dataSize());
329 dest->writeInt32(MARK_END);
330 };
331 bool isValid(void) {
332 return m_isValid;
333 }
334 private:
335 enum {
336 MARK_START = B_PACK_CHARS('B','T','B','S'),
337 MARK_END = B_PACK_CHARS('B','T','B','E'),
338 };
339 bool m_isValid;
340};
341
342class BinderLibTestEvent
343{
344 public:
345 BinderLibTestEvent(void)
346 : m_eventTriggered(false)
347 {
Yi Kong91635562018-06-07 14:38:36 -0700348 pthread_mutex_init(&m_waitMutex, nullptr);
349 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800350 }
351 int waitEvent(int timeout_s)
352 {
353 int ret;
354 pthread_mutex_lock(&m_waitMutex);
355 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800356 struct timespec ts;
357 clock_gettime(CLOCK_REALTIME, &ts);
358 ts.tv_sec += timeout_s;
359 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800360 }
361 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
362 pthread_mutex_unlock(&m_waitMutex);
363 return ret;
364 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200365 pthread_t getTriggeringThread()
366 {
367 return m_triggeringThread;
368 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800369 protected:
370 void triggerEvent(void) {
371 pthread_mutex_lock(&m_waitMutex);
372 pthread_cond_signal(&m_waitCond);
373 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200374 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800375 pthread_mutex_unlock(&m_waitMutex);
376 };
377 private:
378 pthread_mutex_t m_waitMutex;
379 pthread_cond_t m_waitCond;
380 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200381 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800382};
383
384class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
385{
386 public:
387 BinderLibTestCallBack()
388 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700389 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800390 {
391 }
392 status_t getResult(void)
393 {
394 return m_result;
395 }
396
397 private:
398 virtual status_t onTransact(uint32_t code,
399 const Parcel& data, Parcel* reply,
400 uint32_t flags = 0)
401 {
402 (void)reply;
403 (void)flags;
404 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200405 case BINDER_LIB_TEST_CALL_BACK: {
406 status_t status = data.readInt32(&m_result);
407 if (status != NO_ERROR) {
408 m_result = status;
409 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800410 triggerEvent();
411 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200412 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700413 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
414 sp<IBinder> server;
415 int ret;
416 const uint8_t *buf = data.data();
417 size_t size = data.dataSize();
418 if (m_prev_end) {
419 /* 64-bit kernel needs at most 8 bytes to align buffer end */
420 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
421 } else {
422 EXPECT_TRUE(IsPageAligned((void *)buf));
423 }
424
425 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
426
427 if (size > 0) {
428 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
429 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
430 data, reply);
431 EXPECT_EQ(NO_ERROR, ret);
432 }
433 return NO_ERROR;
434 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800435 default:
436 return UNKNOWN_TRANSACTION;
437 }
438 }
439
440 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700441 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800442};
443
444class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
445{
446 private:
447 virtual void binderDied(const wp<IBinder>& who) {
448 (void)who;
449 triggerEvent();
450 };
451};
452
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700453TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
454 // EXPECT_DEATH works by forking the process
455 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
456}
457
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000458TEST_F(BinderLibTest, AddManagerToManager) {
459 sp<IServiceManager> sm = defaultServiceManager();
460 sp<IBinder> binder = IInterface::asBinder(sm);
461 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
462}
463
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500464TEST_F(BinderLibTest, WasParceled) {
465 auto binder = sp<BBinder>::make();
466 EXPECT_FALSE(binder->wasParceled());
467 Parcel data;
468 data.writeStrongBinder(binder);
469 EXPECT_TRUE(binder->wasParceled());
470}
471
Riley Andrews06b01ad2014-12-18 12:10:08 -0800472TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800473 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700474 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
475 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800476}
477
Steven Moreland80844f72020-12-12 02:06:08 +0000478TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000479 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700480 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
481 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000482}
483
Steven Morelandf183fdd2020-10-27 00:12:12 +0000484TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000485 Parcel data, reply;
486 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700487 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
488 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000489}
490
Marco Ballesio7ee17572020-09-08 10:30:03 -0700491TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700492 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700493 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700494
Li Li6f059292021-09-10 09:59:30 -0700495 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700496 if (freezer_file.fail()) {
497 GTEST_SKIP();
498 return;
499 }
500
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700501 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700502 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700503 for (int i = 0; i < 10; i++) {
504 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
505 }
Li Li6f059292021-09-10 09:59:30 -0700506
507 // Pass test on devices where BINDER_FREEZE ioctl is not supported
508 int ret = IPCThreadState::self()->freeze(pid, false, 0);
509 if (ret != 0) {
510 GTEST_SKIP();
511 return;
512 }
513
514 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000515
516 // b/268232063 - succeeds ~0.08% of the time
517 {
518 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
519 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
520 }
521
Li Li6f059292021-09-10 09:59:30 -0700522 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700523 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700524
Li Li4e678b92021-09-14 12:14:42 -0700525 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700526
527 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
528 &async_received));
529
530 EXPECT_EQ(sync_received, 1);
531 EXPECT_EQ(async_received, 0);
532
Li Li4e678b92021-09-14 12:14:42 -0700533 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700534 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
535}
536
Riley Andrews06b01ad2014-12-18 12:10:08 -0800537TEST_F(BinderLibTest, SetError) {
538 int32_t testValue[] = { 0, -123, 123 };
539 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800540 Parcel data, reply;
541 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700542 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
543 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800544 }
545}
546
547TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700548 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800549}
550
551TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800552 int32_t ptrsize;
553 Parcel data, reply;
554 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700555 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700556 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
557 StatusEq(NO_ERROR));
558 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800559 RecordProperty("TestPtrSize", sizeof(void *));
560 RecordProperty("ServerPtrSize", sizeof(void *));
561}
562
563TEST_F(BinderLibTest, IndirectGetId2)
564{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800565 int32_t id;
566 int32_t count;
567 Parcel data, reply;
568 int32_t serverId[3];
569
570 data.writeInt32(ARRAY_SIZE(serverId));
571 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
572 sp<IBinder> server;
573 BinderLibTestBundle datai;
574
575 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700576 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800577 data.writeStrongBinder(server);
578 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
579 datai.appendTo(&data);
580 }
581
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700582 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
583 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800584
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700585 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800586 EXPECT_EQ(0, id);
587
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700588 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700589 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800590
591 for (size_t i = 0; i < (size_t)count; i++) {
592 BinderLibTestBundle replyi(&reply);
593 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700594 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800595 EXPECT_EQ(serverId[i], id);
596 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
597 }
598
599 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
600}
601
602TEST_F(BinderLibTest, IndirectGetId3)
603{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800604 int32_t id;
605 int32_t count;
606 Parcel data, reply;
607 int32_t serverId[3];
608
609 data.writeInt32(ARRAY_SIZE(serverId));
610 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
611 sp<IBinder> server;
612 BinderLibTestBundle datai;
613 BinderLibTestBundle datai2;
614
615 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700616 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800617 data.writeStrongBinder(server);
618 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
619
620 datai.writeInt32(1);
621 datai.writeStrongBinder(m_server);
622 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
623 datai2.appendTo(&datai);
624
625 datai.appendTo(&data);
626 }
627
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700628 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
629 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800630
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700631 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800632 EXPECT_EQ(0, id);
633
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700634 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700635 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800636
637 for (size_t i = 0; i < (size_t)count; i++) {
638 int32_t counti;
639
640 BinderLibTestBundle replyi(&reply);
641 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700642 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800643 EXPECT_EQ(serverId[i], id);
644
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700645 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800646 EXPECT_EQ(1, counti);
647
648 BinderLibTestBundle replyi2(&replyi);
649 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700650 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800651 EXPECT_EQ(0, id);
652 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
653
654 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
655 }
656
657 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
658}
659
660TEST_F(BinderLibTest, CallBack)
661{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800662 Parcel data, reply;
663 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
664 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700665 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
666 StatusEq(NO_ERROR));
667 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
668 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800669}
670
Steven Moreland35626652021-05-15 01:32:04 +0000671TEST_F(BinderLibTest, BinderCallContextGuard) {
672 sp<IBinder> binder = addServer();
673 Parcel data, reply;
674 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
675 StatusEq(DEAD_OBJECT));
676}
677
Riley Andrews06b01ad2014-12-18 12:10:08 -0800678TEST_F(BinderLibTest, AddServer)
679{
680 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700681 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800682}
683
Riley Andrews06b01ad2014-12-18 12:10:08 -0800684TEST_F(BinderLibTest, DeathNotificationStrongRef)
685{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800686 sp<IBinder> sbinder;
687
688 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
689
690 {
691 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700692 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700693 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800694 sbinder = binder;
695 }
696 {
697 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700698 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
699 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800700 }
701 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700702 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
703 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800704}
705
706TEST_F(BinderLibTest, DeathNotificationMultiple)
707{
708 status_t ret;
709 const int clientcount = 2;
710 sp<IBinder> target;
711 sp<IBinder> linkedclient[clientcount];
712 sp<BinderLibTestCallBack> callBack[clientcount];
713 sp<IBinder> passiveclient[clientcount];
714
715 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700716 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800717 for (int i = 0; i < clientcount; i++) {
718 {
719 Parcel data, reply;
720
721 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700722 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800723 callBack[i] = new BinderLibTestCallBack();
724 data.writeStrongBinder(target);
725 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700726 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
727 &reply, TF_ONE_WAY),
728 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800729 }
730 {
731 Parcel data, reply;
732
733 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700734 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800735 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700736 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
737 &reply, TF_ONE_WAY),
738 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800739 }
740 }
741 {
742 Parcel data, reply;
743 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
744 EXPECT_EQ(0, ret);
745 }
746
747 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700748 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
749 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800750 }
751}
752
Martijn Coenenf7100e42017-07-31 12:14:09 +0200753TEST_F(BinderLibTest, DeathNotificationThread)
754{
755 status_t ret;
756 sp<BinderLibTestCallBack> callback;
757 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700758 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200759 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700760 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200761
762 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
763
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700764 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200765
766 {
767 Parcel data, reply;
768 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
769 EXPECT_EQ(0, ret);
770 }
771
772 /* Make sure it's dead */
773 testDeathRecipient->waitEvent(5);
774
775 /* Now, pass the ref to another process and ask that process to
776 * call linkToDeath() on it, and wait for a response. This tests
777 * two things:
778 * 1) You still get death notifications when calling linkToDeath()
779 * on a ref that is already dead when it was passed to you.
780 * 2) That death notifications are not directly pushed to the thread
781 * registering them, but to the threadpool (proc workqueue) instead.
782 *
783 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
784 * is blocked on a condition variable waiting for the death notification to be
785 * called; therefore, that thread is not available for handling proc work.
786 * So, if the death notification was pushed to the thread workqueue, the callback
787 * would never be called, and the test would timeout and fail.
788 *
789 * Note that we can't do this part of the test from this thread itself, because
790 * the binder driver would only push death notifications to the thread if
791 * it is a looper thread, which this thread is not.
792 *
793 * See b/23525545 for details.
794 */
795 {
796 Parcel data, reply;
797
798 callback = new BinderLibTestCallBack();
799 data.writeStrongBinder(target);
800 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700801 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
802 TF_ONE_WAY),
803 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200804 }
805
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700806 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
807 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200808}
809
Riley Andrews06b01ad2014-12-18 12:10:08 -0800810TEST_F(BinderLibTest, PassFile) {
811 int ret;
812 int pipefd[2];
813 uint8_t buf[1] = { 0 };
814 uint8_t write_value = 123;
815
816 ret = pipe2(pipefd, O_NONBLOCK);
817 ASSERT_EQ(0, ret);
818
819 {
820 Parcel data, reply;
821 uint8_t writebuf[1] = { write_value };
822
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700823 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800824
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700825 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800826
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700827 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800828
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700829 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
830 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800831 }
832
833 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700834 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800835 EXPECT_EQ(write_value, buf[0]);
836
837 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
838
839 ret = read(pipefd[0], buf, sizeof(buf));
840 EXPECT_EQ(0, ret);
841
842 close(pipefd[0]);
843}
844
Ryo Hashimotobf551892018-05-31 16:58:35 +0900845TEST_F(BinderLibTest, PassParcelFileDescriptor) {
846 const int datasize = 123;
847 std::vector<uint8_t> writebuf(datasize);
848 for (size_t i = 0; i < writebuf.size(); ++i) {
849 writebuf[i] = i;
850 }
851
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700852 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +0900853 {
854 int pipefd[2];
855 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
856 read_end.reset(pipefd[0]);
857 write_end.reset(pipefd[1]);
858 }
859 {
860 Parcel data;
861 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
862 write_end.reset();
863 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
864 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
865
866 Parcel reply;
867 EXPECT_EQ(NO_ERROR,
868 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
869 &reply));
870 }
871 std::vector<uint8_t> readbuf(datasize);
872 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
873 EXPECT_EQ(writebuf, readbuf);
874
875 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
876
877 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
878}
879
Riley Andrews06b01ad2014-12-18 12:10:08 -0800880TEST_F(BinderLibTest, PromoteLocal) {
881 sp<IBinder> strong = new BBinder();
882 wp<IBinder> weak = strong;
883 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700884 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800885 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700886 strong = nullptr;
887 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800888 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700889 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800890}
891
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700892TEST_F(BinderLibTest, LocalGetExtension) {
893 sp<BBinder> binder = new BBinder();
894 sp<IBinder> ext = new BBinder();
895 binder->setExtension(ext);
896 EXPECT_EQ(ext, binder->getExtension());
897}
898
899TEST_F(BinderLibTest, RemoteGetExtension) {
900 sp<IBinder> server = addServer();
901 ASSERT_TRUE(server != nullptr);
902
903 sp<IBinder> extension;
904 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
905 ASSERT_NE(nullptr, extension.get());
906
907 EXPECT_EQ(NO_ERROR, extension->pingBinder());
908}
909
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700910TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700911 Parcel data, reply;
912
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700913 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
914 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700915
916 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700917 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800918 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
919 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
920 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
921 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700922}
923
Connor O'Brien52be2c92016-09-20 14:18:08 -0700924TEST_F(BinderLibTest, FreedBinder) {
925 status_t ret;
926
927 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700928 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700929
930 __u32 freedHandle;
931 wp<IBinder> keepFreedBinder;
932 {
933 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700934 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
935 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700936 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
937 freedHandle = freed->handle;
938 /* Add a weak ref to the freed binder so the driver does not
939 * delete its reference to it - otherwise the transaction
940 * fails regardless of whether the driver is fixed.
941 */
Steven Morelande171d622019-07-17 16:06:01 -0700942 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700943 }
Steven Morelande171d622019-07-17 16:06:01 -0700944 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700945 {
946 Parcel data, reply;
947 data.writeStrongBinder(server);
948 /* Replace original handle with handle to the freed binder */
949 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
950 __u32 oldHandle = strong->handle;
951 strong->handle = freedHandle;
952 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
953 /* Returns DEAD_OBJECT (-32) if target crashes and
954 * FAILED_TRANSACTION if the driver rejects the invalid
955 * object.
956 */
957 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
958 /* Restore original handle so parcel destructor does not use
959 * the wrong handle.
960 */
961 strong->handle = oldHandle;
962 }
963}
964
Sherry Yang336cdd32017-07-24 14:12:27 -0700965TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700966 Parcel data, reply;
967 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
968 for (int i = 0; i < 2; i++) {
969 BinderLibTestBundle datai;
970 datai.appendFrom(&data, 0, data.dataSize());
971
972 data.freeData();
973 data.writeInt32(1);
974 data.writeStrongBinder(callBack);
975 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
976
977 datai.appendTo(&data);
978 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700979 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
980 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700981}
982
Martijn Coenen45b07b42017-08-09 12:07:45 +0200983TEST_F(BinderLibTest, OnewayQueueing)
984{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200985 Parcel data, data2;
986
987 sp<IBinder> pollServer = addPollServer();
988
989 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
990 data.writeStrongBinder(callBack);
991 data.writeInt32(500000); // delay in us before calling back
992
993 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
994 data2.writeStrongBinder(callBack2);
995 data2.writeInt32(0); // delay in us
996
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700997 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
998 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200999
1000 // The delay ensures that this second transaction will end up on the async_todo list
1001 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001002 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1003 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001004
1005 // The server will ensure that the two transactions are handled in the expected order;
1006 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001007 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1008 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001009
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001010 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1011 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001012}
1013
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001014TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1015{
1016 status_t ret;
1017 Parcel data, reply;
1018 data.writeInterfaceToken(binderLibTestServiceName);
1019 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1020 EXPECT_EQ(-1, reply.readInt32());
1021 EXPECT_EQ(NO_ERROR, ret);
1022}
1023
1024TEST_F(BinderLibTest, WorkSourceSet)
1025{
1026 status_t ret;
1027 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001028 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001029 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001030 data.writeInterfaceToken(binderLibTestServiceName);
1031 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1032 EXPECT_EQ(100, reply.readInt32());
1033 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001034 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1035 EXPECT_EQ(NO_ERROR, ret);
1036}
1037
1038TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1039{
1040 status_t ret;
1041 Parcel data, reply;
1042
1043 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1044 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1045
1046 data.writeInterfaceToken(binderLibTestServiceName);
1047 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1048 EXPECT_EQ(-1, reply.readInt32());
1049 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001050 EXPECT_EQ(NO_ERROR, ret);
1051}
1052
1053TEST_F(BinderLibTest, WorkSourceCleared)
1054{
1055 status_t ret;
1056 Parcel data, reply;
1057
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001058 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001059 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1060 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001061 data.writeInterfaceToken(binderLibTestServiceName);
1062 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1063
1064 EXPECT_EQ(-1, reply.readInt32());
1065 EXPECT_EQ(100, previousWorkSource);
1066 EXPECT_EQ(NO_ERROR, ret);
1067}
1068
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001069TEST_F(BinderLibTest, WorkSourceRestored)
1070{
1071 status_t ret;
1072 Parcel data, reply;
1073
1074 IPCThreadState::self()->setCallingWorkSourceUid(100);
1075 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1076 IPCThreadState::self()->restoreCallingWorkSource(token);
1077
1078 data.writeInterfaceToken(binderLibTestServiceName);
1079 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1080
1081 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001082 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001083 EXPECT_EQ(NO_ERROR, ret);
1084}
1085
Olivier Gaillard91a04802018-11-14 17:32:41 +00001086TEST_F(BinderLibTest, PropagateFlagSet)
1087{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001088 IPCThreadState::self()->clearPropagateWorkSource();
1089 IPCThreadState::self()->setCallingWorkSourceUid(100);
1090 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1091}
1092
1093TEST_F(BinderLibTest, PropagateFlagCleared)
1094{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001095 IPCThreadState::self()->setCallingWorkSourceUid(100);
1096 IPCThreadState::self()->clearPropagateWorkSource();
1097 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1098}
1099
1100TEST_F(BinderLibTest, PropagateFlagRestored)
1101{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001102 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1103 IPCThreadState::self()->restoreCallingWorkSource(token);
1104
1105 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1106}
1107
1108TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1109{
1110 IPCThreadState::self()->setCallingWorkSourceUid(100);
1111
1112 Parcel data, reply;
1113 status_t ret;
1114 data.writeInterfaceToken(binderLibTestServiceName);
1115 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001116 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001117
1118 Parcel data2, reply2;
1119 status_t ret2;
1120 data2.writeInterfaceToken(binderLibTestServiceName);
1121 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1122 EXPECT_EQ(100, reply2.readInt32());
1123 EXPECT_EQ(NO_ERROR, ret2);
1124}
1125
Steven Morelandbf1915b2020-07-16 22:43:02 +00001126TEST_F(BinderLibTest, SchedPolicySet) {
1127 sp<IBinder> server = addServer();
1128 ASSERT_TRUE(server != nullptr);
1129
1130 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001131 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1132 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001133
1134 int policy = reply.readInt32();
1135 int priority = reply.readInt32();
1136
1137 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1138 EXPECT_EQ(kSchedPriority, priority);
1139}
1140
Steven Morelandcf03cf12020-12-04 02:58:40 +00001141TEST_F(BinderLibTest, InheritRt) {
1142 sp<IBinder> server = addServer();
1143 ASSERT_TRUE(server != nullptr);
1144
1145 const struct sched_param param {
1146 .sched_priority = kSchedPriorityMore,
1147 };
1148 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1149
1150 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001151 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1152 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001153
1154 int policy = reply.readInt32();
1155 int priority = reply.readInt32();
1156
1157 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1158 EXPECT_EQ(kSchedPriorityMore, priority);
1159}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001160
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001161TEST_F(BinderLibTest, VectorSent) {
1162 Parcel data, reply;
1163 sp<IBinder> server = addServer();
1164 ASSERT_TRUE(server != nullptr);
1165
1166 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1167 data.writeUint64Vector(testValue);
1168
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001169 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001170 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001171 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001172 EXPECT_EQ(readValue, testValue);
1173}
1174
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001175TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1176 sp<IBinder> server = addServer();
1177 ASSERT_TRUE(server != nullptr);
1178
1179 Parcel reply;
1180 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1181 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001182 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001183 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1184
1185 const int result = fcntl(fd.get(), F_GETFL);
1186 ASSERT_NE(result, -1);
1187 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1188}
1189
Steven Moreland59b84442022-07-12 18:32:44 +00001190// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1191// This value is not exposed, but some code in the framework relies on being able to use
1192// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001193constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001194constexpr size_t kSizeBytesOverFull = 1'050'000;
1195
1196TEST_F(BinderLibTest, GargantuanVectorSent) {
1197 sp<IBinder> server = addServer();
1198 ASSERT_TRUE(server != nullptr);
1199
1200 for (size_t i = 0; i < 10; i++) {
1201 // a slight variation in size is used to consider certain possible caching implementations
1202 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1203
1204 Parcel data, reply;
1205 data.writeUint64Vector(testValue);
1206 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1207 << i;
1208 std::vector<uint64_t> readValue;
1209 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1210 EXPECT_EQ(readValue, testValue);
1211 }
1212}
1213
1214TEST_F(BinderLibTest, LimitExceededVectorSent) {
1215 sp<IBinder> server = addServer();
1216 ASSERT_TRUE(server != nullptr);
1217 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1218
1219 Parcel data, reply;
1220 data.writeUint64Vector(testValue);
1221 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1222 StatusEq(FAILED_TRANSACTION));
1223}
1224
Martijn Coenen82c75312019-07-24 15:18:30 +02001225TEST_F(BinderLibTest, BufRejected) {
1226 Parcel data, reply;
1227 uint32_t buf;
1228 sp<IBinder> server = addServer();
1229 ASSERT_TRUE(server != nullptr);
1230
1231 binder_buffer_object obj {
1232 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001233 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001234 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1235 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001236 };
1237 data.setDataCapacity(1024);
1238 // Write a bogus object at offset 0 to get an entry in the offset table
1239 data.writeFileDescriptor(0);
1240 EXPECT_EQ(data.objectsCount(), 1);
1241 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1242 // And now, overwrite it with the buffer object
1243 memcpy(parcelData, &obj, sizeof(obj));
1244 data.setDataSize(sizeof(obj));
1245
Steven Morelandf2e0a952021-11-01 18:17:23 -07001246 EXPECT_EQ(data.objectsCount(), 1);
1247
Martijn Coenen82c75312019-07-24 15:18:30 +02001248 // Either the kernel should reject this transaction (if it's correct), but
1249 // if it's not, the server implementation should return an error if it
1250 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001251 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001252 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001253}
1254
Steven Morelandf2e0a952021-11-01 18:17:23 -07001255TEST_F(BinderLibTest, WeakRejected) {
1256 Parcel data, reply;
1257 sp<IBinder> server = addServer();
1258 ASSERT_TRUE(server != nullptr);
1259
1260 auto binder = sp<BBinder>::make();
1261 wp<BBinder> wpBinder(binder);
1262 flat_binder_object obj{
1263 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1264 .flags = 0,
1265 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1266 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1267 };
1268 data.setDataCapacity(1024);
1269 // Write a bogus object at offset 0 to get an entry in the offset table
1270 data.writeFileDescriptor(0);
1271 EXPECT_EQ(data.objectsCount(), 1);
1272 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1273 // And now, overwrite it with the weak binder
1274 memcpy(parcelData, &obj, sizeof(obj));
1275 data.setDataSize(sizeof(obj));
1276
1277 // a previous bug caused other objects to be released an extra time, so we
1278 // test with an object that libbinder will actually try to release
1279 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1280
1281 EXPECT_EQ(data.objectsCount(), 2);
1282
1283 // send it many times, since previous error was memory corruption, make it
1284 // more likely that the server crashes
1285 for (size_t i = 0; i < 100; i++) {
1286 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1287 StatusEq(BAD_VALUE));
1288 }
1289
1290 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1291}
1292
Steven Moreland254e8ef2021-04-19 22:28:50 +00001293TEST_F(BinderLibTest, GotSid) {
1294 sp<IBinder> server = addServer();
1295
1296 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001297 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001298}
1299
Andrei Homescu1519b982022-06-09 02:04:44 +00001300struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1301 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1302
1303 // Flattenable protocol
1304 size_t getFlattenedSize() const {
1305 // Return a valid non-zero size here so we don't get an unintended
1306 // BAD_VALUE from Parcel::write
1307 return 16;
1308 }
1309 size_t getFdCount() const { return mFdCount; }
1310 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1311 for (size_t i = 0; i < count; i++) {
1312 fds[i] = STDIN_FILENO;
1313 }
1314 return NO_ERROR;
1315 }
1316 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1317 size_t & /*count*/) {
1318 /* This doesn't get called */
1319 return NO_ERROR;
1320 }
1321
1322 size_t mFdCount;
1323};
1324
1325TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1326 rlimit origNofile;
1327 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1328 ASSERT_EQ(0, ret);
1329
1330 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001331 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001332
1333 rlimit testNofile = {1024, 1024};
1334 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1335 ASSERT_EQ(0, ret);
1336
1337 Parcel parcel;
1338 // Try to write more file descriptors than supported by the OS
1339 TooManyFdsFlattenable tooManyFds1(1024);
1340 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1341
1342 // Try to write more file descriptors than the internal limit
1343 TooManyFdsFlattenable tooManyFds2(1025);
1344 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1345}
1346
Jayant Chowdhary30700942022-01-31 14:12:40 -08001347TEST(ServiceNotifications, Unregister) {
1348 auto sm = defaultServiceManager();
1349 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1350 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1351 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1352 virtual ~LocalRegistrationCallbackImpl() {}
1353 };
1354 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1355
1356 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1357 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1358}
1359
Elie Kheirallah47431c12022-04-21 23:46:17 +00001360TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1361 Parcel data, reply;
1362 sp<IBinder> server = addServer();
1363 ASSERT_TRUE(server != nullptr);
1364 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1365 StatusEq(NO_ERROR));
1366 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001367 // see getThreadPoolMaxTotalThreadCount for why there is a race
1368 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1369
Elie Kheirallah47431c12022-04-21 23:46:17 +00001370 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1371
1372 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001373 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1374 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1375 * started threads from setThreadPoolMaxThreadCount
1376 *
1377 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001378 */
1379 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001380 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001381 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001382 Parcel local_reply;
1383 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1384 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001385 }));
1386 }
1387
Steven Moreland3e9debc2023-06-15 00:35:29 +00001388 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1389 // the time, the below call will pre-empt them (presumably because we have the
1390 // scheduler timeslice already + scheduler hint).
1391 sleep(1);
1392
1393 data.writeInt32(1000);
1394 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001395 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1396
1397 for (auto &t : ts) {
1398 t.join();
1399 }
1400
1401 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1402 StatusEq(NO_ERROR));
1403 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001404 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001405}
1406
Devin Moore4354f712022-12-08 01:44:46 +00001407TEST_F(BinderLibTest, ThreadPoolStarted) {
1408 Parcel data, reply;
1409 sp<IBinder> server = addServer();
1410 ASSERT_TRUE(server != nullptr);
1411 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1412 EXPECT_TRUE(reply.readBool());
1413}
1414
Elie Kheirallah47431c12022-04-21 23:46:17 +00001415size_t epochMillis() {
1416 using std::chrono::duration_cast;
1417 using std::chrono::milliseconds;
1418 using std::chrono::seconds;
1419 using std::chrono::system_clock;
1420 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1421}
1422
1423TEST_F(BinderLibTest, HangingServices) {
1424 Parcel data, reply;
1425 sp<IBinder> server = addServer();
1426 ASSERT_TRUE(server != nullptr);
1427 int32_t delay = 1000; // ms
1428 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001429 // b/266537959 - must take before taking lock, since countdown is started in the remote
1430 // process there.
1431 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001432 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1433 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001434 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1435 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001436 Parcel local_reply;
1437 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1438 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001439 }));
1440 }
1441
1442 for (auto &t : ts) {
1443 t.join();
1444 }
1445 size_t epochMsAfter = epochMillis();
1446
1447 // deadlock occurred and threads only finished after 1s passed.
1448 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1449}
1450
Jing Jibbe9ae62023-10-07 15:26:02 -07001451TEST_F(BinderLibTest, BinderProxyCount) {
1452 Parcel data, reply;
1453 sp<IBinder> server = addServer();
1454 ASSERT_NE(server, nullptr);
1455
1456 uint32_t initialCount = BpBinder::getBinderProxyCount();
1457 size_t iterations = 100;
1458 {
1459 uint32_t count = initialCount;
1460 std::vector<sp<IBinder> > proxies;
1461 sp<IBinder> proxy;
1462 // Create binder proxies and verify the count.
1463 for (size_t i = 0; i < iterations; i++) {
1464 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1465 StatusEq(NO_ERROR));
1466 proxies.push_back(reply.readStrongBinder());
1467 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1468 }
1469 // Remove every other one and verify the count.
1470 auto it = proxies.begin();
1471 for (size_t i = 0; it != proxies.end(); i++) {
1472 if (i % 2 == 0) {
1473 it = proxies.erase(it);
1474 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1475 }
1476 }
1477 }
1478 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1479}
1480
Jing Jibdbe29a2023-10-03 00:03:28 -07001481static constexpr int kBpCountHighWatermark = 20;
1482static constexpr int kBpCountLowWatermark = 10;
1483static constexpr int kBpCountWarningWatermark = 15;
1484static constexpr int kInvalidUid = -1;
1485
1486TEST_F(BinderLibTest, BinderProxyCountCallback) {
1487 Parcel data, reply;
1488 sp<IBinder> server = addServer();
1489 ASSERT_NE(server, nullptr);
1490
1491 BpBinder::enableCountByUid();
1492 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1493 int32_t uid = reply.readInt32();
1494 ASSERT_NE(uid, kInvalidUid);
1495
1496 uint32_t initialCount = BpBinder::getBinderProxyCount();
1497 {
1498 uint32_t count = initialCount;
1499 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1500 kBpCountLowWatermark,
1501 kBpCountWarningWatermark);
1502 int limitCallbackUid = kInvalidUid;
1503 int warningCallbackUid = kInvalidUid;
1504 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1505 [&](int uid) { warningCallbackUid = uid; });
1506
1507 std::vector<sp<IBinder> > proxies;
1508 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1509 warningCallbackUid = limitCallbackUid = kInvalidUid;
1510 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1511 StatusEq(NO_ERROR));
1512 proxies.push_back(reply.readStrongBinder());
1513 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1514 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1515 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1516 };
1517 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1518 warningCallbackUid = limitCallbackUid = kInvalidUid;
1519 proxies.pop_back();
1520 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1521 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1522 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1523 };
1524
1525 // Test the increment/decrement of the binder proxies.
1526 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1527 createProxyOnce(kInvalidUid, kInvalidUid);
1528 }
1529 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1530 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1531 createProxyOnce(kInvalidUid, kInvalidUid);
1532 }
1533 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1534 createProxyOnce(kInvalidUid, kInvalidUid);
1535 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1536 removeProxyOnce(kInvalidUid, kInvalidUid);
1537 }
1538 createProxyOnce(kInvalidUid, kInvalidUid);
1539
1540 // Go down below the low watermark.
1541 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1542 removeProxyOnce(kInvalidUid, kInvalidUid);
1543 }
1544 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1545 createProxyOnce(kInvalidUid, kInvalidUid);
1546 }
1547 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1548 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1549 createProxyOnce(kInvalidUid, kInvalidUid);
1550 }
1551 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1552 createProxyOnce(kInvalidUid, kInvalidUid);
1553 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1554 removeProxyOnce(kInvalidUid, kInvalidUid);
1555 }
1556 createProxyOnce(kInvalidUid, kInvalidUid);
1557 }
1558 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1559}
1560
Yifan Hong84bedeb2021-04-21 21:37:17 -07001561class BinderLibRpcTestBase : public BinderLibTest {
1562public:
1563 void SetUp() override {
1564 if (!base::GetBoolProperty("ro.debuggable", false)) {
1565 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1566 "non-debuggable builds.";
1567 }
1568 BinderLibTest::SetUp();
1569 }
1570
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001571 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001572 auto rpcServer = RpcServer::make();
1573 EXPECT_NE(nullptr, rpcServer);
1574 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001575 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001576 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1577 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001578 return {};
1579 }
1580 return {rpcServer->releaseServer(), port};
1581 }
1582};
1583
Yifan Hong8b890852021-06-10 13:44:09 -07001584class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001585
Yifan Hongbd276552022-02-28 15:28:51 -08001586// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1587// If device is debuggable AND not on user builds, expects matcher.
1588// Otherwise expects INVALID_OPERATION.
1589// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1590static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1591 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1592 android::base::GetProperty("ro.build.type", "") != "user";
1593 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1594}
1595
Yifan Hong8b890852021-06-10 13:44:09 -07001596TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1597 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001598 ASSERT_TRUE(binder != nullptr);
1599 auto [socket, port] = CreateSocket();
1600 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001601 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1602 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001603}
1604
Yifan Hong8b890852021-06-10 13:44:09 -07001605// Tests for multiple RpcServer's on the same binder object.
1606TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1607 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001608 ASSERT_TRUE(binder != nullptr);
1609
1610 auto [socket1, port1] = CreateSocket();
1611 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001612 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001613 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1614 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001615
1616 auto [socket2, port2] = CreateSocket();
1617 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001618 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001619 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1620 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001621}
1622
Yifan Hong8b890852021-06-10 13:44:09 -07001623// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1624// local binders.
1625class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001626public:
1627 sp<IBinder> GetService() {
1628 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1629 }
1630 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1631 return info.param ? "remote" : "local";
1632 }
1633};
1634
Yifan Hong8b890852021-06-10 13:44:09 -07001635TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1636 auto binder = GetService();
1637 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001638 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001639 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001640}
1641
1642TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001643 auto binder = GetService();
1644 ASSERT_TRUE(binder != nullptr);
1645 auto [socket, port] = CreateSocket();
1646 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001647 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1648 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001649}
Yifan Hong8b890852021-06-10 13:44:09 -07001650INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1651 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001652
Yifan Hong543edcd2021-05-18 19:47:30 -07001653class BinderLibTestService : public BBinder {
1654public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001655 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1656 : m_id(id),
1657 m_nextServerId(id + 1),
1658 m_serverStartRequested(false),
1659 m_callback(nullptr),
1660 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001661 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1662 pthread_cond_init(&m_serverWaitCond, nullptr);
1663 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001664 ~BinderLibTestService() {
1665 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1666 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001667
Yifan Hong543edcd2021-05-18 19:47:30 -07001668 void processPendingCall() {
1669 if (m_callback != nullptr) {
1670 Parcel data;
1671 data.writeInt32(NO_ERROR);
1672 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1673 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001674 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001675 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001676
Yifan Hong543edcd2021-05-18 19:47:30 -07001677 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1678 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001679 // TODO(b/182914638): also checks getCallingUid() for RPC
1680 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001681 return PERMISSION_DENIED;
1682 }
1683 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001684 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001685 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001686 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001687 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001688 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001689 return BAD_VALUE;
1690 }
1691
Yifan Hong543edcd2021-05-18 19:47:30 -07001692 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001693
1694 pthread_mutex_lock(&m_serverWaitMutex);
1695 if (m_serverStartRequested) {
1696 m_serverStartRequested = false;
1697 m_serverStarted = binder;
1698 pthread_cond_signal(&m_serverWaitCond);
1699 }
1700 pthread_mutex_unlock(&m_serverWaitMutex);
1701 return NO_ERROR;
1702 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001703 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001704 case BINDER_LIB_TEST_ADD_SERVER: {
1705 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001706 int serverid;
1707
1708 if (m_id != 0) {
1709 return INVALID_OPERATION;
1710 }
1711 pthread_mutex_lock(&m_serverWaitMutex);
1712 if (m_serverStartRequested) {
1713 ret = -EBUSY;
1714 } else {
1715 serverid = m_nextServerId++;
1716 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001717 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001718
1719 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001720 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001721 pthread_mutex_lock(&m_serverWaitMutex);
1722 }
1723 if (ret > 0) {
1724 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001725 struct timespec ts;
1726 clock_gettime(CLOCK_REALTIME, &ts);
1727 ts.tv_sec += 5;
1728 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001729 }
1730 if (m_serverStartRequested) {
1731 m_serverStartRequested = false;
1732 ret = -ETIMEDOUT;
1733 } else {
1734 reply->writeStrongBinder(m_serverStarted);
1735 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001736 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001737 ret = NO_ERROR;
1738 }
1739 } else if (ret >= 0) {
1740 m_serverStartRequested = false;
1741 ret = UNKNOWN_ERROR;
1742 }
1743 pthread_mutex_unlock(&m_serverWaitMutex);
1744 return ret;
1745 }
Steven Moreland35626652021-05-15 01:32:04 +00001746 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1747 IPCThreadState::SpGuard spGuard{
1748 .address = __builtin_frame_address(0),
1749 .context = "GuardInBinderTransaction",
1750 };
1751 const IPCThreadState::SpGuard *origGuard =
1752 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1753
1754 // if the guard works, this should abort
1755 (void)IPCThreadState::self()->getCallingPid();
1756
1757 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1758 return NO_ERROR;
1759 }
1760
Marco Ballesio7ee17572020-09-08 10:30:03 -07001761 case BINDER_LIB_TEST_GETPID:
1762 reply->writeInt32(getpid());
1763 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07001764 case BINDER_LIB_TEST_GETUID:
1765 reply->writeInt32(getuid());
1766 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07001767 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1768 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001769 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001770 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001771 // oneway error codes should be ignored
1772 if (flags & TF_ONE_WAY) {
1773 return UNKNOWN_ERROR;
1774 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001775 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001776 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1777 // Note: this transaction is only designed for use with a
1778 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001779 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001780 // A callback was already pending; this means that
1781 // we received a second call while still processing
1782 // the first one. Fail the test.
1783 sp<IBinder> callback = data.readStrongBinder();
1784 Parcel data2;
1785 data2.writeInt32(UNKNOWN_ERROR);
1786
Yi Kong91635562018-06-07 14:38:36 -07001787 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001788 } else {
1789 m_callback = data.readStrongBinder();
1790 int32_t delayUs = data.readInt32();
1791 /*
1792 * It's necessary that we sleep here, so the next
1793 * transaction the caller makes will be queued to
1794 * the async queue.
1795 */
1796 usleep(delayUs);
1797
1798 /*
1799 * Now when we return, libbinder will tell the kernel
1800 * we are done with this transaction, and the kernel
1801 * can move the queued transaction to either the
1802 * thread todo worklist (for kernels without the fix),
1803 * or the proc todo worklist. In case of the former,
1804 * the next outbound call will pick up the pending
1805 * transaction, which leads to undesired reentrant
1806 * behavior. This is caught in the if() branch above.
1807 */
1808 }
1809
1810 return NO_ERROR;
1811 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001812 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1813 Parcel data2, reply2;
1814 sp<IBinder> binder;
1815 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001816 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001817 return BAD_VALUE;
1818 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001819 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001820 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1821 return NO_ERROR;
1822 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001823 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1824 reply->writeStrongBinder(this);
1825 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001826 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1827 reply->writeInt32(m_id);
1828 return NO_ERROR;
1829 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1830 int32_t count;
1831 uint32_t indirect_code;
1832 sp<IBinder> binder;
1833
1834 count = data.readInt32();
1835 reply->writeInt32(m_id);
1836 reply->writeInt32(count);
1837 for (int i = 0; i < count; i++) {
1838 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001839 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001840 return BAD_VALUE;
1841 }
1842 indirect_code = data.readInt32();
1843 BinderLibTestBundle data2(&data);
1844 if (!data2.isValid()) {
1845 return BAD_VALUE;
1846 }
1847 BinderLibTestBundle reply2;
1848 binder->transact(indirect_code, data2, &reply2);
1849 reply2.appendTo(reply);
1850 }
1851 return NO_ERROR;
1852 }
1853 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1854 reply->setError(data.readInt32());
1855 return NO_ERROR;
1856 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1857 reply->writeInt32(sizeof(void *));
1858 return NO_ERROR;
1859 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1860 return NO_ERROR;
1861 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1862 m_strongRef = data.readStrongBinder();
1863 return NO_ERROR;
1864 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1865 int ret;
1866 Parcel data2, reply2;
1867 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1868 sp<IBinder> target;
1869 sp<IBinder> callback;
1870
1871 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001872 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001873 return BAD_VALUE;
1874 }
1875 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001876 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001877 return BAD_VALUE;
1878 }
1879 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001880 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001881 data2.writeInt32(ret);
1882 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1883 return NO_ERROR;
1884 }
1885 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1886 int ret;
1887 int32_t size;
1888 const void *buf;
1889 int fd;
1890
1891 fd = data.readFileDescriptor();
1892 if (fd < 0) {
1893 return BAD_VALUE;
1894 }
1895 ret = data.readInt32(&size);
1896 if (ret != NO_ERROR) {
1897 return ret;
1898 }
1899 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001900 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001901 return BAD_VALUE;
1902 }
1903 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001904 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001905 return NO_ERROR;
1906 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001907 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1908 int ret;
1909 int32_t size;
1910 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001911 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001912
1913 ret = data.readUniqueParcelFileDescriptor(&fd);
1914 if (ret != NO_ERROR) {
1915 return ret;
1916 }
1917 ret = data.readInt32(&size);
1918 if (ret != NO_ERROR) {
1919 return ret;
1920 }
1921 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001922 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001923 return BAD_VALUE;
1924 }
1925 ret = write(fd.get(), buf, size);
1926 if (ret != size) return UNKNOWN_ERROR;
1927 return NO_ERROR;
1928 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001929 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1930 alarm(10);
1931 return NO_ERROR;
1932 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001933 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001934 ;
1935 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001936 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001937 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001938 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001939 return NO_ERROR;
1940 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001941 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1942 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001943 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001944 return NO_ERROR;
1945 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001946 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1947 int policy = 0;
1948 sched_param param;
1949 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1950 return UNKNOWN_ERROR;
1951 }
1952 reply->writeInt32(policy);
1953 reply->writeInt32(param.sched_priority);
1954 return NO_ERROR;
1955 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001956 case BINDER_LIB_TEST_ECHO_VECTOR: {
1957 std::vector<uint64_t> vector;
1958 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001959 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001960 reply->writeUint64Vector(vector);
1961 return NO_ERROR;
1962 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001963 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1964 std::array<int, 2> sockets;
1965 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1966 if (!created) {
1967 ALOGE("Could not create socket pair");
1968 return UNKNOWN_ERROR;
1969 }
1970
1971 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1972 if (result != 0) {
1973 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1974 return UNKNOWN_ERROR;
1975 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001976 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001977 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1978 if (writeResult != NO_ERROR) {
1979 ALOGE("Could not write unique_fd");
1980 return writeResult;
1981 }
1982 close(sockets[1]); // we don't need the other side of the fd
1983 return NO_ERROR;
1984 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001985 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001986 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1987 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001988 case BINDER_LIB_TEST_CAN_GET_SID: {
1989 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1990 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001991 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1992 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1993 return NO_ERROR;
1994 }
Devin Moore4354f712022-12-08 01:44:46 +00001995 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1996 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1997 return NO_ERROR;
1998 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001999 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002000 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002001 return NO_ERROR;
2002 }
2003 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002004 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002005 return NO_ERROR;
2006 }
2007 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2008 int32_t ms = data.readInt32();
2009 return unlockInMs(ms);
2010 }
2011 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002012 m_blockMutex.lock();
2013 sp<BinderLibTestService> thisService = this;
2014 int32_t value = data.readInt32();
2015 // start local thread to unlock in 1s
2016 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002017 t.detach();
2018 return NO_ERROR;
2019 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002020 default:
2021 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002022 };
2023 }
2024
Elie Kheirallah47431c12022-04-21 23:46:17 +00002025 status_t unlockInMs(int32_t ms) {
2026 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002027 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002028 return NO_ERROR;
2029 }
2030
Yifan Hong543edcd2021-05-18 19:47:30 -07002031private:
2032 int32_t m_id;
2033 int32_t m_nextServerId;
2034 pthread_mutex_t m_serverWaitMutex;
2035 pthread_cond_t m_serverWaitCond;
2036 bool m_serverStartRequested;
2037 sp<IBinder> m_serverStarted;
2038 sp<IBinder> m_strongRef;
2039 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002040 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002041 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002042};
2043
Martijn Coenen45b07b42017-08-09 12:07:45 +02002044int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002045{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002046 binderLibTestServiceName += String16(binderserversuffix);
2047
Steven Moreland35626652021-05-15 01:32:04 +00002048 // Testing to make sure that calls that we are serving can use getCallin*
2049 // even though we don't here.
2050 IPCThreadState::SpGuard spGuard{
2051 .address = __builtin_frame_address(0),
2052 .context = "main server thread",
2053 };
2054 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2055
Riley Andrews06b01ad2014-12-18 12:10:08 -08002056 status_t ret;
2057 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02002058 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002059 {
2060 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002061
Steven Morelandbf1915b2020-07-16 22:43:02 +00002062 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2063
Steven Morelandcf03cf12020-12-04 02:58:40 +00002064 testService->setInheritRt(true);
2065
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002066 /*
2067 * Normally would also contain functionality as well, but we are only
2068 * testing the extension mechanism.
2069 */
2070 testService->setExtension(new BBinder());
2071
Martijn Coenen82c75312019-07-24 15:18:30 +02002072 // Required for test "BufRejected'
2073 testService->setRequestingSid(true);
2074
Martijn Coenen45b07b42017-08-09 12:07:45 +02002075 /*
2076 * We need this below, but can't hold a sp<> because it prevents the
2077 * node from being cleaned up automatically. It's safe in this case
2078 * because of how the tests are written.
2079 */
2080 testServicePtr = testService.get();
2081
Riley Andrews06b01ad2014-12-18 12:10:08 -08002082 if (index == 0) {
2083 ret = sm->addService(binderLibTestServiceName, testService);
2084 } else {
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002085#pragma clang diagnostic push
2086#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -08002087 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002088#pragma clang diagnostic pop
Riley Andrews06b01ad2014-12-18 12:10:08 -08002089 Parcel data, reply;
2090 data.writeInt32(index);
2091 data.writeStrongBinder(testService);
2092
2093 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2094 }
2095 }
2096 write(readypipefd, &ret, sizeof(ret));
2097 close(readypipefd);
2098 //printf("%s: ret %d\n", __func__, ret);
2099 if (ret)
2100 return 1;
2101 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002102 if (usePoll) {
2103 int fd;
2104 struct epoll_event ev;
2105 int epoll_fd;
2106 IPCThreadState::self()->setupPolling(&fd);
2107 if (fd < 0) {
2108 return 1;
2109 }
2110 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2111
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002112 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002113 if (epoll_fd == -1) {
2114 return 1;
2115 }
2116
2117 ev.events = EPOLLIN;
2118 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2119 return 1;
2120 }
2121
2122 while (1) {
2123 /*
2124 * We simulate a single-threaded process using the binder poll
2125 * interface; besides handling binder commands, it can also
2126 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002127 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002128 *
2129 * processPendingCall() will then issue that transaction.
2130 */
2131 struct epoll_event events[1];
2132 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2133 if (numEvents < 0) {
2134 if (errno == EINTR) {
2135 continue;
2136 }
2137 return 1;
2138 }
2139 if (numEvents > 0) {
2140 IPCThreadState::self()->handlePolledCommands();
2141 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2142 testServicePtr->processPendingCall();
2143 }
2144 }
2145 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002146 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002147 ProcessState::self()->startThreadPool();
2148 IPCThreadState::self()->joinThreadPool();
2149 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002150 //printf("%s: joinThreadPool returned\n", __func__);
2151 return 1; /* joinThreadPool should not return */
2152}
2153
Steven Moreland68275d72023-04-21 22:12:45 +00002154int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002155 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002156 binderservername = argv[2];
2157 } else {
2158 binderservername = argv[0];
2159 }
2160
Martijn Coenen45b07b42017-08-09 12:07:45 +02002161 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2162 binderserversuffix = argv[5];
2163 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002164 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002165 binderserversuffix = new char[16];
2166 snprintf(binderserversuffix, 16, "%d", getpid());
2167 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002168
2169 ::testing::InitGoogleTest(&argc, argv);
2170 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2171 ProcessState::self()->startThreadPool();
2172 return RUN_ALL_TESTS();
2173}