blob: 6e1c8ac16a338d8023e8b463365da2564dcc193c [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
Steven Moreland59b84442022-07-12 18:32:44 +00001161// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1162// This value is not exposed, but some code in the framework relies on being able to use
1163// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001164constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001165constexpr size_t kSizeBytesOverFull = 1'050'000;
1166
1167TEST_F(BinderLibTest, GargantuanVectorSent) {
1168 sp<IBinder> server = addServer();
1169 ASSERT_TRUE(server != nullptr);
1170
1171 for (size_t i = 0; i < 10; i++) {
1172 // a slight variation in size is used to consider certain possible caching implementations
1173 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1174
1175 Parcel data, reply;
1176 data.writeUint64Vector(testValue);
1177 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1178 << i;
1179 std::vector<uint64_t> readValue;
1180 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1181 EXPECT_EQ(readValue, testValue);
1182 }
1183}
1184
1185TEST_F(BinderLibTest, LimitExceededVectorSent) {
1186 sp<IBinder> server = addServer();
1187 ASSERT_TRUE(server != nullptr);
1188 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1189
1190 Parcel data, reply;
1191 data.writeUint64Vector(testValue);
1192 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1193 StatusEq(FAILED_TRANSACTION));
1194}
1195
Martijn Coenen82c75312019-07-24 15:18:30 +02001196TEST_F(BinderLibTest, BufRejected) {
1197 Parcel data, reply;
1198 uint32_t buf;
1199 sp<IBinder> server = addServer();
1200 ASSERT_TRUE(server != nullptr);
1201
1202 binder_buffer_object obj {
1203 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001204 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001205 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1206 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001207 };
1208 data.setDataCapacity(1024);
1209 // Write a bogus object at offset 0 to get an entry in the offset table
1210 data.writeFileDescriptor(0);
1211 EXPECT_EQ(data.objectsCount(), 1);
1212 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1213 // And now, overwrite it with the buffer object
1214 memcpy(parcelData, &obj, sizeof(obj));
1215 data.setDataSize(sizeof(obj));
1216
Steven Morelandf2e0a952021-11-01 18:17:23 -07001217 EXPECT_EQ(data.objectsCount(), 1);
1218
Martijn Coenen82c75312019-07-24 15:18:30 +02001219 // Either the kernel should reject this transaction (if it's correct), but
1220 // if it's not, the server implementation should return an error if it
1221 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001222 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001223 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001224}
1225
Steven Morelandf2e0a952021-11-01 18:17:23 -07001226TEST_F(BinderLibTest, WeakRejected) {
1227 Parcel data, reply;
1228 sp<IBinder> server = addServer();
1229 ASSERT_TRUE(server != nullptr);
1230
1231 auto binder = sp<BBinder>::make();
1232 wp<BBinder> wpBinder(binder);
1233 flat_binder_object obj{
1234 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1235 .flags = 0,
1236 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1237 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1238 };
1239 data.setDataCapacity(1024);
1240 // Write a bogus object at offset 0 to get an entry in the offset table
1241 data.writeFileDescriptor(0);
1242 EXPECT_EQ(data.objectsCount(), 1);
1243 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1244 // And now, overwrite it with the weak binder
1245 memcpy(parcelData, &obj, sizeof(obj));
1246 data.setDataSize(sizeof(obj));
1247
1248 // a previous bug caused other objects to be released an extra time, so we
1249 // test with an object that libbinder will actually try to release
1250 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1251
1252 EXPECT_EQ(data.objectsCount(), 2);
1253
1254 // send it many times, since previous error was memory corruption, make it
1255 // more likely that the server crashes
1256 for (size_t i = 0; i < 100; i++) {
1257 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1258 StatusEq(BAD_VALUE));
1259 }
1260
1261 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1262}
1263
Steven Moreland254e8ef2021-04-19 22:28:50 +00001264TEST_F(BinderLibTest, GotSid) {
1265 sp<IBinder> server = addServer();
1266
1267 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001268 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001269}
1270
Andrei Homescu1519b982022-06-09 02:04:44 +00001271struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1272 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1273
1274 // Flattenable protocol
1275 size_t getFlattenedSize() const {
1276 // Return a valid non-zero size here so we don't get an unintended
1277 // BAD_VALUE from Parcel::write
1278 return 16;
1279 }
1280 size_t getFdCount() const { return mFdCount; }
1281 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1282 for (size_t i = 0; i < count; i++) {
1283 fds[i] = STDIN_FILENO;
1284 }
1285 return NO_ERROR;
1286 }
1287 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1288 size_t & /*count*/) {
1289 /* This doesn't get called */
1290 return NO_ERROR;
1291 }
1292
1293 size_t mFdCount;
1294};
1295
1296TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1297 rlimit origNofile;
1298 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1299 ASSERT_EQ(0, ret);
1300
1301 // Restore the original file limits when the test finishes
1302 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1303
1304 rlimit testNofile = {1024, 1024};
1305 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1306 ASSERT_EQ(0, ret);
1307
1308 Parcel parcel;
1309 // Try to write more file descriptors than supported by the OS
1310 TooManyFdsFlattenable tooManyFds1(1024);
1311 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1312
1313 // Try to write more file descriptors than the internal limit
1314 TooManyFdsFlattenable tooManyFds2(1025);
1315 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1316}
1317
Jayant Chowdhary30700942022-01-31 14:12:40 -08001318TEST(ServiceNotifications, Unregister) {
1319 auto sm = defaultServiceManager();
1320 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1321 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1322 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1323 virtual ~LocalRegistrationCallbackImpl() {}
1324 };
1325 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1326
1327 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1328 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1329}
1330
Elie Kheirallah47431c12022-04-21 23:46:17 +00001331TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1332 Parcel data, reply;
1333 sp<IBinder> server = addServer();
1334 ASSERT_TRUE(server != nullptr);
1335 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1336 StatusEq(NO_ERROR));
1337 int32_t replyi = reply.readInt32();
1338 // Expect 16 threads: kKernelThreads = 15 + Pool thread == 16
1339 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
1340 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1341
1342 /*
1343 * This will use all threads in the pool expect the main pool thread.
1344 * The service should run fine without locking, and the thread count should
1345 * not exceed 16 (15 Max + pool thread).
1346 */
1347 std::vector<std::thread> ts;
Steven Morelandb17a5f02022-07-13 01:25:35 +00001348 for (size_t i = 0; i < kKernelThreads; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001349 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001350 Parcel local_reply;
1351 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1352 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001353 }));
1354 }
1355
Steven Morelandb17a5f02022-07-13 01:25:35 +00001356 data.writeInt32(100);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001357 // Give a chance for all threads to be used
1358 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1359
1360 for (auto &t : ts) {
1361 t.join();
1362 }
1363
1364 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1365 StatusEq(NO_ERROR));
1366 replyi = reply.readInt32();
Steven Morelandb17a5f02022-07-13 01:25:35 +00001367 EXPECT_EQ(replyi, kKernelThreads + 1);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001368}
1369
1370size_t epochMillis() {
1371 using std::chrono::duration_cast;
1372 using std::chrono::milliseconds;
1373 using std::chrono::seconds;
1374 using std::chrono::system_clock;
1375 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1376}
1377
1378TEST_F(BinderLibTest, HangingServices) {
1379 Parcel data, reply;
1380 sp<IBinder> server = addServer();
1381 ASSERT_TRUE(server != nullptr);
1382 int32_t delay = 1000; // ms
1383 data.writeInt32(delay);
1384 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1385 std::vector<std::thread> ts;
1386 size_t epochMsBefore = epochMillis();
1387 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1388 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001389 Parcel local_reply;
1390 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1391 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001392 }));
1393 }
1394
1395 for (auto &t : ts) {
1396 t.join();
1397 }
1398 size_t epochMsAfter = epochMillis();
1399
1400 // deadlock occurred and threads only finished after 1s passed.
1401 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1402}
1403
Yifan Hong84bedeb2021-04-21 21:37:17 -07001404class BinderLibRpcTestBase : public BinderLibTest {
1405public:
1406 void SetUp() override {
1407 if (!base::GetBoolProperty("ro.debuggable", false)) {
1408 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1409 "non-debuggable builds.";
1410 }
1411 BinderLibTest::SetUp();
1412 }
1413
1414 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1415 auto rpcServer = RpcServer::make();
1416 EXPECT_NE(nullptr, rpcServer);
1417 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001418 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001419 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1420 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001421 return {};
1422 }
1423 return {rpcServer->releaseServer(), port};
1424 }
1425};
1426
Yifan Hong8b890852021-06-10 13:44:09 -07001427class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001428
Yifan Hongbd276552022-02-28 15:28:51 -08001429// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1430// If device is debuggable AND not on user builds, expects matcher.
1431// Otherwise expects INVALID_OPERATION.
1432// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1433static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1434 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1435 android::base::GetProperty("ro.build.type", "") != "user";
1436 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1437}
1438
Yifan Hong8b890852021-06-10 13:44:09 -07001439TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1440 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001441 ASSERT_TRUE(binder != nullptr);
1442 auto [socket, port] = CreateSocket();
1443 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001444 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1445 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001446}
1447
Yifan Hong8b890852021-06-10 13:44:09 -07001448// Tests for multiple RpcServer's on the same binder object.
1449TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1450 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001451 ASSERT_TRUE(binder != nullptr);
1452
1453 auto [socket1, port1] = CreateSocket();
1454 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001455 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001456 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1457 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001458
1459 auto [socket2, port2] = CreateSocket();
1460 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001461 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001462 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1463 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001464}
1465
Yifan Hong8b890852021-06-10 13:44:09 -07001466// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1467// local binders.
1468class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001469public:
1470 sp<IBinder> GetService() {
1471 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1472 }
1473 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1474 return info.param ? "remote" : "local";
1475 }
1476};
1477
Yifan Hong8b890852021-06-10 13:44:09 -07001478TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1479 auto binder = GetService();
1480 ASSERT_TRUE(binder != nullptr);
1481 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001482 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001483}
1484
1485TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001486 auto binder = GetService();
1487 ASSERT_TRUE(binder != nullptr);
1488 auto [socket, port] = CreateSocket();
1489 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001490 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1491 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001492}
Yifan Hong8b890852021-06-10 13:44:09 -07001493INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1494 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001495
Yifan Hong543edcd2021-05-18 19:47:30 -07001496class BinderLibTestService : public BBinder {
1497public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001498 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1499 : m_id(id),
1500 m_nextServerId(id + 1),
1501 m_serverStartRequested(false),
1502 m_callback(nullptr),
1503 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001504 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1505 pthread_cond_init(&m_serverWaitCond, nullptr);
1506 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001507 ~BinderLibTestService() {
1508 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1509 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001510
Yifan Hong543edcd2021-05-18 19:47:30 -07001511 void processPendingCall() {
1512 if (m_callback != nullptr) {
1513 Parcel data;
1514 data.writeInt32(NO_ERROR);
1515 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1516 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001517 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001518 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001519
Yifan Hong543edcd2021-05-18 19:47:30 -07001520 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1521 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001522 // TODO(b/182914638): also checks getCallingUid() for RPC
1523 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001524 return PERMISSION_DENIED;
1525 }
1526 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001527 case BINDER_LIB_TEST_REGISTER_SERVER: {
1528 int32_t id;
1529 sp<IBinder> binder;
1530 id = data.readInt32();
1531 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001532 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001533 return BAD_VALUE;
1534 }
1535
Yifan Hong543edcd2021-05-18 19:47:30 -07001536 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001537
1538 pthread_mutex_lock(&m_serverWaitMutex);
1539 if (m_serverStartRequested) {
1540 m_serverStartRequested = false;
1541 m_serverStarted = binder;
1542 pthread_cond_signal(&m_serverWaitCond);
1543 }
1544 pthread_mutex_unlock(&m_serverWaitMutex);
1545 return NO_ERROR;
1546 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001547 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001548 case BINDER_LIB_TEST_ADD_SERVER: {
1549 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001550 int serverid;
1551
1552 if (m_id != 0) {
1553 return INVALID_OPERATION;
1554 }
1555 pthread_mutex_lock(&m_serverWaitMutex);
1556 if (m_serverStartRequested) {
1557 ret = -EBUSY;
1558 } else {
1559 serverid = m_nextServerId++;
1560 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001561 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001562
1563 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001564 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001565 pthread_mutex_lock(&m_serverWaitMutex);
1566 }
1567 if (ret > 0) {
1568 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001569 struct timespec ts;
1570 clock_gettime(CLOCK_REALTIME, &ts);
1571 ts.tv_sec += 5;
1572 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001573 }
1574 if (m_serverStartRequested) {
1575 m_serverStartRequested = false;
1576 ret = -ETIMEDOUT;
1577 } else {
1578 reply->writeStrongBinder(m_serverStarted);
1579 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001580 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001581 ret = NO_ERROR;
1582 }
1583 } else if (ret >= 0) {
1584 m_serverStartRequested = false;
1585 ret = UNKNOWN_ERROR;
1586 }
1587 pthread_mutex_unlock(&m_serverWaitMutex);
1588 return ret;
1589 }
Steven Moreland35626652021-05-15 01:32:04 +00001590 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1591 IPCThreadState::SpGuard spGuard{
1592 .address = __builtin_frame_address(0),
1593 .context = "GuardInBinderTransaction",
1594 };
1595 const IPCThreadState::SpGuard *origGuard =
1596 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1597
1598 // if the guard works, this should abort
1599 (void)IPCThreadState::self()->getCallingPid();
1600
1601 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1602 return NO_ERROR;
1603 }
1604
Marco Ballesio7ee17572020-09-08 10:30:03 -07001605 case BINDER_LIB_TEST_GETPID:
1606 reply->writeInt32(getpid());
1607 return NO_ERROR;
1608 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1609 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001610 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001611 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001612 // oneway error codes should be ignored
1613 if (flags & TF_ONE_WAY) {
1614 return UNKNOWN_ERROR;
1615 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001616 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001617 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1618 // Note: this transaction is only designed for use with a
1619 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001620 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001621 // A callback was already pending; this means that
1622 // we received a second call while still processing
1623 // the first one. Fail the test.
1624 sp<IBinder> callback = data.readStrongBinder();
1625 Parcel data2;
1626 data2.writeInt32(UNKNOWN_ERROR);
1627
Yi Kong91635562018-06-07 14:38:36 -07001628 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001629 } else {
1630 m_callback = data.readStrongBinder();
1631 int32_t delayUs = data.readInt32();
1632 /*
1633 * It's necessary that we sleep here, so the next
1634 * transaction the caller makes will be queued to
1635 * the async queue.
1636 */
1637 usleep(delayUs);
1638
1639 /*
1640 * Now when we return, libbinder will tell the kernel
1641 * we are done with this transaction, and the kernel
1642 * can move the queued transaction to either the
1643 * thread todo worklist (for kernels without the fix),
1644 * or the proc todo worklist. In case of the former,
1645 * the next outbound call will pick up the pending
1646 * transaction, which leads to undesired reentrant
1647 * behavior. This is caught in the if() branch above.
1648 */
1649 }
1650
1651 return NO_ERROR;
1652 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001653 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1654 Parcel data2, reply2;
1655 sp<IBinder> binder;
1656 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001657 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001658 return BAD_VALUE;
1659 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001660 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001661 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1662 return NO_ERROR;
1663 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001664 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1665 reply->writeStrongBinder(this);
1666 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001667 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1668 reply->writeInt32(m_id);
1669 return NO_ERROR;
1670 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1671 int32_t count;
1672 uint32_t indirect_code;
1673 sp<IBinder> binder;
1674
1675 count = data.readInt32();
1676 reply->writeInt32(m_id);
1677 reply->writeInt32(count);
1678 for (int i = 0; i < count; i++) {
1679 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001680 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001681 return BAD_VALUE;
1682 }
1683 indirect_code = data.readInt32();
1684 BinderLibTestBundle data2(&data);
1685 if (!data2.isValid()) {
1686 return BAD_VALUE;
1687 }
1688 BinderLibTestBundle reply2;
1689 binder->transact(indirect_code, data2, &reply2);
1690 reply2.appendTo(reply);
1691 }
1692 return NO_ERROR;
1693 }
1694 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1695 reply->setError(data.readInt32());
1696 return NO_ERROR;
1697 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1698 reply->writeInt32(sizeof(void *));
1699 return NO_ERROR;
1700 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1701 return NO_ERROR;
1702 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1703 m_strongRef = data.readStrongBinder();
1704 return NO_ERROR;
1705 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1706 int ret;
1707 Parcel data2, reply2;
1708 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1709 sp<IBinder> target;
1710 sp<IBinder> callback;
1711
1712 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001713 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001714 return BAD_VALUE;
1715 }
1716 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001717 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001718 return BAD_VALUE;
1719 }
1720 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001721 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001722 data2.writeInt32(ret);
1723 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1724 return NO_ERROR;
1725 }
1726 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1727 int ret;
1728 int32_t size;
1729 const void *buf;
1730 int fd;
1731
1732 fd = data.readFileDescriptor();
1733 if (fd < 0) {
1734 return BAD_VALUE;
1735 }
1736 ret = data.readInt32(&size);
1737 if (ret != NO_ERROR) {
1738 return ret;
1739 }
1740 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001741 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001742 return BAD_VALUE;
1743 }
1744 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001745 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001746 return NO_ERROR;
1747 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001748 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1749 int ret;
1750 int32_t size;
1751 const void *buf;
1752 android::base::unique_fd fd;
1753
1754 ret = data.readUniqueParcelFileDescriptor(&fd);
1755 if (ret != NO_ERROR) {
1756 return ret;
1757 }
1758 ret = data.readInt32(&size);
1759 if (ret != NO_ERROR) {
1760 return ret;
1761 }
1762 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001763 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001764 return BAD_VALUE;
1765 }
1766 ret = write(fd.get(), buf, size);
1767 if (ret != size) return UNKNOWN_ERROR;
1768 return NO_ERROR;
1769 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001770 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1771 alarm(10);
1772 return NO_ERROR;
1773 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001774 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001775 ;
1776 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001777 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001778 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001779 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001780 return NO_ERROR;
1781 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001782 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1783 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001784 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001785 return NO_ERROR;
1786 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001787 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1788 int policy = 0;
1789 sched_param param;
1790 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1791 return UNKNOWN_ERROR;
1792 }
1793 reply->writeInt32(policy);
1794 reply->writeInt32(param.sched_priority);
1795 return NO_ERROR;
1796 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001797 case BINDER_LIB_TEST_ECHO_VECTOR: {
1798 std::vector<uint64_t> vector;
1799 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001800 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001801 reply->writeUint64Vector(vector);
1802 return NO_ERROR;
1803 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001804 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001805 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1806 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001807 case BINDER_LIB_TEST_CAN_GET_SID: {
1808 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1809 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001810 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1811 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1812 return NO_ERROR;
1813 }
1814 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001815 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001816 return NO_ERROR;
1817 }
1818 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001819 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001820 return NO_ERROR;
1821 }
1822 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1823 int32_t ms = data.readInt32();
1824 return unlockInMs(ms);
1825 }
1826 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001827 m_blockMutex.lock();
1828 sp<BinderLibTestService> thisService = this;
1829 int32_t value = data.readInt32();
1830 // start local thread to unlock in 1s
1831 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001832 t.detach();
1833 return NO_ERROR;
1834 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001835 default:
1836 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001837 };
1838 }
1839
Elie Kheirallah47431c12022-04-21 23:46:17 +00001840 status_t unlockInMs(int32_t ms) {
1841 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001842 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001843 return NO_ERROR;
1844 }
1845
Yifan Hong543edcd2021-05-18 19:47:30 -07001846private:
1847 int32_t m_id;
1848 int32_t m_nextServerId;
1849 pthread_mutex_t m_serverWaitMutex;
1850 pthread_cond_t m_serverWaitCond;
1851 bool m_serverStartRequested;
1852 sp<IBinder> m_serverStarted;
1853 sp<IBinder> m_strongRef;
1854 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001855 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001856 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001857};
1858
Martijn Coenen45b07b42017-08-09 12:07:45 +02001859int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001860{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001861 binderLibTestServiceName += String16(binderserversuffix);
1862
Steven Moreland35626652021-05-15 01:32:04 +00001863 // Testing to make sure that calls that we are serving can use getCallin*
1864 // even though we don't here.
1865 IPCThreadState::SpGuard spGuard{
1866 .address = __builtin_frame_address(0),
1867 .context = "main server thread",
1868 };
1869 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1870
Riley Andrews06b01ad2014-12-18 12:10:08 -08001871 status_t ret;
1872 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001873 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001874 {
1875 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001876
Steven Morelandbf1915b2020-07-16 22:43:02 +00001877 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1878
Steven Morelandcf03cf12020-12-04 02:58:40 +00001879 testService->setInheritRt(true);
1880
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001881 /*
1882 * Normally would also contain functionality as well, but we are only
1883 * testing the extension mechanism.
1884 */
1885 testService->setExtension(new BBinder());
1886
Martijn Coenen82c75312019-07-24 15:18:30 +02001887 // Required for test "BufRejected'
1888 testService->setRequestingSid(true);
1889
Martijn Coenen45b07b42017-08-09 12:07:45 +02001890 /*
1891 * We need this below, but can't hold a sp<> because it prevents the
1892 * node from being cleaned up automatically. It's safe in this case
1893 * because of how the tests are written.
1894 */
1895 testServicePtr = testService.get();
1896
Riley Andrews06b01ad2014-12-18 12:10:08 -08001897 if (index == 0) {
1898 ret = sm->addService(binderLibTestServiceName, testService);
1899 } else {
1900 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1901 Parcel data, reply;
1902 data.writeInt32(index);
1903 data.writeStrongBinder(testService);
1904
1905 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1906 }
1907 }
1908 write(readypipefd, &ret, sizeof(ret));
1909 close(readypipefd);
1910 //printf("%s: ret %d\n", __func__, ret);
1911 if (ret)
1912 return 1;
1913 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001914 if (usePoll) {
1915 int fd;
1916 struct epoll_event ev;
1917 int epoll_fd;
1918 IPCThreadState::self()->setupPolling(&fd);
1919 if (fd < 0) {
1920 return 1;
1921 }
1922 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1923
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001924 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001925 if (epoll_fd == -1) {
1926 return 1;
1927 }
1928
1929 ev.events = EPOLLIN;
1930 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1931 return 1;
1932 }
1933
1934 while (1) {
1935 /*
1936 * We simulate a single-threaded process using the binder poll
1937 * interface; besides handling binder commands, it can also
1938 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001939 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001940 *
1941 * processPendingCall() will then issue that transaction.
1942 */
1943 struct epoll_event events[1];
1944 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1945 if (numEvents < 0) {
1946 if (errno == EINTR) {
1947 continue;
1948 }
1949 return 1;
1950 }
1951 if (numEvents > 0) {
1952 IPCThreadState::self()->handlePolledCommands();
1953 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1954 testServicePtr->processPendingCall();
1955 }
1956 }
1957 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001958 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001959 ProcessState::self()->startThreadPool();
1960 IPCThreadState::self()->joinThreadPool();
1961 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001962 //printf("%s: joinThreadPool returned\n", __func__);
1963 return 1; /* joinThreadPool should not return */
1964}
1965
1966int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07001967 ExitIfWrongAbi();
1968
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001969 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001970 binderservername = argv[2];
1971 } else {
1972 binderservername = argv[0];
1973 }
1974
Martijn Coenen45b07b42017-08-09 12:07:45 +02001975 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
1976 binderserversuffix = argv[5];
1977 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001978 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001979 binderserversuffix = new char[16];
1980 snprintf(binderserversuffix, 16, "%d", getpid());
1981 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001982
1983 ::testing::InitGoogleTest(&argc, argv);
1984 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
1985 ProcessState::self()->startThreadPool();
1986 return RUN_ALL_TESTS();
1987}