blob: 9b1ba01146fcc21378f5fc50a77ba34088907f43 [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>
Riley Andrews06b01ad2014-12-18 12:10:08 -080032#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070033#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000034#include <binder/Functional.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080035#include <binder/IBinder.h>
36#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070038#include <binder/RpcServer.h>
39#include <binder/RpcSession.h>
Parth Sane81b4d5a2024-05-23 14:11:13 +000040#include <binder/Status.h>
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070041#include <binder/unique_fd.h>
Tomasz Wasilczyk300aa132023-10-26 15:00:04 -070042#include <utils/Flattenable.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
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -070050#include "../Utils.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000051#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070052
Riley Andrews06b01ad2014-12-18 12:10:08 -080053using namespace android;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000054using namespace android::binder::impl;
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;
Parth Sane81b4d5a2024-05-23 14:11:13 +000058using android::binder::Status;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070059using android::binder::unique_fd;
Yifan Hong84bedeb2021-04-21 21:37:17 -070060using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080061using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070062using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070063using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070064
65// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
66MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
67 *result_listener << statusToString(arg);
68 return expected == arg;
69}
Riley Andrews06b01ad2014-12-18 12:10:08 -080070
Sherry Yang336cdd32017-07-24 14:12:27 -070071static ::testing::AssertionResult IsPageAligned(void *buf) {
Vilas Bhat04e28c72024-02-12 21:47:15 +000072 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
Sherry Yang336cdd32017-07-24 14:12:27 -070073 return ::testing::AssertionSuccess();
74 else
75 return ::testing::AssertionFailure() << buf << " is not page aligned";
76}
77
Riley Andrews06b01ad2014-12-18 12:10:08 -080078static testing::Environment* binder_env;
79static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070080static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080081static char binderserverarg[] = "--binderserver";
82
Steven Morelandbf1915b2020-07-16 22:43:02 +000083static constexpr int kSchedPolicy = SCHED_RR;
84static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000085static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000086static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000087
Riley Andrews06b01ad2014-12-18 12:10:08 -080088static String16 binderLibTestServiceName = String16("test.binderLib");
89
90enum BinderLibTestTranscationCode {
91 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
92 BINDER_LIB_TEST_REGISTER_SERVER,
93 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020094 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000095 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -080096 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -070097 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +020098 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -080099 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700100 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800101 BINDER_LIB_TEST_GET_ID_TRANSACTION,
102 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
103 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
104 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
105 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
106 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
107 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900108 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800109 BINDER_LIB_TEST_EXIT_TRANSACTION,
110 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
111 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700112 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100113 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000114 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700115 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
116 BINDER_LIB_TEST_GETPID,
Jing Jibdbe29a2023-10-03 00:03:28 -0700117 BINDER_LIB_TEST_GETUID,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800118 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700119 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700120 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000121 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000122 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
123 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000124 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000125 BINDER_LIB_TEST_LOCK_UNLOCK,
126 BINDER_LIB_TEST_PROCESS_LOCK,
127 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
128 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800129};
130
Martijn Coenen45b07b42017-08-09 12:07:45 +0200131pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800132{
133 int ret;
134 pid_t pid;
135 status_t status;
136 int pipefd[2];
137 char stri[16];
138 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200139 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800140 char *childargv[] = {
141 binderservername,
142 binderserverarg,
143 stri,
144 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200145 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700146 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700147 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800148 };
149
150 ret = pipe(pipefd);
151 if (ret < 0)
152 return ret;
153
154 snprintf(stri, sizeof(stri), "%d", arg2);
155 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200156 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800157
158 pid = fork();
159 if (pid == -1)
160 return pid;
161 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800162 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800163 close(pipefd[0]);
164 execv(binderservername, childargv);
165 status = -errno;
166 write(pipefd[1], &status, sizeof(status));
167 fprintf(stderr, "execv failed, %s\n", strerror(errno));
168 _exit(EXIT_FAILURE);
169 }
170 close(pipefd[1]);
171 ret = read(pipefd[0], &status, sizeof(status));
172 //printf("pipe read returned %d, status %d\n", ret, status);
173 close(pipefd[0]);
174 if (ret == sizeof(status)) {
175 ret = status;
176 } else {
177 kill(pid, SIGKILL);
178 if (ret >= 0) {
179 ret = NO_INIT;
180 }
181 }
182 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700183 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800184 return ret;
185 }
186 return pid;
187}
188
Yifan Hong84bedeb2021-04-21 21:37:17 -0700189android::base::Result<int32_t> GetId(sp<IBinder> service) {
190 using android::base::Error;
191 Parcel data, reply;
192 data.markForBinder(service);
193 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
194 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
195 if (status != OK)
196 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
197 int32_t result = 0;
198 status = reply.readInt32(&result);
199 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
200 return result;
201}
202
Riley Andrews06b01ad2014-12-18 12:10:08 -0800203class BinderLibTestEnv : public ::testing::Environment {
204 public:
205 BinderLibTestEnv() {}
206 sp<IBinder> getServer(void) {
207 return m_server;
208 }
209
210 private:
211 virtual void SetUp() {
212 m_serverpid = start_server_process(0);
213 //printf("m_serverpid %d\n", m_serverpid);
214 ASSERT_GT(m_serverpid, 0);
215
216 sp<IServiceManager> sm = defaultServiceManager();
217 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700218 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -0800219 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700220 LIBBINDER_IGNORE_END()
Yi Kong91635562018-06-07 14:38:36 -0700221 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800222 //printf("%s: pid %d, get service done\n", __func__, m_pid);
223 }
224 virtual void TearDown() {
225 status_t ret;
226 Parcel data, reply;
227 int exitStatus;
228 pid_t pid;
229
230 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700231 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800232 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
233 EXPECT_EQ(0, ret);
234 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
235 EXPECT_EQ(0, ret);
236 }
237 if (m_serverpid > 0) {
238 //printf("wait for %d\n", m_pids[i]);
239 pid = wait(&exitStatus);
240 EXPECT_EQ(m_serverpid, pid);
241 EXPECT_TRUE(WIFEXITED(exitStatus));
242 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
243 }
244 }
245
246 pid_t m_serverpid;
247 sp<IBinder> m_server;
248};
249
250class BinderLibTest : public ::testing::Test {
251 public:
252 virtual void SetUp() {
253 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Parth Sane81b4d5a2024-05-23 14:11:13 +0000254 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800255 }
256 virtual void TearDown() {
257 }
258 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200259 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800260 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800261 int32_t id;
262 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800263
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700264 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800265
Elie Kheirallahb7246642022-05-03 18:01:43 +0000266 sp<IBinder> binder = reply.readStrongBinder();
267 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700268 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800269 if (idPtr)
270 *idPtr = id;
271 return binder;
272 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200273
Yi Kong91635562018-06-07 14:38:36 -0700274 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200275 {
276 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
277 }
278
Yi Kong91635562018-06-07 14:38:36 -0700279 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200280 {
281 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
282 }
283
Riley Andrews06b01ad2014-12-18 12:10:08 -0800284 void waitForReadData(int fd, int timeout_ms) {
285 int ret;
286 pollfd pfd = pollfd();
287
288 pfd.fd = fd;
289 pfd.events = POLLIN;
290 ret = poll(&pfd, 1, timeout_ms);
291 EXPECT_EQ(1, ret);
292 }
293
294 sp<IBinder> m_server;
295};
296
297class BinderLibTestBundle : public Parcel
298{
299 public:
300 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800301 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800302 int32_t mark;
303 int32_t bundleLen;
304 size_t pos;
305
306 if (source->readInt32(&mark))
307 return;
308 if (mark != MARK_START)
309 return;
310 if (source->readInt32(&bundleLen))
311 return;
312 pos = source->dataPosition();
313 if (Parcel::appendFrom(source, pos, bundleLen))
314 return;
315 source->setDataPosition(pos + bundleLen);
316 if (source->readInt32(&mark))
317 return;
318 if (mark != MARK_END)
319 return;
320 m_isValid = true;
321 setDataPosition(0);
322 }
323 void appendTo(Parcel *dest) {
324 dest->writeInt32(MARK_START);
325 dest->writeInt32(dataSize());
326 dest->appendFrom(this, 0, dataSize());
327 dest->writeInt32(MARK_END);
328 };
329 bool isValid(void) {
330 return m_isValid;
331 }
332 private:
333 enum {
334 MARK_START = B_PACK_CHARS('B','T','B','S'),
335 MARK_END = B_PACK_CHARS('B','T','B','E'),
336 };
337 bool m_isValid;
338};
339
340class BinderLibTestEvent
341{
342 public:
343 BinderLibTestEvent(void)
344 : m_eventTriggered(false)
345 {
Yi Kong91635562018-06-07 14:38:36 -0700346 pthread_mutex_init(&m_waitMutex, nullptr);
347 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800348 }
349 int waitEvent(int timeout_s)
350 {
351 int ret;
352 pthread_mutex_lock(&m_waitMutex);
353 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800354 struct timespec ts;
355 clock_gettime(CLOCK_REALTIME, &ts);
356 ts.tv_sec += timeout_s;
357 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800358 }
359 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
360 pthread_mutex_unlock(&m_waitMutex);
361 return ret;
362 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200363 pthread_t getTriggeringThread()
364 {
365 return m_triggeringThread;
366 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800367 protected:
368 void triggerEvent(void) {
369 pthread_mutex_lock(&m_waitMutex);
370 pthread_cond_signal(&m_waitCond);
371 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200372 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800373 pthread_mutex_unlock(&m_waitMutex);
374 };
375 private:
376 pthread_mutex_t m_waitMutex;
377 pthread_cond_t m_waitCond;
378 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200379 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800380};
381
382class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
383{
384 public:
385 BinderLibTestCallBack()
386 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700387 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800388 {
389 }
390 status_t getResult(void)
391 {
392 return m_result;
393 }
394
395 private:
396 virtual status_t onTransact(uint32_t code,
397 const Parcel& data, Parcel* reply,
398 uint32_t flags = 0)
399 {
400 (void)reply;
401 (void)flags;
402 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200403 case BINDER_LIB_TEST_CALL_BACK: {
404 status_t status = data.readInt32(&m_result);
405 if (status != NO_ERROR) {
406 m_result = status;
407 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800408 triggerEvent();
409 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200410 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700411 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
412 sp<IBinder> server;
413 int ret;
414 const uint8_t *buf = data.data();
415 size_t size = data.dataSize();
416 if (m_prev_end) {
417 /* 64-bit kernel needs at most 8 bytes to align buffer end */
418 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
419 } else {
420 EXPECT_TRUE(IsPageAligned((void *)buf));
421 }
422
423 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
424
425 if (size > 0) {
426 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
427 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
428 data, reply);
429 EXPECT_EQ(NO_ERROR, ret);
430 }
431 return NO_ERROR;
432 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800433 default:
434 return UNKNOWN_TRANSACTION;
435 }
436 }
437
438 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700439 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800440};
441
442class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
443{
444 private:
445 virtual void binderDied(const wp<IBinder>& who) {
446 (void)who;
447 triggerEvent();
448 };
449};
450
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700451TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
452 // EXPECT_DEATH works by forking the process
453 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
454}
455
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000456TEST_F(BinderLibTest, AddManagerToManager) {
457 sp<IServiceManager> sm = defaultServiceManager();
458 sp<IBinder> binder = IInterface::asBinder(sm);
459 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
460}
461
Parth Sane81b4d5a2024-05-23 14:11:13 +0000462TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
463 auto sm = defaultServiceManager();
464 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
465 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
466 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
467 virtual ~LocalRegistrationCallbackImpl() {}
468 };
469 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
470
471 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
472 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
473}
474
475TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
476 auto sm = defaultServiceManager();
477 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
478 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
479 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
480 virtual ~LocalRegistrationCallbackImpl() {}
481 };
482 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
483
484 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
485
486 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
487 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
488 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
489}
490
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500491TEST_F(BinderLibTest, WasParceled) {
492 auto binder = sp<BBinder>::make();
493 EXPECT_FALSE(binder->wasParceled());
494 Parcel data;
495 data.writeStrongBinder(binder);
496 EXPECT_TRUE(binder->wasParceled());
497}
498
Riley Andrews06b01ad2014-12-18 12:10:08 -0800499TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800500 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700501 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
502 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800503}
504
Steven Moreland80844f72020-12-12 02:06:08 +0000505TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000506 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700507 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
508 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000509}
510
Steven Morelandf183fdd2020-10-27 00:12:12 +0000511TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000512 Parcel data, reply;
513 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700514 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
515 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000516}
517
Marco Ballesio7ee17572020-09-08 10:30:03 -0700518TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700519 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700520 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700521
Li Li6f059292021-09-10 09:59:30 -0700522 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700523 if (freezer_file.fail()) {
524 GTEST_SKIP();
525 return;
526 }
527
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700528 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700529 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700530 for (int i = 0; i < 10; i++) {
531 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
532 }
Li Li6f059292021-09-10 09:59:30 -0700533
534 // Pass test on devices where BINDER_FREEZE ioctl is not supported
535 int ret = IPCThreadState::self()->freeze(pid, false, 0);
Alice Ryhl4634c902024-04-11 12:52:11 +0000536 if (ret == -EINVAL) {
Li Li6f059292021-09-10 09:59:30 -0700537 GTEST_SKIP();
538 return;
539 }
Alice Ryhl4634c902024-04-11 12:52:11 +0000540 EXPECT_EQ(NO_ERROR, ret);
Li Li6f059292021-09-10 09:59:30 -0700541
542 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000543
544 // b/268232063 - succeeds ~0.08% of the time
545 {
546 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
547 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
548 }
549
Li Li6f059292021-09-10 09:59:30 -0700550 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700551 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700552
Li Li4e678b92021-09-14 12:14:42 -0700553 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700554
555 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
556 &async_received));
557
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700558 EXPECT_EQ(sync_received, 1u);
559 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700560
Li Li4e678b92021-09-14 12:14:42 -0700561 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700562 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
563}
564
Riley Andrews06b01ad2014-12-18 12:10:08 -0800565TEST_F(BinderLibTest, SetError) {
566 int32_t testValue[] = { 0, -123, 123 };
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700567 for (size_t i = 0; i < countof(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800568 Parcel data, reply;
569 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700570 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
571 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800572 }
573}
574
575TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700576 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800577}
578
579TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800580 int32_t ptrsize;
581 Parcel data, reply;
582 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700583 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700584 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
585 StatusEq(NO_ERROR));
586 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800587 RecordProperty("TestPtrSize", sizeof(void *));
588 RecordProperty("ServerPtrSize", sizeof(void *));
589}
590
591TEST_F(BinderLibTest, IndirectGetId2)
592{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800593 int32_t id;
594 int32_t count;
595 Parcel data, reply;
596 int32_t serverId[3];
597
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700598 data.writeInt32(countof(serverId));
599 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800600 sp<IBinder> server;
601 BinderLibTestBundle datai;
602
603 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700604 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800605 data.writeStrongBinder(server);
606 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
607 datai.appendTo(&data);
608 }
609
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700610 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
611 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800612
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700613 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800614 EXPECT_EQ(0, id);
615
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700616 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700617 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800618
619 for (size_t i = 0; i < (size_t)count; i++) {
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 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
625 }
626
627 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
628}
629
630TEST_F(BinderLibTest, IndirectGetId3)
631{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800632 int32_t id;
633 int32_t count;
634 Parcel data, reply;
635 int32_t serverId[3];
636
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700637 data.writeInt32(countof(serverId));
638 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800639 sp<IBinder> server;
640 BinderLibTestBundle datai;
641 BinderLibTestBundle datai2;
642
643 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700644 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800645 data.writeStrongBinder(server);
646 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
647
648 datai.writeInt32(1);
649 datai.writeStrongBinder(m_server);
650 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
651 datai2.appendTo(&datai);
652
653 datai.appendTo(&data);
654 }
655
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700656 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
657 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800658
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700659 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800660 EXPECT_EQ(0, id);
661
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700662 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700663 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800664
665 for (size_t i = 0; i < (size_t)count; i++) {
666 int32_t counti;
667
668 BinderLibTestBundle replyi(&reply);
669 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700670 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800671 EXPECT_EQ(serverId[i], id);
672
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700673 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800674 EXPECT_EQ(1, counti);
675
676 BinderLibTestBundle replyi2(&replyi);
677 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700678 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800679 EXPECT_EQ(0, id);
680 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
681
682 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
683 }
684
685 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
686}
687
688TEST_F(BinderLibTest, CallBack)
689{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800690 Parcel data, reply;
691 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
692 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700693 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
694 StatusEq(NO_ERROR));
695 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
696 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800697}
698
Steven Moreland35626652021-05-15 01:32:04 +0000699TEST_F(BinderLibTest, BinderCallContextGuard) {
700 sp<IBinder> binder = addServer();
701 Parcel data, reply;
702 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
703 StatusEq(DEAD_OBJECT));
704}
705
Riley Andrews06b01ad2014-12-18 12:10:08 -0800706TEST_F(BinderLibTest, AddServer)
707{
708 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700709 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800710}
711
Riley Andrews06b01ad2014-12-18 12:10:08 -0800712TEST_F(BinderLibTest, DeathNotificationStrongRef)
713{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800714 sp<IBinder> sbinder;
715
716 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
717
718 {
719 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700720 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700721 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800722 sbinder = binder;
723 }
724 {
725 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700726 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
727 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800728 }
729 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700730 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
731 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800732}
733
734TEST_F(BinderLibTest, DeathNotificationMultiple)
735{
736 status_t ret;
737 const int clientcount = 2;
738 sp<IBinder> target;
739 sp<IBinder> linkedclient[clientcount];
740 sp<BinderLibTestCallBack> callBack[clientcount];
741 sp<IBinder> passiveclient[clientcount];
742
743 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700744 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800745 for (int i = 0; i < clientcount; i++) {
746 {
747 Parcel data, reply;
748
749 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700750 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800751 callBack[i] = new BinderLibTestCallBack();
752 data.writeStrongBinder(target);
753 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700754 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
755 &reply, TF_ONE_WAY),
756 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800757 }
758 {
759 Parcel data, reply;
760
761 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700762 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800763 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700764 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
765 &reply, TF_ONE_WAY),
766 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800767 }
768 }
769 {
770 Parcel data, reply;
771 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
772 EXPECT_EQ(0, ret);
773 }
774
775 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700776 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
777 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800778 }
779}
780
Martijn Coenenf7100e42017-07-31 12:14:09 +0200781TEST_F(BinderLibTest, DeathNotificationThread)
782{
783 status_t ret;
784 sp<BinderLibTestCallBack> callback;
785 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700786 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200787 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700788 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200789
790 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
791
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700792 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200793
794 {
795 Parcel data, reply;
796 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
797 EXPECT_EQ(0, ret);
798 }
799
800 /* Make sure it's dead */
801 testDeathRecipient->waitEvent(5);
802
803 /* Now, pass the ref to another process and ask that process to
804 * call linkToDeath() on it, and wait for a response. This tests
805 * two things:
806 * 1) You still get death notifications when calling linkToDeath()
807 * on a ref that is already dead when it was passed to you.
808 * 2) That death notifications are not directly pushed to the thread
809 * registering them, but to the threadpool (proc workqueue) instead.
810 *
811 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
812 * is blocked on a condition variable waiting for the death notification to be
813 * called; therefore, that thread is not available for handling proc work.
814 * So, if the death notification was pushed to the thread workqueue, the callback
815 * would never be called, and the test would timeout and fail.
816 *
817 * Note that we can't do this part of the test from this thread itself, because
818 * the binder driver would only push death notifications to the thread if
819 * it is a looper thread, which this thread is not.
820 *
821 * See b/23525545 for details.
822 */
823 {
824 Parcel data, reply;
825
826 callback = new BinderLibTestCallBack();
827 data.writeStrongBinder(target);
828 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700829 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
830 TF_ONE_WAY),
831 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200832 }
833
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700834 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
835 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200836}
837
Riley Andrews06b01ad2014-12-18 12:10:08 -0800838TEST_F(BinderLibTest, PassFile) {
839 int ret;
840 int pipefd[2];
841 uint8_t buf[1] = { 0 };
842 uint8_t write_value = 123;
843
844 ret = pipe2(pipefd, O_NONBLOCK);
845 ASSERT_EQ(0, ret);
846
847 {
848 Parcel data, reply;
849 uint8_t writebuf[1] = { write_value };
850
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700851 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800852
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700853 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800854
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700855 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800856
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700857 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
858 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800859 }
860
861 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700862 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800863 EXPECT_EQ(write_value, buf[0]);
864
865 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
866
867 ret = read(pipefd[0], buf, sizeof(buf));
868 EXPECT_EQ(0, ret);
869
870 close(pipefd[0]);
871}
872
Ryo Hashimotobf551892018-05-31 16:58:35 +0900873TEST_F(BinderLibTest, PassParcelFileDescriptor) {
874 const int datasize = 123;
875 std::vector<uint8_t> writebuf(datasize);
876 for (size_t i = 0; i < writebuf.size(); ++i) {
877 writebuf[i] = i;
878 }
879
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -0700880 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +0900881 {
882 int pipefd[2];
883 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
884 read_end.reset(pipefd[0]);
885 write_end.reset(pipefd[1]);
886 }
887 {
888 Parcel data;
889 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
890 write_end.reset();
891 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
892 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
893
894 Parcel reply;
895 EXPECT_EQ(NO_ERROR,
896 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
897 &reply));
898 }
899 std::vector<uint8_t> readbuf(datasize);
900 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
901 EXPECT_EQ(writebuf, readbuf);
902
903 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
904
905 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
906}
907
Riley Andrews06b01ad2014-12-18 12:10:08 -0800908TEST_F(BinderLibTest, PromoteLocal) {
909 sp<IBinder> strong = new BBinder();
910 wp<IBinder> weak = strong;
911 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700912 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800913 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700914 strong = nullptr;
915 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800916 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700917 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800918}
919
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700920TEST_F(BinderLibTest, LocalGetExtension) {
921 sp<BBinder> binder = new BBinder();
922 sp<IBinder> ext = new BBinder();
923 binder->setExtension(ext);
924 EXPECT_EQ(ext, binder->getExtension());
925}
926
927TEST_F(BinderLibTest, RemoteGetExtension) {
928 sp<IBinder> server = addServer();
929 ASSERT_TRUE(server != nullptr);
930
931 sp<IBinder> extension;
932 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
933 ASSERT_NE(nullptr, extension.get());
934
935 EXPECT_EQ(NO_ERROR, extension->pingBinder());
936}
937
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700938TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700939 Parcel data, reply;
940
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700941 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
942 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700943
944 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700945 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800946 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
947 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
948 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
949 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700950}
951
Connor O'Brien52be2c92016-09-20 14:18:08 -0700952TEST_F(BinderLibTest, FreedBinder) {
953 status_t ret;
954
955 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700956 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700957
958 __u32 freedHandle;
959 wp<IBinder> keepFreedBinder;
960 {
961 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700962 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
963 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700964 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
965 freedHandle = freed->handle;
966 /* Add a weak ref to the freed binder so the driver does not
967 * delete its reference to it - otherwise the transaction
968 * fails regardless of whether the driver is fixed.
969 */
Steven Morelande171d622019-07-17 16:06:01 -0700970 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700971 }
Steven Morelande171d622019-07-17 16:06:01 -0700972 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700973 {
974 Parcel data, reply;
975 data.writeStrongBinder(server);
976 /* Replace original handle with handle to the freed binder */
977 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
978 __u32 oldHandle = strong->handle;
979 strong->handle = freedHandle;
980 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
981 /* Returns DEAD_OBJECT (-32) if target crashes and
982 * FAILED_TRANSACTION if the driver rejects the invalid
983 * object.
984 */
985 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
986 /* Restore original handle so parcel destructor does not use
987 * the wrong handle.
988 */
989 strong->handle = oldHandle;
990 }
991}
992
Sherry Yang336cdd32017-07-24 14:12:27 -0700993TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700994 Parcel data, reply;
995 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
996 for (int i = 0; i < 2; i++) {
997 BinderLibTestBundle datai;
998 datai.appendFrom(&data, 0, data.dataSize());
999
1000 data.freeData();
1001 data.writeInt32(1);
1002 data.writeStrongBinder(callBack);
1003 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1004
1005 datai.appendTo(&data);
1006 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001007 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1008 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -07001009}
1010
Martijn Coenen45b07b42017-08-09 12:07:45 +02001011TEST_F(BinderLibTest, OnewayQueueing)
1012{
Martijn Coenen45b07b42017-08-09 12:07:45 +02001013 Parcel data, data2;
1014
1015 sp<IBinder> pollServer = addPollServer();
1016
1017 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1018 data.writeStrongBinder(callBack);
1019 data.writeInt32(500000); // delay in us before calling back
1020
1021 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1022 data2.writeStrongBinder(callBack2);
1023 data2.writeInt32(0); // delay in us
1024
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001025 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1026 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001027
1028 // The delay ensures that this second transaction will end up on the async_todo list
1029 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001030 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1031 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001032
1033 // The server will ensure that the two transactions are handled in the expected order;
1034 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001035 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1036 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001037
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001038 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1039 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001040}
1041
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001042TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1043{
1044 status_t ret;
1045 Parcel data, reply;
1046 data.writeInterfaceToken(binderLibTestServiceName);
1047 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1048 EXPECT_EQ(-1, reply.readInt32());
1049 EXPECT_EQ(NO_ERROR, ret);
1050}
1051
1052TEST_F(BinderLibTest, WorkSourceSet)
1053{
1054 status_t ret;
1055 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001056 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001057 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001058 data.writeInterfaceToken(binderLibTestServiceName);
1059 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1060 EXPECT_EQ(100, reply.readInt32());
1061 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001062 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1063 EXPECT_EQ(NO_ERROR, ret);
1064}
1065
1066TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1067{
1068 status_t ret;
1069 Parcel data, reply;
1070
1071 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1072 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1073
1074 data.writeInterfaceToken(binderLibTestServiceName);
1075 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1076 EXPECT_EQ(-1, reply.readInt32());
1077 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001078 EXPECT_EQ(NO_ERROR, ret);
1079}
1080
1081TEST_F(BinderLibTest, WorkSourceCleared)
1082{
1083 status_t ret;
1084 Parcel data, reply;
1085
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001086 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001087 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1088 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001089 data.writeInterfaceToken(binderLibTestServiceName);
1090 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1091
1092 EXPECT_EQ(-1, reply.readInt32());
1093 EXPECT_EQ(100, previousWorkSource);
1094 EXPECT_EQ(NO_ERROR, ret);
1095}
1096
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001097TEST_F(BinderLibTest, WorkSourceRestored)
1098{
1099 status_t ret;
1100 Parcel data, reply;
1101
1102 IPCThreadState::self()->setCallingWorkSourceUid(100);
1103 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1104 IPCThreadState::self()->restoreCallingWorkSource(token);
1105
1106 data.writeInterfaceToken(binderLibTestServiceName);
1107 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1108
1109 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001110 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001111 EXPECT_EQ(NO_ERROR, ret);
1112}
1113
Olivier Gaillard91a04802018-11-14 17:32:41 +00001114TEST_F(BinderLibTest, PropagateFlagSet)
1115{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001116 IPCThreadState::self()->clearPropagateWorkSource();
1117 IPCThreadState::self()->setCallingWorkSourceUid(100);
1118 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1119}
1120
1121TEST_F(BinderLibTest, PropagateFlagCleared)
1122{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001123 IPCThreadState::self()->setCallingWorkSourceUid(100);
1124 IPCThreadState::self()->clearPropagateWorkSource();
1125 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1126}
1127
1128TEST_F(BinderLibTest, PropagateFlagRestored)
1129{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001130 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1131 IPCThreadState::self()->restoreCallingWorkSource(token);
1132
1133 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1134}
1135
1136TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1137{
1138 IPCThreadState::self()->setCallingWorkSourceUid(100);
1139
1140 Parcel data, reply;
1141 status_t ret;
1142 data.writeInterfaceToken(binderLibTestServiceName);
1143 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001144 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001145
1146 Parcel data2, reply2;
1147 status_t ret2;
1148 data2.writeInterfaceToken(binderLibTestServiceName);
1149 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1150 EXPECT_EQ(100, reply2.readInt32());
1151 EXPECT_EQ(NO_ERROR, ret2);
1152}
1153
Steven Morelandbf1915b2020-07-16 22:43:02 +00001154TEST_F(BinderLibTest, SchedPolicySet) {
1155 sp<IBinder> server = addServer();
1156 ASSERT_TRUE(server != nullptr);
1157
1158 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001159 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1160 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001161
1162 int policy = reply.readInt32();
1163 int priority = reply.readInt32();
1164
1165 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1166 EXPECT_EQ(kSchedPriority, priority);
1167}
1168
Steven Morelandcf03cf12020-12-04 02:58:40 +00001169TEST_F(BinderLibTest, InheritRt) {
1170 sp<IBinder> server = addServer();
1171 ASSERT_TRUE(server != nullptr);
1172
1173 const struct sched_param param {
1174 .sched_priority = kSchedPriorityMore,
1175 };
1176 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1177
1178 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001179 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1180 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001181
1182 int policy = reply.readInt32();
1183 int priority = reply.readInt32();
1184
1185 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1186 EXPECT_EQ(kSchedPriorityMore, priority);
1187}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001188
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001189TEST_F(BinderLibTest, VectorSent) {
1190 Parcel data, reply;
1191 sp<IBinder> server = addServer();
1192 ASSERT_TRUE(server != nullptr);
1193
1194 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1195 data.writeUint64Vector(testValue);
1196
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001197 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001198 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001199 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001200 EXPECT_EQ(readValue, testValue);
1201}
1202
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001203TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1204 sp<IBinder> server = addServer();
1205 ASSERT_TRUE(server != nullptr);
1206
1207 Parcel reply;
1208 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1209 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001210 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001211 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1212
1213 const int result = fcntl(fd.get(), F_GETFL);
1214 ASSERT_NE(result, -1);
1215 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1216}
1217
Steven Moreland59b84442022-07-12 18:32:44 +00001218// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1219// This value is not exposed, but some code in the framework relies on being able to use
1220// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001221constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001222constexpr size_t kSizeBytesOverFull = 1'050'000;
1223
1224TEST_F(BinderLibTest, GargantuanVectorSent) {
1225 sp<IBinder> server = addServer();
1226 ASSERT_TRUE(server != nullptr);
1227
1228 for (size_t i = 0; i < 10; i++) {
1229 // a slight variation in size is used to consider certain possible caching implementations
1230 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1231
1232 Parcel data, reply;
1233 data.writeUint64Vector(testValue);
1234 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1235 << i;
1236 std::vector<uint64_t> readValue;
1237 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1238 EXPECT_EQ(readValue, testValue);
1239 }
1240}
1241
1242TEST_F(BinderLibTest, LimitExceededVectorSent) {
1243 sp<IBinder> server = addServer();
1244 ASSERT_TRUE(server != nullptr);
1245 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1246
1247 Parcel data, reply;
1248 data.writeUint64Vector(testValue);
1249 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1250 StatusEq(FAILED_TRANSACTION));
1251}
1252
Martijn Coenen82c75312019-07-24 15:18:30 +02001253TEST_F(BinderLibTest, BufRejected) {
1254 Parcel data, reply;
1255 uint32_t buf;
1256 sp<IBinder> server = addServer();
1257 ASSERT_TRUE(server != nullptr);
1258
1259 binder_buffer_object obj {
1260 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001261 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001262 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1263 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001264 };
1265 data.setDataCapacity(1024);
1266 // Write a bogus object at offset 0 to get an entry in the offset table
1267 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001268 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001269 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1270 // And now, overwrite it with the buffer object
1271 memcpy(parcelData, &obj, sizeof(obj));
1272 data.setDataSize(sizeof(obj));
1273
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001274 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001275
Martijn Coenen82c75312019-07-24 15:18:30 +02001276 // Either the kernel should reject this transaction (if it's correct), but
1277 // if it's not, the server implementation should return an error if it
1278 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001279 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001280 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001281}
1282
Steven Morelandf2e0a952021-11-01 18:17:23 -07001283TEST_F(BinderLibTest, WeakRejected) {
1284 Parcel data, reply;
1285 sp<IBinder> server = addServer();
1286 ASSERT_TRUE(server != nullptr);
1287
1288 auto binder = sp<BBinder>::make();
1289 wp<BBinder> wpBinder(binder);
1290 flat_binder_object obj{
1291 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1292 .flags = 0,
1293 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1294 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1295 };
1296 data.setDataCapacity(1024);
1297 // Write a bogus object at offset 0 to get an entry in the offset table
1298 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001299 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001300 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1301 // And now, overwrite it with the weak binder
1302 memcpy(parcelData, &obj, sizeof(obj));
1303 data.setDataSize(sizeof(obj));
1304
1305 // a previous bug caused other objects to be released an extra time, so we
1306 // test with an object that libbinder will actually try to release
1307 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1308
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001309 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001310
1311 // send it many times, since previous error was memory corruption, make it
1312 // more likely that the server crashes
1313 for (size_t i = 0; i < 100; i++) {
1314 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1315 StatusEq(BAD_VALUE));
1316 }
1317
1318 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1319}
1320
Steven Moreland254e8ef2021-04-19 22:28:50 +00001321TEST_F(BinderLibTest, GotSid) {
1322 sp<IBinder> server = addServer();
1323
1324 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001325 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001326}
1327
Andrei Homescu1519b982022-06-09 02:04:44 +00001328struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1329 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1330
1331 // Flattenable protocol
1332 size_t getFlattenedSize() const {
1333 // Return a valid non-zero size here so we don't get an unintended
1334 // BAD_VALUE from Parcel::write
1335 return 16;
1336 }
1337 size_t getFdCount() const { return mFdCount; }
1338 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1339 for (size_t i = 0; i < count; i++) {
1340 fds[i] = STDIN_FILENO;
1341 }
1342 return NO_ERROR;
1343 }
1344 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1345 size_t & /*count*/) {
1346 /* This doesn't get called */
1347 return NO_ERROR;
1348 }
1349
1350 size_t mFdCount;
1351};
1352
1353TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1354 rlimit origNofile;
1355 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1356 ASSERT_EQ(0, ret);
1357
1358 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001359 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001360
1361 rlimit testNofile = {1024, 1024};
1362 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1363 ASSERT_EQ(0, ret);
1364
1365 Parcel parcel;
1366 // Try to write more file descriptors than supported by the OS
1367 TooManyFdsFlattenable tooManyFds1(1024);
1368 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1369
1370 // Try to write more file descriptors than the internal limit
1371 TooManyFdsFlattenable tooManyFds2(1025);
1372 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1373}
1374
Jayant Chowdhary30700942022-01-31 14:12:40 -08001375TEST(ServiceNotifications, Unregister) {
1376 auto sm = defaultServiceManager();
1377 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1378 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1379 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1380 virtual ~LocalRegistrationCallbackImpl() {}
1381 };
1382 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1383
1384 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1385 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1386}
1387
Elie Kheirallah47431c12022-04-21 23:46:17 +00001388TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1389 Parcel data, reply;
1390 sp<IBinder> server = addServer();
1391 ASSERT_TRUE(server != nullptr);
1392 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1393 StatusEq(NO_ERROR));
1394 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001395 // see getThreadPoolMaxTotalThreadCount for why there is a race
1396 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1397
Elie Kheirallah47431c12022-04-21 23:46:17 +00001398 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1399
1400 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001401 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1402 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1403 * started threads from setThreadPoolMaxThreadCount
1404 *
1405 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001406 */
1407 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001408 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001409 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001410 Parcel local_reply;
1411 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1412 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001413 }));
1414 }
1415
Steven Moreland3e9debc2023-06-15 00:35:29 +00001416 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1417 // the time, the below call will pre-empt them (presumably because we have the
1418 // scheduler timeslice already + scheduler hint).
1419 sleep(1);
1420
1421 data.writeInt32(1000);
1422 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001423 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1424
1425 for (auto &t : ts) {
1426 t.join();
1427 }
1428
1429 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1430 StatusEq(NO_ERROR));
1431 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001432 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001433}
1434
Devin Moore4354f712022-12-08 01:44:46 +00001435TEST_F(BinderLibTest, ThreadPoolStarted) {
1436 Parcel data, reply;
1437 sp<IBinder> server = addServer();
1438 ASSERT_TRUE(server != nullptr);
1439 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1440 EXPECT_TRUE(reply.readBool());
1441}
1442
Elie Kheirallah47431c12022-04-21 23:46:17 +00001443size_t epochMillis() {
1444 using std::chrono::duration_cast;
1445 using std::chrono::milliseconds;
1446 using std::chrono::seconds;
1447 using std::chrono::system_clock;
1448 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1449}
1450
1451TEST_F(BinderLibTest, HangingServices) {
1452 Parcel data, reply;
1453 sp<IBinder> server = addServer();
1454 ASSERT_TRUE(server != nullptr);
1455 int32_t delay = 1000; // ms
1456 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001457 // b/266537959 - must take before taking lock, since countdown is started in the remote
1458 // process there.
1459 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001460 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1461 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001462 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1463 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001464 Parcel local_reply;
1465 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1466 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001467 }));
1468 }
1469
1470 for (auto &t : ts) {
1471 t.join();
1472 }
1473 size_t epochMsAfter = epochMillis();
1474
1475 // deadlock occurred and threads only finished after 1s passed.
1476 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1477}
1478
Jing Jibbe9ae62023-10-07 15:26:02 -07001479TEST_F(BinderLibTest, BinderProxyCount) {
1480 Parcel data, reply;
1481 sp<IBinder> server = addServer();
1482 ASSERT_NE(server, nullptr);
1483
1484 uint32_t initialCount = BpBinder::getBinderProxyCount();
1485 size_t iterations = 100;
1486 {
1487 uint32_t count = initialCount;
1488 std::vector<sp<IBinder> > proxies;
1489 sp<IBinder> proxy;
1490 // Create binder proxies and verify the count.
1491 for (size_t i = 0; i < iterations; i++) {
1492 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1493 StatusEq(NO_ERROR));
1494 proxies.push_back(reply.readStrongBinder());
1495 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1496 }
1497 // Remove every other one and verify the count.
1498 auto it = proxies.begin();
1499 for (size_t i = 0; it != proxies.end(); i++) {
1500 if (i % 2 == 0) {
1501 it = proxies.erase(it);
1502 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1503 }
1504 }
1505 }
1506 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1507}
1508
Jing Jibdbe29a2023-10-03 00:03:28 -07001509static constexpr int kBpCountHighWatermark = 20;
1510static constexpr int kBpCountLowWatermark = 10;
1511static constexpr int kBpCountWarningWatermark = 15;
1512static constexpr int kInvalidUid = -1;
1513
1514TEST_F(BinderLibTest, BinderProxyCountCallback) {
1515 Parcel data, reply;
1516 sp<IBinder> server = addServer();
1517 ASSERT_NE(server, nullptr);
1518
1519 BpBinder::enableCountByUid();
1520 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1521 int32_t uid = reply.readInt32();
1522 ASSERT_NE(uid, kInvalidUid);
1523
1524 uint32_t initialCount = BpBinder::getBinderProxyCount();
1525 {
1526 uint32_t count = initialCount;
1527 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1528 kBpCountLowWatermark,
1529 kBpCountWarningWatermark);
1530 int limitCallbackUid = kInvalidUid;
1531 int warningCallbackUid = kInvalidUid;
1532 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1533 [&](int uid) { warningCallbackUid = uid; });
1534
1535 std::vector<sp<IBinder> > proxies;
1536 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1537 warningCallbackUid = limitCallbackUid = kInvalidUid;
1538 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1539 StatusEq(NO_ERROR));
1540 proxies.push_back(reply.readStrongBinder());
1541 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1542 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1543 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1544 };
1545 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1546 warningCallbackUid = limitCallbackUid = kInvalidUid;
1547 proxies.pop_back();
1548 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1549 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1550 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1551 };
1552
1553 // Test the increment/decrement of the binder proxies.
1554 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1555 createProxyOnce(kInvalidUid, kInvalidUid);
1556 }
1557 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1558 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1559 createProxyOnce(kInvalidUid, kInvalidUid);
1560 }
1561 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1562 createProxyOnce(kInvalidUid, kInvalidUid);
1563 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1564 removeProxyOnce(kInvalidUid, kInvalidUid);
1565 }
1566 createProxyOnce(kInvalidUid, kInvalidUid);
1567
1568 // Go down below the low watermark.
1569 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1570 removeProxyOnce(kInvalidUid, kInvalidUid);
1571 }
1572 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1573 createProxyOnce(kInvalidUid, kInvalidUid);
1574 }
1575 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1576 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1577 createProxyOnce(kInvalidUid, kInvalidUid);
1578 }
1579 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1580 createProxyOnce(kInvalidUid, kInvalidUid);
1581 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1582 removeProxyOnce(kInvalidUid, kInvalidUid);
1583 }
1584 createProxyOnce(kInvalidUid, kInvalidUid);
1585 }
1586 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1587}
1588
Yifan Hong84bedeb2021-04-21 21:37:17 -07001589class BinderLibRpcTestBase : public BinderLibTest {
1590public:
1591 void SetUp() override {
1592 if (!base::GetBoolProperty("ro.debuggable", false)) {
1593 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1594 "non-debuggable builds.";
1595 }
1596 BinderLibTest::SetUp();
1597 }
1598
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001599 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001600 auto rpcServer = RpcServer::make();
1601 EXPECT_NE(nullptr, rpcServer);
1602 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001603 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001604 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1605 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001606 return {};
1607 }
1608 return {rpcServer->releaseServer(), port};
1609 }
1610};
1611
Yifan Hong8b890852021-06-10 13:44:09 -07001612class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001613
Yifan Hongbd276552022-02-28 15:28:51 -08001614// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1615// If device is debuggable AND not on user builds, expects matcher.
1616// Otherwise expects INVALID_OPERATION.
1617// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1618static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1619 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1620 android::base::GetProperty("ro.build.type", "") != "user";
1621 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1622}
1623
Yifan Hong8b890852021-06-10 13:44:09 -07001624TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1625 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001626 ASSERT_TRUE(binder != nullptr);
1627 auto [socket, port] = CreateSocket();
1628 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001629 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1630 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001631}
1632
Yifan Hong8b890852021-06-10 13:44:09 -07001633// Tests for multiple RpcServer's on the same binder object.
1634TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1635 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001636 ASSERT_TRUE(binder != nullptr);
1637
1638 auto [socket1, port1] = CreateSocket();
1639 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001640 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001641 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1642 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001643
1644 auto [socket2, port2] = CreateSocket();
1645 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001646 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001647 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1648 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001649}
1650
Yifan Hong8b890852021-06-10 13:44:09 -07001651// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1652// local binders.
1653class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001654public:
1655 sp<IBinder> GetService() {
1656 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1657 }
1658 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1659 return info.param ? "remote" : "local";
1660 }
1661};
1662
Yifan Hong8b890852021-06-10 13:44:09 -07001663TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1664 auto binder = GetService();
1665 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001666 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001667 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001668}
1669
1670TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001671 auto binder = GetService();
1672 ASSERT_TRUE(binder != nullptr);
1673 auto [socket, port] = CreateSocket();
1674 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001675 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1676 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001677}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001678INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1679 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001680
Yifan Hong543edcd2021-05-18 19:47:30 -07001681class BinderLibTestService : public BBinder {
1682public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001683 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1684 : m_id(id),
1685 m_nextServerId(id + 1),
1686 m_serverStartRequested(false),
1687 m_callback(nullptr),
1688 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001689 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1690 pthread_cond_init(&m_serverWaitCond, nullptr);
1691 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001692 ~BinderLibTestService() {
1693 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1694 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001695
Yifan Hong543edcd2021-05-18 19:47:30 -07001696 void processPendingCall() {
1697 if (m_callback != nullptr) {
1698 Parcel data;
1699 data.writeInt32(NO_ERROR);
1700 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1701 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001702 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001703 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001704
Yifan Hong543edcd2021-05-18 19:47:30 -07001705 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1706 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001707 // TODO(b/182914638): also checks getCallingUid() for RPC
1708 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001709 return PERMISSION_DENIED;
1710 }
1711 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001712 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001713 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001714 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001715 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001716 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001717 return BAD_VALUE;
1718 }
1719
Yifan Hong543edcd2021-05-18 19:47:30 -07001720 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001721
1722 pthread_mutex_lock(&m_serverWaitMutex);
1723 if (m_serverStartRequested) {
1724 m_serverStartRequested = false;
1725 m_serverStarted = binder;
1726 pthread_cond_signal(&m_serverWaitCond);
1727 }
1728 pthread_mutex_unlock(&m_serverWaitMutex);
1729 return NO_ERROR;
1730 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001731 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001732 case BINDER_LIB_TEST_ADD_SERVER: {
1733 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001734 int serverid;
1735
1736 if (m_id != 0) {
1737 return INVALID_OPERATION;
1738 }
1739 pthread_mutex_lock(&m_serverWaitMutex);
1740 if (m_serverStartRequested) {
1741 ret = -EBUSY;
1742 } else {
1743 serverid = m_nextServerId++;
1744 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001745 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001746
1747 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001748 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001749 pthread_mutex_lock(&m_serverWaitMutex);
1750 }
1751 if (ret > 0) {
1752 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001753 struct timespec ts;
1754 clock_gettime(CLOCK_REALTIME, &ts);
1755 ts.tv_sec += 5;
1756 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001757 }
1758 if (m_serverStartRequested) {
1759 m_serverStartRequested = false;
1760 ret = -ETIMEDOUT;
1761 } else {
1762 reply->writeStrongBinder(m_serverStarted);
1763 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001764 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001765 ret = NO_ERROR;
1766 }
1767 } else if (ret >= 0) {
1768 m_serverStartRequested = false;
1769 ret = UNKNOWN_ERROR;
1770 }
1771 pthread_mutex_unlock(&m_serverWaitMutex);
1772 return ret;
1773 }
Steven Moreland35626652021-05-15 01:32:04 +00001774 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1775 IPCThreadState::SpGuard spGuard{
1776 .address = __builtin_frame_address(0),
1777 .context = "GuardInBinderTransaction",
1778 };
1779 const IPCThreadState::SpGuard *origGuard =
1780 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1781
1782 // if the guard works, this should abort
1783 (void)IPCThreadState::self()->getCallingPid();
1784
1785 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1786 return NO_ERROR;
1787 }
1788
Marco Ballesio7ee17572020-09-08 10:30:03 -07001789 case BINDER_LIB_TEST_GETPID:
1790 reply->writeInt32(getpid());
1791 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07001792 case BINDER_LIB_TEST_GETUID:
1793 reply->writeInt32(getuid());
1794 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07001795 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1796 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001797 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001798 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001799 // oneway error codes should be ignored
1800 if (flags & TF_ONE_WAY) {
1801 return UNKNOWN_ERROR;
1802 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001803 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001804 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1805 // Note: this transaction is only designed for use with a
1806 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001807 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001808 // A callback was already pending; this means that
1809 // we received a second call while still processing
1810 // the first one. Fail the test.
1811 sp<IBinder> callback = data.readStrongBinder();
1812 Parcel data2;
1813 data2.writeInt32(UNKNOWN_ERROR);
1814
Yi Kong91635562018-06-07 14:38:36 -07001815 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001816 } else {
1817 m_callback = data.readStrongBinder();
1818 int32_t delayUs = data.readInt32();
1819 /*
1820 * It's necessary that we sleep here, so the next
1821 * transaction the caller makes will be queued to
1822 * the async queue.
1823 */
1824 usleep(delayUs);
1825
1826 /*
1827 * Now when we return, libbinder will tell the kernel
1828 * we are done with this transaction, and the kernel
1829 * can move the queued transaction to either the
1830 * thread todo worklist (for kernels without the fix),
1831 * or the proc todo worklist. In case of the former,
1832 * the next outbound call will pick up the pending
1833 * transaction, which leads to undesired reentrant
1834 * behavior. This is caught in the if() branch above.
1835 */
1836 }
1837
1838 return NO_ERROR;
1839 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001840 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1841 Parcel data2, reply2;
1842 sp<IBinder> binder;
1843 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001844 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001845 return BAD_VALUE;
1846 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001847 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001848 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1849 return NO_ERROR;
1850 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001851 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1852 reply->writeStrongBinder(this);
1853 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001854 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1855 reply->writeInt32(m_id);
1856 return NO_ERROR;
1857 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1858 int32_t count;
1859 uint32_t indirect_code;
1860 sp<IBinder> binder;
1861
1862 count = data.readInt32();
1863 reply->writeInt32(m_id);
1864 reply->writeInt32(count);
1865 for (int i = 0; i < count; i++) {
1866 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001867 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001868 return BAD_VALUE;
1869 }
1870 indirect_code = data.readInt32();
1871 BinderLibTestBundle data2(&data);
1872 if (!data2.isValid()) {
1873 return BAD_VALUE;
1874 }
1875 BinderLibTestBundle reply2;
1876 binder->transact(indirect_code, data2, &reply2);
1877 reply2.appendTo(reply);
1878 }
1879 return NO_ERROR;
1880 }
1881 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1882 reply->setError(data.readInt32());
1883 return NO_ERROR;
1884 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1885 reply->writeInt32(sizeof(void *));
1886 return NO_ERROR;
1887 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1888 return NO_ERROR;
1889 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1890 m_strongRef = data.readStrongBinder();
1891 return NO_ERROR;
1892 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1893 int ret;
1894 Parcel data2, reply2;
1895 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1896 sp<IBinder> target;
1897 sp<IBinder> callback;
1898
1899 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001900 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001901 return BAD_VALUE;
1902 }
1903 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001904 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001905 return BAD_VALUE;
1906 }
1907 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001908 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001909 data2.writeInt32(ret);
1910 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1911 return NO_ERROR;
1912 }
1913 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1914 int ret;
1915 int32_t size;
1916 const void *buf;
1917 int fd;
1918
1919 fd = data.readFileDescriptor();
1920 if (fd < 0) {
1921 return BAD_VALUE;
1922 }
1923 ret = data.readInt32(&size);
1924 if (ret != NO_ERROR) {
1925 return ret;
1926 }
1927 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001928 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001929 return BAD_VALUE;
1930 }
1931 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001932 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001933 return NO_ERROR;
1934 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001935 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1936 int ret;
1937 int32_t size;
1938 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001939 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001940
1941 ret = data.readUniqueParcelFileDescriptor(&fd);
1942 if (ret != NO_ERROR) {
1943 return ret;
1944 }
1945 ret = data.readInt32(&size);
1946 if (ret != NO_ERROR) {
1947 return ret;
1948 }
1949 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001950 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001951 return BAD_VALUE;
1952 }
1953 ret = write(fd.get(), buf, size);
1954 if (ret != size) return UNKNOWN_ERROR;
1955 return NO_ERROR;
1956 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001957 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1958 alarm(10);
1959 return NO_ERROR;
1960 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001961 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001962 ;
1963 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001964 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001965 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001966 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001967 return NO_ERROR;
1968 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001969 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1970 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001971 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001972 return NO_ERROR;
1973 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001974 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1975 int policy = 0;
1976 sched_param param;
1977 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1978 return UNKNOWN_ERROR;
1979 }
1980 reply->writeInt32(policy);
1981 reply->writeInt32(param.sched_priority);
1982 return NO_ERROR;
1983 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001984 case BINDER_LIB_TEST_ECHO_VECTOR: {
1985 std::vector<uint64_t> vector;
1986 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001987 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001988 reply->writeUint64Vector(vector);
1989 return NO_ERROR;
1990 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001991 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1992 std::array<int, 2> sockets;
1993 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1994 if (!created) {
1995 ALOGE("Could not create socket pair");
1996 return UNKNOWN_ERROR;
1997 }
1998
1999 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2000 if (result != 0) {
2001 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2002 return UNKNOWN_ERROR;
2003 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002004 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002005 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2006 if (writeResult != NO_ERROR) {
2007 ALOGE("Could not write unique_fd");
2008 return writeResult;
2009 }
2010 close(sockets[1]); // we don't need the other side of the fd
2011 return NO_ERROR;
2012 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07002013 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02002014 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2015 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00002016 case BINDER_LIB_TEST_CAN_GET_SID: {
2017 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2018 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002019 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2020 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2021 return NO_ERROR;
2022 }
Devin Moore4354f712022-12-08 01:44:46 +00002023 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2024 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2025 return NO_ERROR;
2026 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002027 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002028 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002029 return NO_ERROR;
2030 }
2031 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002032 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002033 return NO_ERROR;
2034 }
2035 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2036 int32_t ms = data.readInt32();
2037 return unlockInMs(ms);
2038 }
2039 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002040 m_blockMutex.lock();
2041 sp<BinderLibTestService> thisService = this;
2042 int32_t value = data.readInt32();
2043 // start local thread to unlock in 1s
2044 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002045 t.detach();
2046 return NO_ERROR;
2047 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002048 default:
2049 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002050 };
2051 }
2052
Elie Kheirallah47431c12022-04-21 23:46:17 +00002053 status_t unlockInMs(int32_t ms) {
2054 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002055 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002056 return NO_ERROR;
2057 }
2058
Yifan Hong543edcd2021-05-18 19:47:30 -07002059private:
2060 int32_t m_id;
2061 int32_t m_nextServerId;
2062 pthread_mutex_t m_serverWaitMutex;
2063 pthread_cond_t m_serverWaitCond;
2064 bool m_serverStartRequested;
2065 sp<IBinder> m_serverStarted;
2066 sp<IBinder> m_strongRef;
2067 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002068 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002069 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002070};
2071
Martijn Coenen45b07b42017-08-09 12:07:45 +02002072int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002073{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002074 binderLibTestServiceName += String16(binderserversuffix);
2075
Steven Moreland35626652021-05-15 01:32:04 +00002076 // Testing to make sure that calls that we are serving can use getCallin*
2077 // even though we don't here.
2078 IPCThreadState::SpGuard spGuard{
2079 .address = __builtin_frame_address(0),
2080 .context = "main server thread",
2081 };
2082 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2083
Riley Andrews06b01ad2014-12-18 12:10:08 -08002084 status_t ret;
2085 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02002086 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002087 {
2088 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002089
Steven Morelandbf1915b2020-07-16 22:43:02 +00002090 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2091
Steven Morelandcf03cf12020-12-04 02:58:40 +00002092 testService->setInheritRt(true);
2093
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002094 /*
2095 * Normally would also contain functionality as well, but we are only
2096 * testing the extension mechanism.
2097 */
2098 testService->setExtension(new BBinder());
2099
Martijn Coenen82c75312019-07-24 15:18:30 +02002100 // Required for test "BufRejected'
2101 testService->setRequestingSid(true);
2102
Martijn Coenen45b07b42017-08-09 12:07:45 +02002103 /*
2104 * We need this below, but can't hold a sp<> because it prevents the
2105 * node from being cleaned up automatically. It's safe in this case
2106 * because of how the tests are written.
2107 */
2108 testServicePtr = testService.get();
2109
Riley Andrews06b01ad2014-12-18 12:10:08 -08002110 if (index == 0) {
2111 ret = sm->addService(binderLibTestServiceName, testService);
2112 } else {
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002113 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -08002114 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002115 LIBBINDER_IGNORE_END()
Riley Andrews06b01ad2014-12-18 12:10:08 -08002116 Parcel data, reply;
2117 data.writeInt32(index);
2118 data.writeStrongBinder(testService);
2119
2120 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2121 }
2122 }
2123 write(readypipefd, &ret, sizeof(ret));
2124 close(readypipefd);
2125 //printf("%s: ret %d\n", __func__, ret);
2126 if (ret)
2127 return 1;
2128 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002129 if (usePoll) {
2130 int fd;
2131 struct epoll_event ev;
2132 int epoll_fd;
2133 IPCThreadState::self()->setupPolling(&fd);
2134 if (fd < 0) {
2135 return 1;
2136 }
2137 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2138
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002139 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002140 if (epoll_fd == -1) {
2141 return 1;
2142 }
2143
2144 ev.events = EPOLLIN;
2145 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2146 return 1;
2147 }
2148
2149 while (1) {
2150 /*
2151 * We simulate a single-threaded process using the binder poll
2152 * interface; besides handling binder commands, it can also
2153 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002154 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002155 *
2156 * processPendingCall() will then issue that transaction.
2157 */
2158 struct epoll_event events[1];
2159 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2160 if (numEvents < 0) {
2161 if (errno == EINTR) {
2162 continue;
2163 }
2164 return 1;
2165 }
2166 if (numEvents > 0) {
2167 IPCThreadState::self()->handlePolledCommands();
2168 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2169 testServicePtr->processPendingCall();
2170 }
2171 }
2172 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002173 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002174 ProcessState::self()->startThreadPool();
2175 IPCThreadState::self()->joinThreadPool();
2176 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002177 //printf("%s: joinThreadPool returned\n", __func__);
2178 return 1; /* joinThreadPool should not return */
2179}
2180
Steven Moreland68275d72023-04-21 22:12:45 +00002181int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002182 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002183 binderservername = argv[2];
2184 } else {
2185 binderservername = argv[0];
2186 }
2187
Martijn Coenen45b07b42017-08-09 12:07:45 +02002188 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2189 binderserversuffix = argv[5];
2190 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002191 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002192 binderserversuffix = new char[16];
2193 snprintf(binderserversuffix, 16, "%d", getpid());
2194 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002195
2196 ::testing::InitGoogleTest(&argc, argv);
2197 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2198 ProcessState::self()->startThreadPool();
2199 return RUN_ALL_TESTS();
2200}