blob: 25b524fcf2df7984cfa7861776280d95d0cdde6e [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,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700118 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700119 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000120 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000121 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
122 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
123 BINDER_LIB_TEST_LOCK_UNLOCK,
124 BINDER_LIB_TEST_PROCESS_LOCK,
125 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
126 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800127};
128
Martijn Coenen45b07b42017-08-09 12:07:45 +0200129pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800130{
131 int ret;
132 pid_t pid;
133 status_t status;
134 int pipefd[2];
135 char stri[16];
136 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200137 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800138 char *childargv[] = {
139 binderservername,
140 binderserverarg,
141 stri,
142 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200143 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700144 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700145 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800146 };
147
148 ret = pipe(pipefd);
149 if (ret < 0)
150 return ret;
151
152 snprintf(stri, sizeof(stri), "%d", arg2);
153 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200154 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800155
156 pid = fork();
157 if (pid == -1)
158 return pid;
159 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800160 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800161 close(pipefd[0]);
162 execv(binderservername, childargv);
163 status = -errno;
164 write(pipefd[1], &status, sizeof(status));
165 fprintf(stderr, "execv failed, %s\n", strerror(errno));
166 _exit(EXIT_FAILURE);
167 }
168 close(pipefd[1]);
169 ret = read(pipefd[0], &status, sizeof(status));
170 //printf("pipe read returned %d, status %d\n", ret, status);
171 close(pipefd[0]);
172 if (ret == sizeof(status)) {
173 ret = status;
174 } else {
175 kill(pid, SIGKILL);
176 if (ret >= 0) {
177 ret = NO_INIT;
178 }
179 }
180 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700181 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800182 return ret;
183 }
184 return pid;
185}
186
Yifan Hong84bedeb2021-04-21 21:37:17 -0700187android::base::Result<int32_t> GetId(sp<IBinder> service) {
188 using android::base::Error;
189 Parcel data, reply;
190 data.markForBinder(service);
191 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
192 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
193 if (status != OK)
194 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
195 int32_t result = 0;
196 status = reply.readInt32(&result);
197 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
198 return result;
199}
200
Riley Andrews06b01ad2014-12-18 12:10:08 -0800201class BinderLibTestEnv : public ::testing::Environment {
202 public:
203 BinderLibTestEnv() {}
204 sp<IBinder> getServer(void) {
205 return m_server;
206 }
207
208 private:
209 virtual void SetUp() {
210 m_serverpid = start_server_process(0);
211 //printf("m_serverpid %d\n", m_serverpid);
212 ASSERT_GT(m_serverpid, 0);
213
214 sp<IServiceManager> sm = defaultServiceManager();
215 //printf("%s: pid %d, get service\n", __func__, m_pid);
216 m_server = sm->getService(binderLibTestServiceName);
Yi Kong91635562018-06-07 14:38:36 -0700217 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800218 //printf("%s: pid %d, get service done\n", __func__, m_pid);
219 }
220 virtual void TearDown() {
221 status_t ret;
222 Parcel data, reply;
223 int exitStatus;
224 pid_t pid;
225
226 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700227 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800228 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
229 EXPECT_EQ(0, ret);
230 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
231 EXPECT_EQ(0, ret);
232 }
233 if (m_serverpid > 0) {
234 //printf("wait for %d\n", m_pids[i]);
235 pid = wait(&exitStatus);
236 EXPECT_EQ(m_serverpid, pid);
237 EXPECT_TRUE(WIFEXITED(exitStatus));
238 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
239 }
240 }
241
242 pid_t m_serverpid;
243 sp<IBinder> m_server;
244};
245
246class BinderLibTest : public ::testing::Test {
247 public:
248 virtual void SetUp() {
249 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000250 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800251 }
252 virtual void TearDown() {
253 }
254 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200255 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800256 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800257 int32_t id;
258 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800259
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700260 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800261
Elie Kheirallahb7246642022-05-03 18:01:43 +0000262 sp<IBinder> binder = reply.readStrongBinder();
263 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700264 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800265 if (idPtr)
266 *idPtr = id;
267 return binder;
268 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200269
Yi Kong91635562018-06-07 14:38:36 -0700270 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200271 {
272 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
273 }
274
Yi Kong91635562018-06-07 14:38:36 -0700275 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200276 {
277 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
278 }
279
Riley Andrews06b01ad2014-12-18 12:10:08 -0800280 void waitForReadData(int fd, int timeout_ms) {
281 int ret;
282 pollfd pfd = pollfd();
283
284 pfd.fd = fd;
285 pfd.events = POLLIN;
286 ret = poll(&pfd, 1, timeout_ms);
287 EXPECT_EQ(1, ret);
288 }
289
290 sp<IBinder> m_server;
291};
292
293class BinderLibTestBundle : public Parcel
294{
295 public:
296 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800297 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800298 int32_t mark;
299 int32_t bundleLen;
300 size_t pos;
301
302 if (source->readInt32(&mark))
303 return;
304 if (mark != MARK_START)
305 return;
306 if (source->readInt32(&bundleLen))
307 return;
308 pos = source->dataPosition();
309 if (Parcel::appendFrom(source, pos, bundleLen))
310 return;
311 source->setDataPosition(pos + bundleLen);
312 if (source->readInt32(&mark))
313 return;
314 if (mark != MARK_END)
315 return;
316 m_isValid = true;
317 setDataPosition(0);
318 }
319 void appendTo(Parcel *dest) {
320 dest->writeInt32(MARK_START);
321 dest->writeInt32(dataSize());
322 dest->appendFrom(this, 0, dataSize());
323 dest->writeInt32(MARK_END);
324 };
325 bool isValid(void) {
326 return m_isValid;
327 }
328 private:
329 enum {
330 MARK_START = B_PACK_CHARS('B','T','B','S'),
331 MARK_END = B_PACK_CHARS('B','T','B','E'),
332 };
333 bool m_isValid;
334};
335
336class BinderLibTestEvent
337{
338 public:
339 BinderLibTestEvent(void)
340 : m_eventTriggered(false)
341 {
Yi Kong91635562018-06-07 14:38:36 -0700342 pthread_mutex_init(&m_waitMutex, nullptr);
343 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800344 }
345 int waitEvent(int timeout_s)
346 {
347 int ret;
348 pthread_mutex_lock(&m_waitMutex);
349 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800350 struct timespec ts;
351 clock_gettime(CLOCK_REALTIME, &ts);
352 ts.tv_sec += timeout_s;
353 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800354 }
355 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
356 pthread_mutex_unlock(&m_waitMutex);
357 return ret;
358 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200359 pthread_t getTriggeringThread()
360 {
361 return m_triggeringThread;
362 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800363 protected:
364 void triggerEvent(void) {
365 pthread_mutex_lock(&m_waitMutex);
366 pthread_cond_signal(&m_waitCond);
367 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200368 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800369 pthread_mutex_unlock(&m_waitMutex);
370 };
371 private:
372 pthread_mutex_t m_waitMutex;
373 pthread_cond_t m_waitCond;
374 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200375 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800376};
377
378class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
379{
380 public:
381 BinderLibTestCallBack()
382 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700383 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800384 {
385 }
386 status_t getResult(void)
387 {
388 return m_result;
389 }
390
391 private:
392 virtual status_t onTransact(uint32_t code,
393 const Parcel& data, Parcel* reply,
394 uint32_t flags = 0)
395 {
396 (void)reply;
397 (void)flags;
398 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200399 case BINDER_LIB_TEST_CALL_BACK: {
400 status_t status = data.readInt32(&m_result);
401 if (status != NO_ERROR) {
402 m_result = status;
403 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800404 triggerEvent();
405 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200406 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700407 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
408 sp<IBinder> server;
409 int ret;
410 const uint8_t *buf = data.data();
411 size_t size = data.dataSize();
412 if (m_prev_end) {
413 /* 64-bit kernel needs at most 8 bytes to align buffer end */
414 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
415 } else {
416 EXPECT_TRUE(IsPageAligned((void *)buf));
417 }
418
419 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
420
421 if (size > 0) {
422 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
423 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
424 data, reply);
425 EXPECT_EQ(NO_ERROR, ret);
426 }
427 return NO_ERROR;
428 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800429 default:
430 return UNKNOWN_TRANSACTION;
431 }
432 }
433
434 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700435 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800436};
437
438class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
439{
440 private:
441 virtual void binderDied(const wp<IBinder>& who) {
442 (void)who;
443 triggerEvent();
444 };
445};
446
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700447TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
448 // EXPECT_DEATH works by forking the process
449 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
450}
451
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000452TEST_F(BinderLibTest, AddManagerToManager) {
453 sp<IServiceManager> sm = defaultServiceManager();
454 sp<IBinder> binder = IInterface::asBinder(sm);
455 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
456}
457
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500458TEST_F(BinderLibTest, WasParceled) {
459 auto binder = sp<BBinder>::make();
460 EXPECT_FALSE(binder->wasParceled());
461 Parcel data;
462 data.writeStrongBinder(binder);
463 EXPECT_TRUE(binder->wasParceled());
464}
465
Riley Andrews06b01ad2014-12-18 12:10:08 -0800466TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800467 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700468 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
469 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800470}
471
Steven Moreland80844f72020-12-12 02:06:08 +0000472TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000473 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700474 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
475 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000476}
477
Steven Morelandf183fdd2020-10-27 00:12:12 +0000478TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000479 Parcel data, reply;
480 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700481 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
482 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000483}
484
Marco Ballesio7ee17572020-09-08 10:30:03 -0700485TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700486 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700487 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700488
Li Li6f059292021-09-10 09:59:30 -0700489 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700490 if (freezer_file.fail()) {
491 GTEST_SKIP();
492 return;
493 }
494
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700495 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700496 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700497 for (int i = 0; i < 10; i++) {
498 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
499 }
Li Li6f059292021-09-10 09:59:30 -0700500
501 // Pass test on devices where BINDER_FREEZE ioctl is not supported
502 int ret = IPCThreadState::self()->freeze(pid, false, 0);
503 if (ret != 0) {
504 GTEST_SKIP();
505 return;
506 }
507
508 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
509 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
510 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700511 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700512
Li Li4e678b92021-09-14 12:14:42 -0700513 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700514
515 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
516 &async_received));
517
518 EXPECT_EQ(sync_received, 1);
519 EXPECT_EQ(async_received, 0);
520
Li Li4e678b92021-09-14 12:14:42 -0700521 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700522 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
523}
524
Riley Andrews06b01ad2014-12-18 12:10:08 -0800525TEST_F(BinderLibTest, SetError) {
526 int32_t testValue[] = { 0, -123, 123 };
527 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800528 Parcel data, reply;
529 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700530 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
531 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800532 }
533}
534
535TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700536 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800537}
538
539TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800540 int32_t ptrsize;
541 Parcel data, reply;
542 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700543 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700544 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
545 StatusEq(NO_ERROR));
546 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800547 RecordProperty("TestPtrSize", sizeof(void *));
548 RecordProperty("ServerPtrSize", sizeof(void *));
549}
550
551TEST_F(BinderLibTest, IndirectGetId2)
552{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800553 int32_t id;
554 int32_t count;
555 Parcel data, reply;
556 int32_t serverId[3];
557
558 data.writeInt32(ARRAY_SIZE(serverId));
559 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
560 sp<IBinder> server;
561 BinderLibTestBundle datai;
562
563 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700564 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800565 data.writeStrongBinder(server);
566 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
567 datai.appendTo(&data);
568 }
569
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700570 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
571 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800572
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700573 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800574 EXPECT_EQ(0, id);
575
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700576 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700577 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800578
579 for (size_t i = 0; i < (size_t)count; i++) {
580 BinderLibTestBundle replyi(&reply);
581 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700582 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800583 EXPECT_EQ(serverId[i], id);
584 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
585 }
586
587 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
588}
589
590TEST_F(BinderLibTest, IndirectGetId3)
591{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800592 int32_t id;
593 int32_t count;
594 Parcel data, reply;
595 int32_t serverId[3];
596
597 data.writeInt32(ARRAY_SIZE(serverId));
598 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
599 sp<IBinder> server;
600 BinderLibTestBundle datai;
601 BinderLibTestBundle datai2;
602
603 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700604 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800605 data.writeStrongBinder(server);
606 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
607
608 datai.writeInt32(1);
609 datai.writeStrongBinder(m_server);
610 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
611 datai2.appendTo(&datai);
612
613 datai.appendTo(&data);
614 }
615
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700616 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
617 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800618
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700619 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800620 EXPECT_EQ(0, id);
621
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700622 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700623 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800624
625 for (size_t i = 0; i < (size_t)count; i++) {
626 int32_t counti;
627
628 BinderLibTestBundle replyi(&reply);
629 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700630 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800631 EXPECT_EQ(serverId[i], id);
632
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700633 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800634 EXPECT_EQ(1, counti);
635
636 BinderLibTestBundle replyi2(&replyi);
637 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700638 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800639 EXPECT_EQ(0, id);
640 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
641
642 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
643 }
644
645 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
646}
647
648TEST_F(BinderLibTest, CallBack)
649{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800650 Parcel data, reply;
651 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
652 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700653 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
654 StatusEq(NO_ERROR));
655 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
656 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800657}
658
Steven Moreland35626652021-05-15 01:32:04 +0000659TEST_F(BinderLibTest, BinderCallContextGuard) {
660 sp<IBinder> binder = addServer();
661 Parcel data, reply;
662 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
663 StatusEq(DEAD_OBJECT));
664}
665
Riley Andrews06b01ad2014-12-18 12:10:08 -0800666TEST_F(BinderLibTest, AddServer)
667{
668 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700669 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800670}
671
Riley Andrews06b01ad2014-12-18 12:10:08 -0800672TEST_F(BinderLibTest, DeathNotificationStrongRef)
673{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800674 sp<IBinder> sbinder;
675
676 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
677
678 {
679 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700680 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700681 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800682 sbinder = binder;
683 }
684 {
685 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700686 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
687 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800688 }
689 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700690 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
691 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800692}
693
694TEST_F(BinderLibTest, DeathNotificationMultiple)
695{
696 status_t ret;
697 const int clientcount = 2;
698 sp<IBinder> target;
699 sp<IBinder> linkedclient[clientcount];
700 sp<BinderLibTestCallBack> callBack[clientcount];
701 sp<IBinder> passiveclient[clientcount];
702
703 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700704 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800705 for (int i = 0; i < clientcount; i++) {
706 {
707 Parcel data, reply;
708
709 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700710 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800711 callBack[i] = new BinderLibTestCallBack();
712 data.writeStrongBinder(target);
713 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700714 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
715 &reply, TF_ONE_WAY),
716 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800717 }
718 {
719 Parcel data, reply;
720
721 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700722 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800723 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700724 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
725 &reply, TF_ONE_WAY),
726 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800727 }
728 }
729 {
730 Parcel data, reply;
731 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
732 EXPECT_EQ(0, ret);
733 }
734
735 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700736 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
737 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800738 }
739}
740
Martijn Coenenf7100e42017-07-31 12:14:09 +0200741TEST_F(BinderLibTest, DeathNotificationThread)
742{
743 status_t ret;
744 sp<BinderLibTestCallBack> callback;
745 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700746 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200747 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700748 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200749
750 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
751
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700752 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200753
754 {
755 Parcel data, reply;
756 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
757 EXPECT_EQ(0, ret);
758 }
759
760 /* Make sure it's dead */
761 testDeathRecipient->waitEvent(5);
762
763 /* Now, pass the ref to another process and ask that process to
764 * call linkToDeath() on it, and wait for a response. This tests
765 * two things:
766 * 1) You still get death notifications when calling linkToDeath()
767 * on a ref that is already dead when it was passed to you.
768 * 2) That death notifications are not directly pushed to the thread
769 * registering them, but to the threadpool (proc workqueue) instead.
770 *
771 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
772 * is blocked on a condition variable waiting for the death notification to be
773 * called; therefore, that thread is not available for handling proc work.
774 * So, if the death notification was pushed to the thread workqueue, the callback
775 * would never be called, and the test would timeout and fail.
776 *
777 * Note that we can't do this part of the test from this thread itself, because
778 * the binder driver would only push death notifications to the thread if
779 * it is a looper thread, which this thread is not.
780 *
781 * See b/23525545 for details.
782 */
783 {
784 Parcel data, reply;
785
786 callback = new BinderLibTestCallBack();
787 data.writeStrongBinder(target);
788 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700789 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
790 TF_ONE_WAY),
791 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200792 }
793
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700794 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
795 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200796}
797
Riley Andrews06b01ad2014-12-18 12:10:08 -0800798TEST_F(BinderLibTest, PassFile) {
799 int ret;
800 int pipefd[2];
801 uint8_t buf[1] = { 0 };
802 uint8_t write_value = 123;
803
804 ret = pipe2(pipefd, O_NONBLOCK);
805 ASSERT_EQ(0, ret);
806
807 {
808 Parcel data, reply;
809 uint8_t writebuf[1] = { write_value };
810
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700811 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800812
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700813 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800814
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700815 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800816
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700817 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
818 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800819 }
820
821 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700822 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800823 EXPECT_EQ(write_value, buf[0]);
824
825 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
826
827 ret = read(pipefd[0], buf, sizeof(buf));
828 EXPECT_EQ(0, ret);
829
830 close(pipefd[0]);
831}
832
Ryo Hashimotobf551892018-05-31 16:58:35 +0900833TEST_F(BinderLibTest, PassParcelFileDescriptor) {
834 const int datasize = 123;
835 std::vector<uint8_t> writebuf(datasize);
836 for (size_t i = 0; i < writebuf.size(); ++i) {
837 writebuf[i] = i;
838 }
839
840 android::base::unique_fd read_end, write_end;
841 {
842 int pipefd[2];
843 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
844 read_end.reset(pipefd[0]);
845 write_end.reset(pipefd[1]);
846 }
847 {
848 Parcel data;
849 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
850 write_end.reset();
851 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
852 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
853
854 Parcel reply;
855 EXPECT_EQ(NO_ERROR,
856 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
857 &reply));
858 }
859 std::vector<uint8_t> readbuf(datasize);
860 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
861 EXPECT_EQ(writebuf, readbuf);
862
863 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
864
865 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
866}
867
Riley Andrews06b01ad2014-12-18 12:10:08 -0800868TEST_F(BinderLibTest, PromoteLocal) {
869 sp<IBinder> strong = new BBinder();
870 wp<IBinder> weak = strong;
871 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700872 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800873 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700874 strong = nullptr;
875 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800876 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700877 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800878}
879
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700880TEST_F(BinderLibTest, LocalGetExtension) {
881 sp<BBinder> binder = new BBinder();
882 sp<IBinder> ext = new BBinder();
883 binder->setExtension(ext);
884 EXPECT_EQ(ext, binder->getExtension());
885}
886
887TEST_F(BinderLibTest, RemoteGetExtension) {
888 sp<IBinder> server = addServer();
889 ASSERT_TRUE(server != nullptr);
890
891 sp<IBinder> extension;
892 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
893 ASSERT_NE(nullptr, extension.get());
894
895 EXPECT_EQ(NO_ERROR, extension->pingBinder());
896}
897
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700898TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700899 Parcel data, reply;
900
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700901 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
902 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700903
904 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700905 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800906 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
907 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
908 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
909 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700910}
911
Connor O'Brien52be2c92016-09-20 14:18:08 -0700912TEST_F(BinderLibTest, FreedBinder) {
913 status_t ret;
914
915 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700916 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700917
918 __u32 freedHandle;
919 wp<IBinder> keepFreedBinder;
920 {
921 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700922 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
923 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700924 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
925 freedHandle = freed->handle;
926 /* Add a weak ref to the freed binder so the driver does not
927 * delete its reference to it - otherwise the transaction
928 * fails regardless of whether the driver is fixed.
929 */
Steven Morelande171d622019-07-17 16:06:01 -0700930 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700931 }
Steven Morelande171d622019-07-17 16:06:01 -0700932 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700933 {
934 Parcel data, reply;
935 data.writeStrongBinder(server);
936 /* Replace original handle with handle to the freed binder */
937 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
938 __u32 oldHandle = strong->handle;
939 strong->handle = freedHandle;
940 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
941 /* Returns DEAD_OBJECT (-32) if target crashes and
942 * FAILED_TRANSACTION if the driver rejects the invalid
943 * object.
944 */
945 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
946 /* Restore original handle so parcel destructor does not use
947 * the wrong handle.
948 */
949 strong->handle = oldHandle;
950 }
951}
952
Sherry Yang336cdd32017-07-24 14:12:27 -0700953TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700954 Parcel data, reply;
955 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
956 for (int i = 0; i < 2; i++) {
957 BinderLibTestBundle datai;
958 datai.appendFrom(&data, 0, data.dataSize());
959
960 data.freeData();
961 data.writeInt32(1);
962 data.writeStrongBinder(callBack);
963 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
964
965 datai.appendTo(&data);
966 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700967 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
968 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700969}
970
Martijn Coenen45b07b42017-08-09 12:07:45 +0200971TEST_F(BinderLibTest, OnewayQueueing)
972{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200973 Parcel data, data2;
974
975 sp<IBinder> pollServer = addPollServer();
976
977 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
978 data.writeStrongBinder(callBack);
979 data.writeInt32(500000); // delay in us before calling back
980
981 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
982 data2.writeStrongBinder(callBack2);
983 data2.writeInt32(0); // delay in us
984
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700985 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
986 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200987
988 // The delay ensures that this second transaction will end up on the async_todo list
989 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700990 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
991 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200992
993 // The server will ensure that the two transactions are handled in the expected order;
994 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700995 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
996 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200997
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700998 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
999 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001000}
1001
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001002TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1003{
1004 status_t ret;
1005 Parcel data, reply;
1006 data.writeInterfaceToken(binderLibTestServiceName);
1007 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1008 EXPECT_EQ(-1, reply.readInt32());
1009 EXPECT_EQ(NO_ERROR, ret);
1010}
1011
1012TEST_F(BinderLibTest, WorkSourceSet)
1013{
1014 status_t ret;
1015 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001016 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001017 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001018 data.writeInterfaceToken(binderLibTestServiceName);
1019 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1020 EXPECT_EQ(100, reply.readInt32());
1021 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001022 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1023 EXPECT_EQ(NO_ERROR, ret);
1024}
1025
1026TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1027{
1028 status_t ret;
1029 Parcel data, reply;
1030
1031 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1032 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1033
1034 data.writeInterfaceToken(binderLibTestServiceName);
1035 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1036 EXPECT_EQ(-1, reply.readInt32());
1037 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001038 EXPECT_EQ(NO_ERROR, ret);
1039}
1040
1041TEST_F(BinderLibTest, WorkSourceCleared)
1042{
1043 status_t ret;
1044 Parcel data, reply;
1045
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001046 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001047 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1048 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001049 data.writeInterfaceToken(binderLibTestServiceName);
1050 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1051
1052 EXPECT_EQ(-1, reply.readInt32());
1053 EXPECT_EQ(100, previousWorkSource);
1054 EXPECT_EQ(NO_ERROR, ret);
1055}
1056
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001057TEST_F(BinderLibTest, WorkSourceRestored)
1058{
1059 status_t ret;
1060 Parcel data, reply;
1061
1062 IPCThreadState::self()->setCallingWorkSourceUid(100);
1063 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1064 IPCThreadState::self()->restoreCallingWorkSource(token);
1065
1066 data.writeInterfaceToken(binderLibTestServiceName);
1067 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1068
1069 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001070 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001071 EXPECT_EQ(NO_ERROR, ret);
1072}
1073
Olivier Gaillard91a04802018-11-14 17:32:41 +00001074TEST_F(BinderLibTest, PropagateFlagSet)
1075{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001076 IPCThreadState::self()->clearPropagateWorkSource();
1077 IPCThreadState::self()->setCallingWorkSourceUid(100);
1078 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1079}
1080
1081TEST_F(BinderLibTest, PropagateFlagCleared)
1082{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001083 IPCThreadState::self()->setCallingWorkSourceUid(100);
1084 IPCThreadState::self()->clearPropagateWorkSource();
1085 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1086}
1087
1088TEST_F(BinderLibTest, PropagateFlagRestored)
1089{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001090 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1091 IPCThreadState::self()->restoreCallingWorkSource(token);
1092
1093 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1094}
1095
1096TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1097{
1098 IPCThreadState::self()->setCallingWorkSourceUid(100);
1099
1100 Parcel data, reply;
1101 status_t ret;
1102 data.writeInterfaceToken(binderLibTestServiceName);
1103 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1104
1105 Parcel data2, reply2;
1106 status_t ret2;
1107 data2.writeInterfaceToken(binderLibTestServiceName);
1108 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1109 EXPECT_EQ(100, reply2.readInt32());
1110 EXPECT_EQ(NO_ERROR, ret2);
1111}
1112
Steven Morelandbf1915b2020-07-16 22:43:02 +00001113TEST_F(BinderLibTest, SchedPolicySet) {
1114 sp<IBinder> server = addServer();
1115 ASSERT_TRUE(server != nullptr);
1116
1117 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001118 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1119 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001120
1121 int policy = reply.readInt32();
1122 int priority = reply.readInt32();
1123
1124 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1125 EXPECT_EQ(kSchedPriority, priority);
1126}
1127
Steven Morelandcf03cf12020-12-04 02:58:40 +00001128TEST_F(BinderLibTest, InheritRt) {
1129 sp<IBinder> server = addServer();
1130 ASSERT_TRUE(server != nullptr);
1131
1132 const struct sched_param param {
1133 .sched_priority = kSchedPriorityMore,
1134 };
1135 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1136
1137 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001138 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1139 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001140
1141 int policy = reply.readInt32();
1142 int priority = reply.readInt32();
1143
1144 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1145 EXPECT_EQ(kSchedPriorityMore, priority);
1146}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001147
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001148TEST_F(BinderLibTest, VectorSent) {
1149 Parcel data, reply;
1150 sp<IBinder> server = addServer();
1151 ASSERT_TRUE(server != nullptr);
1152
1153 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1154 data.writeUint64Vector(testValue);
1155
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001156 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001157 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001158 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001159 EXPECT_EQ(readValue, testValue);
1160}
1161
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001162TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1163 sp<IBinder> server = addServer();
1164 ASSERT_TRUE(server != nullptr);
1165
1166 Parcel reply;
1167 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1168 StatusEq(NO_ERROR));
1169 base::unique_fd fd;
1170 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1171
1172 const int result = fcntl(fd.get(), F_GETFL);
1173 ASSERT_NE(result, -1);
1174 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1175}
1176
Steven Moreland59b84442022-07-12 18:32:44 +00001177// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1178// This value is not exposed, but some code in the framework relies on being able to use
1179// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001180constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001181constexpr size_t kSizeBytesOverFull = 1'050'000;
1182
1183TEST_F(BinderLibTest, GargantuanVectorSent) {
1184 sp<IBinder> server = addServer();
1185 ASSERT_TRUE(server != nullptr);
1186
1187 for (size_t i = 0; i < 10; i++) {
1188 // a slight variation in size is used to consider certain possible caching implementations
1189 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1190
1191 Parcel data, reply;
1192 data.writeUint64Vector(testValue);
1193 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1194 << i;
1195 std::vector<uint64_t> readValue;
1196 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1197 EXPECT_EQ(readValue, testValue);
1198 }
1199}
1200
1201TEST_F(BinderLibTest, LimitExceededVectorSent) {
1202 sp<IBinder> server = addServer();
1203 ASSERT_TRUE(server != nullptr);
1204 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1205
1206 Parcel data, reply;
1207 data.writeUint64Vector(testValue);
1208 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1209 StatusEq(FAILED_TRANSACTION));
1210}
1211
Martijn Coenen82c75312019-07-24 15:18:30 +02001212TEST_F(BinderLibTest, BufRejected) {
1213 Parcel data, reply;
1214 uint32_t buf;
1215 sp<IBinder> server = addServer();
1216 ASSERT_TRUE(server != nullptr);
1217
1218 binder_buffer_object obj {
1219 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001220 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001221 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1222 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001223 };
1224 data.setDataCapacity(1024);
1225 // Write a bogus object at offset 0 to get an entry in the offset table
1226 data.writeFileDescriptor(0);
1227 EXPECT_EQ(data.objectsCount(), 1);
1228 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1229 // And now, overwrite it with the buffer object
1230 memcpy(parcelData, &obj, sizeof(obj));
1231 data.setDataSize(sizeof(obj));
1232
Steven Morelandf2e0a952021-11-01 18:17:23 -07001233 EXPECT_EQ(data.objectsCount(), 1);
1234
Martijn Coenen82c75312019-07-24 15:18:30 +02001235 // Either the kernel should reject this transaction (if it's correct), but
1236 // if it's not, the server implementation should return an error if it
1237 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001238 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001239 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001240}
1241
Steven Morelandf2e0a952021-11-01 18:17:23 -07001242TEST_F(BinderLibTest, WeakRejected) {
1243 Parcel data, reply;
1244 sp<IBinder> server = addServer();
1245 ASSERT_TRUE(server != nullptr);
1246
1247 auto binder = sp<BBinder>::make();
1248 wp<BBinder> wpBinder(binder);
1249 flat_binder_object obj{
1250 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1251 .flags = 0,
1252 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1253 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1254 };
1255 data.setDataCapacity(1024);
1256 // Write a bogus object at offset 0 to get an entry in the offset table
1257 data.writeFileDescriptor(0);
1258 EXPECT_EQ(data.objectsCount(), 1);
1259 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1260 // And now, overwrite it with the weak binder
1261 memcpy(parcelData, &obj, sizeof(obj));
1262 data.setDataSize(sizeof(obj));
1263
1264 // a previous bug caused other objects to be released an extra time, so we
1265 // test with an object that libbinder will actually try to release
1266 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1267
1268 EXPECT_EQ(data.objectsCount(), 2);
1269
1270 // send it many times, since previous error was memory corruption, make it
1271 // more likely that the server crashes
1272 for (size_t i = 0; i < 100; i++) {
1273 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1274 StatusEq(BAD_VALUE));
1275 }
1276
1277 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1278}
1279
Steven Moreland254e8ef2021-04-19 22:28:50 +00001280TEST_F(BinderLibTest, GotSid) {
1281 sp<IBinder> server = addServer();
1282
1283 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001284 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001285}
1286
Andrei Homescu1519b982022-06-09 02:04:44 +00001287struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1288 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1289
1290 // Flattenable protocol
1291 size_t getFlattenedSize() const {
1292 // Return a valid non-zero size here so we don't get an unintended
1293 // BAD_VALUE from Parcel::write
1294 return 16;
1295 }
1296 size_t getFdCount() const { return mFdCount; }
1297 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1298 for (size_t i = 0; i < count; i++) {
1299 fds[i] = STDIN_FILENO;
1300 }
1301 return NO_ERROR;
1302 }
1303 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1304 size_t & /*count*/) {
1305 /* This doesn't get called */
1306 return NO_ERROR;
1307 }
1308
1309 size_t mFdCount;
1310};
1311
1312TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1313 rlimit origNofile;
1314 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1315 ASSERT_EQ(0, ret);
1316
1317 // Restore the original file limits when the test finishes
1318 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1319
1320 rlimit testNofile = {1024, 1024};
1321 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1322 ASSERT_EQ(0, ret);
1323
1324 Parcel parcel;
1325 // Try to write more file descriptors than supported by the OS
1326 TooManyFdsFlattenable tooManyFds1(1024);
1327 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1328
1329 // Try to write more file descriptors than the internal limit
1330 TooManyFdsFlattenable tooManyFds2(1025);
1331 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1332}
1333
Jayant Chowdhary30700942022-01-31 14:12:40 -08001334TEST(ServiceNotifications, Unregister) {
1335 auto sm = defaultServiceManager();
1336 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1337 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1338 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1339 virtual ~LocalRegistrationCallbackImpl() {}
1340 };
1341 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1342
1343 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1344 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1345}
1346
Elie Kheirallah47431c12022-04-21 23:46:17 +00001347TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1348 Parcel data, reply;
1349 sp<IBinder> server = addServer();
1350 ASSERT_TRUE(server != nullptr);
1351 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1352 StatusEq(NO_ERROR));
1353 int32_t replyi = reply.readInt32();
1354 // Expect 16 threads: kKernelThreads = 15 + Pool thread == 16
1355 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
1356 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1357
1358 /*
1359 * This will use all threads in the pool expect the main pool thread.
1360 * The service should run fine without locking, and the thread count should
1361 * not exceed 16 (15 Max + pool thread).
1362 */
1363 std::vector<std::thread> ts;
Steven Morelandb17a5f02022-07-13 01:25:35 +00001364 for (size_t i = 0; i < kKernelThreads; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001365 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001366 Parcel local_reply;
1367 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1368 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001369 }));
1370 }
1371
Steven Morelandb17a5f02022-07-13 01:25:35 +00001372 data.writeInt32(100);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001373 // Give a chance for all threads to be used
1374 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1375
1376 for (auto &t : ts) {
1377 t.join();
1378 }
1379
1380 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1381 StatusEq(NO_ERROR));
1382 replyi = reply.readInt32();
Steven Morelandb17a5f02022-07-13 01:25:35 +00001383 EXPECT_EQ(replyi, kKernelThreads + 1);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001384}
1385
1386size_t epochMillis() {
1387 using std::chrono::duration_cast;
1388 using std::chrono::milliseconds;
1389 using std::chrono::seconds;
1390 using std::chrono::system_clock;
1391 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1392}
1393
1394TEST_F(BinderLibTest, HangingServices) {
1395 Parcel data, reply;
1396 sp<IBinder> server = addServer();
1397 ASSERT_TRUE(server != nullptr);
1398 int32_t delay = 1000; // ms
1399 data.writeInt32(delay);
1400 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1401 std::vector<std::thread> ts;
1402 size_t epochMsBefore = epochMillis();
1403 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1404 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001405 Parcel local_reply;
1406 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1407 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001408 }));
1409 }
1410
1411 for (auto &t : ts) {
1412 t.join();
1413 }
1414 size_t epochMsAfter = epochMillis();
1415
1416 // deadlock occurred and threads only finished after 1s passed.
1417 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1418}
1419
Yifan Hong84bedeb2021-04-21 21:37:17 -07001420class BinderLibRpcTestBase : public BinderLibTest {
1421public:
1422 void SetUp() override {
1423 if (!base::GetBoolProperty("ro.debuggable", false)) {
1424 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1425 "non-debuggable builds.";
1426 }
1427 BinderLibTest::SetUp();
1428 }
1429
1430 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1431 auto rpcServer = RpcServer::make();
1432 EXPECT_NE(nullptr, rpcServer);
1433 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001434 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001435 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1436 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001437 return {};
1438 }
1439 return {rpcServer->releaseServer(), port};
1440 }
1441};
1442
Yifan Hong8b890852021-06-10 13:44:09 -07001443class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001444
Yifan Hongbd276552022-02-28 15:28:51 -08001445// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1446// If device is debuggable AND not on user builds, expects matcher.
1447// Otherwise expects INVALID_OPERATION.
1448// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1449static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1450 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1451 android::base::GetProperty("ro.build.type", "") != "user";
1452 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1453}
1454
Yifan Hong8b890852021-06-10 13:44:09 -07001455TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1456 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001457 ASSERT_TRUE(binder != nullptr);
1458 auto [socket, port] = CreateSocket();
1459 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001460 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1461 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001462}
1463
Yifan Hong8b890852021-06-10 13:44:09 -07001464// Tests for multiple RpcServer's on the same binder object.
1465TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1466 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001467 ASSERT_TRUE(binder != nullptr);
1468
1469 auto [socket1, port1] = CreateSocket();
1470 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001471 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001472 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1473 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001474
1475 auto [socket2, port2] = CreateSocket();
1476 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001477 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001478 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1479 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001480}
1481
Yifan Hong8b890852021-06-10 13:44:09 -07001482// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1483// local binders.
1484class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001485public:
1486 sp<IBinder> GetService() {
1487 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1488 }
1489 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1490 return info.param ? "remote" : "local";
1491 }
1492};
1493
Yifan Hong8b890852021-06-10 13:44:09 -07001494TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1495 auto binder = GetService();
1496 ASSERT_TRUE(binder != nullptr);
1497 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001498 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001499}
1500
1501TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001502 auto binder = GetService();
1503 ASSERT_TRUE(binder != nullptr);
1504 auto [socket, port] = CreateSocket();
1505 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001506 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1507 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001508}
Yifan Hong8b890852021-06-10 13:44:09 -07001509INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1510 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001511
Yifan Hong543edcd2021-05-18 19:47:30 -07001512class BinderLibTestService : public BBinder {
1513public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001514 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1515 : m_id(id),
1516 m_nextServerId(id + 1),
1517 m_serverStartRequested(false),
1518 m_callback(nullptr),
1519 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001520 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1521 pthread_cond_init(&m_serverWaitCond, nullptr);
1522 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001523 ~BinderLibTestService() {
1524 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1525 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001526
Yifan Hong543edcd2021-05-18 19:47:30 -07001527 void processPendingCall() {
1528 if (m_callback != nullptr) {
1529 Parcel data;
1530 data.writeInt32(NO_ERROR);
1531 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1532 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001533 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001534 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001535
Yifan Hong543edcd2021-05-18 19:47:30 -07001536 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1537 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001538 // TODO(b/182914638): also checks getCallingUid() for RPC
1539 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001540 return PERMISSION_DENIED;
1541 }
1542 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001543 case BINDER_LIB_TEST_REGISTER_SERVER: {
1544 int32_t id;
1545 sp<IBinder> binder;
1546 id = data.readInt32();
1547 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001548 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001549 return BAD_VALUE;
1550 }
1551
Yifan Hong543edcd2021-05-18 19:47:30 -07001552 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001553
1554 pthread_mutex_lock(&m_serverWaitMutex);
1555 if (m_serverStartRequested) {
1556 m_serverStartRequested = false;
1557 m_serverStarted = binder;
1558 pthread_cond_signal(&m_serverWaitCond);
1559 }
1560 pthread_mutex_unlock(&m_serverWaitMutex);
1561 return NO_ERROR;
1562 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001563 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001564 case BINDER_LIB_TEST_ADD_SERVER: {
1565 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001566 int serverid;
1567
1568 if (m_id != 0) {
1569 return INVALID_OPERATION;
1570 }
1571 pthread_mutex_lock(&m_serverWaitMutex);
1572 if (m_serverStartRequested) {
1573 ret = -EBUSY;
1574 } else {
1575 serverid = m_nextServerId++;
1576 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001577 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001578
1579 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001580 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001581 pthread_mutex_lock(&m_serverWaitMutex);
1582 }
1583 if (ret > 0) {
1584 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001585 struct timespec ts;
1586 clock_gettime(CLOCK_REALTIME, &ts);
1587 ts.tv_sec += 5;
1588 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001589 }
1590 if (m_serverStartRequested) {
1591 m_serverStartRequested = false;
1592 ret = -ETIMEDOUT;
1593 } else {
1594 reply->writeStrongBinder(m_serverStarted);
1595 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001596 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001597 ret = NO_ERROR;
1598 }
1599 } else if (ret >= 0) {
1600 m_serverStartRequested = false;
1601 ret = UNKNOWN_ERROR;
1602 }
1603 pthread_mutex_unlock(&m_serverWaitMutex);
1604 return ret;
1605 }
Steven Moreland35626652021-05-15 01:32:04 +00001606 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1607 IPCThreadState::SpGuard spGuard{
1608 .address = __builtin_frame_address(0),
1609 .context = "GuardInBinderTransaction",
1610 };
1611 const IPCThreadState::SpGuard *origGuard =
1612 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1613
1614 // if the guard works, this should abort
1615 (void)IPCThreadState::self()->getCallingPid();
1616
1617 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1618 return NO_ERROR;
1619 }
1620
Marco Ballesio7ee17572020-09-08 10:30:03 -07001621 case BINDER_LIB_TEST_GETPID:
1622 reply->writeInt32(getpid());
1623 return NO_ERROR;
1624 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1625 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001626 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001627 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001628 // oneway error codes should be ignored
1629 if (flags & TF_ONE_WAY) {
1630 return UNKNOWN_ERROR;
1631 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001632 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001633 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1634 // Note: this transaction is only designed for use with a
1635 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001636 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001637 // A callback was already pending; this means that
1638 // we received a second call while still processing
1639 // the first one. Fail the test.
1640 sp<IBinder> callback = data.readStrongBinder();
1641 Parcel data2;
1642 data2.writeInt32(UNKNOWN_ERROR);
1643
Yi Kong91635562018-06-07 14:38:36 -07001644 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001645 } else {
1646 m_callback = data.readStrongBinder();
1647 int32_t delayUs = data.readInt32();
1648 /*
1649 * It's necessary that we sleep here, so the next
1650 * transaction the caller makes will be queued to
1651 * the async queue.
1652 */
1653 usleep(delayUs);
1654
1655 /*
1656 * Now when we return, libbinder will tell the kernel
1657 * we are done with this transaction, and the kernel
1658 * can move the queued transaction to either the
1659 * thread todo worklist (for kernels without the fix),
1660 * or the proc todo worklist. In case of the former,
1661 * the next outbound call will pick up the pending
1662 * transaction, which leads to undesired reentrant
1663 * behavior. This is caught in the if() branch above.
1664 */
1665 }
1666
1667 return NO_ERROR;
1668 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001669 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1670 Parcel data2, reply2;
1671 sp<IBinder> binder;
1672 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001673 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001674 return BAD_VALUE;
1675 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001676 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001677 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1678 return NO_ERROR;
1679 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001680 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1681 reply->writeStrongBinder(this);
1682 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001683 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1684 reply->writeInt32(m_id);
1685 return NO_ERROR;
1686 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1687 int32_t count;
1688 uint32_t indirect_code;
1689 sp<IBinder> binder;
1690
1691 count = data.readInt32();
1692 reply->writeInt32(m_id);
1693 reply->writeInt32(count);
1694 for (int i = 0; i < count; i++) {
1695 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001696 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001697 return BAD_VALUE;
1698 }
1699 indirect_code = data.readInt32();
1700 BinderLibTestBundle data2(&data);
1701 if (!data2.isValid()) {
1702 return BAD_VALUE;
1703 }
1704 BinderLibTestBundle reply2;
1705 binder->transact(indirect_code, data2, &reply2);
1706 reply2.appendTo(reply);
1707 }
1708 return NO_ERROR;
1709 }
1710 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1711 reply->setError(data.readInt32());
1712 return NO_ERROR;
1713 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1714 reply->writeInt32(sizeof(void *));
1715 return NO_ERROR;
1716 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1717 return NO_ERROR;
1718 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1719 m_strongRef = data.readStrongBinder();
1720 return NO_ERROR;
1721 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1722 int ret;
1723 Parcel data2, reply2;
1724 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1725 sp<IBinder> target;
1726 sp<IBinder> callback;
1727
1728 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001729 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001730 return BAD_VALUE;
1731 }
1732 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001733 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001734 return BAD_VALUE;
1735 }
1736 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001737 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001738 data2.writeInt32(ret);
1739 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1740 return NO_ERROR;
1741 }
1742 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1743 int ret;
1744 int32_t size;
1745 const void *buf;
1746 int fd;
1747
1748 fd = data.readFileDescriptor();
1749 if (fd < 0) {
1750 return BAD_VALUE;
1751 }
1752 ret = data.readInt32(&size);
1753 if (ret != NO_ERROR) {
1754 return ret;
1755 }
1756 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001757 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001758 return BAD_VALUE;
1759 }
1760 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001761 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001762 return NO_ERROR;
1763 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001764 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1765 int ret;
1766 int32_t size;
1767 const void *buf;
1768 android::base::unique_fd fd;
1769
1770 ret = data.readUniqueParcelFileDescriptor(&fd);
1771 if (ret != NO_ERROR) {
1772 return ret;
1773 }
1774 ret = data.readInt32(&size);
1775 if (ret != NO_ERROR) {
1776 return ret;
1777 }
1778 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001779 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001780 return BAD_VALUE;
1781 }
1782 ret = write(fd.get(), buf, size);
1783 if (ret != size) return UNKNOWN_ERROR;
1784 return NO_ERROR;
1785 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001786 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1787 alarm(10);
1788 return NO_ERROR;
1789 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001790 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001791 ;
1792 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001793 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001794 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001795 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001796 return NO_ERROR;
1797 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001798 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1799 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001800 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001801 return NO_ERROR;
1802 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001803 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1804 int policy = 0;
1805 sched_param param;
1806 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1807 return UNKNOWN_ERROR;
1808 }
1809 reply->writeInt32(policy);
1810 reply->writeInt32(param.sched_priority);
1811 return NO_ERROR;
1812 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001813 case BINDER_LIB_TEST_ECHO_VECTOR: {
1814 std::vector<uint64_t> vector;
1815 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001816 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001817 reply->writeUint64Vector(vector);
1818 return NO_ERROR;
1819 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001820 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1821 std::array<int, 2> sockets;
1822 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1823 if (!created) {
1824 ALOGE("Could not create socket pair");
1825 return UNKNOWN_ERROR;
1826 }
1827
1828 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1829 if (result != 0) {
1830 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1831 return UNKNOWN_ERROR;
1832 }
1833 base::unique_fd out(sockets[0]);
1834 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1835 if (writeResult != NO_ERROR) {
1836 ALOGE("Could not write unique_fd");
1837 return writeResult;
1838 }
1839 close(sockets[1]); // we don't need the other side of the fd
1840 return NO_ERROR;
1841 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001842 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001843 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1844 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001845 case BINDER_LIB_TEST_CAN_GET_SID: {
1846 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1847 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001848 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1849 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1850 return NO_ERROR;
1851 }
1852 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001853 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001854 return NO_ERROR;
1855 }
1856 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001857 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001858 return NO_ERROR;
1859 }
1860 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1861 int32_t ms = data.readInt32();
1862 return unlockInMs(ms);
1863 }
1864 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001865 m_blockMutex.lock();
1866 sp<BinderLibTestService> thisService = this;
1867 int32_t value = data.readInt32();
1868 // start local thread to unlock in 1s
1869 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001870 t.detach();
1871 return NO_ERROR;
1872 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001873 default:
1874 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001875 };
1876 }
1877
Elie Kheirallah47431c12022-04-21 23:46:17 +00001878 status_t unlockInMs(int32_t ms) {
1879 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001880 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001881 return NO_ERROR;
1882 }
1883
Yifan Hong543edcd2021-05-18 19:47:30 -07001884private:
1885 int32_t m_id;
1886 int32_t m_nextServerId;
1887 pthread_mutex_t m_serverWaitMutex;
1888 pthread_cond_t m_serverWaitCond;
1889 bool m_serverStartRequested;
1890 sp<IBinder> m_serverStarted;
1891 sp<IBinder> m_strongRef;
1892 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001893 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001894 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001895};
1896
Martijn Coenen45b07b42017-08-09 12:07:45 +02001897int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001898{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001899 binderLibTestServiceName += String16(binderserversuffix);
1900
Steven Moreland35626652021-05-15 01:32:04 +00001901 // Testing to make sure that calls that we are serving can use getCallin*
1902 // even though we don't here.
1903 IPCThreadState::SpGuard spGuard{
1904 .address = __builtin_frame_address(0),
1905 .context = "main server thread",
1906 };
1907 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1908
Riley Andrews06b01ad2014-12-18 12:10:08 -08001909 status_t ret;
1910 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001911 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001912 {
1913 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001914
Steven Morelandbf1915b2020-07-16 22:43:02 +00001915 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1916
Steven Morelandcf03cf12020-12-04 02:58:40 +00001917 testService->setInheritRt(true);
1918
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001919 /*
1920 * Normally would also contain functionality as well, but we are only
1921 * testing the extension mechanism.
1922 */
1923 testService->setExtension(new BBinder());
1924
Martijn Coenen82c75312019-07-24 15:18:30 +02001925 // Required for test "BufRejected'
1926 testService->setRequestingSid(true);
1927
Martijn Coenen45b07b42017-08-09 12:07:45 +02001928 /*
1929 * We need this below, but can't hold a sp<> because it prevents the
1930 * node from being cleaned up automatically. It's safe in this case
1931 * because of how the tests are written.
1932 */
1933 testServicePtr = testService.get();
1934
Riley Andrews06b01ad2014-12-18 12:10:08 -08001935 if (index == 0) {
1936 ret = sm->addService(binderLibTestServiceName, testService);
1937 } else {
1938 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1939 Parcel data, reply;
1940 data.writeInt32(index);
1941 data.writeStrongBinder(testService);
1942
1943 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1944 }
1945 }
1946 write(readypipefd, &ret, sizeof(ret));
1947 close(readypipefd);
1948 //printf("%s: ret %d\n", __func__, ret);
1949 if (ret)
1950 return 1;
1951 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001952 if (usePoll) {
1953 int fd;
1954 struct epoll_event ev;
1955 int epoll_fd;
1956 IPCThreadState::self()->setupPolling(&fd);
1957 if (fd < 0) {
1958 return 1;
1959 }
1960 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1961
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001962 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001963 if (epoll_fd == -1) {
1964 return 1;
1965 }
1966
1967 ev.events = EPOLLIN;
1968 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1969 return 1;
1970 }
1971
1972 while (1) {
1973 /*
1974 * We simulate a single-threaded process using the binder poll
1975 * interface; besides handling binder commands, it can also
1976 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001977 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001978 *
1979 * processPendingCall() will then issue that transaction.
1980 */
1981 struct epoll_event events[1];
1982 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1983 if (numEvents < 0) {
1984 if (errno == EINTR) {
1985 continue;
1986 }
1987 return 1;
1988 }
1989 if (numEvents > 0) {
1990 IPCThreadState::self()->handlePolledCommands();
1991 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1992 testServicePtr->processPendingCall();
1993 }
1994 }
1995 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001996 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001997 ProcessState::self()->startThreadPool();
1998 IPCThreadState::self()->joinThreadPool();
1999 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002000 //printf("%s: joinThreadPool returned\n", __func__);
2001 return 1; /* joinThreadPool should not return */
2002}
2003
2004int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07002005 ExitIfWrongAbi();
2006
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002007 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002008 binderservername = argv[2];
2009 } else {
2010 binderservername = argv[0];
2011 }
2012
Martijn Coenen45b07b42017-08-09 12:07:45 +02002013 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2014 binderserversuffix = argv[5];
2015 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002016 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002017 binderserversuffix = new char[16];
2018 snprintf(binderserversuffix, 16, "%d", getpid());
2019 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002020
2021 ::testing::InitGoogleTest(&argc, argv);
2022 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2023 ProcessState::self()->startThreadPool();
2024 return RUN_ALL_TESTS();
2025}