blob: 659943a718f72b75081a9074ccb95eef58496a40 [file] [log] [blame]
Riley Andrews06b01ad2014-12-18 12:10:08 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080018#include <poll.h>
19#include <pthread.h>
20#include <stdio.h>
21#include <stdlib.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070022
23#include <chrono>
Yifan Hong8b890852021-06-10 13:44:09 -070024#include <fstream>
Steven Morelandd7088702021-01-13 00:27:00 +000025#include <thread>
Riley Andrews06b01ad2014-12-18 12:10:08 -080026
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070027#include <gmock/gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080028#include <gtest/gtest.h>
29
Yifan Hong84bedeb2021-04-21 21:37:17 -070030#include <android-base/properties.h>
Yifan Hong28d6c352021-06-04 17:27:35 -070031#include <android-base/result-gmock.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070032#include <android-base/result.h>
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +000033#include <android-base/scopeguard.h>
Yifan Hong8b890852021-06-10 13:44:09 -070034#include <android-base/strings.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070035#include <android-base/unique_fd.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080036#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070037#include <binder/BpBinder.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080038#include <binder/IBinder.h>
39#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070041#include <binder/RpcServer.h>
42#include <binder/RpcSession.h>
Tomasz Wasilczyk300aa132023-10-26 15:00:04 -070043#include <utils/Flattenable.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080044
Steven Morelandcf03cf12020-12-04 02:58:40 +000045#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020046#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080047#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070048#include <sys/socket.h>
49#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020050
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 -080053#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
54
55using namespace android;
Yifan Hong84bedeb2021-04-21 21:37:17 -070056using namespace std::string_literals;
57using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070058using android::base::testing::HasValue;
Yifan Hong8b890852021-06-10 13:44:09 -070059using android::base::testing::Ok;
Yifan Hong84bedeb2021-04-21 21:37:17 -070060using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080061using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070062using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070063using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070064
65// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
66MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
67 *result_listener << statusToString(arg);
68 return expected == arg;
69}
Riley Andrews06b01ad2014-12-18 12:10:08 -080070
Sherry Yang336cdd32017-07-24 14:12:27 -070071static ::testing::AssertionResult IsPageAligned(void *buf) {
72 if (((unsigned long)buf & ((unsigned long)PAGE_SIZE - 1)) == 0)
73 return ::testing::AssertionSuccess();
74 else
75 return ::testing::AssertionFailure() << buf << " is not page aligned";
76}
77
Riley Andrews06b01ad2014-12-18 12:10:08 -080078static testing::Environment* binder_env;
79static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070080static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080081static char binderserverarg[] = "--binderserver";
82
Steven Morelandbf1915b2020-07-16 22:43:02 +000083static constexpr int kSchedPolicy = SCHED_RR;
84static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000085static constexpr int kSchedPriorityMore = 8;
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,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800117 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700118 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700119 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000120 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000121 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
122 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000123 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000124 BINDER_LIB_TEST_LOCK_UNLOCK,
125 BINDER_LIB_TEST_PROCESS_LOCK,
126 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
127 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800128};
129
Martijn Coenen45b07b42017-08-09 12:07:45 +0200130pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800131{
132 int ret;
133 pid_t pid;
134 status_t status;
135 int pipefd[2];
136 char stri[16];
137 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200138 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800139 char *childargv[] = {
140 binderservername,
141 binderserverarg,
142 stri,
143 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200144 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700145 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700146 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800147 };
148
149 ret = pipe(pipefd);
150 if (ret < 0)
151 return ret;
152
153 snprintf(stri, sizeof(stri), "%d", arg2);
154 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200155 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800156
157 pid = fork();
158 if (pid == -1)
159 return pid;
160 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800161 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800162 close(pipefd[0]);
163 execv(binderservername, childargv);
164 status = -errno;
165 write(pipefd[1], &status, sizeof(status));
166 fprintf(stderr, "execv failed, %s\n", strerror(errno));
167 _exit(EXIT_FAILURE);
168 }
169 close(pipefd[1]);
170 ret = read(pipefd[0], &status, sizeof(status));
171 //printf("pipe read returned %d, status %d\n", ret, status);
172 close(pipefd[0]);
173 if (ret == sizeof(status)) {
174 ret = status;
175 } else {
176 kill(pid, SIGKILL);
177 if (ret >= 0) {
178 ret = NO_INIT;
179 }
180 }
181 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700182 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800183 return ret;
184 }
185 return pid;
186}
187
Yifan Hong84bedeb2021-04-21 21:37:17 -0700188android::base::Result<int32_t> GetId(sp<IBinder> service) {
189 using android::base::Error;
190 Parcel data, reply;
191 data.markForBinder(service);
192 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
193 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
194 if (status != OK)
195 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
196 int32_t result = 0;
197 status = reply.readInt32(&result);
198 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
199 return result;
200}
201
Riley Andrews06b01ad2014-12-18 12:10:08 -0800202class BinderLibTestEnv : public ::testing::Environment {
203 public:
204 BinderLibTestEnv() {}
205 sp<IBinder> getServer(void) {
206 return m_server;
207 }
208
209 private:
210 virtual void SetUp() {
211 m_serverpid = start_server_process(0);
212 //printf("m_serverpid %d\n", m_serverpid);
213 ASSERT_GT(m_serverpid, 0);
214
215 sp<IServiceManager> sm = defaultServiceManager();
216 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000217#pragma clang diagnostic push
218#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -0800219 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000220#pragma clang diagnostic pop
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();
Olivier Gaillard91a04802018-11-14 17:32:41 +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
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500462TEST_F(BinderLibTest, WasParceled) {
463 auto binder = sp<BBinder>::make();
464 EXPECT_FALSE(binder->wasParceled());
465 Parcel data;
466 data.writeStrongBinder(binder);
467 EXPECT_TRUE(binder->wasParceled());
468}
469
Riley Andrews06b01ad2014-12-18 12:10:08 -0800470TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800471 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700472 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
473 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800474}
475
Steven Moreland80844f72020-12-12 02:06:08 +0000476TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000477 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700478 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
479 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000480}
481
Steven Morelandf183fdd2020-10-27 00:12:12 +0000482TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000483 Parcel data, reply;
484 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700485 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
486 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000487}
488
Marco Ballesio7ee17572020-09-08 10:30:03 -0700489TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700490 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700491 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700492
Li Li6f059292021-09-10 09:59:30 -0700493 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700494 if (freezer_file.fail()) {
495 GTEST_SKIP();
496 return;
497 }
498
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700499 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700500 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700501 for (int i = 0; i < 10; i++) {
502 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
503 }
Li Li6f059292021-09-10 09:59:30 -0700504
505 // Pass test on devices where BINDER_FREEZE ioctl is not supported
506 int ret = IPCThreadState::self()->freeze(pid, false, 0);
507 if (ret != 0) {
508 GTEST_SKIP();
509 return;
510 }
511
512 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000513
514 // b/268232063 - succeeds ~0.08% of the time
515 {
516 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
517 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
518 }
519
Li Li6f059292021-09-10 09:59:30 -0700520 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700521 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700522
Li Li4e678b92021-09-14 12:14:42 -0700523 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700524
525 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
526 &async_received));
527
528 EXPECT_EQ(sync_received, 1);
529 EXPECT_EQ(async_received, 0);
530
Li Li4e678b92021-09-14 12:14:42 -0700531 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700532 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
533}
534
Riley Andrews06b01ad2014-12-18 12:10:08 -0800535TEST_F(BinderLibTest, SetError) {
536 int32_t testValue[] = { 0, -123, 123 };
537 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800538 Parcel data, reply;
539 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700540 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
541 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800542 }
543}
544
545TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700546 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800547}
548
549TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800550 int32_t ptrsize;
551 Parcel data, reply;
552 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700553 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700554 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
555 StatusEq(NO_ERROR));
556 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800557 RecordProperty("TestPtrSize", sizeof(void *));
558 RecordProperty("ServerPtrSize", sizeof(void *));
559}
560
561TEST_F(BinderLibTest, IndirectGetId2)
562{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800563 int32_t id;
564 int32_t count;
565 Parcel data, reply;
566 int32_t serverId[3];
567
568 data.writeInt32(ARRAY_SIZE(serverId));
569 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
570 sp<IBinder> server;
571 BinderLibTestBundle datai;
572
573 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700574 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800575 data.writeStrongBinder(server);
576 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
577 datai.appendTo(&data);
578 }
579
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700580 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
581 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800582
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700583 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800584 EXPECT_EQ(0, id);
585
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700586 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700587 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800588
589 for (size_t i = 0; i < (size_t)count; i++) {
590 BinderLibTestBundle replyi(&reply);
591 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700592 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800593 EXPECT_EQ(serverId[i], id);
594 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
595 }
596
597 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
598}
599
600TEST_F(BinderLibTest, IndirectGetId3)
601{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800602 int32_t id;
603 int32_t count;
604 Parcel data, reply;
605 int32_t serverId[3];
606
607 data.writeInt32(ARRAY_SIZE(serverId));
608 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
609 sp<IBinder> server;
610 BinderLibTestBundle datai;
611 BinderLibTestBundle datai2;
612
613 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700614 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800615 data.writeStrongBinder(server);
616 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
617
618 datai.writeInt32(1);
619 datai.writeStrongBinder(m_server);
620 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
621 datai2.appendTo(&datai);
622
623 datai.appendTo(&data);
624 }
625
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700626 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
627 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800628
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700629 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800630 EXPECT_EQ(0, id);
631
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700632 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700633 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800634
635 for (size_t i = 0; i < (size_t)count; i++) {
636 int32_t counti;
637
638 BinderLibTestBundle replyi(&reply);
639 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700640 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800641 EXPECT_EQ(serverId[i], id);
642
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700643 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800644 EXPECT_EQ(1, counti);
645
646 BinderLibTestBundle replyi2(&replyi);
647 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700648 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800649 EXPECT_EQ(0, id);
650 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
651
652 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
653 }
654
655 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
656}
657
658TEST_F(BinderLibTest, CallBack)
659{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800660 Parcel data, reply;
661 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
662 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700663 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
664 StatusEq(NO_ERROR));
665 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
666 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800667}
668
Steven Moreland35626652021-05-15 01:32:04 +0000669TEST_F(BinderLibTest, BinderCallContextGuard) {
670 sp<IBinder> binder = addServer();
671 Parcel data, reply;
672 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
673 StatusEq(DEAD_OBJECT));
674}
675
Riley Andrews06b01ad2014-12-18 12:10:08 -0800676TEST_F(BinderLibTest, AddServer)
677{
678 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700679 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800680}
681
Riley Andrews06b01ad2014-12-18 12:10:08 -0800682TEST_F(BinderLibTest, DeathNotificationStrongRef)
683{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800684 sp<IBinder> sbinder;
685
686 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
687
688 {
689 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700690 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700691 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800692 sbinder = binder;
693 }
694 {
695 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700696 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
697 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800698 }
699 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700700 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
701 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800702}
703
704TEST_F(BinderLibTest, DeathNotificationMultiple)
705{
706 status_t ret;
707 const int clientcount = 2;
708 sp<IBinder> target;
709 sp<IBinder> linkedclient[clientcount];
710 sp<BinderLibTestCallBack> callBack[clientcount];
711 sp<IBinder> passiveclient[clientcount];
712
713 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700714 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800715 for (int i = 0; i < clientcount; i++) {
716 {
717 Parcel data, reply;
718
719 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700720 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800721 callBack[i] = new BinderLibTestCallBack();
722 data.writeStrongBinder(target);
723 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700724 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
725 &reply, TF_ONE_WAY),
726 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800727 }
728 {
729 Parcel data, reply;
730
731 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700732 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800733 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700734 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
735 &reply, TF_ONE_WAY),
736 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800737 }
738 }
739 {
740 Parcel data, reply;
741 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
742 EXPECT_EQ(0, ret);
743 }
744
745 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700746 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
747 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800748 }
749}
750
Martijn Coenenf7100e42017-07-31 12:14:09 +0200751TEST_F(BinderLibTest, DeathNotificationThread)
752{
753 status_t ret;
754 sp<BinderLibTestCallBack> callback;
755 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700756 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200757 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700758 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200759
760 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
761
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700762 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200763
764 {
765 Parcel data, reply;
766 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
767 EXPECT_EQ(0, ret);
768 }
769
770 /* Make sure it's dead */
771 testDeathRecipient->waitEvent(5);
772
773 /* Now, pass the ref to another process and ask that process to
774 * call linkToDeath() on it, and wait for a response. This tests
775 * two things:
776 * 1) You still get death notifications when calling linkToDeath()
777 * on a ref that is already dead when it was passed to you.
778 * 2) That death notifications are not directly pushed to the thread
779 * registering them, but to the threadpool (proc workqueue) instead.
780 *
781 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
782 * is blocked on a condition variable waiting for the death notification to be
783 * called; therefore, that thread is not available for handling proc work.
784 * So, if the death notification was pushed to the thread workqueue, the callback
785 * would never be called, and the test would timeout and fail.
786 *
787 * Note that we can't do this part of the test from this thread itself, because
788 * the binder driver would only push death notifications to the thread if
789 * it is a looper thread, which this thread is not.
790 *
791 * See b/23525545 for details.
792 */
793 {
794 Parcel data, reply;
795
796 callback = new BinderLibTestCallBack();
797 data.writeStrongBinder(target);
798 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700799 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
800 TF_ONE_WAY),
801 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200802 }
803
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700804 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
805 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200806}
807
Riley Andrews06b01ad2014-12-18 12:10:08 -0800808TEST_F(BinderLibTest, PassFile) {
809 int ret;
810 int pipefd[2];
811 uint8_t buf[1] = { 0 };
812 uint8_t write_value = 123;
813
814 ret = pipe2(pipefd, O_NONBLOCK);
815 ASSERT_EQ(0, ret);
816
817 {
818 Parcel data, reply;
819 uint8_t writebuf[1] = { write_value };
820
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700821 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800822
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700823 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800824
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700825 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800826
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700827 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
828 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800829 }
830
831 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700832 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800833 EXPECT_EQ(write_value, buf[0]);
834
835 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
836
837 ret = read(pipefd[0], buf, sizeof(buf));
838 EXPECT_EQ(0, ret);
839
840 close(pipefd[0]);
841}
842
Ryo Hashimotobf551892018-05-31 16:58:35 +0900843TEST_F(BinderLibTest, PassParcelFileDescriptor) {
844 const int datasize = 123;
845 std::vector<uint8_t> writebuf(datasize);
846 for (size_t i = 0; i < writebuf.size(); ++i) {
847 writebuf[i] = i;
848 }
849
850 android::base::unique_fd read_end, write_end;
851 {
852 int pipefd[2];
853 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
854 read_end.reset(pipefd[0]);
855 write_end.reset(pipefd[1]);
856 }
857 {
858 Parcel data;
859 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
860 write_end.reset();
861 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
862 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
863
864 Parcel reply;
865 EXPECT_EQ(NO_ERROR,
866 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
867 &reply));
868 }
869 std::vector<uint8_t> readbuf(datasize);
870 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
871 EXPECT_EQ(writebuf, readbuf);
872
873 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
874
875 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
876}
877
Riley Andrews06b01ad2014-12-18 12:10:08 -0800878TEST_F(BinderLibTest, PromoteLocal) {
879 sp<IBinder> strong = new BBinder();
880 wp<IBinder> weak = strong;
881 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700882 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800883 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700884 strong = nullptr;
885 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800886 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700887 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800888}
889
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700890TEST_F(BinderLibTest, LocalGetExtension) {
891 sp<BBinder> binder = new BBinder();
892 sp<IBinder> ext = new BBinder();
893 binder->setExtension(ext);
894 EXPECT_EQ(ext, binder->getExtension());
895}
896
897TEST_F(BinderLibTest, RemoteGetExtension) {
898 sp<IBinder> server = addServer();
899 ASSERT_TRUE(server != nullptr);
900
901 sp<IBinder> extension;
902 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
903 ASSERT_NE(nullptr, extension.get());
904
905 EXPECT_EQ(NO_ERROR, extension->pingBinder());
906}
907
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700908TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700909 Parcel data, reply;
910
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700911 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
912 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700913
914 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700915 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800916 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
917 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
918 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
919 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700920}
921
Connor O'Brien52be2c92016-09-20 14:18:08 -0700922TEST_F(BinderLibTest, FreedBinder) {
923 status_t ret;
924
925 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700926 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700927
928 __u32 freedHandle;
929 wp<IBinder> keepFreedBinder;
930 {
931 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700932 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
933 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700934 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
935 freedHandle = freed->handle;
936 /* Add a weak ref to the freed binder so the driver does not
937 * delete its reference to it - otherwise the transaction
938 * fails regardless of whether the driver is fixed.
939 */
Steven Morelande171d622019-07-17 16:06:01 -0700940 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700941 }
Steven Morelande171d622019-07-17 16:06:01 -0700942 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700943 {
944 Parcel data, reply;
945 data.writeStrongBinder(server);
946 /* Replace original handle with handle to the freed binder */
947 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
948 __u32 oldHandle = strong->handle;
949 strong->handle = freedHandle;
950 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
951 /* Returns DEAD_OBJECT (-32) if target crashes and
952 * FAILED_TRANSACTION if the driver rejects the invalid
953 * object.
954 */
955 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
956 /* Restore original handle so parcel destructor does not use
957 * the wrong handle.
958 */
959 strong->handle = oldHandle;
960 }
961}
962
Sherry Yang336cdd32017-07-24 14:12:27 -0700963TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700964 Parcel data, reply;
965 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
966 for (int i = 0; i < 2; i++) {
967 BinderLibTestBundle datai;
968 datai.appendFrom(&data, 0, data.dataSize());
969
970 data.freeData();
971 data.writeInt32(1);
972 data.writeStrongBinder(callBack);
973 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
974
975 datai.appendTo(&data);
976 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700977 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
978 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700979}
980
Martijn Coenen45b07b42017-08-09 12:07:45 +0200981TEST_F(BinderLibTest, OnewayQueueing)
982{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200983 Parcel data, data2;
984
985 sp<IBinder> pollServer = addPollServer();
986
987 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
988 data.writeStrongBinder(callBack);
989 data.writeInt32(500000); // delay in us before calling back
990
991 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
992 data2.writeStrongBinder(callBack2);
993 data2.writeInt32(0); // delay in us
994
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700995 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
996 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200997
998 // The delay ensures that this second transaction will end up on the async_todo list
999 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001000 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1001 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001002
1003 // The server will ensure that the two transactions are handled in the expected order;
1004 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001005 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1006 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001007
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001008 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1009 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001010}
1011
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001012TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1013{
1014 status_t ret;
1015 Parcel data, reply;
1016 data.writeInterfaceToken(binderLibTestServiceName);
1017 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1018 EXPECT_EQ(-1, reply.readInt32());
1019 EXPECT_EQ(NO_ERROR, ret);
1020}
1021
1022TEST_F(BinderLibTest, WorkSourceSet)
1023{
1024 status_t ret;
1025 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001026 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001027 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001028 data.writeInterfaceToken(binderLibTestServiceName);
1029 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1030 EXPECT_EQ(100, reply.readInt32());
1031 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001032 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1033 EXPECT_EQ(NO_ERROR, ret);
1034}
1035
1036TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1037{
1038 status_t ret;
1039 Parcel data, reply;
1040
1041 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1042 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1043
1044 data.writeInterfaceToken(binderLibTestServiceName);
1045 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1046 EXPECT_EQ(-1, reply.readInt32());
1047 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001048 EXPECT_EQ(NO_ERROR, ret);
1049}
1050
1051TEST_F(BinderLibTest, WorkSourceCleared)
1052{
1053 status_t ret;
1054 Parcel data, reply;
1055
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001056 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001057 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1058 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001059 data.writeInterfaceToken(binderLibTestServiceName);
1060 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1061
1062 EXPECT_EQ(-1, reply.readInt32());
1063 EXPECT_EQ(100, previousWorkSource);
1064 EXPECT_EQ(NO_ERROR, ret);
1065}
1066
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001067TEST_F(BinderLibTest, WorkSourceRestored)
1068{
1069 status_t ret;
1070 Parcel data, reply;
1071
1072 IPCThreadState::self()->setCallingWorkSourceUid(100);
1073 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1074 IPCThreadState::self()->restoreCallingWorkSource(token);
1075
1076 data.writeInterfaceToken(binderLibTestServiceName);
1077 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1078
1079 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001080 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001081 EXPECT_EQ(NO_ERROR, ret);
1082}
1083
Olivier Gaillard91a04802018-11-14 17:32:41 +00001084TEST_F(BinderLibTest, PropagateFlagSet)
1085{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001086 IPCThreadState::self()->clearPropagateWorkSource();
1087 IPCThreadState::self()->setCallingWorkSourceUid(100);
1088 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1089}
1090
1091TEST_F(BinderLibTest, PropagateFlagCleared)
1092{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001093 IPCThreadState::self()->setCallingWorkSourceUid(100);
1094 IPCThreadState::self()->clearPropagateWorkSource();
1095 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1096}
1097
1098TEST_F(BinderLibTest, PropagateFlagRestored)
1099{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001100 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1101 IPCThreadState::self()->restoreCallingWorkSource(token);
1102
1103 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1104}
1105
1106TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1107{
1108 IPCThreadState::self()->setCallingWorkSourceUid(100);
1109
1110 Parcel data, reply;
1111 status_t ret;
1112 data.writeInterfaceToken(binderLibTestServiceName);
1113 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001114 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001115
1116 Parcel data2, reply2;
1117 status_t ret2;
1118 data2.writeInterfaceToken(binderLibTestServiceName);
1119 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1120 EXPECT_EQ(100, reply2.readInt32());
1121 EXPECT_EQ(NO_ERROR, ret2);
1122}
1123
Steven Morelandbf1915b2020-07-16 22:43:02 +00001124TEST_F(BinderLibTest, SchedPolicySet) {
1125 sp<IBinder> server = addServer();
1126 ASSERT_TRUE(server != nullptr);
1127
1128 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001129 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1130 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001131
1132 int policy = reply.readInt32();
1133 int priority = reply.readInt32();
1134
1135 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1136 EXPECT_EQ(kSchedPriority, priority);
1137}
1138
Steven Morelandcf03cf12020-12-04 02:58:40 +00001139TEST_F(BinderLibTest, InheritRt) {
1140 sp<IBinder> server = addServer();
1141 ASSERT_TRUE(server != nullptr);
1142
1143 const struct sched_param param {
1144 .sched_priority = kSchedPriorityMore,
1145 };
1146 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1147
1148 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001149 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1150 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001151
1152 int policy = reply.readInt32();
1153 int priority = reply.readInt32();
1154
1155 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1156 EXPECT_EQ(kSchedPriorityMore, priority);
1157}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001158
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001159TEST_F(BinderLibTest, VectorSent) {
1160 Parcel data, reply;
1161 sp<IBinder> server = addServer();
1162 ASSERT_TRUE(server != nullptr);
1163
1164 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1165 data.writeUint64Vector(testValue);
1166
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001167 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001168 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001169 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001170 EXPECT_EQ(readValue, testValue);
1171}
1172
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001173TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1174 sp<IBinder> server = addServer();
1175 ASSERT_TRUE(server != nullptr);
1176
1177 Parcel reply;
1178 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1179 StatusEq(NO_ERROR));
1180 base::unique_fd fd;
1181 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1182
1183 const int result = fcntl(fd.get(), F_GETFL);
1184 ASSERT_NE(result, -1);
1185 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1186}
1187
Steven Moreland59b84442022-07-12 18:32:44 +00001188// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1189// This value is not exposed, but some code in the framework relies on being able to use
1190// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001191constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001192constexpr size_t kSizeBytesOverFull = 1'050'000;
1193
1194TEST_F(BinderLibTest, GargantuanVectorSent) {
1195 sp<IBinder> server = addServer();
1196 ASSERT_TRUE(server != nullptr);
1197
1198 for (size_t i = 0; i < 10; i++) {
1199 // a slight variation in size is used to consider certain possible caching implementations
1200 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1201
1202 Parcel data, reply;
1203 data.writeUint64Vector(testValue);
1204 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1205 << i;
1206 std::vector<uint64_t> readValue;
1207 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1208 EXPECT_EQ(readValue, testValue);
1209 }
1210}
1211
1212TEST_F(BinderLibTest, LimitExceededVectorSent) {
1213 sp<IBinder> server = addServer();
1214 ASSERT_TRUE(server != nullptr);
1215 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1216
1217 Parcel data, reply;
1218 data.writeUint64Vector(testValue);
1219 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1220 StatusEq(FAILED_TRANSACTION));
1221}
1222
Martijn Coenen82c75312019-07-24 15:18:30 +02001223TEST_F(BinderLibTest, BufRejected) {
1224 Parcel data, reply;
1225 uint32_t buf;
1226 sp<IBinder> server = addServer();
1227 ASSERT_TRUE(server != nullptr);
1228
1229 binder_buffer_object obj {
1230 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001231 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001232 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1233 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001234 };
1235 data.setDataCapacity(1024);
1236 // Write a bogus object at offset 0 to get an entry in the offset table
1237 data.writeFileDescriptor(0);
1238 EXPECT_EQ(data.objectsCount(), 1);
1239 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1240 // And now, overwrite it with the buffer object
1241 memcpy(parcelData, &obj, sizeof(obj));
1242 data.setDataSize(sizeof(obj));
1243
Steven Morelandf2e0a952021-11-01 18:17:23 -07001244 EXPECT_EQ(data.objectsCount(), 1);
1245
Martijn Coenen82c75312019-07-24 15:18:30 +02001246 // Either the kernel should reject this transaction (if it's correct), but
1247 // if it's not, the server implementation should return an error if it
1248 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001249 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001250 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001251}
1252
Steven Morelandf2e0a952021-11-01 18:17:23 -07001253TEST_F(BinderLibTest, WeakRejected) {
1254 Parcel data, reply;
1255 sp<IBinder> server = addServer();
1256 ASSERT_TRUE(server != nullptr);
1257
1258 auto binder = sp<BBinder>::make();
1259 wp<BBinder> wpBinder(binder);
1260 flat_binder_object obj{
1261 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1262 .flags = 0,
1263 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1264 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1265 };
1266 data.setDataCapacity(1024);
1267 // Write a bogus object at offset 0 to get an entry in the offset table
1268 data.writeFileDescriptor(0);
1269 EXPECT_EQ(data.objectsCount(), 1);
1270 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1271 // And now, overwrite it with the weak binder
1272 memcpy(parcelData, &obj, sizeof(obj));
1273 data.setDataSize(sizeof(obj));
1274
1275 // a previous bug caused other objects to be released an extra time, so we
1276 // test with an object that libbinder will actually try to release
1277 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1278
1279 EXPECT_EQ(data.objectsCount(), 2);
1280
1281 // send it many times, since previous error was memory corruption, make it
1282 // more likely that the server crashes
1283 for (size_t i = 0; i < 100; i++) {
1284 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1285 StatusEq(BAD_VALUE));
1286 }
1287
1288 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1289}
1290
Steven Moreland254e8ef2021-04-19 22:28:50 +00001291TEST_F(BinderLibTest, GotSid) {
1292 sp<IBinder> server = addServer();
1293
1294 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001295 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001296}
1297
Andrei Homescu1519b982022-06-09 02:04:44 +00001298struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1299 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1300
1301 // Flattenable protocol
1302 size_t getFlattenedSize() const {
1303 // Return a valid non-zero size here so we don't get an unintended
1304 // BAD_VALUE from Parcel::write
1305 return 16;
1306 }
1307 size_t getFdCount() const { return mFdCount; }
1308 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1309 for (size_t i = 0; i < count; i++) {
1310 fds[i] = STDIN_FILENO;
1311 }
1312 return NO_ERROR;
1313 }
1314 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1315 size_t & /*count*/) {
1316 /* This doesn't get called */
1317 return NO_ERROR;
1318 }
1319
1320 size_t mFdCount;
1321};
1322
1323TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1324 rlimit origNofile;
1325 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1326 ASSERT_EQ(0, ret);
1327
1328 // Restore the original file limits when the test finishes
Sebastian Pickl25c1a3b2023-10-30 08:02:24 +00001329 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001330
1331 rlimit testNofile = {1024, 1024};
1332 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1333 ASSERT_EQ(0, ret);
1334
1335 Parcel parcel;
1336 // Try to write more file descriptors than supported by the OS
1337 TooManyFdsFlattenable tooManyFds1(1024);
1338 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1339
1340 // Try to write more file descriptors than the internal limit
1341 TooManyFdsFlattenable tooManyFds2(1025);
1342 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1343}
1344
Jayant Chowdhary30700942022-01-31 14:12:40 -08001345TEST(ServiceNotifications, Unregister) {
1346 auto sm = defaultServiceManager();
1347 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1348 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1349 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1350 virtual ~LocalRegistrationCallbackImpl() {}
1351 };
1352 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1353
1354 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1355 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1356}
1357
Elie Kheirallah47431c12022-04-21 23:46:17 +00001358TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1359 Parcel data, reply;
1360 sp<IBinder> server = addServer();
1361 ASSERT_TRUE(server != nullptr);
1362 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1363 StatusEq(NO_ERROR));
1364 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001365 // see getThreadPoolMaxTotalThreadCount for why there is a race
1366 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1367
Elie Kheirallah47431c12022-04-21 23:46:17 +00001368 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1369
1370 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001371 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1372 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1373 * started threads from setThreadPoolMaxThreadCount
1374 *
1375 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001376 */
1377 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001378 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001379 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001380 Parcel local_reply;
1381 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1382 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001383 }));
1384 }
1385
Steven Moreland3e9debc2023-06-15 00:35:29 +00001386 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1387 // the time, the below call will pre-empt them (presumably because we have the
1388 // scheduler timeslice already + scheduler hint).
1389 sleep(1);
1390
1391 data.writeInt32(1000);
1392 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001393 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1394
1395 for (auto &t : ts) {
1396 t.join();
1397 }
1398
1399 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1400 StatusEq(NO_ERROR));
1401 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001402 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001403}
1404
Devin Moore4354f712022-12-08 01:44:46 +00001405TEST_F(BinderLibTest, ThreadPoolStarted) {
1406 Parcel data, reply;
1407 sp<IBinder> server = addServer();
1408 ASSERT_TRUE(server != nullptr);
1409 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1410 EXPECT_TRUE(reply.readBool());
1411}
1412
Elie Kheirallah47431c12022-04-21 23:46:17 +00001413size_t epochMillis() {
1414 using std::chrono::duration_cast;
1415 using std::chrono::milliseconds;
1416 using std::chrono::seconds;
1417 using std::chrono::system_clock;
1418 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1419}
1420
1421TEST_F(BinderLibTest, HangingServices) {
1422 Parcel data, reply;
1423 sp<IBinder> server = addServer();
1424 ASSERT_TRUE(server != nullptr);
1425 int32_t delay = 1000; // ms
1426 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001427 // b/266537959 - must take before taking lock, since countdown is started in the remote
1428 // process there.
1429 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001430 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1431 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001432 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1433 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001434 Parcel local_reply;
1435 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1436 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001437 }));
1438 }
1439
1440 for (auto &t : ts) {
1441 t.join();
1442 }
1443 size_t epochMsAfter = epochMillis();
1444
1445 // deadlock occurred and threads only finished after 1s passed.
1446 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1447}
1448
Jing Jibbe9ae62023-10-07 15:26:02 -07001449TEST_F(BinderLibTest, BinderProxyCount) {
1450 Parcel data, reply;
1451 sp<IBinder> server = addServer();
1452 ASSERT_NE(server, nullptr);
1453
1454 uint32_t initialCount = BpBinder::getBinderProxyCount();
1455 size_t iterations = 100;
1456 {
1457 uint32_t count = initialCount;
1458 std::vector<sp<IBinder> > proxies;
1459 sp<IBinder> proxy;
1460 // Create binder proxies and verify the count.
1461 for (size_t i = 0; i < iterations; i++) {
1462 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1463 StatusEq(NO_ERROR));
1464 proxies.push_back(reply.readStrongBinder());
1465 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1466 }
1467 // Remove every other one and verify the count.
1468 auto it = proxies.begin();
1469 for (size_t i = 0; it != proxies.end(); i++) {
1470 if (i % 2 == 0) {
1471 it = proxies.erase(it);
1472 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1473 }
1474 }
1475 }
1476 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1477}
1478
Yifan Hong84bedeb2021-04-21 21:37:17 -07001479class BinderLibRpcTestBase : public BinderLibTest {
1480public:
1481 void SetUp() override {
1482 if (!base::GetBoolProperty("ro.debuggable", false)) {
1483 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1484 "non-debuggable builds.";
1485 }
1486 BinderLibTest::SetUp();
1487 }
1488
1489 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1490 auto rpcServer = RpcServer::make();
1491 EXPECT_NE(nullptr, rpcServer);
1492 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001493 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001494 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1495 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001496 return {};
1497 }
1498 return {rpcServer->releaseServer(), port};
1499 }
1500};
1501
Yifan Hong8b890852021-06-10 13:44:09 -07001502class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001503
Yifan Hongbd276552022-02-28 15:28:51 -08001504// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1505// If device is debuggable AND not on user builds, expects matcher.
1506// Otherwise expects INVALID_OPERATION.
1507// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1508static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1509 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1510 android::base::GetProperty("ro.build.type", "") != "user";
1511 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1512}
1513
Yifan Hong8b890852021-06-10 13:44:09 -07001514TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1515 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001516 ASSERT_TRUE(binder != nullptr);
1517 auto [socket, port] = CreateSocket();
1518 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001519 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1520 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001521}
1522
Yifan Hong8b890852021-06-10 13:44:09 -07001523// Tests for multiple RpcServer's on the same binder object.
1524TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1525 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001526 ASSERT_TRUE(binder != nullptr);
1527
1528 auto [socket1, port1] = CreateSocket();
1529 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001530 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001531 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1532 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001533
1534 auto [socket2, port2] = CreateSocket();
1535 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001536 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001537 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1538 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001539}
1540
Yifan Hong8b890852021-06-10 13:44:09 -07001541// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1542// local binders.
1543class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001544public:
1545 sp<IBinder> GetService() {
1546 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1547 }
1548 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1549 return info.param ? "remote" : "local";
1550 }
1551};
1552
Yifan Hong8b890852021-06-10 13:44:09 -07001553TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1554 auto binder = GetService();
1555 ASSERT_TRUE(binder != nullptr);
1556 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001557 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001558}
1559
1560TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001561 auto binder = GetService();
1562 ASSERT_TRUE(binder != nullptr);
1563 auto [socket, port] = CreateSocket();
1564 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001565 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1566 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001567}
Yifan Hong8b890852021-06-10 13:44:09 -07001568INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1569 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001570
Yifan Hong543edcd2021-05-18 19:47:30 -07001571class BinderLibTestService : public BBinder {
1572public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001573 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1574 : m_id(id),
1575 m_nextServerId(id + 1),
1576 m_serverStartRequested(false),
1577 m_callback(nullptr),
1578 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001579 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1580 pthread_cond_init(&m_serverWaitCond, nullptr);
1581 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001582 ~BinderLibTestService() {
1583 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1584 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001585
Yifan Hong543edcd2021-05-18 19:47:30 -07001586 void processPendingCall() {
1587 if (m_callback != nullptr) {
1588 Parcel data;
1589 data.writeInt32(NO_ERROR);
1590 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1591 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001592 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001593 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001594
Yifan Hong543edcd2021-05-18 19:47:30 -07001595 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1596 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001597 // TODO(b/182914638): also checks getCallingUid() for RPC
1598 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001599 return PERMISSION_DENIED;
1600 }
1601 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001602 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001603 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001604 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001605 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001606 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001607 return BAD_VALUE;
1608 }
1609
Yifan Hong543edcd2021-05-18 19:47:30 -07001610 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001611
1612 pthread_mutex_lock(&m_serverWaitMutex);
1613 if (m_serverStartRequested) {
1614 m_serverStartRequested = false;
1615 m_serverStarted = binder;
1616 pthread_cond_signal(&m_serverWaitCond);
1617 }
1618 pthread_mutex_unlock(&m_serverWaitMutex);
1619 return NO_ERROR;
1620 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001621 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001622 case BINDER_LIB_TEST_ADD_SERVER: {
1623 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001624 int serverid;
1625
1626 if (m_id != 0) {
1627 return INVALID_OPERATION;
1628 }
1629 pthread_mutex_lock(&m_serverWaitMutex);
1630 if (m_serverStartRequested) {
1631 ret = -EBUSY;
1632 } else {
1633 serverid = m_nextServerId++;
1634 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001635 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001636
1637 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001638 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001639 pthread_mutex_lock(&m_serverWaitMutex);
1640 }
1641 if (ret > 0) {
1642 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001643 struct timespec ts;
1644 clock_gettime(CLOCK_REALTIME, &ts);
1645 ts.tv_sec += 5;
1646 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001647 }
1648 if (m_serverStartRequested) {
1649 m_serverStartRequested = false;
1650 ret = -ETIMEDOUT;
1651 } else {
1652 reply->writeStrongBinder(m_serverStarted);
1653 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001654 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001655 ret = NO_ERROR;
1656 }
1657 } else if (ret >= 0) {
1658 m_serverStartRequested = false;
1659 ret = UNKNOWN_ERROR;
1660 }
1661 pthread_mutex_unlock(&m_serverWaitMutex);
1662 return ret;
1663 }
Steven Moreland35626652021-05-15 01:32:04 +00001664 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1665 IPCThreadState::SpGuard spGuard{
1666 .address = __builtin_frame_address(0),
1667 .context = "GuardInBinderTransaction",
1668 };
1669 const IPCThreadState::SpGuard *origGuard =
1670 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1671
1672 // if the guard works, this should abort
1673 (void)IPCThreadState::self()->getCallingPid();
1674
1675 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1676 return NO_ERROR;
1677 }
1678
Marco Ballesio7ee17572020-09-08 10:30:03 -07001679 case BINDER_LIB_TEST_GETPID:
1680 reply->writeInt32(getpid());
1681 return NO_ERROR;
1682 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1683 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001684 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001685 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001686 // oneway error codes should be ignored
1687 if (flags & TF_ONE_WAY) {
1688 return UNKNOWN_ERROR;
1689 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001690 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001691 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1692 // Note: this transaction is only designed for use with a
1693 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001694 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001695 // A callback was already pending; this means that
1696 // we received a second call while still processing
1697 // the first one. Fail the test.
1698 sp<IBinder> callback = data.readStrongBinder();
1699 Parcel data2;
1700 data2.writeInt32(UNKNOWN_ERROR);
1701
Yi Kong91635562018-06-07 14:38:36 -07001702 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001703 } else {
1704 m_callback = data.readStrongBinder();
1705 int32_t delayUs = data.readInt32();
1706 /*
1707 * It's necessary that we sleep here, so the next
1708 * transaction the caller makes will be queued to
1709 * the async queue.
1710 */
1711 usleep(delayUs);
1712
1713 /*
1714 * Now when we return, libbinder will tell the kernel
1715 * we are done with this transaction, and the kernel
1716 * can move the queued transaction to either the
1717 * thread todo worklist (for kernels without the fix),
1718 * or the proc todo worklist. In case of the former,
1719 * the next outbound call will pick up the pending
1720 * transaction, which leads to undesired reentrant
1721 * behavior. This is caught in the if() branch above.
1722 */
1723 }
1724
1725 return NO_ERROR;
1726 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001727 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1728 Parcel data2, reply2;
1729 sp<IBinder> binder;
1730 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001731 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001732 return BAD_VALUE;
1733 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001734 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001735 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1736 return NO_ERROR;
1737 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001738 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1739 reply->writeStrongBinder(this);
1740 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001741 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1742 reply->writeInt32(m_id);
1743 return NO_ERROR;
1744 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1745 int32_t count;
1746 uint32_t indirect_code;
1747 sp<IBinder> binder;
1748
1749 count = data.readInt32();
1750 reply->writeInt32(m_id);
1751 reply->writeInt32(count);
1752 for (int i = 0; i < count; i++) {
1753 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001754 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001755 return BAD_VALUE;
1756 }
1757 indirect_code = data.readInt32();
1758 BinderLibTestBundle data2(&data);
1759 if (!data2.isValid()) {
1760 return BAD_VALUE;
1761 }
1762 BinderLibTestBundle reply2;
1763 binder->transact(indirect_code, data2, &reply2);
1764 reply2.appendTo(reply);
1765 }
1766 return NO_ERROR;
1767 }
1768 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1769 reply->setError(data.readInt32());
1770 return NO_ERROR;
1771 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1772 reply->writeInt32(sizeof(void *));
1773 return NO_ERROR;
1774 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1775 return NO_ERROR;
1776 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1777 m_strongRef = data.readStrongBinder();
1778 return NO_ERROR;
1779 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1780 int ret;
1781 Parcel data2, reply2;
1782 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1783 sp<IBinder> target;
1784 sp<IBinder> callback;
1785
1786 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001787 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001788 return BAD_VALUE;
1789 }
1790 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001791 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001792 return BAD_VALUE;
1793 }
1794 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001795 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001796 data2.writeInt32(ret);
1797 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1798 return NO_ERROR;
1799 }
1800 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1801 int ret;
1802 int32_t size;
1803 const void *buf;
1804 int fd;
1805
1806 fd = data.readFileDescriptor();
1807 if (fd < 0) {
1808 return BAD_VALUE;
1809 }
1810 ret = data.readInt32(&size);
1811 if (ret != NO_ERROR) {
1812 return ret;
1813 }
1814 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001815 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001816 return BAD_VALUE;
1817 }
1818 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001819 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001820 return NO_ERROR;
1821 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001822 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1823 int ret;
1824 int32_t size;
1825 const void *buf;
1826 android::base::unique_fd fd;
1827
1828 ret = data.readUniqueParcelFileDescriptor(&fd);
1829 if (ret != NO_ERROR) {
1830 return ret;
1831 }
1832 ret = data.readInt32(&size);
1833 if (ret != NO_ERROR) {
1834 return ret;
1835 }
1836 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001837 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001838 return BAD_VALUE;
1839 }
1840 ret = write(fd.get(), buf, size);
1841 if (ret != size) return UNKNOWN_ERROR;
1842 return NO_ERROR;
1843 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001844 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1845 alarm(10);
1846 return NO_ERROR;
1847 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001848 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001849 ;
1850 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001851 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001852 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001853 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001854 return NO_ERROR;
1855 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001856 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1857 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001858 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001859 return NO_ERROR;
1860 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001861 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1862 int policy = 0;
1863 sched_param param;
1864 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1865 return UNKNOWN_ERROR;
1866 }
1867 reply->writeInt32(policy);
1868 reply->writeInt32(param.sched_priority);
1869 return NO_ERROR;
1870 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001871 case BINDER_LIB_TEST_ECHO_VECTOR: {
1872 std::vector<uint64_t> vector;
1873 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001874 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001875 reply->writeUint64Vector(vector);
1876 return NO_ERROR;
1877 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001878 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1879 std::array<int, 2> sockets;
1880 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1881 if (!created) {
1882 ALOGE("Could not create socket pair");
1883 return UNKNOWN_ERROR;
1884 }
1885
1886 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1887 if (result != 0) {
1888 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1889 return UNKNOWN_ERROR;
1890 }
1891 base::unique_fd out(sockets[0]);
1892 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1893 if (writeResult != NO_ERROR) {
1894 ALOGE("Could not write unique_fd");
1895 return writeResult;
1896 }
1897 close(sockets[1]); // we don't need the other side of the fd
1898 return NO_ERROR;
1899 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001900 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001901 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1902 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001903 case BINDER_LIB_TEST_CAN_GET_SID: {
1904 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1905 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001906 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1907 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1908 return NO_ERROR;
1909 }
Devin Moore4354f712022-12-08 01:44:46 +00001910 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1911 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1912 return NO_ERROR;
1913 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001914 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001915 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001916 return NO_ERROR;
1917 }
1918 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001919 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001920 return NO_ERROR;
1921 }
1922 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1923 int32_t ms = data.readInt32();
1924 return unlockInMs(ms);
1925 }
1926 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001927 m_blockMutex.lock();
1928 sp<BinderLibTestService> thisService = this;
1929 int32_t value = data.readInt32();
1930 // start local thread to unlock in 1s
1931 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001932 t.detach();
1933 return NO_ERROR;
1934 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001935 default:
1936 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001937 };
1938 }
1939
Elie Kheirallah47431c12022-04-21 23:46:17 +00001940 status_t unlockInMs(int32_t ms) {
1941 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001942 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001943 return NO_ERROR;
1944 }
1945
Yifan Hong543edcd2021-05-18 19:47:30 -07001946private:
1947 int32_t m_id;
1948 int32_t m_nextServerId;
1949 pthread_mutex_t m_serverWaitMutex;
1950 pthread_cond_t m_serverWaitCond;
1951 bool m_serverStartRequested;
1952 sp<IBinder> m_serverStarted;
1953 sp<IBinder> m_strongRef;
1954 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001955 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001956 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001957};
1958
Martijn Coenen45b07b42017-08-09 12:07:45 +02001959int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001960{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001961 binderLibTestServiceName += String16(binderserversuffix);
1962
Steven Moreland35626652021-05-15 01:32:04 +00001963 // Testing to make sure that calls that we are serving can use getCallin*
1964 // even though we don't here.
1965 IPCThreadState::SpGuard spGuard{
1966 .address = __builtin_frame_address(0),
1967 .context = "main server thread",
1968 };
1969 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1970
Riley Andrews06b01ad2014-12-18 12:10:08 -08001971 status_t ret;
1972 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001973 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001974 {
1975 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001976
Steven Morelandbf1915b2020-07-16 22:43:02 +00001977 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1978
Steven Morelandcf03cf12020-12-04 02:58:40 +00001979 testService->setInheritRt(true);
1980
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001981 /*
1982 * Normally would also contain functionality as well, but we are only
1983 * testing the extension mechanism.
1984 */
1985 testService->setExtension(new BBinder());
1986
Martijn Coenen82c75312019-07-24 15:18:30 +02001987 // Required for test "BufRejected'
1988 testService->setRequestingSid(true);
1989
Martijn Coenen45b07b42017-08-09 12:07:45 +02001990 /*
1991 * We need this below, but can't hold a sp<> because it prevents the
1992 * node from being cleaned up automatically. It's safe in this case
1993 * because of how the tests are written.
1994 */
1995 testServicePtr = testService.get();
1996
Riley Andrews06b01ad2014-12-18 12:10:08 -08001997 if (index == 0) {
1998 ret = sm->addService(binderLibTestServiceName, testService);
1999 } else {
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002000#pragma clang diagnostic push
2001#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -08002002 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002003#pragma clang diagnostic pop
Riley Andrews06b01ad2014-12-18 12:10:08 -08002004 Parcel data, reply;
2005 data.writeInt32(index);
2006 data.writeStrongBinder(testService);
2007
2008 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2009 }
2010 }
2011 write(readypipefd, &ret, sizeof(ret));
2012 close(readypipefd);
2013 //printf("%s: ret %d\n", __func__, ret);
2014 if (ret)
2015 return 1;
2016 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002017 if (usePoll) {
2018 int fd;
2019 struct epoll_event ev;
2020 int epoll_fd;
2021 IPCThreadState::self()->setupPolling(&fd);
2022 if (fd < 0) {
2023 return 1;
2024 }
2025 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2026
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002027 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002028 if (epoll_fd == -1) {
2029 return 1;
2030 }
2031
2032 ev.events = EPOLLIN;
2033 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2034 return 1;
2035 }
2036
2037 while (1) {
2038 /*
2039 * We simulate a single-threaded process using the binder poll
2040 * interface; besides handling binder commands, it can also
2041 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002042 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002043 *
2044 * processPendingCall() will then issue that transaction.
2045 */
2046 struct epoll_event events[1];
2047 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2048 if (numEvents < 0) {
2049 if (errno == EINTR) {
2050 continue;
2051 }
2052 return 1;
2053 }
2054 if (numEvents > 0) {
2055 IPCThreadState::self()->handlePolledCommands();
2056 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2057 testServicePtr->processPendingCall();
2058 }
2059 }
2060 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002061 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002062 ProcessState::self()->startThreadPool();
2063 IPCThreadState::self()->joinThreadPool();
2064 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002065 //printf("%s: joinThreadPool returned\n", __func__);
2066 return 1; /* joinThreadPool should not return */
2067}
2068
Steven Moreland68275d72023-04-21 22:12:45 +00002069int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002070 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002071 binderservername = argv[2];
2072 } else {
2073 binderservername = argv[0];
2074 }
2075
Martijn Coenen45b07b42017-08-09 12:07:45 +02002076 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2077 binderserversuffix = argv[5];
2078 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002079 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002080 binderserversuffix = new char[16];
2081 snprintf(binderserversuffix, 16, "%d", getpid());
2082 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002083
2084 ::testing::InitGoogleTest(&argc, argv);
2085 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2086 ProcessState::self()->startThreadPool();
2087 return RUN_ALL_TESTS();
2088}