blob: b3ecf4ca30bd242fc78e6b7ba815f2e137831092 [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([&] {
1315 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &reply), NO_ERROR);
1316 }));
1317 }
1318
1319 data.writeInt32(1);
1320 // Give a chance for all threads to be used
1321 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1322
1323 for (auto &t : ts) {
1324 t.join();
1325 }
1326
1327 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1328 StatusEq(NO_ERROR));
1329 replyi = reply.readInt32();
1330 // No more than 16 threads should exist.
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001331 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001332}
1333
1334size_t epochMillis() {
1335 using std::chrono::duration_cast;
1336 using std::chrono::milliseconds;
1337 using std::chrono::seconds;
1338 using std::chrono::system_clock;
1339 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1340}
1341
1342TEST_F(BinderLibTest, HangingServices) {
1343 Parcel data, reply;
1344 sp<IBinder> server = addServer();
1345 ASSERT_TRUE(server != nullptr);
1346 int32_t delay = 1000; // ms
1347 data.writeInt32(delay);
1348 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1349 std::vector<std::thread> ts;
1350 size_t epochMsBefore = epochMillis();
1351 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1352 ts.push_back(std::thread([&] {
1353 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &reply), NO_ERROR);
1354 }));
1355 }
1356
1357 for (auto &t : ts) {
1358 t.join();
1359 }
1360 size_t epochMsAfter = epochMillis();
1361
1362 // deadlock occurred and threads only finished after 1s passed.
1363 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1364}
1365
Yifan Hong84bedeb2021-04-21 21:37:17 -07001366class BinderLibRpcTestBase : public BinderLibTest {
1367public:
1368 void SetUp() override {
1369 if (!base::GetBoolProperty("ro.debuggable", false)) {
1370 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1371 "non-debuggable builds.";
1372 }
1373 BinderLibTest::SetUp();
1374 }
1375
1376 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1377 auto rpcServer = RpcServer::make();
1378 EXPECT_NE(nullptr, rpcServer);
1379 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001380 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001381 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1382 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001383 return {};
1384 }
1385 return {rpcServer->releaseServer(), port};
1386 }
1387};
1388
Yifan Hong8b890852021-06-10 13:44:09 -07001389class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001390
Yifan Hongbd276552022-02-28 15:28:51 -08001391// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1392// If device is debuggable AND not on user builds, expects matcher.
1393// Otherwise expects INVALID_OPERATION.
1394// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1395static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1396 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1397 android::base::GetProperty("ro.build.type", "") != "user";
1398 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1399}
1400
Yifan Hong8b890852021-06-10 13:44:09 -07001401TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1402 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001403 ASSERT_TRUE(binder != nullptr);
1404 auto [socket, port] = CreateSocket();
1405 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001406 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1407 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001408}
1409
Yifan Hong8b890852021-06-10 13:44:09 -07001410// Tests for multiple RpcServer's on the same binder object.
1411TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1412 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001413 ASSERT_TRUE(binder != nullptr);
1414
1415 auto [socket1, port1] = CreateSocket();
1416 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001417 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001418 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1419 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001420
1421 auto [socket2, port2] = CreateSocket();
1422 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001423 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001424 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1425 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001426}
1427
Yifan Hong8b890852021-06-10 13:44:09 -07001428// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1429// local binders.
1430class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001431public:
1432 sp<IBinder> GetService() {
1433 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1434 }
1435 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1436 return info.param ? "remote" : "local";
1437 }
1438};
1439
Yifan Hong8b890852021-06-10 13:44:09 -07001440TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1441 auto binder = GetService();
1442 ASSERT_TRUE(binder != nullptr);
1443 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001444 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001445}
1446
1447TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001448 auto binder = GetService();
1449 ASSERT_TRUE(binder != nullptr);
1450 auto [socket, port] = CreateSocket();
1451 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001452 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1453 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001454}
Yifan Hong8b890852021-06-10 13:44:09 -07001455INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1456 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001457
Yifan Hong543edcd2021-05-18 19:47:30 -07001458class BinderLibTestService : public BBinder {
1459public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001460 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1461 : m_id(id),
1462 m_nextServerId(id + 1),
1463 m_serverStartRequested(false),
1464 m_callback(nullptr),
1465 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001466 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1467 pthread_cond_init(&m_serverWaitCond, nullptr);
1468 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001469 ~BinderLibTestService() {
1470 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1471 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001472
Yifan Hong543edcd2021-05-18 19:47:30 -07001473 void processPendingCall() {
1474 if (m_callback != nullptr) {
1475 Parcel data;
1476 data.writeInt32(NO_ERROR);
1477 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1478 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001479 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001480 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001481
Yifan Hong543edcd2021-05-18 19:47:30 -07001482 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1483 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001484 // TODO(b/182914638): also checks getCallingUid() for RPC
1485 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001486 return PERMISSION_DENIED;
1487 }
1488 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001489 case BINDER_LIB_TEST_REGISTER_SERVER: {
1490 int32_t id;
1491 sp<IBinder> binder;
1492 id = data.readInt32();
1493 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001494 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001495 return BAD_VALUE;
1496 }
1497
Yifan Hong543edcd2021-05-18 19:47:30 -07001498 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001499
1500 pthread_mutex_lock(&m_serverWaitMutex);
1501 if (m_serverStartRequested) {
1502 m_serverStartRequested = false;
1503 m_serverStarted = binder;
1504 pthread_cond_signal(&m_serverWaitCond);
1505 }
1506 pthread_mutex_unlock(&m_serverWaitMutex);
1507 return NO_ERROR;
1508 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001509 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001510 case BINDER_LIB_TEST_ADD_SERVER: {
1511 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001512 int serverid;
1513
1514 if (m_id != 0) {
1515 return INVALID_OPERATION;
1516 }
1517 pthread_mutex_lock(&m_serverWaitMutex);
1518 if (m_serverStartRequested) {
1519 ret = -EBUSY;
1520 } else {
1521 serverid = m_nextServerId++;
1522 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001523 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001524
1525 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001526 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001527 pthread_mutex_lock(&m_serverWaitMutex);
1528 }
1529 if (ret > 0) {
1530 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001531 struct timespec ts;
1532 clock_gettime(CLOCK_REALTIME, &ts);
1533 ts.tv_sec += 5;
1534 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001535 }
1536 if (m_serverStartRequested) {
1537 m_serverStartRequested = false;
1538 ret = -ETIMEDOUT;
1539 } else {
1540 reply->writeStrongBinder(m_serverStarted);
1541 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001542 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001543 ret = NO_ERROR;
1544 }
1545 } else if (ret >= 0) {
1546 m_serverStartRequested = false;
1547 ret = UNKNOWN_ERROR;
1548 }
1549 pthread_mutex_unlock(&m_serverWaitMutex);
1550 return ret;
1551 }
Steven Moreland35626652021-05-15 01:32:04 +00001552 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1553 IPCThreadState::SpGuard spGuard{
1554 .address = __builtin_frame_address(0),
1555 .context = "GuardInBinderTransaction",
1556 };
1557 const IPCThreadState::SpGuard *origGuard =
1558 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1559
1560 // if the guard works, this should abort
1561 (void)IPCThreadState::self()->getCallingPid();
1562
1563 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1564 return NO_ERROR;
1565 }
1566
Marco Ballesio7ee17572020-09-08 10:30:03 -07001567 case BINDER_LIB_TEST_GETPID:
1568 reply->writeInt32(getpid());
1569 return NO_ERROR;
1570 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1571 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001572 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001573 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001574 // oneway error codes should be ignored
1575 if (flags & TF_ONE_WAY) {
1576 return UNKNOWN_ERROR;
1577 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001578 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001579 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1580 // Note: this transaction is only designed for use with a
1581 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001582 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001583 // A callback was already pending; this means that
1584 // we received a second call while still processing
1585 // the first one. Fail the test.
1586 sp<IBinder> callback = data.readStrongBinder();
1587 Parcel data2;
1588 data2.writeInt32(UNKNOWN_ERROR);
1589
Yi Kong91635562018-06-07 14:38:36 -07001590 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001591 } else {
1592 m_callback = data.readStrongBinder();
1593 int32_t delayUs = data.readInt32();
1594 /*
1595 * It's necessary that we sleep here, so the next
1596 * transaction the caller makes will be queued to
1597 * the async queue.
1598 */
1599 usleep(delayUs);
1600
1601 /*
1602 * Now when we return, libbinder will tell the kernel
1603 * we are done with this transaction, and the kernel
1604 * can move the queued transaction to either the
1605 * thread todo worklist (for kernels without the fix),
1606 * or the proc todo worklist. In case of the former,
1607 * the next outbound call will pick up the pending
1608 * transaction, which leads to undesired reentrant
1609 * behavior. This is caught in the if() branch above.
1610 */
1611 }
1612
1613 return NO_ERROR;
1614 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001615 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1616 Parcel data2, reply2;
1617 sp<IBinder> binder;
1618 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001619 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001620 return BAD_VALUE;
1621 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001622 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001623 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1624 return NO_ERROR;
1625 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001626 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1627 reply->writeStrongBinder(this);
1628 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001629 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1630 reply->writeInt32(m_id);
1631 return NO_ERROR;
1632 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1633 int32_t count;
1634 uint32_t indirect_code;
1635 sp<IBinder> binder;
1636
1637 count = data.readInt32();
1638 reply->writeInt32(m_id);
1639 reply->writeInt32(count);
1640 for (int i = 0; i < count; i++) {
1641 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001642 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001643 return BAD_VALUE;
1644 }
1645 indirect_code = data.readInt32();
1646 BinderLibTestBundle data2(&data);
1647 if (!data2.isValid()) {
1648 return BAD_VALUE;
1649 }
1650 BinderLibTestBundle reply2;
1651 binder->transact(indirect_code, data2, &reply2);
1652 reply2.appendTo(reply);
1653 }
1654 return NO_ERROR;
1655 }
1656 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1657 reply->setError(data.readInt32());
1658 return NO_ERROR;
1659 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1660 reply->writeInt32(sizeof(void *));
1661 return NO_ERROR;
1662 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1663 return NO_ERROR;
1664 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1665 m_strongRef = data.readStrongBinder();
1666 return NO_ERROR;
1667 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1668 int ret;
1669 Parcel data2, reply2;
1670 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1671 sp<IBinder> target;
1672 sp<IBinder> callback;
1673
1674 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001675 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001676 return BAD_VALUE;
1677 }
1678 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001679 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001680 return BAD_VALUE;
1681 }
1682 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001683 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001684 data2.writeInt32(ret);
1685 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1686 return NO_ERROR;
1687 }
1688 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1689 int ret;
1690 int32_t size;
1691 const void *buf;
1692 int fd;
1693
1694 fd = data.readFileDescriptor();
1695 if (fd < 0) {
1696 return BAD_VALUE;
1697 }
1698 ret = data.readInt32(&size);
1699 if (ret != NO_ERROR) {
1700 return ret;
1701 }
1702 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001703 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001704 return BAD_VALUE;
1705 }
1706 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001707 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001708 return NO_ERROR;
1709 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001710 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1711 int ret;
1712 int32_t size;
1713 const void *buf;
1714 android::base::unique_fd fd;
1715
1716 ret = data.readUniqueParcelFileDescriptor(&fd);
1717 if (ret != NO_ERROR) {
1718 return ret;
1719 }
1720 ret = data.readInt32(&size);
1721 if (ret != NO_ERROR) {
1722 return ret;
1723 }
1724 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001725 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001726 return BAD_VALUE;
1727 }
1728 ret = write(fd.get(), buf, size);
1729 if (ret != size) return UNKNOWN_ERROR;
1730 return NO_ERROR;
1731 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001732 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1733 alarm(10);
1734 return NO_ERROR;
1735 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001736 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001737 ;
1738 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001739 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001740 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001741 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001742 return NO_ERROR;
1743 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001744 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1745 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001746 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001747 return NO_ERROR;
1748 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001749 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1750 int policy = 0;
1751 sched_param param;
1752 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1753 return UNKNOWN_ERROR;
1754 }
1755 reply->writeInt32(policy);
1756 reply->writeInt32(param.sched_priority);
1757 return NO_ERROR;
1758 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001759 case BINDER_LIB_TEST_ECHO_VECTOR: {
1760 std::vector<uint64_t> vector;
1761 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001762 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001763 reply->writeUint64Vector(vector);
1764 return NO_ERROR;
1765 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001766 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001767 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1768 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001769 case BINDER_LIB_TEST_CAN_GET_SID: {
1770 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1771 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001772 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1773 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1774 return NO_ERROR;
1775 }
1776 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001777 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001778 return NO_ERROR;
1779 }
1780 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001781 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001782 return NO_ERROR;
1783 }
1784 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1785 int32_t ms = data.readInt32();
1786 return unlockInMs(ms);
1787 }
1788 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001789 m_blockMutex.lock();
1790 sp<BinderLibTestService> thisService = this;
1791 int32_t value = data.readInt32();
1792 // start local thread to unlock in 1s
1793 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001794 t.detach();
1795 return NO_ERROR;
1796 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001797 default:
1798 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001799 };
1800 }
1801
Elie Kheirallah47431c12022-04-21 23:46:17 +00001802 status_t unlockInMs(int32_t ms) {
1803 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001804 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001805 return NO_ERROR;
1806 }
1807
Yifan Hong543edcd2021-05-18 19:47:30 -07001808private:
1809 int32_t m_id;
1810 int32_t m_nextServerId;
1811 pthread_mutex_t m_serverWaitMutex;
1812 pthread_cond_t m_serverWaitCond;
1813 bool m_serverStartRequested;
1814 sp<IBinder> m_serverStarted;
1815 sp<IBinder> m_strongRef;
1816 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001817 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001818 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001819};
1820
Martijn Coenen45b07b42017-08-09 12:07:45 +02001821int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001822{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001823 binderLibTestServiceName += String16(binderserversuffix);
1824
Steven Moreland35626652021-05-15 01:32:04 +00001825 // Testing to make sure that calls that we are serving can use getCallin*
1826 // even though we don't here.
1827 IPCThreadState::SpGuard spGuard{
1828 .address = __builtin_frame_address(0),
1829 .context = "main server thread",
1830 };
1831 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1832
Riley Andrews06b01ad2014-12-18 12:10:08 -08001833 status_t ret;
1834 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001835 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001836 {
1837 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001838
Steven Morelandbf1915b2020-07-16 22:43:02 +00001839 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1840
Steven Morelandcf03cf12020-12-04 02:58:40 +00001841 testService->setInheritRt(true);
1842
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001843 /*
1844 * Normally would also contain functionality as well, but we are only
1845 * testing the extension mechanism.
1846 */
1847 testService->setExtension(new BBinder());
1848
Martijn Coenen82c75312019-07-24 15:18:30 +02001849 // Required for test "BufRejected'
1850 testService->setRequestingSid(true);
1851
Martijn Coenen45b07b42017-08-09 12:07:45 +02001852 /*
1853 * We need this below, but can't hold a sp<> because it prevents the
1854 * node from being cleaned up automatically. It's safe in this case
1855 * because of how the tests are written.
1856 */
1857 testServicePtr = testService.get();
1858
Riley Andrews06b01ad2014-12-18 12:10:08 -08001859 if (index == 0) {
1860 ret = sm->addService(binderLibTestServiceName, testService);
1861 } else {
1862 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1863 Parcel data, reply;
1864 data.writeInt32(index);
1865 data.writeStrongBinder(testService);
1866
1867 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1868 }
1869 }
1870 write(readypipefd, &ret, sizeof(ret));
1871 close(readypipefd);
1872 //printf("%s: ret %d\n", __func__, ret);
1873 if (ret)
1874 return 1;
1875 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001876 if (usePoll) {
1877 int fd;
1878 struct epoll_event ev;
1879 int epoll_fd;
1880 IPCThreadState::self()->setupPolling(&fd);
1881 if (fd < 0) {
1882 return 1;
1883 }
1884 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1885
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001886 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001887 if (epoll_fd == -1) {
1888 return 1;
1889 }
1890
1891 ev.events = EPOLLIN;
1892 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1893 return 1;
1894 }
1895
1896 while (1) {
1897 /*
1898 * We simulate a single-threaded process using the binder poll
1899 * interface; besides handling binder commands, it can also
1900 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001901 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001902 *
1903 * processPendingCall() will then issue that transaction.
1904 */
1905 struct epoll_event events[1];
1906 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1907 if (numEvents < 0) {
1908 if (errno == EINTR) {
1909 continue;
1910 }
1911 return 1;
1912 }
1913 if (numEvents > 0) {
1914 IPCThreadState::self()->handlePolledCommands();
1915 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1916 testServicePtr->processPendingCall();
1917 }
1918 }
1919 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001920 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001921 ProcessState::self()->startThreadPool();
1922 IPCThreadState::self()->joinThreadPool();
1923 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001924 //printf("%s: joinThreadPool returned\n", __func__);
1925 return 1; /* joinThreadPool should not return */
1926}
1927
1928int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07001929 ExitIfWrongAbi();
1930
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001931 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001932 binderservername = argv[2];
1933 } else {
1934 binderservername = argv[0];
1935 }
1936
Martijn Coenen45b07b42017-08-09 12:07:45 +02001937 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
1938 binderserversuffix = argv[5];
1939 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001940 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001941 binderserversuffix = new char[16];
1942 snprintf(binderserversuffix, 16, "%d", getpid());
1943 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001944
1945 ::testing::InitGoogleTest(&argc, argv);
1946 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
1947 ProcessState::self()->startThreadPool();
1948 return RUN_ALL_TESTS();
1949}