blob: 853be01a2a15c9e3be987d955a029f5620a3c68e [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
Riley Andrews06b01ad2014-12-18 12:10:08 -080052#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
53
54using namespace android;
Yifan Hong84bedeb2021-04-21 21:37:17 -070055using namespace std::string_literals;
56using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070057using android::base::testing::HasValue;
Yifan Hong8b890852021-06-10 13:44:09 -070058using android::base::testing::Ok;
Yifan Hong84bedeb2021-04-21 21:37:17 -070059using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080060using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070061using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070062using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070063
64// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
65MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
66 *result_listener << statusToString(arg);
67 return expected == arg;
68}
Riley Andrews06b01ad2014-12-18 12:10:08 -080069
Sherry Yang336cdd32017-07-24 14:12:27 -070070static ::testing::AssertionResult IsPageAligned(void *buf) {
71 if (((unsigned long)buf & ((unsigned long)PAGE_SIZE - 1)) == 0)
72 return ::testing::AssertionSuccess();
73 else
74 return ::testing::AssertionFailure() << buf << " is not page aligned";
75}
76
Riley Andrews06b01ad2014-12-18 12:10:08 -080077static testing::Environment* binder_env;
78static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070079static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080080static char binderserverarg[] = "--binderserver";
81
Steven Morelandbf1915b2020-07-16 22:43:02 +000082static constexpr int kSchedPolicy = SCHED_RR;
83static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000084static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000085static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000086
Riley Andrews06b01ad2014-12-18 12:10:08 -080087static String16 binderLibTestServiceName = String16("test.binderLib");
88
89enum BinderLibTestTranscationCode {
90 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
91 BINDER_LIB_TEST_REGISTER_SERVER,
92 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020093 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000094 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -080095 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -070096 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +020097 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -080098 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -070099 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800100 BINDER_LIB_TEST_GET_ID_TRANSACTION,
101 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
102 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
103 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
104 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
105 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
106 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900107 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800108 BINDER_LIB_TEST_EXIT_TRANSACTION,
109 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
110 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700111 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100112 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000113 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700114 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
115 BINDER_LIB_TEST_GETPID,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800116 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700117 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
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,
Devin Moore4354f712022-12-08 01:44:46 +0000122 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000123 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);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000216#pragma clang diagnostic push
217#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -0800218 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000219#pragma clang diagnostic pop
Yi Kong91635562018-06-07 14:38:36 -0700220 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800221 //printf("%s: pid %d, get service done\n", __func__, m_pid);
222 }
223 virtual void TearDown() {
224 status_t ret;
225 Parcel data, reply;
226 int exitStatus;
227 pid_t pid;
228
229 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700230 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800231 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
232 EXPECT_EQ(0, ret);
233 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
234 EXPECT_EQ(0, ret);
235 }
236 if (m_serverpid > 0) {
237 //printf("wait for %d\n", m_pids[i]);
238 pid = wait(&exitStatus);
239 EXPECT_EQ(m_serverpid, pid);
240 EXPECT_TRUE(WIFEXITED(exitStatus));
241 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
242 }
243 }
244
245 pid_t m_serverpid;
246 sp<IBinder> m_server;
247};
248
249class BinderLibTest : public ::testing::Test {
250 public:
251 virtual void SetUp() {
252 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000253 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800254 }
255 virtual void TearDown() {
256 }
257 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200258 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800259 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800260 int32_t id;
261 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800262
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700263 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800264
Elie Kheirallahb7246642022-05-03 18:01:43 +0000265 sp<IBinder> binder = reply.readStrongBinder();
266 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700267 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800268 if (idPtr)
269 *idPtr = id;
270 return binder;
271 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200272
Yi Kong91635562018-06-07 14:38:36 -0700273 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200274 {
275 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
276 }
277
Yi Kong91635562018-06-07 14:38:36 -0700278 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200279 {
280 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
281 }
282
Riley Andrews06b01ad2014-12-18 12:10:08 -0800283 void waitForReadData(int fd, int timeout_ms) {
284 int ret;
285 pollfd pfd = pollfd();
286
287 pfd.fd = fd;
288 pfd.events = POLLIN;
289 ret = poll(&pfd, 1, timeout_ms);
290 EXPECT_EQ(1, ret);
291 }
292
293 sp<IBinder> m_server;
294};
295
296class BinderLibTestBundle : public Parcel
297{
298 public:
299 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800300 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800301 int32_t mark;
302 int32_t bundleLen;
303 size_t pos;
304
305 if (source->readInt32(&mark))
306 return;
307 if (mark != MARK_START)
308 return;
309 if (source->readInt32(&bundleLen))
310 return;
311 pos = source->dataPosition();
312 if (Parcel::appendFrom(source, pos, bundleLen))
313 return;
314 source->setDataPosition(pos + bundleLen);
315 if (source->readInt32(&mark))
316 return;
317 if (mark != MARK_END)
318 return;
319 m_isValid = true;
320 setDataPosition(0);
321 }
322 void appendTo(Parcel *dest) {
323 dest->writeInt32(MARK_START);
324 dest->writeInt32(dataSize());
325 dest->appendFrom(this, 0, dataSize());
326 dest->writeInt32(MARK_END);
327 };
328 bool isValid(void) {
329 return m_isValid;
330 }
331 private:
332 enum {
333 MARK_START = B_PACK_CHARS('B','T','B','S'),
334 MARK_END = B_PACK_CHARS('B','T','B','E'),
335 };
336 bool m_isValid;
337};
338
339class BinderLibTestEvent
340{
341 public:
342 BinderLibTestEvent(void)
343 : m_eventTriggered(false)
344 {
Yi Kong91635562018-06-07 14:38:36 -0700345 pthread_mutex_init(&m_waitMutex, nullptr);
346 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800347 }
348 int waitEvent(int timeout_s)
349 {
350 int ret;
351 pthread_mutex_lock(&m_waitMutex);
352 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800353 struct timespec ts;
354 clock_gettime(CLOCK_REALTIME, &ts);
355 ts.tv_sec += timeout_s;
356 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800357 }
358 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
359 pthread_mutex_unlock(&m_waitMutex);
360 return ret;
361 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200362 pthread_t getTriggeringThread()
363 {
364 return m_triggeringThread;
365 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800366 protected:
367 void triggerEvent(void) {
368 pthread_mutex_lock(&m_waitMutex);
369 pthread_cond_signal(&m_waitCond);
370 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200371 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800372 pthread_mutex_unlock(&m_waitMutex);
373 };
374 private:
375 pthread_mutex_t m_waitMutex;
376 pthread_cond_t m_waitCond;
377 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200378 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800379};
380
381class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
382{
383 public:
384 BinderLibTestCallBack()
385 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700386 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800387 {
388 }
389 status_t getResult(void)
390 {
391 return m_result;
392 }
393
394 private:
395 virtual status_t onTransact(uint32_t code,
396 const Parcel& data, Parcel* reply,
397 uint32_t flags = 0)
398 {
399 (void)reply;
400 (void)flags;
401 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200402 case BINDER_LIB_TEST_CALL_BACK: {
403 status_t status = data.readInt32(&m_result);
404 if (status != NO_ERROR) {
405 m_result = status;
406 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800407 triggerEvent();
408 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200409 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700410 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
411 sp<IBinder> server;
412 int ret;
413 const uint8_t *buf = data.data();
414 size_t size = data.dataSize();
415 if (m_prev_end) {
416 /* 64-bit kernel needs at most 8 bytes to align buffer end */
417 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
418 } else {
419 EXPECT_TRUE(IsPageAligned((void *)buf));
420 }
421
422 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
423
424 if (size > 0) {
425 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
426 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
427 data, reply);
428 EXPECT_EQ(NO_ERROR, ret);
429 }
430 return NO_ERROR;
431 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800432 default:
433 return UNKNOWN_TRANSACTION;
434 }
435 }
436
437 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700438 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800439};
440
441class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
442{
443 private:
444 virtual void binderDied(const wp<IBinder>& who) {
445 (void)who;
446 triggerEvent();
447 };
448};
449
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700450TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
451 // EXPECT_DEATH works by forking the process
452 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
453}
454
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000455TEST_F(BinderLibTest, AddManagerToManager) {
456 sp<IServiceManager> sm = defaultServiceManager();
457 sp<IBinder> binder = IInterface::asBinder(sm);
458 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
459}
460
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500461TEST_F(BinderLibTest, WasParceled) {
462 auto binder = sp<BBinder>::make();
463 EXPECT_FALSE(binder->wasParceled());
464 Parcel data;
465 data.writeStrongBinder(binder);
466 EXPECT_TRUE(binder->wasParceled());
467}
468
Riley Andrews06b01ad2014-12-18 12:10:08 -0800469TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800470 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700471 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
472 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800473}
474
Steven Moreland80844f72020-12-12 02:06:08 +0000475TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000476 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700477 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
478 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000479}
480
Steven Morelandf183fdd2020-10-27 00:12:12 +0000481TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000482 Parcel data, reply;
483 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700484 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
485 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000486}
487
Marco Ballesio7ee17572020-09-08 10:30:03 -0700488TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700489 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700490 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700491
Li Li6f059292021-09-10 09:59:30 -0700492 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700493 if (freezer_file.fail()) {
494 GTEST_SKIP();
495 return;
496 }
497
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700498 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700499 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700500 for (int i = 0; i < 10; i++) {
501 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
502 }
Li Li6f059292021-09-10 09:59:30 -0700503
504 // Pass test on devices where BINDER_FREEZE ioctl is not supported
505 int ret = IPCThreadState::self()->freeze(pid, false, 0);
506 if (ret != 0) {
507 GTEST_SKIP();
508 return;
509 }
510
511 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000512
513 // b/268232063 - succeeds ~0.08% of the time
514 {
515 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
516 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
517 }
518
Li Li6f059292021-09-10 09:59:30 -0700519 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700520 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700521
Li Li4e678b92021-09-14 12:14:42 -0700522 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700523
524 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
525 &async_received));
526
527 EXPECT_EQ(sync_received, 1);
528 EXPECT_EQ(async_received, 0);
529
Li Li4e678b92021-09-14 12:14:42 -0700530 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700531 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
532}
533
Riley Andrews06b01ad2014-12-18 12:10:08 -0800534TEST_F(BinderLibTest, SetError) {
535 int32_t testValue[] = { 0, -123, 123 };
536 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800537 Parcel data, reply;
538 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700539 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
540 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800541 }
542}
543
544TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700545 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800546}
547
548TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800549 int32_t ptrsize;
550 Parcel data, reply;
551 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700552 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700553 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
554 StatusEq(NO_ERROR));
555 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800556 RecordProperty("TestPtrSize", sizeof(void *));
557 RecordProperty("ServerPtrSize", sizeof(void *));
558}
559
560TEST_F(BinderLibTest, IndirectGetId2)
561{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800562 int32_t id;
563 int32_t count;
564 Parcel data, reply;
565 int32_t serverId[3];
566
567 data.writeInt32(ARRAY_SIZE(serverId));
568 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
569 sp<IBinder> server;
570 BinderLibTestBundle datai;
571
572 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700573 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800574 data.writeStrongBinder(server);
575 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
576 datai.appendTo(&data);
577 }
578
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700579 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
580 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800581
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700582 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800583 EXPECT_EQ(0, id);
584
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700585 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700586 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800587
588 for (size_t i = 0; i < (size_t)count; i++) {
589 BinderLibTestBundle replyi(&reply);
590 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700591 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800592 EXPECT_EQ(serverId[i], id);
593 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
594 }
595
596 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
597}
598
599TEST_F(BinderLibTest, IndirectGetId3)
600{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800601 int32_t id;
602 int32_t count;
603 Parcel data, reply;
604 int32_t serverId[3];
605
606 data.writeInt32(ARRAY_SIZE(serverId));
607 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
608 sp<IBinder> server;
609 BinderLibTestBundle datai;
610 BinderLibTestBundle datai2;
611
612 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700613 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800614 data.writeStrongBinder(server);
615 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
616
617 datai.writeInt32(1);
618 datai.writeStrongBinder(m_server);
619 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
620 datai2.appendTo(&datai);
621
622 datai.appendTo(&data);
623 }
624
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700625 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
626 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800627
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700628 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800629 EXPECT_EQ(0, id);
630
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700631 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700632 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800633
634 for (size_t i = 0; i < (size_t)count; i++) {
635 int32_t counti;
636
637 BinderLibTestBundle replyi(&reply);
638 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700639 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800640 EXPECT_EQ(serverId[i], id);
641
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700642 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800643 EXPECT_EQ(1, counti);
644
645 BinderLibTestBundle replyi2(&replyi);
646 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700647 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800648 EXPECT_EQ(0, id);
649 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
650
651 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
652 }
653
654 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
655}
656
657TEST_F(BinderLibTest, CallBack)
658{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800659 Parcel data, reply;
660 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
661 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700662 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
663 StatusEq(NO_ERROR));
664 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
665 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800666}
667
Steven Moreland35626652021-05-15 01:32:04 +0000668TEST_F(BinderLibTest, BinderCallContextGuard) {
669 sp<IBinder> binder = addServer();
670 Parcel data, reply;
671 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
672 StatusEq(DEAD_OBJECT));
673}
674
Riley Andrews06b01ad2014-12-18 12:10:08 -0800675TEST_F(BinderLibTest, AddServer)
676{
677 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700678 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800679}
680
Riley Andrews06b01ad2014-12-18 12:10:08 -0800681TEST_F(BinderLibTest, DeathNotificationStrongRef)
682{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800683 sp<IBinder> sbinder;
684
685 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
686
687 {
688 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700689 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700690 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800691 sbinder = binder;
692 }
693 {
694 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700695 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
696 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800697 }
698 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700699 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
700 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800701}
702
703TEST_F(BinderLibTest, DeathNotificationMultiple)
704{
705 status_t ret;
706 const int clientcount = 2;
707 sp<IBinder> target;
708 sp<IBinder> linkedclient[clientcount];
709 sp<BinderLibTestCallBack> callBack[clientcount];
710 sp<IBinder> passiveclient[clientcount];
711
712 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700713 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800714 for (int i = 0; i < clientcount; i++) {
715 {
716 Parcel data, reply;
717
718 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700719 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800720 callBack[i] = new BinderLibTestCallBack();
721 data.writeStrongBinder(target);
722 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700723 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
724 &reply, TF_ONE_WAY),
725 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800726 }
727 {
728 Parcel data, reply;
729
730 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700731 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800732 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700733 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
734 &reply, TF_ONE_WAY),
735 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800736 }
737 }
738 {
739 Parcel data, reply;
740 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
741 EXPECT_EQ(0, ret);
742 }
743
744 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700745 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
746 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800747 }
748}
749
Martijn Coenenf7100e42017-07-31 12:14:09 +0200750TEST_F(BinderLibTest, DeathNotificationThread)
751{
752 status_t ret;
753 sp<BinderLibTestCallBack> callback;
754 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700755 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200756 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700757 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200758
759 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
760
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700761 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200762
763 {
764 Parcel data, reply;
765 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
766 EXPECT_EQ(0, ret);
767 }
768
769 /* Make sure it's dead */
770 testDeathRecipient->waitEvent(5);
771
772 /* Now, pass the ref to another process and ask that process to
773 * call linkToDeath() on it, and wait for a response. This tests
774 * two things:
775 * 1) You still get death notifications when calling linkToDeath()
776 * on a ref that is already dead when it was passed to you.
777 * 2) That death notifications are not directly pushed to the thread
778 * registering them, but to the threadpool (proc workqueue) instead.
779 *
780 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
781 * is blocked on a condition variable waiting for the death notification to be
782 * called; therefore, that thread is not available for handling proc work.
783 * So, if the death notification was pushed to the thread workqueue, the callback
784 * would never be called, and the test would timeout and fail.
785 *
786 * Note that we can't do this part of the test from this thread itself, because
787 * the binder driver would only push death notifications to the thread if
788 * it is a looper thread, which this thread is not.
789 *
790 * See b/23525545 for details.
791 */
792 {
793 Parcel data, reply;
794
795 callback = new BinderLibTestCallBack();
796 data.writeStrongBinder(target);
797 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700798 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
799 TF_ONE_WAY),
800 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200801 }
802
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700803 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
804 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200805}
806
Riley Andrews06b01ad2014-12-18 12:10:08 -0800807TEST_F(BinderLibTest, PassFile) {
808 int ret;
809 int pipefd[2];
810 uint8_t buf[1] = { 0 };
811 uint8_t write_value = 123;
812
813 ret = pipe2(pipefd, O_NONBLOCK);
814 ASSERT_EQ(0, ret);
815
816 {
817 Parcel data, reply;
818 uint8_t writebuf[1] = { write_value };
819
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700820 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800821
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700822 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800823
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700824 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800825
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700826 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
827 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800828 }
829
830 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700831 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800832 EXPECT_EQ(write_value, buf[0]);
833
834 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
835
836 ret = read(pipefd[0], buf, sizeof(buf));
837 EXPECT_EQ(0, ret);
838
839 close(pipefd[0]);
840}
841
Ryo Hashimotobf551892018-05-31 16:58:35 +0900842TEST_F(BinderLibTest, PassParcelFileDescriptor) {
843 const int datasize = 123;
844 std::vector<uint8_t> writebuf(datasize);
845 for (size_t i = 0; i < writebuf.size(); ++i) {
846 writebuf[i] = i;
847 }
848
849 android::base::unique_fd read_end, write_end;
850 {
851 int pipefd[2];
852 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
853 read_end.reset(pipefd[0]);
854 write_end.reset(pipefd[1]);
855 }
856 {
857 Parcel data;
858 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
859 write_end.reset();
860 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
861 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
862
863 Parcel reply;
864 EXPECT_EQ(NO_ERROR,
865 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
866 &reply));
867 }
868 std::vector<uint8_t> readbuf(datasize);
869 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
870 EXPECT_EQ(writebuf, readbuf);
871
872 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
873
874 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
875}
876
Riley Andrews06b01ad2014-12-18 12:10:08 -0800877TEST_F(BinderLibTest, PromoteLocal) {
878 sp<IBinder> strong = new BBinder();
879 wp<IBinder> weak = strong;
880 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700881 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800882 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700883 strong = nullptr;
884 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800885 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700886 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800887}
888
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700889TEST_F(BinderLibTest, LocalGetExtension) {
890 sp<BBinder> binder = new BBinder();
891 sp<IBinder> ext = new BBinder();
892 binder->setExtension(ext);
893 EXPECT_EQ(ext, binder->getExtension());
894}
895
896TEST_F(BinderLibTest, RemoteGetExtension) {
897 sp<IBinder> server = addServer();
898 ASSERT_TRUE(server != nullptr);
899
900 sp<IBinder> extension;
901 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
902 ASSERT_NE(nullptr, extension.get());
903
904 EXPECT_EQ(NO_ERROR, extension->pingBinder());
905}
906
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700907TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700908 Parcel data, reply;
909
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700910 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
911 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700912
913 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700914 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800915 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
916 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
917 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
918 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700919}
920
Connor O'Brien52be2c92016-09-20 14:18:08 -0700921TEST_F(BinderLibTest, FreedBinder) {
922 status_t ret;
923
924 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700925 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700926
927 __u32 freedHandle;
928 wp<IBinder> keepFreedBinder;
929 {
930 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700931 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
932 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700933 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
934 freedHandle = freed->handle;
935 /* Add a weak ref to the freed binder so the driver does not
936 * delete its reference to it - otherwise the transaction
937 * fails regardless of whether the driver is fixed.
938 */
Steven Morelande171d622019-07-17 16:06:01 -0700939 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700940 }
Steven Morelande171d622019-07-17 16:06:01 -0700941 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700942 {
943 Parcel data, reply;
944 data.writeStrongBinder(server);
945 /* Replace original handle with handle to the freed binder */
946 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
947 __u32 oldHandle = strong->handle;
948 strong->handle = freedHandle;
949 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
950 /* Returns DEAD_OBJECT (-32) if target crashes and
951 * FAILED_TRANSACTION if the driver rejects the invalid
952 * object.
953 */
954 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
955 /* Restore original handle so parcel destructor does not use
956 * the wrong handle.
957 */
958 strong->handle = oldHandle;
959 }
960}
961
Sherry Yang336cdd32017-07-24 14:12:27 -0700962TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700963 Parcel data, reply;
964 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
965 for (int i = 0; i < 2; i++) {
966 BinderLibTestBundle datai;
967 datai.appendFrom(&data, 0, data.dataSize());
968
969 data.freeData();
970 data.writeInt32(1);
971 data.writeStrongBinder(callBack);
972 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
973
974 datai.appendTo(&data);
975 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700976 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
977 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700978}
979
Martijn Coenen45b07b42017-08-09 12:07:45 +0200980TEST_F(BinderLibTest, OnewayQueueing)
981{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200982 Parcel data, data2;
983
984 sp<IBinder> pollServer = addPollServer();
985
986 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
987 data.writeStrongBinder(callBack);
988 data.writeInt32(500000); // delay in us before calling back
989
990 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
991 data2.writeStrongBinder(callBack2);
992 data2.writeInt32(0); // delay in us
993
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700994 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
995 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200996
997 // The delay ensures that this second transaction will end up on the async_todo list
998 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700999 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1000 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001001
1002 // The server will ensure that the two transactions are handled in the expected order;
1003 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001004 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1005 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001006
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001007 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1008 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001009}
1010
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001011TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1012{
1013 status_t ret;
1014 Parcel data, reply;
1015 data.writeInterfaceToken(binderLibTestServiceName);
1016 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1017 EXPECT_EQ(-1, reply.readInt32());
1018 EXPECT_EQ(NO_ERROR, ret);
1019}
1020
1021TEST_F(BinderLibTest, WorkSourceSet)
1022{
1023 status_t ret;
1024 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001025 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001026 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001027 data.writeInterfaceToken(binderLibTestServiceName);
1028 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1029 EXPECT_EQ(100, reply.readInt32());
1030 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001031 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1032 EXPECT_EQ(NO_ERROR, ret);
1033}
1034
1035TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1036{
1037 status_t ret;
1038 Parcel data, reply;
1039
1040 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1041 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1042
1043 data.writeInterfaceToken(binderLibTestServiceName);
1044 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1045 EXPECT_EQ(-1, reply.readInt32());
1046 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001047 EXPECT_EQ(NO_ERROR, ret);
1048}
1049
1050TEST_F(BinderLibTest, WorkSourceCleared)
1051{
1052 status_t ret;
1053 Parcel data, reply;
1054
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001055 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001056 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1057 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001058 data.writeInterfaceToken(binderLibTestServiceName);
1059 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1060
1061 EXPECT_EQ(-1, reply.readInt32());
1062 EXPECT_EQ(100, previousWorkSource);
1063 EXPECT_EQ(NO_ERROR, ret);
1064}
1065
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001066TEST_F(BinderLibTest, WorkSourceRestored)
1067{
1068 status_t ret;
1069 Parcel data, reply;
1070
1071 IPCThreadState::self()->setCallingWorkSourceUid(100);
1072 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1073 IPCThreadState::self()->restoreCallingWorkSource(token);
1074
1075 data.writeInterfaceToken(binderLibTestServiceName);
1076 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1077
1078 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001079 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001080 EXPECT_EQ(NO_ERROR, ret);
1081}
1082
Olivier Gaillard91a04802018-11-14 17:32:41 +00001083TEST_F(BinderLibTest, PropagateFlagSet)
1084{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001085 IPCThreadState::self()->clearPropagateWorkSource();
1086 IPCThreadState::self()->setCallingWorkSourceUid(100);
1087 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1088}
1089
1090TEST_F(BinderLibTest, PropagateFlagCleared)
1091{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001092 IPCThreadState::self()->setCallingWorkSourceUid(100);
1093 IPCThreadState::self()->clearPropagateWorkSource();
1094 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1095}
1096
1097TEST_F(BinderLibTest, PropagateFlagRestored)
1098{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001099 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1100 IPCThreadState::self()->restoreCallingWorkSource(token);
1101
1102 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1103}
1104
1105TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1106{
1107 IPCThreadState::self()->setCallingWorkSourceUid(100);
1108
1109 Parcel data, reply;
1110 status_t ret;
1111 data.writeInterfaceToken(binderLibTestServiceName);
1112 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001113 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001114
1115 Parcel data2, reply2;
1116 status_t ret2;
1117 data2.writeInterfaceToken(binderLibTestServiceName);
1118 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1119 EXPECT_EQ(100, reply2.readInt32());
1120 EXPECT_EQ(NO_ERROR, ret2);
1121}
1122
Steven Morelandbf1915b2020-07-16 22:43:02 +00001123TEST_F(BinderLibTest, SchedPolicySet) {
1124 sp<IBinder> server = addServer();
1125 ASSERT_TRUE(server != nullptr);
1126
1127 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001128 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1129 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001130
1131 int policy = reply.readInt32();
1132 int priority = reply.readInt32();
1133
1134 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1135 EXPECT_EQ(kSchedPriority, priority);
1136}
1137
Steven Morelandcf03cf12020-12-04 02:58:40 +00001138TEST_F(BinderLibTest, InheritRt) {
1139 sp<IBinder> server = addServer();
1140 ASSERT_TRUE(server != nullptr);
1141
1142 const struct sched_param param {
1143 .sched_priority = kSchedPriorityMore,
1144 };
1145 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1146
1147 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001148 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1149 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001150
1151 int policy = reply.readInt32();
1152 int priority = reply.readInt32();
1153
1154 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1155 EXPECT_EQ(kSchedPriorityMore, priority);
1156}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001157
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001158TEST_F(BinderLibTest, VectorSent) {
1159 Parcel data, reply;
1160 sp<IBinder> server = addServer();
1161 ASSERT_TRUE(server != nullptr);
1162
1163 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1164 data.writeUint64Vector(testValue);
1165
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001166 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001167 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001168 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001169 EXPECT_EQ(readValue, testValue);
1170}
1171
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001172TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1173 sp<IBinder> server = addServer();
1174 ASSERT_TRUE(server != nullptr);
1175
1176 Parcel reply;
1177 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1178 StatusEq(NO_ERROR));
1179 base::unique_fd fd;
1180 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1181
1182 const int result = fcntl(fd.get(), F_GETFL);
1183 ASSERT_NE(result, -1);
1184 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1185}
1186
Steven Moreland59b84442022-07-12 18:32:44 +00001187// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1188// This value is not exposed, but some code in the framework relies on being able to use
1189// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001190constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001191constexpr size_t kSizeBytesOverFull = 1'050'000;
1192
1193TEST_F(BinderLibTest, GargantuanVectorSent) {
1194 sp<IBinder> server = addServer();
1195 ASSERT_TRUE(server != nullptr);
1196
1197 for (size_t i = 0; i < 10; i++) {
1198 // a slight variation in size is used to consider certain possible caching implementations
1199 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1200
1201 Parcel data, reply;
1202 data.writeUint64Vector(testValue);
1203 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1204 << i;
1205 std::vector<uint64_t> readValue;
1206 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1207 EXPECT_EQ(readValue, testValue);
1208 }
1209}
1210
1211TEST_F(BinderLibTest, LimitExceededVectorSent) {
1212 sp<IBinder> server = addServer();
1213 ASSERT_TRUE(server != nullptr);
1214 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1215
1216 Parcel data, reply;
1217 data.writeUint64Vector(testValue);
1218 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1219 StatusEq(FAILED_TRANSACTION));
1220}
1221
Martijn Coenen82c75312019-07-24 15:18:30 +02001222TEST_F(BinderLibTest, BufRejected) {
1223 Parcel data, reply;
1224 uint32_t buf;
1225 sp<IBinder> server = addServer();
1226 ASSERT_TRUE(server != nullptr);
1227
1228 binder_buffer_object obj {
1229 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001230 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001231 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1232 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001233 };
1234 data.setDataCapacity(1024);
1235 // Write a bogus object at offset 0 to get an entry in the offset table
1236 data.writeFileDescriptor(0);
1237 EXPECT_EQ(data.objectsCount(), 1);
1238 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1239 // And now, overwrite it with the buffer object
1240 memcpy(parcelData, &obj, sizeof(obj));
1241 data.setDataSize(sizeof(obj));
1242
Steven Morelandf2e0a952021-11-01 18:17:23 -07001243 EXPECT_EQ(data.objectsCount(), 1);
1244
Martijn Coenen82c75312019-07-24 15:18:30 +02001245 // Either the kernel should reject this transaction (if it's correct), but
1246 // if it's not, the server implementation should return an error if it
1247 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001248 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001249 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001250}
1251
Steven Morelandf2e0a952021-11-01 18:17:23 -07001252TEST_F(BinderLibTest, WeakRejected) {
1253 Parcel data, reply;
1254 sp<IBinder> server = addServer();
1255 ASSERT_TRUE(server != nullptr);
1256
1257 auto binder = sp<BBinder>::make();
1258 wp<BBinder> wpBinder(binder);
1259 flat_binder_object obj{
1260 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1261 .flags = 0,
1262 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1263 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1264 };
1265 data.setDataCapacity(1024);
1266 // Write a bogus object at offset 0 to get an entry in the offset table
1267 data.writeFileDescriptor(0);
1268 EXPECT_EQ(data.objectsCount(), 1);
1269 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1270 // And now, overwrite it with the weak binder
1271 memcpy(parcelData, &obj, sizeof(obj));
1272 data.setDataSize(sizeof(obj));
1273
1274 // a previous bug caused other objects to be released an extra time, so we
1275 // test with an object that libbinder will actually try to release
1276 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1277
1278 EXPECT_EQ(data.objectsCount(), 2);
1279
1280 // send it many times, since previous error was memory corruption, make it
1281 // more likely that the server crashes
1282 for (size_t i = 0; i < 100; i++) {
1283 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1284 StatusEq(BAD_VALUE));
1285 }
1286
1287 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1288}
1289
Steven Moreland254e8ef2021-04-19 22:28:50 +00001290TEST_F(BinderLibTest, GotSid) {
1291 sp<IBinder> server = addServer();
1292
1293 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001294 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001295}
1296
Andrei Homescu1519b982022-06-09 02:04:44 +00001297struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1298 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1299
1300 // Flattenable protocol
1301 size_t getFlattenedSize() const {
1302 // Return a valid non-zero size here so we don't get an unintended
1303 // BAD_VALUE from Parcel::write
1304 return 16;
1305 }
1306 size_t getFdCount() const { return mFdCount; }
1307 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1308 for (size_t i = 0; i < count; i++) {
1309 fds[i] = STDIN_FILENO;
1310 }
1311 return NO_ERROR;
1312 }
1313 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1314 size_t & /*count*/) {
1315 /* This doesn't get called */
1316 return NO_ERROR;
1317 }
1318
1319 size_t mFdCount;
1320};
1321
1322TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1323 rlimit origNofile;
1324 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1325 ASSERT_EQ(0, ret);
1326
1327 // Restore the original file limits when the test finishes
1328 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1329
1330 rlimit testNofile = {1024, 1024};
1331 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1332 ASSERT_EQ(0, ret);
1333
1334 Parcel parcel;
1335 // Try to write more file descriptors than supported by the OS
1336 TooManyFdsFlattenable tooManyFds1(1024);
1337 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1338
1339 // Try to write more file descriptors than the internal limit
1340 TooManyFdsFlattenable tooManyFds2(1025);
1341 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1342}
1343
Jayant Chowdhary30700942022-01-31 14:12:40 -08001344TEST(ServiceNotifications, Unregister) {
1345 auto sm = defaultServiceManager();
1346 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1347 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1348 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1349 virtual ~LocalRegistrationCallbackImpl() {}
1350 };
1351 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1352
1353 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1354 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1355}
1356
Elie Kheirallah47431c12022-04-21 23:46:17 +00001357TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1358 Parcel data, reply;
1359 sp<IBinder> server = addServer();
1360 ASSERT_TRUE(server != nullptr);
1361 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1362 StatusEq(NO_ERROR));
1363 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001364 // see getThreadPoolMaxTotalThreadCount for why there is a race
1365 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1366
Elie Kheirallah47431c12022-04-21 23:46:17 +00001367 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1368
1369 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001370 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1371 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1372 * started threads from setThreadPoolMaxThreadCount
1373 *
1374 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001375 */
1376 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001377 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001378 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001379 Parcel local_reply;
1380 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1381 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001382 }));
1383 }
1384
Steven Moreland3e9debc2023-06-15 00:35:29 +00001385 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1386 // the time, the below call will pre-empt them (presumably because we have the
1387 // scheduler timeslice already + scheduler hint).
1388 sleep(1);
1389
1390 data.writeInt32(1000);
1391 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001392 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1393
1394 for (auto &t : ts) {
1395 t.join();
1396 }
1397
1398 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1399 StatusEq(NO_ERROR));
1400 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001401 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001402}
1403
Devin Moore4354f712022-12-08 01:44:46 +00001404TEST_F(BinderLibTest, ThreadPoolStarted) {
1405 Parcel data, reply;
1406 sp<IBinder> server = addServer();
1407 ASSERT_TRUE(server != nullptr);
1408 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1409 EXPECT_TRUE(reply.readBool());
1410}
1411
Elie Kheirallah47431c12022-04-21 23:46:17 +00001412size_t epochMillis() {
1413 using std::chrono::duration_cast;
1414 using std::chrono::milliseconds;
1415 using std::chrono::seconds;
1416 using std::chrono::system_clock;
1417 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1418}
1419
1420TEST_F(BinderLibTest, HangingServices) {
1421 Parcel data, reply;
1422 sp<IBinder> server = addServer();
1423 ASSERT_TRUE(server != nullptr);
1424 int32_t delay = 1000; // ms
1425 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001426 // b/266537959 - must take before taking lock, since countdown is started in the remote
1427 // process there.
1428 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001429 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1430 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001431 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1432 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001433 Parcel local_reply;
1434 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1435 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001436 }));
1437 }
1438
1439 for (auto &t : ts) {
1440 t.join();
1441 }
1442 size_t epochMsAfter = epochMillis();
1443
1444 // deadlock occurred and threads only finished after 1s passed.
1445 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1446}
1447
Yifan Hong84bedeb2021-04-21 21:37:17 -07001448class BinderLibRpcTestBase : public BinderLibTest {
1449public:
1450 void SetUp() override {
1451 if (!base::GetBoolProperty("ro.debuggable", false)) {
1452 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1453 "non-debuggable builds.";
1454 }
1455 BinderLibTest::SetUp();
1456 }
1457
1458 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1459 auto rpcServer = RpcServer::make();
1460 EXPECT_NE(nullptr, rpcServer);
1461 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001462 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001463 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1464 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001465 return {};
1466 }
1467 return {rpcServer->releaseServer(), port};
1468 }
1469};
1470
Yifan Hong8b890852021-06-10 13:44:09 -07001471class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001472
Yifan Hongbd276552022-02-28 15:28:51 -08001473// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1474// If device is debuggable AND not on user builds, expects matcher.
1475// Otherwise expects INVALID_OPERATION.
1476// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1477static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1478 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1479 android::base::GetProperty("ro.build.type", "") != "user";
1480 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1481}
1482
Yifan Hong8b890852021-06-10 13:44:09 -07001483TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1484 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001485 ASSERT_TRUE(binder != nullptr);
1486 auto [socket, port] = CreateSocket();
1487 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001488 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1489 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001490}
1491
Yifan Hong8b890852021-06-10 13:44:09 -07001492// Tests for multiple RpcServer's on the same binder object.
1493TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1494 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001495 ASSERT_TRUE(binder != nullptr);
1496
1497 auto [socket1, port1] = CreateSocket();
1498 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001499 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001500 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1501 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001502
1503 auto [socket2, port2] = CreateSocket();
1504 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001505 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001506 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1507 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001508}
1509
Yifan Hong8b890852021-06-10 13:44:09 -07001510// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1511// local binders.
1512class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001513public:
1514 sp<IBinder> GetService() {
1515 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1516 }
1517 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1518 return info.param ? "remote" : "local";
1519 }
1520};
1521
Yifan Hong8b890852021-06-10 13:44:09 -07001522TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1523 auto binder = GetService();
1524 ASSERT_TRUE(binder != nullptr);
1525 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001526 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001527}
1528
1529TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001530 auto binder = GetService();
1531 ASSERT_TRUE(binder != nullptr);
1532 auto [socket, port] = CreateSocket();
1533 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001534 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1535 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001536}
Yifan Hong8b890852021-06-10 13:44:09 -07001537INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1538 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001539
Yifan Hong543edcd2021-05-18 19:47:30 -07001540class BinderLibTestService : public BBinder {
1541public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001542 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1543 : m_id(id),
1544 m_nextServerId(id + 1),
1545 m_serverStartRequested(false),
1546 m_callback(nullptr),
1547 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001548 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1549 pthread_cond_init(&m_serverWaitCond, nullptr);
1550 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001551 ~BinderLibTestService() {
1552 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1553 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001554
Yifan Hong543edcd2021-05-18 19:47:30 -07001555 void processPendingCall() {
1556 if (m_callback != nullptr) {
1557 Parcel data;
1558 data.writeInt32(NO_ERROR);
1559 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1560 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001561 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001562 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001563
Yifan Hong543edcd2021-05-18 19:47:30 -07001564 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1565 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001566 // TODO(b/182914638): also checks getCallingUid() for RPC
1567 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001568 return PERMISSION_DENIED;
1569 }
1570 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001571 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001572 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001573 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001574 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001575 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001576 return BAD_VALUE;
1577 }
1578
Yifan Hong543edcd2021-05-18 19:47:30 -07001579 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001580
1581 pthread_mutex_lock(&m_serverWaitMutex);
1582 if (m_serverStartRequested) {
1583 m_serverStartRequested = false;
1584 m_serverStarted = binder;
1585 pthread_cond_signal(&m_serverWaitCond);
1586 }
1587 pthread_mutex_unlock(&m_serverWaitMutex);
1588 return NO_ERROR;
1589 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001590 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001591 case BINDER_LIB_TEST_ADD_SERVER: {
1592 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001593 int serverid;
1594
1595 if (m_id != 0) {
1596 return INVALID_OPERATION;
1597 }
1598 pthread_mutex_lock(&m_serverWaitMutex);
1599 if (m_serverStartRequested) {
1600 ret = -EBUSY;
1601 } else {
1602 serverid = m_nextServerId++;
1603 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001604 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001605
1606 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001607 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001608 pthread_mutex_lock(&m_serverWaitMutex);
1609 }
1610 if (ret > 0) {
1611 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001612 struct timespec ts;
1613 clock_gettime(CLOCK_REALTIME, &ts);
1614 ts.tv_sec += 5;
1615 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001616 }
1617 if (m_serverStartRequested) {
1618 m_serverStartRequested = false;
1619 ret = -ETIMEDOUT;
1620 } else {
1621 reply->writeStrongBinder(m_serverStarted);
1622 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001623 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001624 ret = NO_ERROR;
1625 }
1626 } else if (ret >= 0) {
1627 m_serverStartRequested = false;
1628 ret = UNKNOWN_ERROR;
1629 }
1630 pthread_mutex_unlock(&m_serverWaitMutex);
1631 return ret;
1632 }
Steven Moreland35626652021-05-15 01:32:04 +00001633 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1634 IPCThreadState::SpGuard spGuard{
1635 .address = __builtin_frame_address(0),
1636 .context = "GuardInBinderTransaction",
1637 };
1638 const IPCThreadState::SpGuard *origGuard =
1639 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1640
1641 // if the guard works, this should abort
1642 (void)IPCThreadState::self()->getCallingPid();
1643
1644 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1645 return NO_ERROR;
1646 }
1647
Marco Ballesio7ee17572020-09-08 10:30:03 -07001648 case BINDER_LIB_TEST_GETPID:
1649 reply->writeInt32(getpid());
1650 return NO_ERROR;
1651 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1652 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001653 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001654 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001655 // oneway error codes should be ignored
1656 if (flags & TF_ONE_WAY) {
1657 return UNKNOWN_ERROR;
1658 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001659 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001660 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1661 // Note: this transaction is only designed for use with a
1662 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001663 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001664 // A callback was already pending; this means that
1665 // we received a second call while still processing
1666 // the first one. Fail the test.
1667 sp<IBinder> callback = data.readStrongBinder();
1668 Parcel data2;
1669 data2.writeInt32(UNKNOWN_ERROR);
1670
Yi Kong91635562018-06-07 14:38:36 -07001671 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001672 } else {
1673 m_callback = data.readStrongBinder();
1674 int32_t delayUs = data.readInt32();
1675 /*
1676 * It's necessary that we sleep here, so the next
1677 * transaction the caller makes will be queued to
1678 * the async queue.
1679 */
1680 usleep(delayUs);
1681
1682 /*
1683 * Now when we return, libbinder will tell the kernel
1684 * we are done with this transaction, and the kernel
1685 * can move the queued transaction to either the
1686 * thread todo worklist (for kernels without the fix),
1687 * or the proc todo worklist. In case of the former,
1688 * the next outbound call will pick up the pending
1689 * transaction, which leads to undesired reentrant
1690 * behavior. This is caught in the if() branch above.
1691 */
1692 }
1693
1694 return NO_ERROR;
1695 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001696 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1697 Parcel data2, reply2;
1698 sp<IBinder> binder;
1699 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001700 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001701 return BAD_VALUE;
1702 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001703 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001704 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1705 return NO_ERROR;
1706 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001707 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1708 reply->writeStrongBinder(this);
1709 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001710 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1711 reply->writeInt32(m_id);
1712 return NO_ERROR;
1713 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1714 int32_t count;
1715 uint32_t indirect_code;
1716 sp<IBinder> binder;
1717
1718 count = data.readInt32();
1719 reply->writeInt32(m_id);
1720 reply->writeInt32(count);
1721 for (int i = 0; i < count; i++) {
1722 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001723 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001724 return BAD_VALUE;
1725 }
1726 indirect_code = data.readInt32();
1727 BinderLibTestBundle data2(&data);
1728 if (!data2.isValid()) {
1729 return BAD_VALUE;
1730 }
1731 BinderLibTestBundle reply2;
1732 binder->transact(indirect_code, data2, &reply2);
1733 reply2.appendTo(reply);
1734 }
1735 return NO_ERROR;
1736 }
1737 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1738 reply->setError(data.readInt32());
1739 return NO_ERROR;
1740 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1741 reply->writeInt32(sizeof(void *));
1742 return NO_ERROR;
1743 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1744 return NO_ERROR;
1745 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1746 m_strongRef = data.readStrongBinder();
1747 return NO_ERROR;
1748 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1749 int ret;
1750 Parcel data2, reply2;
1751 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1752 sp<IBinder> target;
1753 sp<IBinder> callback;
1754
1755 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001756 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001757 return BAD_VALUE;
1758 }
1759 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001760 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001761 return BAD_VALUE;
1762 }
1763 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001764 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001765 data2.writeInt32(ret);
1766 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1767 return NO_ERROR;
1768 }
1769 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1770 int ret;
1771 int32_t size;
1772 const void *buf;
1773 int fd;
1774
1775 fd = data.readFileDescriptor();
1776 if (fd < 0) {
1777 return BAD_VALUE;
1778 }
1779 ret = data.readInt32(&size);
1780 if (ret != NO_ERROR) {
1781 return ret;
1782 }
1783 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001784 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001785 return BAD_VALUE;
1786 }
1787 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001788 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001789 return NO_ERROR;
1790 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001791 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1792 int ret;
1793 int32_t size;
1794 const void *buf;
1795 android::base::unique_fd fd;
1796
1797 ret = data.readUniqueParcelFileDescriptor(&fd);
1798 if (ret != NO_ERROR) {
1799 return ret;
1800 }
1801 ret = data.readInt32(&size);
1802 if (ret != NO_ERROR) {
1803 return ret;
1804 }
1805 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001806 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001807 return BAD_VALUE;
1808 }
1809 ret = write(fd.get(), buf, size);
1810 if (ret != size) return UNKNOWN_ERROR;
1811 return NO_ERROR;
1812 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001813 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1814 alarm(10);
1815 return NO_ERROR;
1816 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001817 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001818 ;
1819 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001820 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001821 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001822 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001823 return NO_ERROR;
1824 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001825 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1826 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001827 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001828 return NO_ERROR;
1829 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001830 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1831 int policy = 0;
1832 sched_param param;
1833 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1834 return UNKNOWN_ERROR;
1835 }
1836 reply->writeInt32(policy);
1837 reply->writeInt32(param.sched_priority);
1838 return NO_ERROR;
1839 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001840 case BINDER_LIB_TEST_ECHO_VECTOR: {
1841 std::vector<uint64_t> vector;
1842 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001843 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001844 reply->writeUint64Vector(vector);
1845 return NO_ERROR;
1846 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001847 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1848 std::array<int, 2> sockets;
1849 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1850 if (!created) {
1851 ALOGE("Could not create socket pair");
1852 return UNKNOWN_ERROR;
1853 }
1854
1855 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1856 if (result != 0) {
1857 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1858 return UNKNOWN_ERROR;
1859 }
1860 base::unique_fd out(sockets[0]);
1861 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1862 if (writeResult != NO_ERROR) {
1863 ALOGE("Could not write unique_fd");
1864 return writeResult;
1865 }
1866 close(sockets[1]); // we don't need the other side of the fd
1867 return NO_ERROR;
1868 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001869 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001870 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1871 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001872 case BINDER_LIB_TEST_CAN_GET_SID: {
1873 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1874 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001875 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1876 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1877 return NO_ERROR;
1878 }
Devin Moore4354f712022-12-08 01:44:46 +00001879 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1880 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1881 return NO_ERROR;
1882 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001883 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001884 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001885 return NO_ERROR;
1886 }
1887 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001888 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001889 return NO_ERROR;
1890 }
1891 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1892 int32_t ms = data.readInt32();
1893 return unlockInMs(ms);
1894 }
1895 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001896 m_blockMutex.lock();
1897 sp<BinderLibTestService> thisService = this;
1898 int32_t value = data.readInt32();
1899 // start local thread to unlock in 1s
1900 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001901 t.detach();
1902 return NO_ERROR;
1903 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001904 default:
1905 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001906 };
1907 }
1908
Elie Kheirallah47431c12022-04-21 23:46:17 +00001909 status_t unlockInMs(int32_t ms) {
1910 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001911 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001912 return NO_ERROR;
1913 }
1914
Yifan Hong543edcd2021-05-18 19:47:30 -07001915private:
1916 int32_t m_id;
1917 int32_t m_nextServerId;
1918 pthread_mutex_t m_serverWaitMutex;
1919 pthread_cond_t m_serverWaitCond;
1920 bool m_serverStartRequested;
1921 sp<IBinder> m_serverStarted;
1922 sp<IBinder> m_strongRef;
1923 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001924 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001925 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001926};
1927
Martijn Coenen45b07b42017-08-09 12:07:45 +02001928int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001929{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001930 binderLibTestServiceName += String16(binderserversuffix);
1931
Steven Moreland35626652021-05-15 01:32:04 +00001932 // Testing to make sure that calls that we are serving can use getCallin*
1933 // even though we don't here.
1934 IPCThreadState::SpGuard spGuard{
1935 .address = __builtin_frame_address(0),
1936 .context = "main server thread",
1937 };
1938 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1939
Riley Andrews06b01ad2014-12-18 12:10:08 -08001940 status_t ret;
1941 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001942 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001943 {
1944 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001945
Steven Morelandbf1915b2020-07-16 22:43:02 +00001946 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1947
Steven Morelandcf03cf12020-12-04 02:58:40 +00001948 testService->setInheritRt(true);
1949
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001950 /*
1951 * Normally would also contain functionality as well, but we are only
1952 * testing the extension mechanism.
1953 */
1954 testService->setExtension(new BBinder());
1955
Martijn Coenen82c75312019-07-24 15:18:30 +02001956 // Required for test "BufRejected'
1957 testService->setRequestingSid(true);
1958
Martijn Coenen45b07b42017-08-09 12:07:45 +02001959 /*
1960 * We need this below, but can't hold a sp<> because it prevents the
1961 * node from being cleaned up automatically. It's safe in this case
1962 * because of how the tests are written.
1963 */
1964 testServicePtr = testService.get();
1965
Riley Andrews06b01ad2014-12-18 12:10:08 -08001966 if (index == 0) {
1967 ret = sm->addService(binderLibTestServiceName, testService);
1968 } else {
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001969#pragma clang diagnostic push
1970#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -08001971 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001972#pragma clang diagnostic pop
Riley Andrews06b01ad2014-12-18 12:10:08 -08001973 Parcel data, reply;
1974 data.writeInt32(index);
1975 data.writeStrongBinder(testService);
1976
1977 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1978 }
1979 }
1980 write(readypipefd, &ret, sizeof(ret));
1981 close(readypipefd);
1982 //printf("%s: ret %d\n", __func__, ret);
1983 if (ret)
1984 return 1;
1985 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001986 if (usePoll) {
1987 int fd;
1988 struct epoll_event ev;
1989 int epoll_fd;
1990 IPCThreadState::self()->setupPolling(&fd);
1991 if (fd < 0) {
1992 return 1;
1993 }
1994 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1995
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001996 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001997 if (epoll_fd == -1) {
1998 return 1;
1999 }
2000
2001 ev.events = EPOLLIN;
2002 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2003 return 1;
2004 }
2005
2006 while (1) {
2007 /*
2008 * We simulate a single-threaded process using the binder poll
2009 * interface; besides handling binder commands, it can also
2010 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002011 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002012 *
2013 * processPendingCall() will then issue that transaction.
2014 */
2015 struct epoll_event events[1];
2016 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2017 if (numEvents < 0) {
2018 if (errno == EINTR) {
2019 continue;
2020 }
2021 return 1;
2022 }
2023 if (numEvents > 0) {
2024 IPCThreadState::self()->handlePolledCommands();
2025 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2026 testServicePtr->processPendingCall();
2027 }
2028 }
2029 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002030 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002031 ProcessState::self()->startThreadPool();
2032 IPCThreadState::self()->joinThreadPool();
2033 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002034 //printf("%s: joinThreadPool returned\n", __func__);
2035 return 1; /* joinThreadPool should not return */
2036}
2037
Steven Moreland68275d72023-04-21 22:12:45 +00002038int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002039 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002040 binderservername = argv[2];
2041 } else {
2042 binderservername = argv[0];
2043 }
2044
Martijn Coenen45b07b42017-08-09 12:07:45 +02002045 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2046 binderserversuffix = argv[5];
2047 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002048 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002049 binderserversuffix = new char[16];
2050 snprintf(binderserversuffix, 16, "%d", getpid());
2051 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002052
2053 ::testing::InitGoogleTest(&argc, argv);
2054 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2055 ProcessState::self()->startThreadPool();
2056 return RUN_ALL_TESTS();
2057}