blob: e021af026435a94e9736cae11e6acb7f8d59a0ea [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);
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));
Steven Morelandee739eb2023-02-13 21:03:49 +0000509
510 // b/268232063 - succeeds ~0.08% of the time
511 {
512 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
513 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
514 }
515
Li Li6f059292021-09-10 09:59:30 -0700516 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700517 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700518
Li Li4e678b92021-09-14 12:14:42 -0700519 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700520
521 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
522 &async_received));
523
524 EXPECT_EQ(sync_received, 1);
525 EXPECT_EQ(async_received, 0);
526
Li Li4e678b92021-09-14 12:14:42 -0700527 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700528 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
529}
530
Riley Andrews06b01ad2014-12-18 12:10:08 -0800531TEST_F(BinderLibTest, SetError) {
532 int32_t testValue[] = { 0, -123, 123 };
533 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800534 Parcel data, reply;
535 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700536 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
537 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800538 }
539}
540
541TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700542 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800543}
544
545TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800546 int32_t ptrsize;
547 Parcel data, reply;
548 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700549 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700550 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
551 StatusEq(NO_ERROR));
552 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800553 RecordProperty("TestPtrSize", sizeof(void *));
554 RecordProperty("ServerPtrSize", sizeof(void *));
555}
556
557TEST_F(BinderLibTest, IndirectGetId2)
558{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800559 int32_t id;
560 int32_t count;
561 Parcel data, reply;
562 int32_t serverId[3];
563
564 data.writeInt32(ARRAY_SIZE(serverId));
565 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
566 sp<IBinder> server;
567 BinderLibTestBundle datai;
568
569 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700570 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800571 data.writeStrongBinder(server);
572 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
573 datai.appendTo(&data);
574 }
575
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700576 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
577 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800578
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700579 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800580 EXPECT_EQ(0, id);
581
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700582 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700583 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800584
585 for (size_t i = 0; i < (size_t)count; i++) {
586 BinderLibTestBundle replyi(&reply);
587 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700588 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800589 EXPECT_EQ(serverId[i], id);
590 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
591 }
592
593 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
594}
595
596TEST_F(BinderLibTest, IndirectGetId3)
597{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800598 int32_t id;
599 int32_t count;
600 Parcel data, reply;
601 int32_t serverId[3];
602
603 data.writeInt32(ARRAY_SIZE(serverId));
604 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
605 sp<IBinder> server;
606 BinderLibTestBundle datai;
607 BinderLibTestBundle datai2;
608
609 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700610 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800611 data.writeStrongBinder(server);
612 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
613
614 datai.writeInt32(1);
615 datai.writeStrongBinder(m_server);
616 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
617 datai2.appendTo(&datai);
618
619 datai.appendTo(&data);
620 }
621
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700622 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
623 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800624
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700625 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800626 EXPECT_EQ(0, id);
627
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700628 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700629 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800630
631 for (size_t i = 0; i < (size_t)count; i++) {
632 int32_t counti;
633
634 BinderLibTestBundle replyi(&reply);
635 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700636 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800637 EXPECT_EQ(serverId[i], id);
638
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700639 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800640 EXPECT_EQ(1, counti);
641
642 BinderLibTestBundle replyi2(&replyi);
643 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700644 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800645 EXPECT_EQ(0, id);
646 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
647
648 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
649 }
650
651 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
652}
653
654TEST_F(BinderLibTest, CallBack)
655{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800656 Parcel data, reply;
657 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
658 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700659 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
660 StatusEq(NO_ERROR));
661 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
662 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800663}
664
Steven Moreland35626652021-05-15 01:32:04 +0000665TEST_F(BinderLibTest, BinderCallContextGuard) {
666 sp<IBinder> binder = addServer();
667 Parcel data, reply;
668 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
669 StatusEq(DEAD_OBJECT));
670}
671
Riley Andrews06b01ad2014-12-18 12:10:08 -0800672TEST_F(BinderLibTest, AddServer)
673{
674 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700675 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800676}
677
Riley Andrews06b01ad2014-12-18 12:10:08 -0800678TEST_F(BinderLibTest, DeathNotificationStrongRef)
679{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800680 sp<IBinder> sbinder;
681
682 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
683
684 {
685 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700686 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700687 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800688 sbinder = binder;
689 }
690 {
691 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700692 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
693 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800694 }
695 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700696 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
697 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800698}
699
700TEST_F(BinderLibTest, DeathNotificationMultiple)
701{
702 status_t ret;
703 const int clientcount = 2;
704 sp<IBinder> target;
705 sp<IBinder> linkedclient[clientcount];
706 sp<BinderLibTestCallBack> callBack[clientcount];
707 sp<IBinder> passiveclient[clientcount];
708
709 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700710 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800711 for (int i = 0; i < clientcount; i++) {
712 {
713 Parcel data, reply;
714
715 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700716 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800717 callBack[i] = new BinderLibTestCallBack();
718 data.writeStrongBinder(target);
719 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700720 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
721 &reply, TF_ONE_WAY),
722 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800723 }
724 {
725 Parcel data, reply;
726
727 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700728 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800729 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700730 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
731 &reply, TF_ONE_WAY),
732 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800733 }
734 }
735 {
736 Parcel data, reply;
737 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
738 EXPECT_EQ(0, ret);
739 }
740
741 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700742 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
743 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800744 }
745}
746
Martijn Coenenf7100e42017-07-31 12:14:09 +0200747TEST_F(BinderLibTest, DeathNotificationThread)
748{
749 status_t ret;
750 sp<BinderLibTestCallBack> callback;
751 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700752 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200753 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700754 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200755
756 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
757
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700758 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200759
760 {
761 Parcel data, reply;
762 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
763 EXPECT_EQ(0, ret);
764 }
765
766 /* Make sure it's dead */
767 testDeathRecipient->waitEvent(5);
768
769 /* Now, pass the ref to another process and ask that process to
770 * call linkToDeath() on it, and wait for a response. This tests
771 * two things:
772 * 1) You still get death notifications when calling linkToDeath()
773 * on a ref that is already dead when it was passed to you.
774 * 2) That death notifications are not directly pushed to the thread
775 * registering them, but to the threadpool (proc workqueue) instead.
776 *
777 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
778 * is blocked on a condition variable waiting for the death notification to be
779 * called; therefore, that thread is not available for handling proc work.
780 * So, if the death notification was pushed to the thread workqueue, the callback
781 * would never be called, and the test would timeout and fail.
782 *
783 * Note that we can't do this part of the test from this thread itself, because
784 * the binder driver would only push death notifications to the thread if
785 * it is a looper thread, which this thread is not.
786 *
787 * See b/23525545 for details.
788 */
789 {
790 Parcel data, reply;
791
792 callback = new BinderLibTestCallBack();
793 data.writeStrongBinder(target);
794 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700795 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
796 TF_ONE_WAY),
797 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200798 }
799
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700800 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
801 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200802}
803
Riley Andrews06b01ad2014-12-18 12:10:08 -0800804TEST_F(BinderLibTest, PassFile) {
805 int ret;
806 int pipefd[2];
807 uint8_t buf[1] = { 0 };
808 uint8_t write_value = 123;
809
810 ret = pipe2(pipefd, O_NONBLOCK);
811 ASSERT_EQ(0, ret);
812
813 {
814 Parcel data, reply;
815 uint8_t writebuf[1] = { write_value };
816
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700817 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800818
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700819 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800820
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700821 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800822
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700823 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
824 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800825 }
826
827 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700828 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800829 EXPECT_EQ(write_value, buf[0]);
830
831 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
832
833 ret = read(pipefd[0], buf, sizeof(buf));
834 EXPECT_EQ(0, ret);
835
836 close(pipefd[0]);
837}
838
Ryo Hashimotobf551892018-05-31 16:58:35 +0900839TEST_F(BinderLibTest, PassParcelFileDescriptor) {
840 const int datasize = 123;
841 std::vector<uint8_t> writebuf(datasize);
842 for (size_t i = 0; i < writebuf.size(); ++i) {
843 writebuf[i] = i;
844 }
845
846 android::base::unique_fd read_end, write_end;
847 {
848 int pipefd[2];
849 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
850 read_end.reset(pipefd[0]);
851 write_end.reset(pipefd[1]);
852 }
853 {
854 Parcel data;
855 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
856 write_end.reset();
857 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
858 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
859
860 Parcel reply;
861 EXPECT_EQ(NO_ERROR,
862 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
863 &reply));
864 }
865 std::vector<uint8_t> readbuf(datasize);
866 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
867 EXPECT_EQ(writebuf, readbuf);
868
869 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
870
871 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
872}
873
Riley Andrews06b01ad2014-12-18 12:10:08 -0800874TEST_F(BinderLibTest, PromoteLocal) {
875 sp<IBinder> strong = new BBinder();
876 wp<IBinder> weak = strong;
877 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700878 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800879 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700880 strong = nullptr;
881 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800882 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700883 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800884}
885
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700886TEST_F(BinderLibTest, LocalGetExtension) {
887 sp<BBinder> binder = new BBinder();
888 sp<IBinder> ext = new BBinder();
889 binder->setExtension(ext);
890 EXPECT_EQ(ext, binder->getExtension());
891}
892
893TEST_F(BinderLibTest, RemoteGetExtension) {
894 sp<IBinder> server = addServer();
895 ASSERT_TRUE(server != nullptr);
896
897 sp<IBinder> extension;
898 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
899 ASSERT_NE(nullptr, extension.get());
900
901 EXPECT_EQ(NO_ERROR, extension->pingBinder());
902}
903
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700904TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700905 Parcel data, reply;
906
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700907 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
908 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700909
910 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700911 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800912 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
913 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
914 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
915 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700916}
917
Connor O'Brien52be2c92016-09-20 14:18:08 -0700918TEST_F(BinderLibTest, FreedBinder) {
919 status_t ret;
920
921 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700922 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700923
924 __u32 freedHandle;
925 wp<IBinder> keepFreedBinder;
926 {
927 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700928 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
929 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700930 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
931 freedHandle = freed->handle;
932 /* Add a weak ref to the freed binder so the driver does not
933 * delete its reference to it - otherwise the transaction
934 * fails regardless of whether the driver is fixed.
935 */
Steven Morelande171d622019-07-17 16:06:01 -0700936 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700937 }
Steven Morelande171d622019-07-17 16:06:01 -0700938 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700939 {
940 Parcel data, reply;
941 data.writeStrongBinder(server);
942 /* Replace original handle with handle to the freed binder */
943 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
944 __u32 oldHandle = strong->handle;
945 strong->handle = freedHandle;
946 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
947 /* Returns DEAD_OBJECT (-32) if target crashes and
948 * FAILED_TRANSACTION if the driver rejects the invalid
949 * object.
950 */
951 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
952 /* Restore original handle so parcel destructor does not use
953 * the wrong handle.
954 */
955 strong->handle = oldHandle;
956 }
957}
958
Sherry Yang336cdd32017-07-24 14:12:27 -0700959TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700960 Parcel data, reply;
961 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
962 for (int i = 0; i < 2; i++) {
963 BinderLibTestBundle datai;
964 datai.appendFrom(&data, 0, data.dataSize());
965
966 data.freeData();
967 data.writeInt32(1);
968 data.writeStrongBinder(callBack);
969 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
970
971 datai.appendTo(&data);
972 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700973 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
974 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700975}
976
Martijn Coenen45b07b42017-08-09 12:07:45 +0200977TEST_F(BinderLibTest, OnewayQueueing)
978{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200979 Parcel data, data2;
980
981 sp<IBinder> pollServer = addPollServer();
982
983 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
984 data.writeStrongBinder(callBack);
985 data.writeInt32(500000); // delay in us before calling back
986
987 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
988 data2.writeStrongBinder(callBack2);
989 data2.writeInt32(0); // delay in us
990
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700991 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
992 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200993
994 // The delay ensures that this second transaction will end up on the async_todo list
995 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700996 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
997 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200998
999 // The server will ensure that the two transactions are handled in the expected order;
1000 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001001 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1002 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001003
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001004 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1005 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001006}
1007
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001008TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1009{
1010 status_t ret;
1011 Parcel data, reply;
1012 data.writeInterfaceToken(binderLibTestServiceName);
1013 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1014 EXPECT_EQ(-1, reply.readInt32());
1015 EXPECT_EQ(NO_ERROR, ret);
1016}
1017
1018TEST_F(BinderLibTest, WorkSourceSet)
1019{
1020 status_t ret;
1021 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001022 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001023 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001024 data.writeInterfaceToken(binderLibTestServiceName);
1025 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1026 EXPECT_EQ(100, reply.readInt32());
1027 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001028 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1029 EXPECT_EQ(NO_ERROR, ret);
1030}
1031
1032TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1033{
1034 status_t ret;
1035 Parcel data, reply;
1036
1037 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1038 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1039
1040 data.writeInterfaceToken(binderLibTestServiceName);
1041 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1042 EXPECT_EQ(-1, reply.readInt32());
1043 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001044 EXPECT_EQ(NO_ERROR, ret);
1045}
1046
1047TEST_F(BinderLibTest, WorkSourceCleared)
1048{
1049 status_t ret;
1050 Parcel data, reply;
1051
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001052 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001053 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1054 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001055 data.writeInterfaceToken(binderLibTestServiceName);
1056 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1057
1058 EXPECT_EQ(-1, reply.readInt32());
1059 EXPECT_EQ(100, previousWorkSource);
1060 EXPECT_EQ(NO_ERROR, ret);
1061}
1062
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001063TEST_F(BinderLibTest, WorkSourceRestored)
1064{
1065 status_t ret;
1066 Parcel data, reply;
1067
1068 IPCThreadState::self()->setCallingWorkSourceUid(100);
1069 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1070 IPCThreadState::self()->restoreCallingWorkSource(token);
1071
1072 data.writeInterfaceToken(binderLibTestServiceName);
1073 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1074
1075 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001076 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001077 EXPECT_EQ(NO_ERROR, ret);
1078}
1079
Olivier Gaillard91a04802018-11-14 17:32:41 +00001080TEST_F(BinderLibTest, PropagateFlagSet)
1081{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001082 IPCThreadState::self()->clearPropagateWorkSource();
1083 IPCThreadState::self()->setCallingWorkSourceUid(100);
1084 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1085}
1086
1087TEST_F(BinderLibTest, PropagateFlagCleared)
1088{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001089 IPCThreadState::self()->setCallingWorkSourceUid(100);
1090 IPCThreadState::self()->clearPropagateWorkSource();
1091 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1092}
1093
1094TEST_F(BinderLibTest, PropagateFlagRestored)
1095{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001096 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1097 IPCThreadState::self()->restoreCallingWorkSource(token);
1098
1099 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1100}
1101
1102TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1103{
1104 IPCThreadState::self()->setCallingWorkSourceUid(100);
1105
1106 Parcel data, reply;
1107 status_t ret;
1108 data.writeInterfaceToken(binderLibTestServiceName);
1109 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1110
1111 Parcel data2, reply2;
1112 status_t ret2;
1113 data2.writeInterfaceToken(binderLibTestServiceName);
1114 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1115 EXPECT_EQ(100, reply2.readInt32());
1116 EXPECT_EQ(NO_ERROR, ret2);
1117}
1118
Steven Morelandbf1915b2020-07-16 22:43:02 +00001119TEST_F(BinderLibTest, SchedPolicySet) {
1120 sp<IBinder> server = addServer();
1121 ASSERT_TRUE(server != nullptr);
1122
1123 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001124 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1125 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001126
1127 int policy = reply.readInt32();
1128 int priority = reply.readInt32();
1129
1130 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1131 EXPECT_EQ(kSchedPriority, priority);
1132}
1133
Steven Morelandcf03cf12020-12-04 02:58:40 +00001134TEST_F(BinderLibTest, InheritRt) {
1135 sp<IBinder> server = addServer();
1136 ASSERT_TRUE(server != nullptr);
1137
1138 const struct sched_param param {
1139 .sched_priority = kSchedPriorityMore,
1140 };
1141 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1142
1143 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001144 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1145 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001146
1147 int policy = reply.readInt32();
1148 int priority = reply.readInt32();
1149
1150 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1151 EXPECT_EQ(kSchedPriorityMore, priority);
1152}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001153
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001154TEST_F(BinderLibTest, VectorSent) {
1155 Parcel data, reply;
1156 sp<IBinder> server = addServer();
1157 ASSERT_TRUE(server != nullptr);
1158
1159 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1160 data.writeUint64Vector(testValue);
1161
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001162 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001163 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001164 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001165 EXPECT_EQ(readValue, testValue);
1166}
1167
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001168TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1169 sp<IBinder> server = addServer();
1170 ASSERT_TRUE(server != nullptr);
1171
1172 Parcel reply;
1173 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1174 StatusEq(NO_ERROR));
1175 base::unique_fd fd;
1176 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1177
1178 const int result = fcntl(fd.get(), F_GETFL);
1179 ASSERT_NE(result, -1);
1180 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1181}
1182
Steven Moreland59b84442022-07-12 18:32:44 +00001183// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1184// This value is not exposed, but some code in the framework relies on being able to use
1185// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001186constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001187constexpr size_t kSizeBytesOverFull = 1'050'000;
1188
1189TEST_F(BinderLibTest, GargantuanVectorSent) {
1190 sp<IBinder> server = addServer();
1191 ASSERT_TRUE(server != nullptr);
1192
1193 for (size_t i = 0; i < 10; i++) {
1194 // a slight variation in size is used to consider certain possible caching implementations
1195 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1196
1197 Parcel data, reply;
1198 data.writeUint64Vector(testValue);
1199 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1200 << i;
1201 std::vector<uint64_t> readValue;
1202 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1203 EXPECT_EQ(readValue, testValue);
1204 }
1205}
1206
1207TEST_F(BinderLibTest, LimitExceededVectorSent) {
1208 sp<IBinder> server = addServer();
1209 ASSERT_TRUE(server != nullptr);
1210 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1211
1212 Parcel data, reply;
1213 data.writeUint64Vector(testValue);
1214 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1215 StatusEq(FAILED_TRANSACTION));
1216}
1217
Martijn Coenen82c75312019-07-24 15:18:30 +02001218TEST_F(BinderLibTest, BufRejected) {
1219 Parcel data, reply;
1220 uint32_t buf;
1221 sp<IBinder> server = addServer();
1222 ASSERT_TRUE(server != nullptr);
1223
1224 binder_buffer_object obj {
1225 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001226 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001227 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1228 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001229 };
1230 data.setDataCapacity(1024);
1231 // Write a bogus object at offset 0 to get an entry in the offset table
1232 data.writeFileDescriptor(0);
1233 EXPECT_EQ(data.objectsCount(), 1);
1234 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1235 // And now, overwrite it with the buffer object
1236 memcpy(parcelData, &obj, sizeof(obj));
1237 data.setDataSize(sizeof(obj));
1238
Steven Morelandf2e0a952021-11-01 18:17:23 -07001239 EXPECT_EQ(data.objectsCount(), 1);
1240
Martijn Coenen82c75312019-07-24 15:18:30 +02001241 // Either the kernel should reject this transaction (if it's correct), but
1242 // if it's not, the server implementation should return an error if it
1243 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001244 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001245 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001246}
1247
Steven Morelandf2e0a952021-11-01 18:17:23 -07001248TEST_F(BinderLibTest, WeakRejected) {
1249 Parcel data, reply;
1250 sp<IBinder> server = addServer();
1251 ASSERT_TRUE(server != nullptr);
1252
1253 auto binder = sp<BBinder>::make();
1254 wp<BBinder> wpBinder(binder);
1255 flat_binder_object obj{
1256 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1257 .flags = 0,
1258 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1259 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1260 };
1261 data.setDataCapacity(1024);
1262 // Write a bogus object at offset 0 to get an entry in the offset table
1263 data.writeFileDescriptor(0);
1264 EXPECT_EQ(data.objectsCount(), 1);
1265 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1266 // And now, overwrite it with the weak binder
1267 memcpy(parcelData, &obj, sizeof(obj));
1268 data.setDataSize(sizeof(obj));
1269
1270 // a previous bug caused other objects to be released an extra time, so we
1271 // test with an object that libbinder will actually try to release
1272 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1273
1274 EXPECT_EQ(data.objectsCount(), 2);
1275
1276 // send it many times, since previous error was memory corruption, make it
1277 // more likely that the server crashes
1278 for (size_t i = 0; i < 100; i++) {
1279 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1280 StatusEq(BAD_VALUE));
1281 }
1282
1283 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1284}
1285
Steven Moreland254e8ef2021-04-19 22:28:50 +00001286TEST_F(BinderLibTest, GotSid) {
1287 sp<IBinder> server = addServer();
1288
1289 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001290 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001291}
1292
Andrei Homescu1519b982022-06-09 02:04:44 +00001293struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1294 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1295
1296 // Flattenable protocol
1297 size_t getFlattenedSize() const {
1298 // Return a valid non-zero size here so we don't get an unintended
1299 // BAD_VALUE from Parcel::write
1300 return 16;
1301 }
1302 size_t getFdCount() const { return mFdCount; }
1303 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1304 for (size_t i = 0; i < count; i++) {
1305 fds[i] = STDIN_FILENO;
1306 }
1307 return NO_ERROR;
1308 }
1309 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1310 size_t & /*count*/) {
1311 /* This doesn't get called */
1312 return NO_ERROR;
1313 }
1314
1315 size_t mFdCount;
1316};
1317
1318TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1319 rlimit origNofile;
1320 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1321 ASSERT_EQ(0, ret);
1322
1323 // Restore the original file limits when the test finishes
1324 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1325
1326 rlimit testNofile = {1024, 1024};
1327 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1328 ASSERT_EQ(0, ret);
1329
1330 Parcel parcel;
1331 // Try to write more file descriptors than supported by the OS
1332 TooManyFdsFlattenable tooManyFds1(1024);
1333 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1334
1335 // Try to write more file descriptors than the internal limit
1336 TooManyFdsFlattenable tooManyFds2(1025);
1337 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1338}
1339
Jayant Chowdhary30700942022-01-31 14:12:40 -08001340TEST(ServiceNotifications, Unregister) {
1341 auto sm = defaultServiceManager();
1342 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1343 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1344 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1345 virtual ~LocalRegistrationCallbackImpl() {}
1346 };
1347 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1348
1349 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1350 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1351}
1352
Elie Kheirallah47431c12022-04-21 23:46:17 +00001353TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1354 Parcel data, reply;
1355 sp<IBinder> server = addServer();
1356 ASSERT_TRUE(server != nullptr);
1357 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1358 StatusEq(NO_ERROR));
1359 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001360 // see getThreadPoolMaxTotalThreadCount for why there is a race
1361 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1362
Elie Kheirallah47431c12022-04-21 23:46:17 +00001363 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1364
1365 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001366 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1367 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1368 * started threads from setThreadPoolMaxThreadCount
1369 *
1370 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001371 */
1372 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001373 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001374 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001375 Parcel local_reply;
1376 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1377 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001378 }));
1379 }
1380
Steven Moreland3e9debc2023-06-15 00:35:29 +00001381 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1382 // the time, the below call will pre-empt them (presumably because we have the
1383 // scheduler timeslice already + scheduler hint).
1384 sleep(1);
1385
1386 data.writeInt32(1000);
1387 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001388 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1389
1390 for (auto &t : ts) {
1391 t.join();
1392 }
1393
1394 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1395 StatusEq(NO_ERROR));
1396 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001397 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001398}
1399
Devin Moore4354f712022-12-08 01:44:46 +00001400TEST_F(BinderLibTest, ThreadPoolStarted) {
1401 Parcel data, reply;
1402 sp<IBinder> server = addServer();
1403 ASSERT_TRUE(server != nullptr);
1404 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1405 EXPECT_TRUE(reply.readBool());
1406}
1407
Elie Kheirallah47431c12022-04-21 23:46:17 +00001408size_t epochMillis() {
1409 using std::chrono::duration_cast;
1410 using std::chrono::milliseconds;
1411 using std::chrono::seconds;
1412 using std::chrono::system_clock;
1413 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1414}
1415
1416TEST_F(BinderLibTest, HangingServices) {
1417 Parcel data, reply;
1418 sp<IBinder> server = addServer();
1419 ASSERT_TRUE(server != nullptr);
1420 int32_t delay = 1000; // ms
1421 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001422 // b/266537959 - must take before taking lock, since countdown is started in the remote
1423 // process there.
1424 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001425 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1426 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001427 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1428 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001429 Parcel local_reply;
1430 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1431 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001432 }));
1433 }
1434
1435 for (auto &t : ts) {
1436 t.join();
1437 }
1438 size_t epochMsAfter = epochMillis();
1439
1440 // deadlock occurred and threads only finished after 1s passed.
1441 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1442}
1443
Yifan Hong84bedeb2021-04-21 21:37:17 -07001444class BinderLibRpcTestBase : public BinderLibTest {
1445public:
1446 void SetUp() override {
1447 if (!base::GetBoolProperty("ro.debuggable", false)) {
1448 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1449 "non-debuggable builds.";
1450 }
1451 BinderLibTest::SetUp();
1452 }
1453
1454 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1455 auto rpcServer = RpcServer::make();
1456 EXPECT_NE(nullptr, rpcServer);
1457 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001458 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001459 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1460 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001461 return {};
1462 }
1463 return {rpcServer->releaseServer(), port};
1464 }
1465};
1466
Yifan Hong8b890852021-06-10 13:44:09 -07001467class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001468
Yifan Hongbd276552022-02-28 15:28:51 -08001469// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1470// If device is debuggable AND not on user builds, expects matcher.
1471// Otherwise expects INVALID_OPERATION.
1472// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1473static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1474 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1475 android::base::GetProperty("ro.build.type", "") != "user";
1476 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1477}
1478
Yifan Hong8b890852021-06-10 13:44:09 -07001479TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1480 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001481 ASSERT_TRUE(binder != nullptr);
1482 auto [socket, port] = CreateSocket();
1483 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001484 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1485 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001486}
1487
Yifan Hong8b890852021-06-10 13:44:09 -07001488// Tests for multiple RpcServer's on the same binder object.
1489TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1490 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001491 ASSERT_TRUE(binder != nullptr);
1492
1493 auto [socket1, port1] = CreateSocket();
1494 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001495 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001496 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1497 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001498
1499 auto [socket2, port2] = CreateSocket();
1500 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001501 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001502 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1503 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001504}
1505
Yifan Hong8b890852021-06-10 13:44:09 -07001506// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1507// local binders.
1508class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001509public:
1510 sp<IBinder> GetService() {
1511 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1512 }
1513 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1514 return info.param ? "remote" : "local";
1515 }
1516};
1517
Yifan Hong8b890852021-06-10 13:44:09 -07001518TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1519 auto binder = GetService();
1520 ASSERT_TRUE(binder != nullptr);
1521 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001522 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001523}
1524
1525TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001526 auto binder = GetService();
1527 ASSERT_TRUE(binder != nullptr);
1528 auto [socket, port] = CreateSocket();
1529 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001530 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1531 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001532}
Yifan Hong8b890852021-06-10 13:44:09 -07001533INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1534 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001535
Yifan Hong543edcd2021-05-18 19:47:30 -07001536class BinderLibTestService : public BBinder {
1537public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001538 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1539 : m_id(id),
1540 m_nextServerId(id + 1),
1541 m_serverStartRequested(false),
1542 m_callback(nullptr),
1543 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001544 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1545 pthread_cond_init(&m_serverWaitCond, nullptr);
1546 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001547 ~BinderLibTestService() {
1548 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1549 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001550
Yifan Hong543edcd2021-05-18 19:47:30 -07001551 void processPendingCall() {
1552 if (m_callback != nullptr) {
1553 Parcel data;
1554 data.writeInt32(NO_ERROR);
1555 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1556 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001557 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001558 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001559
Yifan Hong543edcd2021-05-18 19:47:30 -07001560 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1561 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001562 // TODO(b/182914638): also checks getCallingUid() for RPC
1563 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001564 return PERMISSION_DENIED;
1565 }
1566 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001567 case BINDER_LIB_TEST_REGISTER_SERVER: {
1568 int32_t id;
1569 sp<IBinder> binder;
1570 id = data.readInt32();
1571 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001572 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001573 return BAD_VALUE;
1574 }
1575
Yifan Hong543edcd2021-05-18 19:47:30 -07001576 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001577
1578 pthread_mutex_lock(&m_serverWaitMutex);
1579 if (m_serverStartRequested) {
1580 m_serverStartRequested = false;
1581 m_serverStarted = binder;
1582 pthread_cond_signal(&m_serverWaitCond);
1583 }
1584 pthread_mutex_unlock(&m_serverWaitMutex);
1585 return NO_ERROR;
1586 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001587 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001588 case BINDER_LIB_TEST_ADD_SERVER: {
1589 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001590 int serverid;
1591
1592 if (m_id != 0) {
1593 return INVALID_OPERATION;
1594 }
1595 pthread_mutex_lock(&m_serverWaitMutex);
1596 if (m_serverStartRequested) {
1597 ret = -EBUSY;
1598 } else {
1599 serverid = m_nextServerId++;
1600 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001601 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001602
1603 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001604 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001605 pthread_mutex_lock(&m_serverWaitMutex);
1606 }
1607 if (ret > 0) {
1608 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001609 struct timespec ts;
1610 clock_gettime(CLOCK_REALTIME, &ts);
1611 ts.tv_sec += 5;
1612 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001613 }
1614 if (m_serverStartRequested) {
1615 m_serverStartRequested = false;
1616 ret = -ETIMEDOUT;
1617 } else {
1618 reply->writeStrongBinder(m_serverStarted);
1619 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001620 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001621 ret = NO_ERROR;
1622 }
1623 } else if (ret >= 0) {
1624 m_serverStartRequested = false;
1625 ret = UNKNOWN_ERROR;
1626 }
1627 pthread_mutex_unlock(&m_serverWaitMutex);
1628 return ret;
1629 }
Steven Moreland35626652021-05-15 01:32:04 +00001630 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1631 IPCThreadState::SpGuard spGuard{
1632 .address = __builtin_frame_address(0),
1633 .context = "GuardInBinderTransaction",
1634 };
1635 const IPCThreadState::SpGuard *origGuard =
1636 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1637
1638 // if the guard works, this should abort
1639 (void)IPCThreadState::self()->getCallingPid();
1640
1641 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1642 return NO_ERROR;
1643 }
1644
Marco Ballesio7ee17572020-09-08 10:30:03 -07001645 case BINDER_LIB_TEST_GETPID:
1646 reply->writeInt32(getpid());
1647 return NO_ERROR;
1648 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1649 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001650 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001651 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001652 // oneway error codes should be ignored
1653 if (flags & TF_ONE_WAY) {
1654 return UNKNOWN_ERROR;
1655 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001656 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001657 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1658 // Note: this transaction is only designed for use with a
1659 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001660 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001661 // A callback was already pending; this means that
1662 // we received a second call while still processing
1663 // the first one. Fail the test.
1664 sp<IBinder> callback = data.readStrongBinder();
1665 Parcel data2;
1666 data2.writeInt32(UNKNOWN_ERROR);
1667
Yi Kong91635562018-06-07 14:38:36 -07001668 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001669 } else {
1670 m_callback = data.readStrongBinder();
1671 int32_t delayUs = data.readInt32();
1672 /*
1673 * It's necessary that we sleep here, so the next
1674 * transaction the caller makes will be queued to
1675 * the async queue.
1676 */
1677 usleep(delayUs);
1678
1679 /*
1680 * Now when we return, libbinder will tell the kernel
1681 * we are done with this transaction, and the kernel
1682 * can move the queued transaction to either the
1683 * thread todo worklist (for kernels without the fix),
1684 * or the proc todo worklist. In case of the former,
1685 * the next outbound call will pick up the pending
1686 * transaction, which leads to undesired reentrant
1687 * behavior. This is caught in the if() branch above.
1688 */
1689 }
1690
1691 return NO_ERROR;
1692 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001693 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1694 Parcel data2, reply2;
1695 sp<IBinder> binder;
1696 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001697 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001698 return BAD_VALUE;
1699 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001700 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001701 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1702 return NO_ERROR;
1703 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001704 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1705 reply->writeStrongBinder(this);
1706 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001707 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1708 reply->writeInt32(m_id);
1709 return NO_ERROR;
1710 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1711 int32_t count;
1712 uint32_t indirect_code;
1713 sp<IBinder> binder;
1714
1715 count = data.readInt32();
1716 reply->writeInt32(m_id);
1717 reply->writeInt32(count);
1718 for (int i = 0; i < count; i++) {
1719 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001720 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001721 return BAD_VALUE;
1722 }
1723 indirect_code = data.readInt32();
1724 BinderLibTestBundle data2(&data);
1725 if (!data2.isValid()) {
1726 return BAD_VALUE;
1727 }
1728 BinderLibTestBundle reply2;
1729 binder->transact(indirect_code, data2, &reply2);
1730 reply2.appendTo(reply);
1731 }
1732 return NO_ERROR;
1733 }
1734 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1735 reply->setError(data.readInt32());
1736 return NO_ERROR;
1737 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1738 reply->writeInt32(sizeof(void *));
1739 return NO_ERROR;
1740 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1741 return NO_ERROR;
1742 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1743 m_strongRef = data.readStrongBinder();
1744 return NO_ERROR;
1745 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1746 int ret;
1747 Parcel data2, reply2;
1748 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1749 sp<IBinder> target;
1750 sp<IBinder> callback;
1751
1752 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001753 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001754 return BAD_VALUE;
1755 }
1756 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001757 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001758 return BAD_VALUE;
1759 }
1760 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001761 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001762 data2.writeInt32(ret);
1763 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1764 return NO_ERROR;
1765 }
1766 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1767 int ret;
1768 int32_t size;
1769 const void *buf;
1770 int fd;
1771
1772 fd = data.readFileDescriptor();
1773 if (fd < 0) {
1774 return BAD_VALUE;
1775 }
1776 ret = data.readInt32(&size);
1777 if (ret != NO_ERROR) {
1778 return ret;
1779 }
1780 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001781 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001782 return BAD_VALUE;
1783 }
1784 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001785 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001786 return NO_ERROR;
1787 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001788 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1789 int ret;
1790 int32_t size;
1791 const void *buf;
1792 android::base::unique_fd fd;
1793
1794 ret = data.readUniqueParcelFileDescriptor(&fd);
1795 if (ret != NO_ERROR) {
1796 return ret;
1797 }
1798 ret = data.readInt32(&size);
1799 if (ret != NO_ERROR) {
1800 return ret;
1801 }
1802 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001803 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001804 return BAD_VALUE;
1805 }
1806 ret = write(fd.get(), buf, size);
1807 if (ret != size) return UNKNOWN_ERROR;
1808 return NO_ERROR;
1809 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001810 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1811 alarm(10);
1812 return NO_ERROR;
1813 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001814 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001815 ;
1816 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001817 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001818 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001819 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001820 return NO_ERROR;
1821 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001822 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1823 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001824 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001825 return NO_ERROR;
1826 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001827 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1828 int policy = 0;
1829 sched_param param;
1830 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1831 return UNKNOWN_ERROR;
1832 }
1833 reply->writeInt32(policy);
1834 reply->writeInt32(param.sched_priority);
1835 return NO_ERROR;
1836 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001837 case BINDER_LIB_TEST_ECHO_VECTOR: {
1838 std::vector<uint64_t> vector;
1839 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001840 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001841 reply->writeUint64Vector(vector);
1842 return NO_ERROR;
1843 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001844 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1845 std::array<int, 2> sockets;
1846 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1847 if (!created) {
1848 ALOGE("Could not create socket pair");
1849 return UNKNOWN_ERROR;
1850 }
1851
1852 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1853 if (result != 0) {
1854 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1855 return UNKNOWN_ERROR;
1856 }
1857 base::unique_fd out(sockets[0]);
1858 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1859 if (writeResult != NO_ERROR) {
1860 ALOGE("Could not write unique_fd");
1861 return writeResult;
1862 }
1863 close(sockets[1]); // we don't need the other side of the fd
1864 return NO_ERROR;
1865 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001866 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001867 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1868 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001869 case BINDER_LIB_TEST_CAN_GET_SID: {
1870 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1871 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001872 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1873 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1874 return NO_ERROR;
1875 }
Devin Moore4354f712022-12-08 01:44:46 +00001876 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1877 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1878 return NO_ERROR;
1879 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001880 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001881 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001882 return NO_ERROR;
1883 }
1884 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001885 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001886 return NO_ERROR;
1887 }
1888 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1889 int32_t ms = data.readInt32();
1890 return unlockInMs(ms);
1891 }
1892 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001893 m_blockMutex.lock();
1894 sp<BinderLibTestService> thisService = this;
1895 int32_t value = data.readInt32();
1896 // start local thread to unlock in 1s
1897 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001898 t.detach();
1899 return NO_ERROR;
1900 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001901 default:
1902 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001903 };
1904 }
1905
Elie Kheirallah47431c12022-04-21 23:46:17 +00001906 status_t unlockInMs(int32_t ms) {
1907 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001908 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001909 return NO_ERROR;
1910 }
1911
Yifan Hong543edcd2021-05-18 19:47:30 -07001912private:
1913 int32_t m_id;
1914 int32_t m_nextServerId;
1915 pthread_mutex_t m_serverWaitMutex;
1916 pthread_cond_t m_serverWaitCond;
1917 bool m_serverStartRequested;
1918 sp<IBinder> m_serverStarted;
1919 sp<IBinder> m_strongRef;
1920 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001921 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001922 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001923};
1924
Martijn Coenen45b07b42017-08-09 12:07:45 +02001925int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001926{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001927 binderLibTestServiceName += String16(binderserversuffix);
1928
Steven Moreland35626652021-05-15 01:32:04 +00001929 // Testing to make sure that calls that we are serving can use getCallin*
1930 // even though we don't here.
1931 IPCThreadState::SpGuard spGuard{
1932 .address = __builtin_frame_address(0),
1933 .context = "main server thread",
1934 };
1935 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1936
Riley Andrews06b01ad2014-12-18 12:10:08 -08001937 status_t ret;
1938 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001939 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001940 {
1941 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001942
Steven Morelandbf1915b2020-07-16 22:43:02 +00001943 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1944
Steven Morelandcf03cf12020-12-04 02:58:40 +00001945 testService->setInheritRt(true);
1946
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001947 /*
1948 * Normally would also contain functionality as well, but we are only
1949 * testing the extension mechanism.
1950 */
1951 testService->setExtension(new BBinder());
1952
Martijn Coenen82c75312019-07-24 15:18:30 +02001953 // Required for test "BufRejected'
1954 testService->setRequestingSid(true);
1955
Martijn Coenen45b07b42017-08-09 12:07:45 +02001956 /*
1957 * We need this below, but can't hold a sp<> because it prevents the
1958 * node from being cleaned up automatically. It's safe in this case
1959 * because of how the tests are written.
1960 */
1961 testServicePtr = testService.get();
1962
Riley Andrews06b01ad2014-12-18 12:10:08 -08001963 if (index == 0) {
1964 ret = sm->addService(binderLibTestServiceName, testService);
1965 } else {
1966 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1967 Parcel data, reply;
1968 data.writeInt32(index);
1969 data.writeStrongBinder(testService);
1970
1971 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1972 }
1973 }
1974 write(readypipefd, &ret, sizeof(ret));
1975 close(readypipefd);
1976 //printf("%s: ret %d\n", __func__, ret);
1977 if (ret)
1978 return 1;
1979 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001980 if (usePoll) {
1981 int fd;
1982 struct epoll_event ev;
1983 int epoll_fd;
1984 IPCThreadState::self()->setupPolling(&fd);
1985 if (fd < 0) {
1986 return 1;
1987 }
1988 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1989
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001990 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001991 if (epoll_fd == -1) {
1992 return 1;
1993 }
1994
1995 ev.events = EPOLLIN;
1996 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1997 return 1;
1998 }
1999
2000 while (1) {
2001 /*
2002 * We simulate a single-threaded process using the binder poll
2003 * interface; besides handling binder commands, it can also
2004 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002005 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002006 *
2007 * processPendingCall() will then issue that transaction.
2008 */
2009 struct epoll_event events[1];
2010 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2011 if (numEvents < 0) {
2012 if (errno == EINTR) {
2013 continue;
2014 }
2015 return 1;
2016 }
2017 if (numEvents > 0) {
2018 IPCThreadState::self()->handlePolledCommands();
2019 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2020 testServicePtr->processPendingCall();
2021 }
2022 }
2023 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002024 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002025 ProcessState::self()->startThreadPool();
2026 IPCThreadState::self()->joinThreadPool();
2027 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002028 //printf("%s: joinThreadPool returned\n", __func__);
2029 return 1; /* joinThreadPool should not return */
2030}
2031
Steven Moreland68275d72023-04-21 22:12:45 +00002032int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002033 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002034 binderservername = argv[2];
2035 } else {
2036 binderservername = argv[0];
2037 }
2038
Martijn Coenen45b07b42017-08-09 12:07:45 +02002039 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2040 binderserversuffix = argv[5];
2041 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002042 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002043 binderserversuffix = new char[16];
2044 snprintf(binderserversuffix, 16, "%d", getpid());
2045 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002046
2047 ::testing::InitGoogleTest(&argc, argv);
2048 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2049 ProcessState::self()->startThreadPool();
2050 return RUN_ALL_TESTS();
2051}