blob: a0f12cf902984c274a515167a8550ed6df66c671 [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>
Yifan Hong8b890852021-06-10 13:44:09 -070033#include <android-base/strings.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070034#include <android-base/unique_fd.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080035#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070036#include <binder/BpBinder.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080037#include <binder/IBinder.h>
38#include <binder/IPCThreadState.h>
39#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070040#include <binder/RpcServer.h>
41#include <binder/RpcSession.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080042
Steven Morelandcf03cf12020-12-04 02:58:40 +000043#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020044#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080045#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070046#include <sys/socket.h>
47#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020048
Steven Moreland6ba5a252021-05-04 22:49:00 +000049#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070050#include "binderAbiHelper.h"
51
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;
Elie Kheirallah47431c12022-04-21 23:46:17 +000085static constexpr int kKernelThreads = 15;
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,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700117 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000118 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000119 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
120 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
121 BINDER_LIB_TEST_LOCK_UNLOCK,
122 BINDER_LIB_TEST_PROCESS_LOCK,
123 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
124 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800125};
126
Martijn Coenen45b07b42017-08-09 12:07:45 +0200127pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800128{
129 int ret;
130 pid_t pid;
131 status_t status;
132 int pipefd[2];
133 char stri[16];
134 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200135 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800136 char *childargv[] = {
137 binderservername,
138 binderserverarg,
139 stri,
140 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200141 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700142 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700143 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800144 };
145
146 ret = pipe(pipefd);
147 if (ret < 0)
148 return ret;
149
150 snprintf(stri, sizeof(stri), "%d", arg2);
151 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200152 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800153
154 pid = fork();
155 if (pid == -1)
156 return pid;
157 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800158 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800159 close(pipefd[0]);
160 execv(binderservername, childargv);
161 status = -errno;
162 write(pipefd[1], &status, sizeof(status));
163 fprintf(stderr, "execv failed, %s\n", strerror(errno));
164 _exit(EXIT_FAILURE);
165 }
166 close(pipefd[1]);
167 ret = read(pipefd[0], &status, sizeof(status));
168 //printf("pipe read returned %d, status %d\n", ret, status);
169 close(pipefd[0]);
170 if (ret == sizeof(status)) {
171 ret = status;
172 } else {
173 kill(pid, SIGKILL);
174 if (ret >= 0) {
175 ret = NO_INIT;
176 }
177 }
178 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700179 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800180 return ret;
181 }
182 return pid;
183}
184
Yifan Hong84bedeb2021-04-21 21:37:17 -0700185android::base::Result<int32_t> GetId(sp<IBinder> service) {
186 using android::base::Error;
187 Parcel data, reply;
188 data.markForBinder(service);
189 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
190 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
191 if (status != OK)
192 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
193 int32_t result = 0;
194 status = reply.readInt32(&result);
195 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
196 return result;
197}
198
Riley Andrews06b01ad2014-12-18 12:10:08 -0800199class BinderLibTestEnv : public ::testing::Environment {
200 public:
201 BinderLibTestEnv() {}
202 sp<IBinder> getServer(void) {
203 return m_server;
204 }
205
206 private:
207 virtual void SetUp() {
208 m_serverpid = start_server_process(0);
209 //printf("m_serverpid %d\n", m_serverpid);
210 ASSERT_GT(m_serverpid, 0);
211
212 sp<IServiceManager> sm = defaultServiceManager();
213 //printf("%s: pid %d, get service\n", __func__, m_pid);
214 m_server = sm->getService(binderLibTestServiceName);
Yi Kong91635562018-06-07 14:38:36 -0700215 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800216 //printf("%s: pid %d, get service done\n", __func__, m_pid);
217 }
218 virtual void TearDown() {
219 status_t ret;
220 Parcel data, reply;
221 int exitStatus;
222 pid_t pid;
223
224 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700225 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800226 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
227 EXPECT_EQ(0, ret);
228 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
229 EXPECT_EQ(0, ret);
230 }
231 if (m_serverpid > 0) {
232 //printf("wait for %d\n", m_pids[i]);
233 pid = wait(&exitStatus);
234 EXPECT_EQ(m_serverpid, pid);
235 EXPECT_TRUE(WIFEXITED(exitStatus));
236 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
237 }
238 }
239
240 pid_t m_serverpid;
241 sp<IBinder> m_server;
242};
243
244class BinderLibTest : public ::testing::Test {
245 public:
246 virtual void SetUp() {
247 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000248 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800249 }
250 virtual void TearDown() {
251 }
252 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200253 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800254 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800255 int32_t id;
256 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800257
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700258 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800259
Elie Kheirallahb7246642022-05-03 18:01:43 +0000260 sp<IBinder> binder = reply.readStrongBinder();
261 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700262 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800263 if (idPtr)
264 *idPtr = id;
265 return binder;
266 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200267
Yi Kong91635562018-06-07 14:38:36 -0700268 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200269 {
270 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
271 }
272
Yi Kong91635562018-06-07 14:38:36 -0700273 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200274 {
275 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
276 }
277
Riley Andrews06b01ad2014-12-18 12:10:08 -0800278 void waitForReadData(int fd, int timeout_ms) {
279 int ret;
280 pollfd pfd = pollfd();
281
282 pfd.fd = fd;
283 pfd.events = POLLIN;
284 ret = poll(&pfd, 1, timeout_ms);
285 EXPECT_EQ(1, ret);
286 }
287
288 sp<IBinder> m_server;
289};
290
291class BinderLibTestBundle : public Parcel
292{
293 public:
294 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800295 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800296 int32_t mark;
297 int32_t bundleLen;
298 size_t pos;
299
300 if (source->readInt32(&mark))
301 return;
302 if (mark != MARK_START)
303 return;
304 if (source->readInt32(&bundleLen))
305 return;
306 pos = source->dataPosition();
307 if (Parcel::appendFrom(source, pos, bundleLen))
308 return;
309 source->setDataPosition(pos + bundleLen);
310 if (source->readInt32(&mark))
311 return;
312 if (mark != MARK_END)
313 return;
314 m_isValid = true;
315 setDataPosition(0);
316 }
317 void appendTo(Parcel *dest) {
318 dest->writeInt32(MARK_START);
319 dest->writeInt32(dataSize());
320 dest->appendFrom(this, 0, dataSize());
321 dest->writeInt32(MARK_END);
322 };
323 bool isValid(void) {
324 return m_isValid;
325 }
326 private:
327 enum {
328 MARK_START = B_PACK_CHARS('B','T','B','S'),
329 MARK_END = B_PACK_CHARS('B','T','B','E'),
330 };
331 bool m_isValid;
332};
333
334class BinderLibTestEvent
335{
336 public:
337 BinderLibTestEvent(void)
338 : m_eventTriggered(false)
339 {
Yi Kong91635562018-06-07 14:38:36 -0700340 pthread_mutex_init(&m_waitMutex, nullptr);
341 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800342 }
343 int waitEvent(int timeout_s)
344 {
345 int ret;
346 pthread_mutex_lock(&m_waitMutex);
347 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800348 struct timespec ts;
349 clock_gettime(CLOCK_REALTIME, &ts);
350 ts.tv_sec += timeout_s;
351 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800352 }
353 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
354 pthread_mutex_unlock(&m_waitMutex);
355 return ret;
356 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200357 pthread_t getTriggeringThread()
358 {
359 return m_triggeringThread;
360 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800361 protected:
362 void triggerEvent(void) {
363 pthread_mutex_lock(&m_waitMutex);
364 pthread_cond_signal(&m_waitCond);
365 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200366 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800367 pthread_mutex_unlock(&m_waitMutex);
368 };
369 private:
370 pthread_mutex_t m_waitMutex;
371 pthread_cond_t m_waitCond;
372 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200373 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800374};
375
376class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
377{
378 public:
379 BinderLibTestCallBack()
380 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700381 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800382 {
383 }
384 status_t getResult(void)
385 {
386 return m_result;
387 }
388
389 private:
390 virtual status_t onTransact(uint32_t code,
391 const Parcel& data, Parcel* reply,
392 uint32_t flags = 0)
393 {
394 (void)reply;
395 (void)flags;
396 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200397 case BINDER_LIB_TEST_CALL_BACK: {
398 status_t status = data.readInt32(&m_result);
399 if (status != NO_ERROR) {
400 m_result = status;
401 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800402 triggerEvent();
403 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200404 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700405 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
406 sp<IBinder> server;
407 int ret;
408 const uint8_t *buf = data.data();
409 size_t size = data.dataSize();
410 if (m_prev_end) {
411 /* 64-bit kernel needs at most 8 bytes to align buffer end */
412 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
413 } else {
414 EXPECT_TRUE(IsPageAligned((void *)buf));
415 }
416
417 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
418
419 if (size > 0) {
420 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
421 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
422 data, reply);
423 EXPECT_EQ(NO_ERROR, ret);
424 }
425 return NO_ERROR;
426 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800427 default:
428 return UNKNOWN_TRANSACTION;
429 }
430 }
431
432 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700433 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800434};
435
436class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
437{
438 private:
439 virtual void binderDied(const wp<IBinder>& who) {
440 (void)who;
441 triggerEvent();
442 };
443};
444
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700445TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
446 // EXPECT_DEATH works by forking the process
447 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
448}
449
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500450TEST_F(BinderLibTest, WasParceled) {
451 auto binder = sp<BBinder>::make();
452 EXPECT_FALSE(binder->wasParceled());
453 Parcel data;
454 data.writeStrongBinder(binder);
455 EXPECT_TRUE(binder->wasParceled());
456}
457
Riley Andrews06b01ad2014-12-18 12:10:08 -0800458TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800459 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700460 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
461 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800462}
463
Steven Moreland80844f72020-12-12 02:06:08 +0000464TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000465 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700466 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
467 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000468}
469
Steven Morelandf183fdd2020-10-27 00:12:12 +0000470TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000471 Parcel data, reply;
472 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700473 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
474 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000475}
476
Marco Ballesio7ee17572020-09-08 10:30:03 -0700477TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700478 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700479 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700480
Li Li6f059292021-09-10 09:59:30 -0700481 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700482 if (freezer_file.fail()) {
483 GTEST_SKIP();
484 return;
485 }
486
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700487 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700488 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700489 for (int i = 0; i < 10; i++) {
490 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
491 }
Li Li6f059292021-09-10 09:59:30 -0700492
493 // Pass test on devices where BINDER_FREEZE ioctl is not supported
494 int ret = IPCThreadState::self()->freeze(pid, false, 0);
495 if (ret != 0) {
496 GTEST_SKIP();
497 return;
498 }
499
500 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
501 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
502 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700503 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700504
Li Li4e678b92021-09-14 12:14:42 -0700505 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700506
507 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
508 &async_received));
509
510 EXPECT_EQ(sync_received, 1);
511 EXPECT_EQ(async_received, 0);
512
Li Li4e678b92021-09-14 12:14:42 -0700513 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700514 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
515}
516
Riley Andrews06b01ad2014-12-18 12:10:08 -0800517TEST_F(BinderLibTest, SetError) {
518 int32_t testValue[] = { 0, -123, 123 };
519 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800520 Parcel data, reply;
521 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700522 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
523 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800524 }
525}
526
527TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700528 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800529}
530
531TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800532 int32_t ptrsize;
533 Parcel data, reply;
534 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700535 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700536 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
537 StatusEq(NO_ERROR));
538 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800539 RecordProperty("TestPtrSize", sizeof(void *));
540 RecordProperty("ServerPtrSize", sizeof(void *));
541}
542
543TEST_F(BinderLibTest, IndirectGetId2)
544{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800545 int32_t id;
546 int32_t count;
547 Parcel data, reply;
548 int32_t serverId[3];
549
550 data.writeInt32(ARRAY_SIZE(serverId));
551 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
552 sp<IBinder> server;
553 BinderLibTestBundle datai;
554
555 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700556 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800557 data.writeStrongBinder(server);
558 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
559 datai.appendTo(&data);
560 }
561
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700562 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
563 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800564
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700565 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800566 EXPECT_EQ(0, id);
567
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700568 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700569 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800570
571 for (size_t i = 0; i < (size_t)count; i++) {
572 BinderLibTestBundle replyi(&reply);
573 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700574 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800575 EXPECT_EQ(serverId[i], id);
576 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
577 }
578
579 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
580}
581
582TEST_F(BinderLibTest, IndirectGetId3)
583{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800584 int32_t id;
585 int32_t count;
586 Parcel data, reply;
587 int32_t serverId[3];
588
589 data.writeInt32(ARRAY_SIZE(serverId));
590 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
591 sp<IBinder> server;
592 BinderLibTestBundle datai;
593 BinderLibTestBundle datai2;
594
595 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700596 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800597 data.writeStrongBinder(server);
598 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
599
600 datai.writeInt32(1);
601 datai.writeStrongBinder(m_server);
602 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
603 datai2.appendTo(&datai);
604
605 datai.appendTo(&data);
606 }
607
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700608 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
609 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800610
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700611 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800612 EXPECT_EQ(0, id);
613
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700614 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700615 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800616
617 for (size_t i = 0; i < (size_t)count; i++) {
618 int32_t counti;
619
620 BinderLibTestBundle replyi(&reply);
621 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700622 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800623 EXPECT_EQ(serverId[i], id);
624
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700625 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800626 EXPECT_EQ(1, counti);
627
628 BinderLibTestBundle replyi2(&replyi);
629 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700630 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800631 EXPECT_EQ(0, id);
632 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
633
634 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
635 }
636
637 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
638}
639
640TEST_F(BinderLibTest, CallBack)
641{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800642 Parcel data, reply;
643 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
644 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700645 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
646 StatusEq(NO_ERROR));
647 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
648 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800649}
650
Steven Moreland35626652021-05-15 01:32:04 +0000651TEST_F(BinderLibTest, BinderCallContextGuard) {
652 sp<IBinder> binder = addServer();
653 Parcel data, reply;
654 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
655 StatusEq(DEAD_OBJECT));
656}
657
Riley Andrews06b01ad2014-12-18 12:10:08 -0800658TEST_F(BinderLibTest, AddServer)
659{
660 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700661 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800662}
663
Riley Andrews06b01ad2014-12-18 12:10:08 -0800664TEST_F(BinderLibTest, DeathNotificationStrongRef)
665{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800666 sp<IBinder> sbinder;
667
668 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
669
670 {
671 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700672 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700673 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800674 sbinder = binder;
675 }
676 {
677 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700678 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
679 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800680 }
681 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700682 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
683 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800684}
685
686TEST_F(BinderLibTest, DeathNotificationMultiple)
687{
688 status_t ret;
689 const int clientcount = 2;
690 sp<IBinder> target;
691 sp<IBinder> linkedclient[clientcount];
692 sp<BinderLibTestCallBack> callBack[clientcount];
693 sp<IBinder> passiveclient[clientcount];
694
695 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700696 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800697 for (int i = 0; i < clientcount; i++) {
698 {
699 Parcel data, reply;
700
701 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700702 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800703 callBack[i] = new BinderLibTestCallBack();
704 data.writeStrongBinder(target);
705 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700706 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
707 &reply, TF_ONE_WAY),
708 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800709 }
710 {
711 Parcel data, reply;
712
713 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700714 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800715 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700716 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
717 &reply, TF_ONE_WAY),
718 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800719 }
720 }
721 {
722 Parcel data, reply;
723 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
724 EXPECT_EQ(0, ret);
725 }
726
727 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700728 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
729 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800730 }
731}
732
Martijn Coenenf7100e42017-07-31 12:14:09 +0200733TEST_F(BinderLibTest, DeathNotificationThread)
734{
735 status_t ret;
736 sp<BinderLibTestCallBack> callback;
737 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700738 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200739 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700740 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200741
742 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
743
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700744 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200745
746 {
747 Parcel data, reply;
748 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
749 EXPECT_EQ(0, ret);
750 }
751
752 /* Make sure it's dead */
753 testDeathRecipient->waitEvent(5);
754
755 /* Now, pass the ref to another process and ask that process to
756 * call linkToDeath() on it, and wait for a response. This tests
757 * two things:
758 * 1) You still get death notifications when calling linkToDeath()
759 * on a ref that is already dead when it was passed to you.
760 * 2) That death notifications are not directly pushed to the thread
761 * registering them, but to the threadpool (proc workqueue) instead.
762 *
763 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
764 * is blocked on a condition variable waiting for the death notification to be
765 * called; therefore, that thread is not available for handling proc work.
766 * So, if the death notification was pushed to the thread workqueue, the callback
767 * would never be called, and the test would timeout and fail.
768 *
769 * Note that we can't do this part of the test from this thread itself, because
770 * the binder driver would only push death notifications to the thread if
771 * it is a looper thread, which this thread is not.
772 *
773 * See b/23525545 for details.
774 */
775 {
776 Parcel data, reply;
777
778 callback = new BinderLibTestCallBack();
779 data.writeStrongBinder(target);
780 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700781 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
782 TF_ONE_WAY),
783 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200784 }
785
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700786 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
787 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200788}
789
Riley Andrews06b01ad2014-12-18 12:10:08 -0800790TEST_F(BinderLibTest, PassFile) {
791 int ret;
792 int pipefd[2];
793 uint8_t buf[1] = { 0 };
794 uint8_t write_value = 123;
795
796 ret = pipe2(pipefd, O_NONBLOCK);
797 ASSERT_EQ(0, ret);
798
799 {
800 Parcel data, reply;
801 uint8_t writebuf[1] = { write_value };
802
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700803 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800804
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700805 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800806
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700807 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800808
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700809 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
810 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800811 }
812
813 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700814 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800815 EXPECT_EQ(write_value, buf[0]);
816
817 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
818
819 ret = read(pipefd[0], buf, sizeof(buf));
820 EXPECT_EQ(0, ret);
821
822 close(pipefd[0]);
823}
824
Ryo Hashimotobf551892018-05-31 16:58:35 +0900825TEST_F(BinderLibTest, PassParcelFileDescriptor) {
826 const int datasize = 123;
827 std::vector<uint8_t> writebuf(datasize);
828 for (size_t i = 0; i < writebuf.size(); ++i) {
829 writebuf[i] = i;
830 }
831
832 android::base::unique_fd read_end, write_end;
833 {
834 int pipefd[2];
835 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
836 read_end.reset(pipefd[0]);
837 write_end.reset(pipefd[1]);
838 }
839 {
840 Parcel data;
841 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
842 write_end.reset();
843 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
844 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
845
846 Parcel reply;
847 EXPECT_EQ(NO_ERROR,
848 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
849 &reply));
850 }
851 std::vector<uint8_t> readbuf(datasize);
852 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
853 EXPECT_EQ(writebuf, readbuf);
854
855 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
856
857 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
858}
859
Riley Andrews06b01ad2014-12-18 12:10:08 -0800860TEST_F(BinderLibTest, PromoteLocal) {
861 sp<IBinder> strong = new BBinder();
862 wp<IBinder> weak = strong;
863 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700864 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800865 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700866 strong = nullptr;
867 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800868 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700869 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800870}
871
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700872TEST_F(BinderLibTest, LocalGetExtension) {
873 sp<BBinder> binder = new BBinder();
874 sp<IBinder> ext = new BBinder();
875 binder->setExtension(ext);
876 EXPECT_EQ(ext, binder->getExtension());
877}
878
879TEST_F(BinderLibTest, RemoteGetExtension) {
880 sp<IBinder> server = addServer();
881 ASSERT_TRUE(server != nullptr);
882
883 sp<IBinder> extension;
884 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
885 ASSERT_NE(nullptr, extension.get());
886
887 EXPECT_EQ(NO_ERROR, extension->pingBinder());
888}
889
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700890TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700891 Parcel data, reply;
892
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700893 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
894 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700895
896 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700897 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800898 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
899 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
900 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
901 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700902}
903
Connor O'Brien52be2c92016-09-20 14:18:08 -0700904TEST_F(BinderLibTest, FreedBinder) {
905 status_t ret;
906
907 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700908 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700909
910 __u32 freedHandle;
911 wp<IBinder> keepFreedBinder;
912 {
913 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700914 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
915 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700916 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
917 freedHandle = freed->handle;
918 /* Add a weak ref to the freed binder so the driver does not
919 * delete its reference to it - otherwise the transaction
920 * fails regardless of whether the driver is fixed.
921 */
Steven Morelande171d622019-07-17 16:06:01 -0700922 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700923 }
Steven Morelande171d622019-07-17 16:06:01 -0700924 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700925 {
926 Parcel data, reply;
927 data.writeStrongBinder(server);
928 /* Replace original handle with handle to the freed binder */
929 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
930 __u32 oldHandle = strong->handle;
931 strong->handle = freedHandle;
932 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
933 /* Returns DEAD_OBJECT (-32) if target crashes and
934 * FAILED_TRANSACTION if the driver rejects the invalid
935 * object.
936 */
937 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
938 /* Restore original handle so parcel destructor does not use
939 * the wrong handle.
940 */
941 strong->handle = oldHandle;
942 }
943}
944
Sherry Yang336cdd32017-07-24 14:12:27 -0700945TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700946 Parcel data, reply;
947 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
948 for (int i = 0; i < 2; i++) {
949 BinderLibTestBundle datai;
950 datai.appendFrom(&data, 0, data.dataSize());
951
952 data.freeData();
953 data.writeInt32(1);
954 data.writeStrongBinder(callBack);
955 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
956
957 datai.appendTo(&data);
958 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700959 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
960 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700961}
962
Martijn Coenen45b07b42017-08-09 12:07:45 +0200963TEST_F(BinderLibTest, OnewayQueueing)
964{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200965 Parcel data, data2;
966
967 sp<IBinder> pollServer = addPollServer();
968
969 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
970 data.writeStrongBinder(callBack);
971 data.writeInt32(500000); // delay in us before calling back
972
973 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
974 data2.writeStrongBinder(callBack2);
975 data2.writeInt32(0); // delay in us
976
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700977 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
978 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200979
980 // The delay ensures that this second transaction will end up on the async_todo list
981 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700982 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
983 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200984
985 // The server will ensure that the two transactions are handled in the expected order;
986 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700987 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
988 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200989
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700990 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
991 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200992}
993
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100994TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
995{
996 status_t ret;
997 Parcel data, reply;
998 data.writeInterfaceToken(binderLibTestServiceName);
999 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1000 EXPECT_EQ(-1, reply.readInt32());
1001 EXPECT_EQ(NO_ERROR, ret);
1002}
1003
1004TEST_F(BinderLibTest, WorkSourceSet)
1005{
1006 status_t ret;
1007 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001008 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001009 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001010 data.writeInterfaceToken(binderLibTestServiceName);
1011 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1012 EXPECT_EQ(100, reply.readInt32());
1013 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001014 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1015 EXPECT_EQ(NO_ERROR, ret);
1016}
1017
1018TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1019{
1020 status_t ret;
1021 Parcel data, reply;
1022
1023 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1024 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1025
1026 data.writeInterfaceToken(binderLibTestServiceName);
1027 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1028 EXPECT_EQ(-1, reply.readInt32());
1029 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001030 EXPECT_EQ(NO_ERROR, ret);
1031}
1032
1033TEST_F(BinderLibTest, WorkSourceCleared)
1034{
1035 status_t ret;
1036 Parcel data, reply;
1037
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001038 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001039 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1040 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001041 data.writeInterfaceToken(binderLibTestServiceName);
1042 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1043
1044 EXPECT_EQ(-1, reply.readInt32());
1045 EXPECT_EQ(100, previousWorkSource);
1046 EXPECT_EQ(NO_ERROR, ret);
1047}
1048
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001049TEST_F(BinderLibTest, WorkSourceRestored)
1050{
1051 status_t ret;
1052 Parcel data, reply;
1053
1054 IPCThreadState::self()->setCallingWorkSourceUid(100);
1055 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1056 IPCThreadState::self()->restoreCallingWorkSource(token);
1057
1058 data.writeInterfaceToken(binderLibTestServiceName);
1059 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1060
1061 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001062 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001063 EXPECT_EQ(NO_ERROR, ret);
1064}
1065
Olivier Gaillard91a04802018-11-14 17:32:41 +00001066TEST_F(BinderLibTest, PropagateFlagSet)
1067{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001068 IPCThreadState::self()->clearPropagateWorkSource();
1069 IPCThreadState::self()->setCallingWorkSourceUid(100);
1070 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1071}
1072
1073TEST_F(BinderLibTest, PropagateFlagCleared)
1074{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001075 IPCThreadState::self()->setCallingWorkSourceUid(100);
1076 IPCThreadState::self()->clearPropagateWorkSource();
1077 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1078}
1079
1080TEST_F(BinderLibTest, PropagateFlagRestored)
1081{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001082 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1083 IPCThreadState::self()->restoreCallingWorkSource(token);
1084
1085 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1086}
1087
1088TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1089{
1090 IPCThreadState::self()->setCallingWorkSourceUid(100);
1091
1092 Parcel data, reply;
1093 status_t ret;
1094 data.writeInterfaceToken(binderLibTestServiceName);
1095 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1096
1097 Parcel data2, reply2;
1098 status_t ret2;
1099 data2.writeInterfaceToken(binderLibTestServiceName);
1100 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1101 EXPECT_EQ(100, reply2.readInt32());
1102 EXPECT_EQ(NO_ERROR, ret2);
1103}
1104
Steven Morelandbf1915b2020-07-16 22:43:02 +00001105TEST_F(BinderLibTest, SchedPolicySet) {
1106 sp<IBinder> server = addServer();
1107 ASSERT_TRUE(server != nullptr);
1108
1109 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001110 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1111 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001112
1113 int policy = reply.readInt32();
1114 int priority = reply.readInt32();
1115
1116 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1117 EXPECT_EQ(kSchedPriority, priority);
1118}
1119
Steven Morelandcf03cf12020-12-04 02:58:40 +00001120TEST_F(BinderLibTest, InheritRt) {
1121 sp<IBinder> server = addServer();
1122 ASSERT_TRUE(server != nullptr);
1123
1124 const struct sched_param param {
1125 .sched_priority = kSchedPriorityMore,
1126 };
1127 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1128
1129 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001130 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1131 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001132
1133 int policy = reply.readInt32();
1134 int priority = reply.readInt32();
1135
1136 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1137 EXPECT_EQ(kSchedPriorityMore, priority);
1138}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001139
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001140TEST_F(BinderLibTest, VectorSent) {
1141 Parcel data, reply;
1142 sp<IBinder> server = addServer();
1143 ASSERT_TRUE(server != nullptr);
1144
1145 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1146 data.writeUint64Vector(testValue);
1147
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001148 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001149 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001150 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001151 EXPECT_EQ(readValue, testValue);
1152}
1153
Martijn Coenen82c75312019-07-24 15:18:30 +02001154TEST_F(BinderLibTest, BufRejected) {
1155 Parcel data, reply;
1156 uint32_t buf;
1157 sp<IBinder> server = addServer();
1158 ASSERT_TRUE(server != nullptr);
1159
1160 binder_buffer_object obj {
1161 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001162 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001163 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1164 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001165 };
1166 data.setDataCapacity(1024);
1167 // Write a bogus object at offset 0 to get an entry in the offset table
1168 data.writeFileDescriptor(0);
1169 EXPECT_EQ(data.objectsCount(), 1);
1170 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1171 // And now, overwrite it with the buffer object
1172 memcpy(parcelData, &obj, sizeof(obj));
1173 data.setDataSize(sizeof(obj));
1174
Steven Morelandf2e0a952021-11-01 18:17:23 -07001175 EXPECT_EQ(data.objectsCount(), 1);
1176
Martijn Coenen82c75312019-07-24 15:18:30 +02001177 // Either the kernel should reject this transaction (if it's correct), but
1178 // if it's not, the server implementation should return an error if it
1179 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001180 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001181 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001182}
1183
Steven Morelandf2e0a952021-11-01 18:17:23 -07001184TEST_F(BinderLibTest, WeakRejected) {
1185 Parcel data, reply;
1186 sp<IBinder> server = addServer();
1187 ASSERT_TRUE(server != nullptr);
1188
1189 auto binder = sp<BBinder>::make();
1190 wp<BBinder> wpBinder(binder);
1191 flat_binder_object obj{
1192 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1193 .flags = 0,
1194 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1195 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1196 };
1197 data.setDataCapacity(1024);
1198 // Write a bogus object at offset 0 to get an entry in the offset table
1199 data.writeFileDescriptor(0);
1200 EXPECT_EQ(data.objectsCount(), 1);
1201 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1202 // And now, overwrite it with the weak binder
1203 memcpy(parcelData, &obj, sizeof(obj));
1204 data.setDataSize(sizeof(obj));
1205
1206 // a previous bug caused other objects to be released an extra time, so we
1207 // test with an object that libbinder will actually try to release
1208 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1209
1210 EXPECT_EQ(data.objectsCount(), 2);
1211
1212 // send it many times, since previous error was memory corruption, make it
1213 // more likely that the server crashes
1214 for (size_t i = 0; i < 100; i++) {
1215 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1216 StatusEq(BAD_VALUE));
1217 }
1218
1219 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1220}
1221
Steven Moreland254e8ef2021-04-19 22:28:50 +00001222TEST_F(BinderLibTest, GotSid) {
1223 sp<IBinder> server = addServer();
1224
1225 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001226 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001227}
1228
Jayant Chowdhary30700942022-01-31 14:12:40 -08001229TEST(ServiceNotifications, Unregister) {
1230 auto sm = defaultServiceManager();
1231 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1232 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1233 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1234 virtual ~LocalRegistrationCallbackImpl() {}
1235 };
1236 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1237
1238 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1239 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1240}
1241
Elie Kheirallah47431c12022-04-21 23:46:17 +00001242TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1243 Parcel data, reply;
1244 sp<IBinder> server = addServer();
1245 ASSERT_TRUE(server != nullptr);
1246 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1247 StatusEq(NO_ERROR));
1248 int32_t replyi = reply.readInt32();
1249 // Expect 16 threads: kKernelThreads = 15 + Pool thread == 16
1250 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
1251 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1252
1253 /*
1254 * This will use all threads in the pool expect the main pool thread.
1255 * The service should run fine without locking, and the thread count should
1256 * not exceed 16 (15 Max + pool thread).
1257 */
1258 std::vector<std::thread> ts;
1259 for (size_t i = 0; i < kKernelThreads - 1; i++) {
1260 ts.push_back(std::thread([&] {
1261 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &reply), NO_ERROR);
1262 }));
1263 }
1264
1265 data.writeInt32(1);
1266 // Give a chance for all threads to be used
1267 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1268
1269 for (auto &t : ts) {
1270 t.join();
1271 }
1272
1273 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1274 StatusEq(NO_ERROR));
1275 replyi = reply.readInt32();
1276 // No more than 16 threads should exist.
1277 EXPECT_EQ(replyi, kKernelThreads + 1);
1278}
1279
1280size_t epochMillis() {
1281 using std::chrono::duration_cast;
1282 using std::chrono::milliseconds;
1283 using std::chrono::seconds;
1284 using std::chrono::system_clock;
1285 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1286}
1287
1288TEST_F(BinderLibTest, HangingServices) {
1289 Parcel data, reply;
1290 sp<IBinder> server = addServer();
1291 ASSERT_TRUE(server != nullptr);
1292 int32_t delay = 1000; // ms
1293 data.writeInt32(delay);
1294 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1295 std::vector<std::thread> ts;
1296 size_t epochMsBefore = epochMillis();
1297 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1298 ts.push_back(std::thread([&] {
1299 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &reply), NO_ERROR);
1300 }));
1301 }
1302
1303 for (auto &t : ts) {
1304 t.join();
1305 }
1306 size_t epochMsAfter = epochMillis();
1307
1308 // deadlock occurred and threads only finished after 1s passed.
1309 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1310}
1311
Yifan Hong84bedeb2021-04-21 21:37:17 -07001312class BinderLibRpcTestBase : public BinderLibTest {
1313public:
1314 void SetUp() override {
1315 if (!base::GetBoolProperty("ro.debuggable", false)) {
1316 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1317 "non-debuggable builds.";
1318 }
1319 BinderLibTest::SetUp();
1320 }
1321
1322 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1323 auto rpcServer = RpcServer::make();
1324 EXPECT_NE(nullptr, rpcServer);
1325 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001326 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001327 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1328 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001329 return {};
1330 }
1331 return {rpcServer->releaseServer(), port};
1332 }
1333};
1334
Yifan Hong8b890852021-06-10 13:44:09 -07001335class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001336
Yifan Hongbd276552022-02-28 15:28:51 -08001337// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1338// If device is debuggable AND not on user builds, expects matcher.
1339// Otherwise expects INVALID_OPERATION.
1340// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1341static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1342 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1343 android::base::GetProperty("ro.build.type", "") != "user";
1344 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1345}
1346
Yifan Hong8b890852021-06-10 13:44:09 -07001347TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1348 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001349 ASSERT_TRUE(binder != nullptr);
1350 auto [socket, port] = CreateSocket();
1351 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001352 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1353 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001354}
1355
Yifan Hong8b890852021-06-10 13:44:09 -07001356// Tests for multiple RpcServer's on the same binder object.
1357TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1358 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001359 ASSERT_TRUE(binder != nullptr);
1360
1361 auto [socket1, port1] = CreateSocket();
1362 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001363 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001364 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1365 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001366
1367 auto [socket2, port2] = CreateSocket();
1368 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001369 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001370 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1371 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001372}
1373
Yifan Hong8b890852021-06-10 13:44:09 -07001374// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1375// local binders.
1376class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001377public:
1378 sp<IBinder> GetService() {
1379 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1380 }
1381 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1382 return info.param ? "remote" : "local";
1383 }
1384};
1385
Yifan Hong8b890852021-06-10 13:44:09 -07001386TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1387 auto binder = GetService();
1388 ASSERT_TRUE(binder != nullptr);
1389 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001390 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001391}
1392
1393TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001394 auto binder = GetService();
1395 ASSERT_TRUE(binder != nullptr);
1396 auto [socket, port] = CreateSocket();
1397 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001398 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1399 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001400}
Yifan Hong8b890852021-06-10 13:44:09 -07001401INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1402 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001403
Yifan Hong543edcd2021-05-18 19:47:30 -07001404class BinderLibTestService : public BBinder {
1405public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001406 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1407 : m_id(id),
1408 m_nextServerId(id + 1),
1409 m_serverStartRequested(false),
1410 m_callback(nullptr),
1411 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001412 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1413 pthread_cond_init(&m_serverWaitCond, nullptr);
1414 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001415 ~BinderLibTestService() {
1416 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1417 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001418
Yifan Hong543edcd2021-05-18 19:47:30 -07001419 void processPendingCall() {
1420 if (m_callback != nullptr) {
1421 Parcel data;
1422 data.writeInt32(NO_ERROR);
1423 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1424 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001425 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001426 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001427
Yifan Hong543edcd2021-05-18 19:47:30 -07001428 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1429 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001430 // TODO(b/182914638): also checks getCallingUid() for RPC
1431 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001432 return PERMISSION_DENIED;
1433 }
1434 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001435 case BINDER_LIB_TEST_REGISTER_SERVER: {
1436 int32_t id;
1437 sp<IBinder> binder;
1438 id = data.readInt32();
1439 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001440 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001441 return BAD_VALUE;
1442 }
1443
Yifan Hong543edcd2021-05-18 19:47:30 -07001444 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001445
1446 pthread_mutex_lock(&m_serverWaitMutex);
1447 if (m_serverStartRequested) {
1448 m_serverStartRequested = false;
1449 m_serverStarted = binder;
1450 pthread_cond_signal(&m_serverWaitCond);
1451 }
1452 pthread_mutex_unlock(&m_serverWaitMutex);
1453 return NO_ERROR;
1454 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001455 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001456 case BINDER_LIB_TEST_ADD_SERVER: {
1457 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001458 int serverid;
1459
1460 if (m_id != 0) {
1461 return INVALID_OPERATION;
1462 }
1463 pthread_mutex_lock(&m_serverWaitMutex);
1464 if (m_serverStartRequested) {
1465 ret = -EBUSY;
1466 } else {
1467 serverid = m_nextServerId++;
1468 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001469 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001470
1471 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001472 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001473 pthread_mutex_lock(&m_serverWaitMutex);
1474 }
1475 if (ret > 0) {
1476 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001477 struct timespec ts;
1478 clock_gettime(CLOCK_REALTIME, &ts);
1479 ts.tv_sec += 5;
1480 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001481 }
1482 if (m_serverStartRequested) {
1483 m_serverStartRequested = false;
1484 ret = -ETIMEDOUT;
1485 } else {
1486 reply->writeStrongBinder(m_serverStarted);
1487 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001488 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001489 ret = NO_ERROR;
1490 }
1491 } else if (ret >= 0) {
1492 m_serverStartRequested = false;
1493 ret = UNKNOWN_ERROR;
1494 }
1495 pthread_mutex_unlock(&m_serverWaitMutex);
1496 return ret;
1497 }
Steven Moreland35626652021-05-15 01:32:04 +00001498 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1499 IPCThreadState::SpGuard spGuard{
1500 .address = __builtin_frame_address(0),
1501 .context = "GuardInBinderTransaction",
1502 };
1503 const IPCThreadState::SpGuard *origGuard =
1504 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1505
1506 // if the guard works, this should abort
1507 (void)IPCThreadState::self()->getCallingPid();
1508
1509 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1510 return NO_ERROR;
1511 }
1512
Marco Ballesio7ee17572020-09-08 10:30:03 -07001513 case BINDER_LIB_TEST_GETPID:
1514 reply->writeInt32(getpid());
1515 return NO_ERROR;
1516 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1517 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001518 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001519 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001520 // oneway error codes should be ignored
1521 if (flags & TF_ONE_WAY) {
1522 return UNKNOWN_ERROR;
1523 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001524 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001525 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1526 // Note: this transaction is only designed for use with a
1527 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001528 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001529 // A callback was already pending; this means that
1530 // we received a second call while still processing
1531 // the first one. Fail the test.
1532 sp<IBinder> callback = data.readStrongBinder();
1533 Parcel data2;
1534 data2.writeInt32(UNKNOWN_ERROR);
1535
Yi Kong91635562018-06-07 14:38:36 -07001536 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001537 } else {
1538 m_callback = data.readStrongBinder();
1539 int32_t delayUs = data.readInt32();
1540 /*
1541 * It's necessary that we sleep here, so the next
1542 * transaction the caller makes will be queued to
1543 * the async queue.
1544 */
1545 usleep(delayUs);
1546
1547 /*
1548 * Now when we return, libbinder will tell the kernel
1549 * we are done with this transaction, and the kernel
1550 * can move the queued transaction to either the
1551 * thread todo worklist (for kernels without the fix),
1552 * or the proc todo worklist. In case of the former,
1553 * the next outbound call will pick up the pending
1554 * transaction, which leads to undesired reentrant
1555 * behavior. This is caught in the if() branch above.
1556 */
1557 }
1558
1559 return NO_ERROR;
1560 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001561 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1562 Parcel data2, reply2;
1563 sp<IBinder> binder;
1564 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001565 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001566 return BAD_VALUE;
1567 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001568 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001569 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1570 return NO_ERROR;
1571 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001572 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1573 reply->writeStrongBinder(this);
1574 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001575 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1576 reply->writeInt32(m_id);
1577 return NO_ERROR;
1578 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1579 int32_t count;
1580 uint32_t indirect_code;
1581 sp<IBinder> binder;
1582
1583 count = data.readInt32();
1584 reply->writeInt32(m_id);
1585 reply->writeInt32(count);
1586 for (int i = 0; i < count; i++) {
1587 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001588 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001589 return BAD_VALUE;
1590 }
1591 indirect_code = data.readInt32();
1592 BinderLibTestBundle data2(&data);
1593 if (!data2.isValid()) {
1594 return BAD_VALUE;
1595 }
1596 BinderLibTestBundle reply2;
1597 binder->transact(indirect_code, data2, &reply2);
1598 reply2.appendTo(reply);
1599 }
1600 return NO_ERROR;
1601 }
1602 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1603 reply->setError(data.readInt32());
1604 return NO_ERROR;
1605 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1606 reply->writeInt32(sizeof(void *));
1607 return NO_ERROR;
1608 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1609 return NO_ERROR;
1610 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1611 m_strongRef = data.readStrongBinder();
1612 return NO_ERROR;
1613 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1614 int ret;
1615 Parcel data2, reply2;
1616 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1617 sp<IBinder> target;
1618 sp<IBinder> callback;
1619
1620 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001621 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001622 return BAD_VALUE;
1623 }
1624 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001625 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001626 return BAD_VALUE;
1627 }
1628 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001629 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001630 data2.writeInt32(ret);
1631 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1632 return NO_ERROR;
1633 }
1634 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1635 int ret;
1636 int32_t size;
1637 const void *buf;
1638 int fd;
1639
1640 fd = data.readFileDescriptor();
1641 if (fd < 0) {
1642 return BAD_VALUE;
1643 }
1644 ret = data.readInt32(&size);
1645 if (ret != NO_ERROR) {
1646 return ret;
1647 }
1648 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001649 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001650 return BAD_VALUE;
1651 }
1652 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001653 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001654 return NO_ERROR;
1655 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001656 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1657 int ret;
1658 int32_t size;
1659 const void *buf;
1660 android::base::unique_fd fd;
1661
1662 ret = data.readUniqueParcelFileDescriptor(&fd);
1663 if (ret != NO_ERROR) {
1664 return ret;
1665 }
1666 ret = data.readInt32(&size);
1667 if (ret != NO_ERROR) {
1668 return ret;
1669 }
1670 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001671 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001672 return BAD_VALUE;
1673 }
1674 ret = write(fd.get(), buf, size);
1675 if (ret != size) return UNKNOWN_ERROR;
1676 return NO_ERROR;
1677 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001678 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1679 alarm(10);
1680 return NO_ERROR;
1681 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001682 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001683 ;
1684 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001685 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001686 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001687 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001688 return NO_ERROR;
1689 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001690 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1691 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001692 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001693 return NO_ERROR;
1694 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001695 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1696 int policy = 0;
1697 sched_param param;
1698 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1699 return UNKNOWN_ERROR;
1700 }
1701 reply->writeInt32(policy);
1702 reply->writeInt32(param.sched_priority);
1703 return NO_ERROR;
1704 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001705 case BINDER_LIB_TEST_ECHO_VECTOR: {
1706 std::vector<uint64_t> vector;
1707 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001708 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001709 reply->writeUint64Vector(vector);
1710 return NO_ERROR;
1711 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001712 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001713 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1714 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001715 case BINDER_LIB_TEST_CAN_GET_SID: {
1716 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1717 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001718 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1719 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1720 return NO_ERROR;
1721 }
1722 case BINDER_LIB_TEST_PROCESS_LOCK: {
1723 blockMutex.lock();
1724 return NO_ERROR;
1725 }
1726 case BINDER_LIB_TEST_LOCK_UNLOCK: {
1727 std::lock_guard<std::mutex> _l(blockMutex);
1728 return NO_ERROR;
1729 }
1730 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1731 int32_t ms = data.readInt32();
1732 return unlockInMs(ms);
1733 }
1734 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
1735 blockMutex.lock();
1736 std::thread t([&] {
1737 unlockInMs(data.readInt32());
1738 }); // start local thread to unlock in 1s
1739 t.detach();
1740 return NO_ERROR;
1741 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001742 default:
1743 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001744 };
1745 }
1746
Elie Kheirallah47431c12022-04-21 23:46:17 +00001747 status_t unlockInMs(int32_t ms) {
1748 usleep(ms * 1000);
1749 blockMutex.unlock();
1750 return NO_ERROR;
1751 }
1752
Yifan Hong543edcd2021-05-18 19:47:30 -07001753private:
1754 int32_t m_id;
1755 int32_t m_nextServerId;
1756 pthread_mutex_t m_serverWaitMutex;
1757 pthread_cond_t m_serverWaitCond;
1758 bool m_serverStartRequested;
1759 sp<IBinder> m_serverStarted;
1760 sp<IBinder> m_strongRef;
1761 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001762 bool m_exitOnDestroy;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001763 std::mutex blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001764};
1765
Martijn Coenen45b07b42017-08-09 12:07:45 +02001766int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001767{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001768 binderLibTestServiceName += String16(binderserversuffix);
1769
Steven Moreland35626652021-05-15 01:32:04 +00001770 // Testing to make sure that calls that we are serving can use getCallin*
1771 // even though we don't here.
1772 IPCThreadState::SpGuard spGuard{
1773 .address = __builtin_frame_address(0),
1774 .context = "main server thread",
1775 };
1776 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1777
Riley Andrews06b01ad2014-12-18 12:10:08 -08001778 status_t ret;
1779 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001780 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001781 {
1782 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001783
Steven Morelandbf1915b2020-07-16 22:43:02 +00001784 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1785
Steven Morelandcf03cf12020-12-04 02:58:40 +00001786 testService->setInheritRt(true);
1787
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001788 /*
1789 * Normally would also contain functionality as well, but we are only
1790 * testing the extension mechanism.
1791 */
1792 testService->setExtension(new BBinder());
1793
Martijn Coenen82c75312019-07-24 15:18:30 +02001794 // Required for test "BufRejected'
1795 testService->setRequestingSid(true);
1796
Martijn Coenen45b07b42017-08-09 12:07:45 +02001797 /*
1798 * We need this below, but can't hold a sp<> because it prevents the
1799 * node from being cleaned up automatically. It's safe in this case
1800 * because of how the tests are written.
1801 */
1802 testServicePtr = testService.get();
1803
Riley Andrews06b01ad2014-12-18 12:10:08 -08001804 if (index == 0) {
1805 ret = sm->addService(binderLibTestServiceName, testService);
1806 } else {
1807 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1808 Parcel data, reply;
1809 data.writeInt32(index);
1810 data.writeStrongBinder(testService);
1811
1812 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1813 }
1814 }
1815 write(readypipefd, &ret, sizeof(ret));
1816 close(readypipefd);
1817 //printf("%s: ret %d\n", __func__, ret);
1818 if (ret)
1819 return 1;
1820 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001821 if (usePoll) {
1822 int fd;
1823 struct epoll_event ev;
1824 int epoll_fd;
1825 IPCThreadState::self()->setupPolling(&fd);
1826 if (fd < 0) {
1827 return 1;
1828 }
1829 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1830
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001831 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001832 if (epoll_fd == -1) {
1833 return 1;
1834 }
1835
1836 ev.events = EPOLLIN;
1837 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1838 return 1;
1839 }
1840
1841 while (1) {
1842 /*
1843 * We simulate a single-threaded process using the binder poll
1844 * interface; besides handling binder commands, it can also
1845 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001846 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001847 *
1848 * processPendingCall() will then issue that transaction.
1849 */
1850 struct epoll_event events[1];
1851 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1852 if (numEvents < 0) {
1853 if (errno == EINTR) {
1854 continue;
1855 }
1856 return 1;
1857 }
1858 if (numEvents > 0) {
1859 IPCThreadState::self()->handlePolledCommands();
1860 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
1861 testServicePtr->processPendingCall();
1862 }
1863 }
1864 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001865 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001866 ProcessState::self()->startThreadPool();
1867 IPCThreadState::self()->joinThreadPool();
1868 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001869 //printf("%s: joinThreadPool returned\n", __func__);
1870 return 1; /* joinThreadPool should not return */
1871}
1872
1873int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07001874 ExitIfWrongAbi();
1875
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001876 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001877 binderservername = argv[2];
1878 } else {
1879 binderservername = argv[0];
1880 }
1881
Martijn Coenen45b07b42017-08-09 12:07:45 +02001882 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
1883 binderserversuffix = argv[5];
1884 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001885 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001886 binderserversuffix = new char[16];
1887 snprintf(binderserversuffix, 16, "%d", getpid());
1888 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001889
1890 ::testing::InitGoogleTest(&argc, argv);
1891 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
1892 ProcessState::self()->startThreadPool();
1893 return RUN_ALL_TESTS();
1894}