blob: 4ed3309e0ccf2eb9820e4ce2d7c5a98aab9880f2 [file] [log] [blame]
Riley Andrews06b01ad2014-12-18 12:10:08 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080018#include <poll.h>
19#include <pthread.h>
20#include <stdio.h>
21#include <stdlib.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070022
23#include <chrono>
Yifan Hong8b890852021-06-10 13:44:09 -070024#include <fstream>
Steven Morelandd7088702021-01-13 00:27:00 +000025#include <thread>
Riley Andrews06b01ad2014-12-18 12:10:08 -080026
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070027#include <gmock/gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080028#include <gtest/gtest.h>
29
Yifan Hong84bedeb2021-04-21 21:37:17 -070030#include <android-base/properties.h>
Yifan Hong28d6c352021-06-04 17:27:35 -070031#include <android-base/result-gmock.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070032#include <android-base/result.h>
Andrei Homescu1519b982022-06-09 02:04:44 +000033#include <android-base/scopeguard.h>
Yifan Hong8b890852021-06-10 13:44:09 -070034#include <android-base/strings.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070035#include <android-base/unique_fd.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080036#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070037#include <binder/BpBinder.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080038#include <binder/IBinder.h>
39#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070041#include <binder/RpcServer.h>
42#include <binder/RpcSession.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#include "binderAbiHelper.h"
52
Riley Andrews06b01ad2014-12-18 12:10:08 -080053#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
54
55using namespace android;
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;
Yifan Hong84bedeb2021-04-21 21:37:17 -070060using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080061using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070062using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070063using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070064
65// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
66MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
67 *result_listener << statusToString(arg);
68 return expected == arg;
69}
Riley Andrews06b01ad2014-12-18 12:10:08 -080070
Sherry Yang336cdd32017-07-24 14:12:27 -070071static ::testing::AssertionResult IsPageAligned(void *buf) {
72 if (((unsigned long)buf & ((unsigned long)PAGE_SIZE - 1)) == 0)
73 return ::testing::AssertionSuccess();
74 else
75 return ::testing::AssertionFailure() << buf << " is not page aligned";
76}
77
Riley Andrews06b01ad2014-12-18 12:10:08 -080078static testing::Environment* binder_env;
79static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070080static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080081static char binderserverarg[] = "--binderserver";
82
Steven Morelandbf1915b2020-07-16 22:43:02 +000083static constexpr int kSchedPolicy = SCHED_RR;
84static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000085static constexpr int kSchedPriorityMore = 8;
Elie Kheirallah47431c12022-04-21 23:46:17 +000086static constexpr int kKernelThreads = 15;
Steven Morelandbf1915b2020-07-16 22:43:02 +000087
Riley Andrews06b01ad2014-12-18 12:10:08 -080088static String16 binderLibTestServiceName = String16("test.binderLib");
89
90enum BinderLibTestTranscationCode {
91 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
92 BINDER_LIB_TEST_REGISTER_SERVER,
93 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020094 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000095 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -080096 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -070097 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +020098 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -080099 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700100 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800101 BINDER_LIB_TEST_GET_ID_TRANSACTION,
102 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
103 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
104 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
105 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
106 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
107 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900108 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800109 BINDER_LIB_TEST_EXIT_TRANSACTION,
110 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
111 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700112 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100113 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000114 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700115 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
116 BINDER_LIB_TEST_GETPID,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800117 BINDER_LIB_TEST_ECHO_VECTOR,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700118 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000119 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000120 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
121 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
122 BINDER_LIB_TEST_LOCK_UNLOCK,
123 BINDER_LIB_TEST_PROCESS_LOCK,
124 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
125 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800126};
127
Martijn Coenen45b07b42017-08-09 12:07:45 +0200128pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800129{
130 int ret;
131 pid_t pid;
132 status_t status;
133 int pipefd[2];
134 char stri[16];
135 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200136 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800137 char *childargv[] = {
138 binderservername,
139 binderserverarg,
140 stri,
141 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200142 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700143 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700144 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800145 };
146
147 ret = pipe(pipefd);
148 if (ret < 0)
149 return ret;
150
151 snprintf(stri, sizeof(stri), "%d", arg2);
152 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200153 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800154
155 pid = fork();
156 if (pid == -1)
157 return pid;
158 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800159 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800160 close(pipefd[0]);
161 execv(binderservername, childargv);
162 status = -errno;
163 write(pipefd[1], &status, sizeof(status));
164 fprintf(stderr, "execv failed, %s\n", strerror(errno));
165 _exit(EXIT_FAILURE);
166 }
167 close(pipefd[1]);
168 ret = read(pipefd[0], &status, sizeof(status));
169 //printf("pipe read returned %d, status %d\n", ret, status);
170 close(pipefd[0]);
171 if (ret == sizeof(status)) {
172 ret = status;
173 } else {
174 kill(pid, SIGKILL);
175 if (ret >= 0) {
176 ret = NO_INIT;
177 }
178 }
179 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700180 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800181 return ret;
182 }
183 return pid;
184}
185
Yifan Hong84bedeb2021-04-21 21:37:17 -0700186android::base::Result<int32_t> GetId(sp<IBinder> service) {
187 using android::base::Error;
188 Parcel data, reply;
189 data.markForBinder(service);
190 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
191 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
192 if (status != OK)
193 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
194 int32_t result = 0;
195 status = reply.readInt32(&result);
196 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
197 return result;
198}
199
Riley Andrews06b01ad2014-12-18 12:10:08 -0800200class BinderLibTestEnv : public ::testing::Environment {
201 public:
202 BinderLibTestEnv() {}
203 sp<IBinder> getServer(void) {
204 return m_server;
205 }
206
207 private:
208 virtual void SetUp() {
209 m_serverpid = start_server_process(0);
210 //printf("m_serverpid %d\n", m_serverpid);
211 ASSERT_GT(m_serverpid, 0);
212
213 sp<IServiceManager> sm = defaultServiceManager();
214 //printf("%s: pid %d, get service\n", __func__, m_pid);
215 m_server = sm->getService(binderLibTestServiceName);
Yi Kong91635562018-06-07 14:38:36 -0700216 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800217 //printf("%s: pid %d, get service done\n", __func__, m_pid);
218 }
219 virtual void TearDown() {
220 status_t ret;
221 Parcel data, reply;
222 int exitStatus;
223 pid_t pid;
224
225 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700226 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800227 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
228 EXPECT_EQ(0, ret);
229 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
230 EXPECT_EQ(0, ret);
231 }
232 if (m_serverpid > 0) {
233 //printf("wait for %d\n", m_pids[i]);
234 pid = wait(&exitStatus);
235 EXPECT_EQ(m_serverpid, pid);
236 EXPECT_TRUE(WIFEXITED(exitStatus));
237 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
238 }
239 }
240
241 pid_t m_serverpid;
242 sp<IBinder> m_server;
243};
244
245class BinderLibTest : public ::testing::Test {
246 public:
247 virtual void SetUp() {
248 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000249 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800250 }
251 virtual void TearDown() {
252 }
253 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200254 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800255 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800256 int32_t id;
257 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800258
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700259 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800260
Elie Kheirallahb7246642022-05-03 18:01:43 +0000261 sp<IBinder> binder = reply.readStrongBinder();
262 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700263 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800264 if (idPtr)
265 *idPtr = id;
266 return binder;
267 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200268
Yi Kong91635562018-06-07 14:38:36 -0700269 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200270 {
271 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
272 }
273
Yi Kong91635562018-06-07 14:38:36 -0700274 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200275 {
276 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
277 }
278
Riley Andrews06b01ad2014-12-18 12:10:08 -0800279 void waitForReadData(int fd, int timeout_ms) {
280 int ret;
281 pollfd pfd = pollfd();
282
283 pfd.fd = fd;
284 pfd.events = POLLIN;
285 ret = poll(&pfd, 1, timeout_ms);
286 EXPECT_EQ(1, ret);
287 }
288
289 sp<IBinder> m_server;
290};
291
292class BinderLibTestBundle : public Parcel
293{
294 public:
295 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800296 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800297 int32_t mark;
298 int32_t bundleLen;
299 size_t pos;
300
301 if (source->readInt32(&mark))
302 return;
303 if (mark != MARK_START)
304 return;
305 if (source->readInt32(&bundleLen))
306 return;
307 pos = source->dataPosition();
308 if (Parcel::appendFrom(source, pos, bundleLen))
309 return;
310 source->setDataPosition(pos + bundleLen);
311 if (source->readInt32(&mark))
312 return;
313 if (mark != MARK_END)
314 return;
315 m_isValid = true;
316 setDataPosition(0);
317 }
318 void appendTo(Parcel *dest) {
319 dest->writeInt32(MARK_START);
320 dest->writeInt32(dataSize());
321 dest->appendFrom(this, 0, dataSize());
322 dest->writeInt32(MARK_END);
323 };
324 bool isValid(void) {
325 return m_isValid;
326 }
327 private:
328 enum {
329 MARK_START = B_PACK_CHARS('B','T','B','S'),
330 MARK_END = B_PACK_CHARS('B','T','B','E'),
331 };
332 bool m_isValid;
333};
334
335class BinderLibTestEvent
336{
337 public:
338 BinderLibTestEvent(void)
339 : m_eventTriggered(false)
340 {
Yi Kong91635562018-06-07 14:38:36 -0700341 pthread_mutex_init(&m_waitMutex, nullptr);
342 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800343 }
344 int waitEvent(int timeout_s)
345 {
346 int ret;
347 pthread_mutex_lock(&m_waitMutex);
348 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800349 struct timespec ts;
350 clock_gettime(CLOCK_REALTIME, &ts);
351 ts.tv_sec += timeout_s;
352 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800353 }
354 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
355 pthread_mutex_unlock(&m_waitMutex);
356 return ret;
357 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200358 pthread_t getTriggeringThread()
359 {
360 return m_triggeringThread;
361 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800362 protected:
363 void triggerEvent(void) {
364 pthread_mutex_lock(&m_waitMutex);
365 pthread_cond_signal(&m_waitCond);
366 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200367 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800368 pthread_mutex_unlock(&m_waitMutex);
369 };
370 private:
371 pthread_mutex_t m_waitMutex;
372 pthread_cond_t m_waitCond;
373 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200374 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800375};
376
377class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
378{
379 public:
380 BinderLibTestCallBack()
381 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700382 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800383 {
384 }
385 status_t getResult(void)
386 {
387 return m_result;
388 }
389
390 private:
391 virtual status_t onTransact(uint32_t code,
392 const Parcel& data, Parcel* reply,
393 uint32_t flags = 0)
394 {
395 (void)reply;
396 (void)flags;
397 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200398 case BINDER_LIB_TEST_CALL_BACK: {
399 status_t status = data.readInt32(&m_result);
400 if (status != NO_ERROR) {
401 m_result = status;
402 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800403 triggerEvent();
404 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200405 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700406 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
407 sp<IBinder> server;
408 int ret;
409 const uint8_t *buf = data.data();
410 size_t size = data.dataSize();
411 if (m_prev_end) {
412 /* 64-bit kernel needs at most 8 bytes to align buffer end */
413 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
414 } else {
415 EXPECT_TRUE(IsPageAligned((void *)buf));
416 }
417
418 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
419
420 if (size > 0) {
421 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
422 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
423 data, reply);
424 EXPECT_EQ(NO_ERROR, ret);
425 }
426 return NO_ERROR;
427 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800428 default:
429 return UNKNOWN_TRANSACTION;
430 }
431 }
432
433 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700434 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800435};
436
437class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
438{
439 private:
440 virtual void binderDied(const wp<IBinder>& who) {
441 (void)who;
442 triggerEvent();
443 };
444};
445
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700446TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
447 // EXPECT_DEATH works by forking the process
448 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
449}
450
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000451TEST_F(BinderLibTest, AddManagerToManager) {
452 sp<IServiceManager> sm = defaultServiceManager();
453 sp<IBinder> binder = IInterface::asBinder(sm);
454 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
455}
456
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500457TEST_F(BinderLibTest, WasParceled) {
458 auto binder = sp<BBinder>::make();
459 EXPECT_FALSE(binder->wasParceled());
460 Parcel data;
461 data.writeStrongBinder(binder);
462 EXPECT_TRUE(binder->wasParceled());
463}
464
Riley Andrews06b01ad2014-12-18 12:10:08 -0800465TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800466 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700467 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
468 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800469}
470
Steven Moreland80844f72020-12-12 02:06:08 +0000471TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000472 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700473 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
474 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000475}
476
Steven Morelandf183fdd2020-10-27 00:12:12 +0000477TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000478 Parcel data, reply;
479 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700480 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
481 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000482}
483
Marco Ballesio7ee17572020-09-08 10:30:03 -0700484TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700485 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700486 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700487
Li Li6f059292021-09-10 09:59:30 -0700488 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700489 if (freezer_file.fail()) {
490 GTEST_SKIP();
491 return;
492 }
493
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700494 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700495 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700496 for (int i = 0; i < 10; i++) {
497 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
498 }
Li Li6f059292021-09-10 09:59:30 -0700499
500 // Pass test on devices where BINDER_FREEZE ioctl is not supported
501 int ret = IPCThreadState::self()->freeze(pid, false, 0);
502 if (ret != 0) {
503 GTEST_SKIP();
504 return;
505 }
506
507 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
508 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
509 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700510 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700511
Li Li4e678b92021-09-14 12:14:42 -0700512 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700513
514 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
515 &async_received));
516
517 EXPECT_EQ(sync_received, 1);
518 EXPECT_EQ(async_received, 0);
519
Li Li4e678b92021-09-14 12:14:42 -0700520 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700521 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
522}
523
Riley Andrews06b01ad2014-12-18 12:10:08 -0800524TEST_F(BinderLibTest, SetError) {
525 int32_t testValue[] = { 0, -123, 123 };
526 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800527 Parcel data, reply;
528 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700529 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
530 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800531 }
532}
533
534TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700535 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800536}
537
538TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800539 int32_t ptrsize;
540 Parcel data, reply;
541 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700542 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700543 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
544 StatusEq(NO_ERROR));
545 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800546 RecordProperty("TestPtrSize", sizeof(void *));
547 RecordProperty("ServerPtrSize", sizeof(void *));
548}
549
550TEST_F(BinderLibTest, IndirectGetId2)
551{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800552 int32_t id;
553 int32_t count;
554 Parcel data, reply;
555 int32_t serverId[3];
556
557 data.writeInt32(ARRAY_SIZE(serverId));
558 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
559 sp<IBinder> server;
560 BinderLibTestBundle datai;
561
562 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700563 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800564 data.writeStrongBinder(server);
565 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
566 datai.appendTo(&data);
567 }
568
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700569 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
570 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800571
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700572 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800573 EXPECT_EQ(0, id);
574
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700575 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700576 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800577
578 for (size_t i = 0; i < (size_t)count; i++) {
579 BinderLibTestBundle replyi(&reply);
580 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700581 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800582 EXPECT_EQ(serverId[i], id);
583 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
584 }
585
586 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
587}
588
589TEST_F(BinderLibTest, IndirectGetId3)
590{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800591 int32_t id;
592 int32_t count;
593 Parcel data, reply;
594 int32_t serverId[3];
595
596 data.writeInt32(ARRAY_SIZE(serverId));
597 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
598 sp<IBinder> server;
599 BinderLibTestBundle datai;
600 BinderLibTestBundle datai2;
601
602 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700603 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800604 data.writeStrongBinder(server);
605 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
606
607 datai.writeInt32(1);
608 datai.writeStrongBinder(m_server);
609 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
610 datai2.appendTo(&datai);
611
612 datai.appendTo(&data);
613 }
614
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700615 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
616 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800617
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700618 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800619 EXPECT_EQ(0, id);
620
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700621 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700622 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800623
624 for (size_t i = 0; i < (size_t)count; i++) {
625 int32_t counti;
626
627 BinderLibTestBundle replyi(&reply);
628 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700629 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800630 EXPECT_EQ(serverId[i], id);
631
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700632 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800633 EXPECT_EQ(1, counti);
634
635 BinderLibTestBundle replyi2(&replyi);
636 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700637 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800638 EXPECT_EQ(0, id);
639 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
640
641 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
642 }
643
644 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
645}
646
647TEST_F(BinderLibTest, CallBack)
648{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800649 Parcel data, reply;
650 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
651 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700652 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
653 StatusEq(NO_ERROR));
654 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
655 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800656}
657
Steven Moreland35626652021-05-15 01:32:04 +0000658TEST_F(BinderLibTest, BinderCallContextGuard) {
659 sp<IBinder> binder = addServer();
660 Parcel data, reply;
661 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
662 StatusEq(DEAD_OBJECT));
663}
664
Riley Andrews06b01ad2014-12-18 12:10:08 -0800665TEST_F(BinderLibTest, AddServer)
666{
667 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700668 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800669}
670
Riley Andrews06b01ad2014-12-18 12:10:08 -0800671TEST_F(BinderLibTest, DeathNotificationStrongRef)
672{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800673 sp<IBinder> sbinder;
674
675 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
676
677 {
678 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700679 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700680 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800681 sbinder = binder;
682 }
683 {
684 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700685 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
686 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800687 }
688 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700689 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
690 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800691}
692
693TEST_F(BinderLibTest, DeathNotificationMultiple)
694{
695 status_t ret;
696 const int clientcount = 2;
697 sp<IBinder> target;
698 sp<IBinder> linkedclient[clientcount];
699 sp<BinderLibTestCallBack> callBack[clientcount];
700 sp<IBinder> passiveclient[clientcount];
701
702 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700703 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800704 for (int i = 0; i < clientcount; i++) {
705 {
706 Parcel data, reply;
707
708 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700709 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800710 callBack[i] = new BinderLibTestCallBack();
711 data.writeStrongBinder(target);
712 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700713 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
714 &reply, TF_ONE_WAY),
715 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800716 }
717 {
718 Parcel data, reply;
719
720 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700721 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800722 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700723 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
724 &reply, TF_ONE_WAY),
725 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800726 }
727 }
728 {
729 Parcel data, reply;
730 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
731 EXPECT_EQ(0, ret);
732 }
733
734 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700735 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
736 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800737 }
738}
739
Martijn Coenenf7100e42017-07-31 12:14:09 +0200740TEST_F(BinderLibTest, DeathNotificationThread)
741{
742 status_t ret;
743 sp<BinderLibTestCallBack> callback;
744 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700745 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200746 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700747 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200748
749 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
750
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700751 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200752
753 {
754 Parcel data, reply;
755 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
756 EXPECT_EQ(0, ret);
757 }
758
759 /* Make sure it's dead */
760 testDeathRecipient->waitEvent(5);
761
762 /* Now, pass the ref to another process and ask that process to
763 * call linkToDeath() on it, and wait for a response. This tests
764 * two things:
765 * 1) You still get death notifications when calling linkToDeath()
766 * on a ref that is already dead when it was passed to you.
767 * 2) That death notifications are not directly pushed to the thread
768 * registering them, but to the threadpool (proc workqueue) instead.
769 *
770 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
771 * is blocked on a condition variable waiting for the death notification to be
772 * called; therefore, that thread is not available for handling proc work.
773 * So, if the death notification was pushed to the thread workqueue, the callback
774 * would never be called, and the test would timeout and fail.
775 *
776 * Note that we can't do this part of the test from this thread itself, because
777 * the binder driver would only push death notifications to the thread if
778 * it is a looper thread, which this thread is not.
779 *
780 * See b/23525545 for details.
781 */
782 {
783 Parcel data, reply;
784
785 callback = new BinderLibTestCallBack();
786 data.writeStrongBinder(target);
787 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700788 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
789 TF_ONE_WAY),
790 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200791 }
792
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700793 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
794 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200795}
796
Riley Andrews06b01ad2014-12-18 12:10:08 -0800797TEST_F(BinderLibTest, PassFile) {
798 int ret;
799 int pipefd[2];
800 uint8_t buf[1] = { 0 };
801 uint8_t write_value = 123;
802
803 ret = pipe2(pipefd, O_NONBLOCK);
804 ASSERT_EQ(0, ret);
805
806 {
807 Parcel data, reply;
808 uint8_t writebuf[1] = { write_value };
809
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700810 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800811
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700812 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800813
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700814 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800815
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700816 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
817 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800818 }
819
820 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700821 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800822 EXPECT_EQ(write_value, buf[0]);
823
824 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
825
826 ret = read(pipefd[0], buf, sizeof(buf));
827 EXPECT_EQ(0, ret);
828
829 close(pipefd[0]);
830}
831
Ryo Hashimotobf551892018-05-31 16:58:35 +0900832TEST_F(BinderLibTest, PassParcelFileDescriptor) {
833 const int datasize = 123;
834 std::vector<uint8_t> writebuf(datasize);
835 for (size_t i = 0; i < writebuf.size(); ++i) {
836 writebuf[i] = i;
837 }
838
839 android::base::unique_fd read_end, write_end;
840 {
841 int pipefd[2];
842 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
843 read_end.reset(pipefd[0]);
844 write_end.reset(pipefd[1]);
845 }
846 {
847 Parcel data;
848 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
849 write_end.reset();
850 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
851 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
852
853 Parcel reply;
854 EXPECT_EQ(NO_ERROR,
855 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
856 &reply));
857 }
858 std::vector<uint8_t> readbuf(datasize);
859 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
860 EXPECT_EQ(writebuf, readbuf);
861
862 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
863
864 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
865}
866
Riley Andrews06b01ad2014-12-18 12:10:08 -0800867TEST_F(BinderLibTest, PromoteLocal) {
868 sp<IBinder> strong = new BBinder();
869 wp<IBinder> weak = strong;
870 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700871 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800872 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700873 strong = nullptr;
874 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800875 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700876 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800877}
878
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700879TEST_F(BinderLibTest, LocalGetExtension) {
880 sp<BBinder> binder = new BBinder();
881 sp<IBinder> ext = new BBinder();
882 binder->setExtension(ext);
883 EXPECT_EQ(ext, binder->getExtension());
884}
885
886TEST_F(BinderLibTest, RemoteGetExtension) {
887 sp<IBinder> server = addServer();
888 ASSERT_TRUE(server != nullptr);
889
890 sp<IBinder> extension;
891 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
892 ASSERT_NE(nullptr, extension.get());
893
894 EXPECT_EQ(NO_ERROR, extension->pingBinder());
895}
896
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700897TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700898 Parcel data, reply;
899
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700900 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
901 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700902
903 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700904 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800905 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
906 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
907 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
908 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700909}
910
Connor O'Brien52be2c92016-09-20 14:18:08 -0700911TEST_F(BinderLibTest, FreedBinder) {
912 status_t ret;
913
914 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700915 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700916
917 __u32 freedHandle;
918 wp<IBinder> keepFreedBinder;
919 {
920 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700921 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
922 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700923 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
924 freedHandle = freed->handle;
925 /* Add a weak ref to the freed binder so the driver does not
926 * delete its reference to it - otherwise the transaction
927 * fails regardless of whether the driver is fixed.
928 */
Steven Morelande171d622019-07-17 16:06:01 -0700929 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700930 }
Steven Morelande171d622019-07-17 16:06:01 -0700931 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700932 {
933 Parcel data, reply;
934 data.writeStrongBinder(server);
935 /* Replace original handle with handle to the freed binder */
936 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
937 __u32 oldHandle = strong->handle;
938 strong->handle = freedHandle;
939 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
940 /* Returns DEAD_OBJECT (-32) if target crashes and
941 * FAILED_TRANSACTION if the driver rejects the invalid
942 * object.
943 */
944 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
945 /* Restore original handle so parcel destructor does not use
946 * the wrong handle.
947 */
948 strong->handle = oldHandle;
949 }
950}
951
Sherry Yang336cdd32017-07-24 14:12:27 -0700952TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700953 Parcel data, reply;
954 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
955 for (int i = 0; i < 2; i++) {
956 BinderLibTestBundle datai;
957 datai.appendFrom(&data, 0, data.dataSize());
958
959 data.freeData();
960 data.writeInt32(1);
961 data.writeStrongBinder(callBack);
962 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
963
964 datai.appendTo(&data);
965 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700966 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
967 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700968}
969
Martijn Coenen45b07b42017-08-09 12:07:45 +0200970TEST_F(BinderLibTest, OnewayQueueing)
971{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200972 Parcel data, data2;
973
974 sp<IBinder> pollServer = addPollServer();
975
976 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
977 data.writeStrongBinder(callBack);
978 data.writeInt32(500000); // delay in us before calling back
979
980 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
981 data2.writeStrongBinder(callBack2);
982 data2.writeInt32(0); // delay in us
983
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700984 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
985 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200986
987 // The delay ensures that this second transaction will end up on the async_todo list
988 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700989 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
990 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200991
992 // The server will ensure that the two transactions are handled in the expected order;
993 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700994 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
995 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200996
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700997 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
998 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200999}
1000
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001001TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1002{
1003 status_t ret;
1004 Parcel data, reply;
1005 data.writeInterfaceToken(binderLibTestServiceName);
1006 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1007 EXPECT_EQ(-1, reply.readInt32());
1008 EXPECT_EQ(NO_ERROR, ret);
1009}
1010
1011TEST_F(BinderLibTest, WorkSourceSet)
1012{
1013 status_t ret;
1014 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001015 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001016 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001017 data.writeInterfaceToken(binderLibTestServiceName);
1018 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1019 EXPECT_EQ(100, reply.readInt32());
1020 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001021 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1022 EXPECT_EQ(NO_ERROR, ret);
1023}
1024
1025TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1026{
1027 status_t ret;
1028 Parcel data, reply;
1029
1030 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1031 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1032
1033 data.writeInterfaceToken(binderLibTestServiceName);
1034 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1035 EXPECT_EQ(-1, reply.readInt32());
1036 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001037 EXPECT_EQ(NO_ERROR, ret);
1038}
1039
1040TEST_F(BinderLibTest, WorkSourceCleared)
1041{
1042 status_t ret;
1043 Parcel data, reply;
1044
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001045 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001046 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1047 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001048 data.writeInterfaceToken(binderLibTestServiceName);
1049 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1050
1051 EXPECT_EQ(-1, reply.readInt32());
1052 EXPECT_EQ(100, previousWorkSource);
1053 EXPECT_EQ(NO_ERROR, ret);
1054}
1055
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001056TEST_F(BinderLibTest, WorkSourceRestored)
1057{
1058 status_t ret;
1059 Parcel data, reply;
1060
1061 IPCThreadState::self()->setCallingWorkSourceUid(100);
1062 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1063 IPCThreadState::self()->restoreCallingWorkSource(token);
1064
1065 data.writeInterfaceToken(binderLibTestServiceName);
1066 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1067
1068 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001069 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001070 EXPECT_EQ(NO_ERROR, ret);
1071}
1072
Olivier Gaillard91a04802018-11-14 17:32:41 +00001073TEST_F(BinderLibTest, PropagateFlagSet)
1074{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001075 IPCThreadState::self()->clearPropagateWorkSource();
1076 IPCThreadState::self()->setCallingWorkSourceUid(100);
1077 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1078}
1079
1080TEST_F(BinderLibTest, PropagateFlagCleared)
1081{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001082 IPCThreadState::self()->setCallingWorkSourceUid(100);
1083 IPCThreadState::self()->clearPropagateWorkSource();
1084 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1085}
1086
1087TEST_F(BinderLibTest, PropagateFlagRestored)
1088{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001089 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1090 IPCThreadState::self()->restoreCallingWorkSource(token);
1091
1092 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1093}
1094
1095TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1096{
1097 IPCThreadState::self()->setCallingWorkSourceUid(100);
1098
1099 Parcel data, reply;
1100 status_t ret;
1101 data.writeInterfaceToken(binderLibTestServiceName);
1102 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1103
1104 Parcel data2, reply2;
1105 status_t ret2;
1106 data2.writeInterfaceToken(binderLibTestServiceName);
1107 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1108 EXPECT_EQ(100, reply2.readInt32());
1109 EXPECT_EQ(NO_ERROR, ret2);
1110}
1111
Steven Morelandbf1915b2020-07-16 22:43:02 +00001112TEST_F(BinderLibTest, SchedPolicySet) {
1113 sp<IBinder> server = addServer();
1114 ASSERT_TRUE(server != nullptr);
1115
1116 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001117 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1118 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001119
1120 int policy = reply.readInt32();
1121 int priority = reply.readInt32();
1122
1123 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1124 EXPECT_EQ(kSchedPriority, priority);
1125}
1126
Steven Morelandcf03cf12020-12-04 02:58:40 +00001127TEST_F(BinderLibTest, InheritRt) {
1128 sp<IBinder> server = addServer();
1129 ASSERT_TRUE(server != nullptr);
1130
1131 const struct sched_param param {
1132 .sched_priority = kSchedPriorityMore,
1133 };
1134 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1135
1136 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001137 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1138 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001139
1140 int policy = reply.readInt32();
1141 int priority = reply.readInt32();
1142
1143 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1144 EXPECT_EQ(kSchedPriorityMore, priority);
1145}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001146
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001147TEST_F(BinderLibTest, VectorSent) {
1148 Parcel data, reply;
1149 sp<IBinder> server = addServer();
1150 ASSERT_TRUE(server != nullptr);
1151
1152 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1153 data.writeUint64Vector(testValue);
1154
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001155 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001156 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001157 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001158 EXPECT_EQ(readValue, testValue);
1159}
1160
Martijn Coenen82c75312019-07-24 15:18:30 +02001161TEST_F(BinderLibTest, BufRejected) {
1162 Parcel data, reply;
1163 uint32_t buf;
1164 sp<IBinder> server = addServer();
1165 ASSERT_TRUE(server != nullptr);
1166
1167 binder_buffer_object obj {
1168 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001169 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001170 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1171 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001172 };
1173 data.setDataCapacity(1024);
1174 // Write a bogus object at offset 0 to get an entry in the offset table
1175 data.writeFileDescriptor(0);
1176 EXPECT_EQ(data.objectsCount(), 1);
1177 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1178 // And now, overwrite it with the buffer object
1179 memcpy(parcelData, &obj, sizeof(obj));
1180 data.setDataSize(sizeof(obj));
1181
Steven Morelandf2e0a952021-11-01 18:17:23 -07001182 EXPECT_EQ(data.objectsCount(), 1);
1183
Martijn Coenen82c75312019-07-24 15:18:30 +02001184 // Either the kernel should reject this transaction (if it's correct), but
1185 // if it's not, the server implementation should return an error if it
1186 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001187 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001188 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001189}
1190
Steven Morelandf2e0a952021-11-01 18:17:23 -07001191TEST_F(BinderLibTest, WeakRejected) {
1192 Parcel data, reply;
1193 sp<IBinder> server = addServer();
1194 ASSERT_TRUE(server != nullptr);
1195
1196 auto binder = sp<BBinder>::make();
1197 wp<BBinder> wpBinder(binder);
1198 flat_binder_object obj{
1199 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1200 .flags = 0,
1201 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1202 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1203 };
1204 data.setDataCapacity(1024);
1205 // Write a bogus object at offset 0 to get an entry in the offset table
1206 data.writeFileDescriptor(0);
1207 EXPECT_EQ(data.objectsCount(), 1);
1208 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1209 // And now, overwrite it with the weak binder
1210 memcpy(parcelData, &obj, sizeof(obj));
1211 data.setDataSize(sizeof(obj));
1212
1213 // a previous bug caused other objects to be released an extra time, so we
1214 // test with an object that libbinder will actually try to release
1215 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1216
1217 EXPECT_EQ(data.objectsCount(), 2);
1218
1219 // send it many times, since previous error was memory corruption, make it
1220 // more likely that the server crashes
1221 for (size_t i = 0; i < 100; i++) {
1222 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1223 StatusEq(BAD_VALUE));
1224 }
1225
1226 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1227}
1228
Steven Moreland254e8ef2021-04-19 22:28:50 +00001229TEST_F(BinderLibTest, GotSid) {
1230 sp<IBinder> server = addServer();
1231
1232 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001233 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001234}
1235
Andrei Homescu1519b982022-06-09 02:04:44 +00001236struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1237 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1238
1239 // Flattenable protocol
1240 size_t getFlattenedSize() const {
1241 // Return a valid non-zero size here so we don't get an unintended
1242 // BAD_VALUE from Parcel::write
1243 return 16;
1244 }
1245 size_t getFdCount() const { return mFdCount; }
1246 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1247 for (size_t i = 0; i < count; i++) {
1248 fds[i] = STDIN_FILENO;
1249 }
1250 return NO_ERROR;
1251 }
1252 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1253 size_t & /*count*/) {
1254 /* This doesn't get called */
1255 return NO_ERROR;
1256 }
1257
1258 size_t mFdCount;
1259};
1260
1261TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1262 rlimit origNofile;
1263 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1264 ASSERT_EQ(0, ret);
1265
1266 // Restore the original file limits when the test finishes
1267 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1268
1269 rlimit testNofile = {1024, 1024};
1270 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1271 ASSERT_EQ(0, ret);
1272
1273 Parcel parcel;
1274 // Try to write more file descriptors than supported by the OS
1275 TooManyFdsFlattenable tooManyFds1(1024);
1276 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1277
1278 // Try to write more file descriptors than the internal limit
1279 TooManyFdsFlattenable tooManyFds2(1025);
1280 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1281}
1282
Jayant Chowdhary30700942022-01-31 14:12:40 -08001283TEST(ServiceNotifications, Unregister) {
1284 auto sm = defaultServiceManager();
1285 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1286 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1287 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1288 virtual ~LocalRegistrationCallbackImpl() {}
1289 };
1290 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1291
1292 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1293 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1294}
1295
Elie Kheirallah47431c12022-04-21 23:46:17 +00001296TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1297 Parcel data, reply;
1298 sp<IBinder> server = addServer();
1299 ASSERT_TRUE(server != nullptr);
1300 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1301 StatusEq(NO_ERROR));
1302 int32_t replyi = reply.readInt32();
1303 // Expect 16 threads: kKernelThreads = 15 + Pool thread == 16
1304 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
1305 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1306
1307 /*
1308 * This will use all threads in the pool expect the main pool thread.
1309 * The service should run fine without locking, and the thread count should
1310 * not exceed 16 (15 Max + pool thread).
1311 */
1312 std::vector<std::thread> ts;
1313 for (size_t i = 0; i < kKernelThreads - 1; i++) {
1314 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001315 Parcel local_reply;
1316 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1317 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001318 }));
1319 }
1320
1321 data.writeInt32(1);
1322 // Give a chance for all threads to be used
1323 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1324
1325 for (auto &t : ts) {
1326 t.join();
1327 }
1328
1329 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1330 StatusEq(NO_ERROR));
1331 replyi = reply.readInt32();
1332 // No more than 16 threads should exist.
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001333 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001334}
1335
1336size_t epochMillis() {
1337 using std::chrono::duration_cast;
1338 using std::chrono::milliseconds;
1339 using std::chrono::seconds;
1340 using std::chrono::system_clock;
1341 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1342}
1343
1344TEST_F(BinderLibTest, HangingServices) {
1345 Parcel data, reply;
1346 sp<IBinder> server = addServer();
1347 ASSERT_TRUE(server != nullptr);
1348 int32_t delay = 1000; // ms
1349 data.writeInt32(delay);
1350 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1351 std::vector<std::thread> ts;
1352 size_t epochMsBefore = epochMillis();
1353 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1354 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001355 Parcel local_reply;
1356 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1357 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001358 }));
1359 }
1360
1361 for (auto &t : ts) {
1362 t.join();
1363 }
1364 size_t epochMsAfter = epochMillis();
1365
1366 // deadlock occurred and threads only finished after 1s passed.
1367 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1368}
1369
Yifan Hong84bedeb2021-04-21 21:37:17 -07001370class BinderLibRpcTestBase : public BinderLibTest {
1371public:
1372 void SetUp() override {
1373 if (!base::GetBoolProperty("ro.debuggable", false)) {
1374 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1375 "non-debuggable builds.";
1376 }
1377 BinderLibTest::SetUp();
1378 }
1379
1380 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1381 auto rpcServer = RpcServer::make();
1382 EXPECT_NE(nullptr, rpcServer);
1383 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001384 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001385 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1386 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001387 return {};
1388 }
1389 return {rpcServer->releaseServer(), port};
1390 }
1391};
1392
Yifan Hong8b890852021-06-10 13:44:09 -07001393class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001394
Yifan Hongbd276552022-02-28 15:28:51 -08001395// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1396// If device is debuggable AND not on user builds, expects matcher.
1397// Otherwise expects INVALID_OPERATION.
1398// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1399static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1400 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1401 android::base::GetProperty("ro.build.type", "") != "user";
1402 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1403}
1404
Yifan Hong8b890852021-06-10 13:44:09 -07001405TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1406 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001407 ASSERT_TRUE(binder != nullptr);
1408 auto [socket, port] = CreateSocket();
1409 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001410 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1411 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001412}
1413
Yifan Hong8b890852021-06-10 13:44:09 -07001414// Tests for multiple RpcServer's on the same binder object.
1415TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1416 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001417 ASSERT_TRUE(binder != nullptr);
1418
1419 auto [socket1, port1] = CreateSocket();
1420 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001421 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001422 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1423 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001424
1425 auto [socket2, port2] = CreateSocket();
1426 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001427 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001428 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1429 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001430}
1431
Yifan Hong8b890852021-06-10 13:44:09 -07001432// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1433// local binders.
1434class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001435public:
1436 sp<IBinder> GetService() {
1437 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1438 }
1439 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1440 return info.param ? "remote" : "local";
1441 }
1442};
1443
Yifan Hong8b890852021-06-10 13:44:09 -07001444TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1445 auto binder = GetService();
1446 ASSERT_TRUE(binder != nullptr);
1447 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001448 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001449}
1450
1451TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001452 auto binder = GetService();
1453 ASSERT_TRUE(binder != nullptr);
1454 auto [socket, port] = CreateSocket();
1455 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001456 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1457 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001458}
Yifan Hong8b890852021-06-10 13:44:09 -07001459INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1460 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001461
Yifan Hong543edcd2021-05-18 19:47:30 -07001462class BinderLibTestService : public BBinder {
1463public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001464 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1465 : m_id(id),
1466 m_nextServerId(id + 1),
1467 m_serverStartRequested(false),
1468 m_callback(nullptr),
1469 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001470 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1471 pthread_cond_init(&m_serverWaitCond, nullptr);
1472 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001473 ~BinderLibTestService() {
1474 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1475 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001476
Yifan Hong543edcd2021-05-18 19:47:30 -07001477 void processPendingCall() {
1478 if (m_callback != nullptr) {
1479 Parcel data;
1480 data.writeInt32(NO_ERROR);
1481 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1482 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001483 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001484 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001485
Yifan Hong543edcd2021-05-18 19:47:30 -07001486 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1487 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001488 // TODO(b/182914638): also checks getCallingUid() for RPC
1489 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001490 return PERMISSION_DENIED;
1491 }
1492 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001493 case BINDER_LIB_TEST_REGISTER_SERVER: {
1494 int32_t id;
1495 sp<IBinder> binder;
1496 id = data.readInt32();
1497 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001498 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001499 return BAD_VALUE;
1500 }
1501
Yifan Hong543edcd2021-05-18 19:47:30 -07001502 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001503
1504 pthread_mutex_lock(&m_serverWaitMutex);
1505 if (m_serverStartRequested) {
1506 m_serverStartRequested = false;
1507 m_serverStarted = binder;
1508 pthread_cond_signal(&m_serverWaitCond);
1509 }
1510 pthread_mutex_unlock(&m_serverWaitMutex);
1511 return NO_ERROR;
1512 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001513 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001514 case BINDER_LIB_TEST_ADD_SERVER: {
1515 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001516 int serverid;
1517
1518 if (m_id != 0) {
1519 return INVALID_OPERATION;
1520 }
1521 pthread_mutex_lock(&m_serverWaitMutex);
1522 if (m_serverStartRequested) {
1523 ret = -EBUSY;
1524 } else {
1525 serverid = m_nextServerId++;
1526 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001527 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001528
1529 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001530 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001531 pthread_mutex_lock(&m_serverWaitMutex);
1532 }
1533 if (ret > 0) {
1534 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001535 struct timespec ts;
1536 clock_gettime(CLOCK_REALTIME, &ts);
1537 ts.tv_sec += 5;
1538 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001539 }
1540 if (m_serverStartRequested) {
1541 m_serverStartRequested = false;
1542 ret = -ETIMEDOUT;
1543 } else {
1544 reply->writeStrongBinder(m_serverStarted);
1545 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001546 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001547 ret = NO_ERROR;
1548 }
1549 } else if (ret >= 0) {
1550 m_serverStartRequested = false;
1551 ret = UNKNOWN_ERROR;
1552 }
1553 pthread_mutex_unlock(&m_serverWaitMutex);
1554 return ret;
1555 }
Steven Moreland35626652021-05-15 01:32:04 +00001556 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1557 IPCThreadState::SpGuard spGuard{
1558 .address = __builtin_frame_address(0),
1559 .context = "GuardInBinderTransaction",
1560 };
1561 const IPCThreadState::SpGuard *origGuard =
1562 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1563
1564 // if the guard works, this should abort
1565 (void)IPCThreadState::self()->getCallingPid();
1566
1567 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1568 return NO_ERROR;
1569 }
1570
Marco Ballesio7ee17572020-09-08 10:30:03 -07001571 case BINDER_LIB_TEST_GETPID:
1572 reply->writeInt32(getpid());
1573 return NO_ERROR;
1574 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1575 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001576 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001577 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001578 // oneway error codes should be ignored
1579 if (flags & TF_ONE_WAY) {
1580 return UNKNOWN_ERROR;
1581 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001582 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001583 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1584 // Note: this transaction is only designed for use with a
1585 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001586 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001587 // A callback was already pending; this means that
1588 // we received a second call while still processing
1589 // the first one. Fail the test.
1590 sp<IBinder> callback = data.readStrongBinder();
1591 Parcel data2;
1592 data2.writeInt32(UNKNOWN_ERROR);
1593
Yi Kong91635562018-06-07 14:38:36 -07001594 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001595 } else {
1596 m_callback = data.readStrongBinder();
1597 int32_t delayUs = data.readInt32();
1598 /*
1599 * It's necessary that we sleep here, so the next
1600 * transaction the caller makes will be queued to
1601 * the async queue.
1602 */
1603 usleep(delayUs);
1604
1605 /*
1606 * Now when we return, libbinder will tell the kernel
1607 * we are done with this transaction, and the kernel
1608 * can move the queued transaction to either the
1609 * thread todo worklist (for kernels without the fix),
1610 * or the proc todo worklist. In case of the former,
1611 * the next outbound call will pick up the pending
1612 * transaction, which leads to undesired reentrant
1613 * behavior. This is caught in the if() branch above.
1614 */
1615 }
1616
1617 return NO_ERROR;
1618 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001619 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1620 Parcel data2, reply2;
1621 sp<IBinder> binder;
1622 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001623 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001624 return BAD_VALUE;
1625 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001626 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001627 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1628 return NO_ERROR;
1629 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001630 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1631 reply->writeStrongBinder(this);
1632 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001633 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1634 reply->writeInt32(m_id);
1635 return NO_ERROR;
1636 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1637 int32_t count;
1638 uint32_t indirect_code;
1639 sp<IBinder> binder;
1640
1641 count = data.readInt32();
1642 reply->writeInt32(m_id);
1643 reply->writeInt32(count);
1644 for (int i = 0; i < count; i++) {
1645 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001646 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001647 return BAD_VALUE;
1648 }
1649 indirect_code = data.readInt32();
1650 BinderLibTestBundle data2(&data);
1651 if (!data2.isValid()) {
1652 return BAD_VALUE;
1653 }
1654 BinderLibTestBundle reply2;
1655 binder->transact(indirect_code, data2, &reply2);
1656 reply2.appendTo(reply);
1657 }
1658 return NO_ERROR;
1659 }
1660 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1661 reply->setError(data.readInt32());
1662 return NO_ERROR;
1663 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1664 reply->writeInt32(sizeof(void *));
1665 return NO_ERROR;
1666 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1667 return NO_ERROR;
1668 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1669 m_strongRef = data.readStrongBinder();
1670 return NO_ERROR;
1671 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1672 int ret;
1673 Parcel data2, reply2;
1674 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1675 sp<IBinder> target;
1676 sp<IBinder> callback;
1677
1678 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001679 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001680 return BAD_VALUE;
1681 }
1682 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001683 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001684 return BAD_VALUE;
1685 }
1686 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001687 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001688 data2.writeInt32(ret);
1689 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1690 return NO_ERROR;
1691 }
1692 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1693 int ret;
1694 int32_t size;
1695 const void *buf;
1696 int fd;
1697
1698 fd = data.readFileDescriptor();
1699 if (fd < 0) {
1700 return BAD_VALUE;
1701 }
1702 ret = data.readInt32(&size);
1703 if (ret != NO_ERROR) {
1704 return ret;
1705 }
1706 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001707 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001708 return BAD_VALUE;
1709 }
1710 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001711 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001712 return NO_ERROR;
1713 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001714 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1715 int ret;
1716 int32_t size;
1717 const void *buf;
1718 android::base::unique_fd fd;
1719
1720 ret = data.readUniqueParcelFileDescriptor(&fd);
1721 if (ret != NO_ERROR) {
1722 return ret;
1723 }
1724 ret = data.readInt32(&size);
1725 if (ret != NO_ERROR) {
1726 return ret;
1727 }
1728 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001729 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001730 return BAD_VALUE;
1731 }
1732 ret = write(fd.get(), buf, size);
1733 if (ret != size) return UNKNOWN_ERROR;
1734 return NO_ERROR;
1735 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001736 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1737 alarm(10);
1738 return NO_ERROR;
1739 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001740 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001741 ;
1742 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001743 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001744 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001745 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001746 return NO_ERROR;
1747 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001748 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1749 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001750 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001751 return NO_ERROR;
1752 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001753 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1754 int policy = 0;
1755 sched_param param;
1756 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1757 return UNKNOWN_ERROR;
1758 }
1759 reply->writeInt32(policy);
1760 reply->writeInt32(param.sched_priority);
1761 return NO_ERROR;
1762 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001763 case BINDER_LIB_TEST_ECHO_VECTOR: {
1764 std::vector<uint64_t> vector;
1765 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001766 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001767 reply->writeUint64Vector(vector);
1768 return NO_ERROR;
1769 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001770 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001771 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1772 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001773 case BINDER_LIB_TEST_CAN_GET_SID: {
1774 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1775 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001776 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1777 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1778 return NO_ERROR;
1779 }
1780 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001781 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001782 return NO_ERROR;
1783 }
1784 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001785 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001786 return NO_ERROR;
1787 }
1788 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1789 int32_t ms = data.readInt32();
1790 return unlockInMs(ms);
1791 }
1792 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001793 m_blockMutex.lock();
1794 sp<BinderLibTestService> thisService = this;
1795 int32_t value = data.readInt32();
1796 // start local thread to unlock in 1s
1797 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001798 t.detach();
1799 return NO_ERROR;
1800 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001801 default:
1802 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001803 };
1804 }
1805
Elie Kheirallah47431c12022-04-21 23:46:17 +00001806 status_t unlockInMs(int32_t ms) {
1807 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001808 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001809 return NO_ERROR;
1810 }
1811
Yifan Hong543edcd2021-05-18 19:47:30 -07001812private:
1813 int32_t m_id;
1814 int32_t m_nextServerId;
1815 pthread_mutex_t m_serverWaitMutex;
1816 pthread_cond_t m_serverWaitCond;
1817 bool m_serverStartRequested;
1818 sp<IBinder> m_serverStarted;
1819 sp<IBinder> m_strongRef;
1820 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001821 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001822 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001823};
1824
Martijn Coenen45b07b42017-08-09 12:07:45 +02001825int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001826{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001827 binderLibTestServiceName += String16(binderserversuffix);
1828
Steven Moreland35626652021-05-15 01:32:04 +00001829 // Testing to make sure that calls that we are serving can use getCallin*
1830 // even though we don't here.
1831 IPCThreadState::SpGuard spGuard{
1832 .address = __builtin_frame_address(0),
1833 .context = "main server thread",
1834 };
1835 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1836
Riley Andrews06b01ad2014-12-18 12:10:08 -08001837 status_t ret;
1838 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001839 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001840 {
1841 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001842
Steven Morelandbf1915b2020-07-16 22:43:02 +00001843 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1844
Steven Morelandcf03cf12020-12-04 02:58:40 +00001845 testService->setInheritRt(true);
1846
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001847 /*
1848 * Normally would also contain functionality as well, but we are only
1849 * testing the extension mechanism.
1850 */
1851 testService->setExtension(new BBinder());
1852
Martijn Coenen82c75312019-07-24 15:18:30 +02001853 // Required for test "BufRejected'
1854 testService->setRequestingSid(true);
1855
Martijn Coenen45b07b42017-08-09 12:07:45 +02001856 /*
1857 * We need this below, but can't hold a sp<> because it prevents the
1858 * node from being cleaned up automatically. It's safe in this case
1859 * because of how the tests are written.
1860 */
1861 testServicePtr = testService.get();
1862
Riley Andrews06b01ad2014-12-18 12:10:08 -08001863 if (index == 0) {
1864 ret = sm->addService(binderLibTestServiceName, testService);
1865 } else {
1866 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1867 Parcel data, reply;
1868 data.writeInt32(index);
1869 data.writeStrongBinder(testService);
1870
1871 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1872 }
1873 }
1874 write(readypipefd, &ret, sizeof(ret));
1875 close(readypipefd);
1876 //printf("%s: ret %d\n", __func__, ret);
1877 if (ret)
1878 return 1;
1879 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001880 if (usePoll) {
1881 int fd;
1882 struct epoll_event ev;
1883 int epoll_fd;
1884 IPCThreadState::self()->setupPolling(&fd);
1885 if (fd < 0) {
1886 return 1;
1887 }
1888 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1889
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001890 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001891 if (epoll_fd == -1) {
1892 return 1;
1893 }
1894
1895 ev.events = EPOLLIN;
1896 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1897 return 1;
1898 }
1899
1900 while (1) {
1901 /*
1902 * We simulate a single-threaded process using the binder poll
1903 * interface; besides handling binder commands, it can also
1904 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001905 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001906 *
1907 * processPendingCall() will then issue that transaction.
1908 */
1909 struct epoll_event events[1];
1910 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1911 if (numEvents < 0) {
1912 if (errno == EINTR) {
1913 continue;
1914 }
1915 return 1;
1916 }
1917 if (numEvents > 0) {
1918 IPCThreadState::self()->handlePolledCommands();
1919 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1920 testServicePtr->processPendingCall();
1921 }
1922 }
1923 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001924 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001925 ProcessState::self()->startThreadPool();
1926 IPCThreadState::self()->joinThreadPool();
1927 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001928 //printf("%s: joinThreadPool returned\n", __func__);
1929 return 1; /* joinThreadPool should not return */
1930}
1931
1932int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07001933 ExitIfWrongAbi();
1934
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001935 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001936 binderservername = argv[2];
1937 } else {
1938 binderservername = argv[0];
1939 }
1940
Martijn Coenen45b07b42017-08-09 12:07:45 +02001941 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
1942 binderserversuffix = argv[5];
1943 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001944 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001945 binderserversuffix = new char[16];
1946 snprintf(binderserversuffix, 16, "%d", getpid());
1947 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001948
1949 ::testing::InitGoogleTest(&argc, argv);
1950 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
1951 ProcessState::self()->startThreadPool();
1952 return RUN_ALL_TESTS();
1953}