blob: 8974ad745d704e0f9e322782aa06ce160694cc2a [file] [log] [blame]
Riley Andrews06b01ad2014-12-18 12:10:08 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080018#include <poll.h>
19#include <pthread.h>
20#include <stdio.h>
21#include <stdlib.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070022
23#include <chrono>
Yifan Hong8b890852021-06-10 13:44:09 -070024#include <fstream>
Steven Morelandd7088702021-01-13 00:27:00 +000025#include <thread>
Riley Andrews06b01ad2014-12-18 12:10:08 -080026
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070027#include <gmock/gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080028#include <gtest/gtest.h>
29
Yifan Hong84bedeb2021-04-21 21:37:17 -070030#include <android-base/properties.h>
Yifan Hong28d6c352021-06-04 17:27:35 -070031#include <android-base/result-gmock.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070032#include <android-base/result.h>
Andrei Homescu1519b982022-06-09 02:04:44 +000033#include <android-base/scopeguard.h>
Yifan Hong8b890852021-06-10 13:44:09 -070034#include <android-base/strings.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070035#include <android-base/unique_fd.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080036#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070037#include <binder/BpBinder.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080038#include <binder/IBinder.h>
39#include <binder/IPCThreadState.h>
40#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070041#include <binder/RpcServer.h>
42#include <binder/RpcSession.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080043
Steven Morelandcf03cf12020-12-04 02:58:40 +000044#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020045#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080046#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070047#include <sys/socket.h>
48#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020049
Steven Moreland6ba5a252021-05-04 22:49:00 +000050#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070051#include "binderAbiHelper.h"
52
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;
Elie Kheirallah47431c12022-04-21 23:46:17 +000086static constexpr int kKernelThreads = 15;
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);
217 m_server = sm->getService(binderLibTestServiceName);
Yi Kong91635562018-06-07 14:38:36 -0700218 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800219 //printf("%s: pid %d, get service done\n", __func__, m_pid);
220 }
221 virtual void TearDown() {
222 status_t ret;
223 Parcel data, reply;
224 int exitStatus;
225 pid_t pid;
226
227 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700228 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800229 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
230 EXPECT_EQ(0, ret);
231 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
232 EXPECT_EQ(0, ret);
233 }
234 if (m_serverpid > 0) {
235 //printf("wait for %d\n", m_pids[i]);
236 pid = wait(&exitStatus);
237 EXPECT_EQ(m_serverpid, pid);
238 EXPECT_TRUE(WIFEXITED(exitStatus));
239 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
240 }
241 }
242
243 pid_t m_serverpid;
244 sp<IBinder> m_server;
245};
246
247class BinderLibTest : public ::testing::Test {
248 public:
249 virtual void SetUp() {
250 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Olivier Gaillard91a04802018-11-14 17:32:41 +0000251 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800252 }
253 virtual void TearDown() {
254 }
255 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200256 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800257 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800258 int32_t id;
259 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800260
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700261 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800262
Elie Kheirallahb7246642022-05-03 18:01:43 +0000263 sp<IBinder> binder = reply.readStrongBinder();
264 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700265 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800266 if (idPtr)
267 *idPtr = id;
268 return binder;
269 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200270
Yi Kong91635562018-06-07 14:38:36 -0700271 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200272 {
273 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
274 }
275
Yi Kong91635562018-06-07 14:38:36 -0700276 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200277 {
278 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
279 }
280
Riley Andrews06b01ad2014-12-18 12:10:08 -0800281 void waitForReadData(int fd, int timeout_ms) {
282 int ret;
283 pollfd pfd = pollfd();
284
285 pfd.fd = fd;
286 pfd.events = POLLIN;
287 ret = poll(&pfd, 1, timeout_ms);
288 EXPECT_EQ(1, ret);
289 }
290
291 sp<IBinder> m_server;
292};
293
294class BinderLibTestBundle : public Parcel
295{
296 public:
297 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800298 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800299 int32_t mark;
300 int32_t bundleLen;
301 size_t pos;
302
303 if (source->readInt32(&mark))
304 return;
305 if (mark != MARK_START)
306 return;
307 if (source->readInt32(&bundleLen))
308 return;
309 pos = source->dataPosition();
310 if (Parcel::appendFrom(source, pos, bundleLen))
311 return;
312 source->setDataPosition(pos + bundleLen);
313 if (source->readInt32(&mark))
314 return;
315 if (mark != MARK_END)
316 return;
317 m_isValid = true;
318 setDataPosition(0);
319 }
320 void appendTo(Parcel *dest) {
321 dest->writeInt32(MARK_START);
322 dest->writeInt32(dataSize());
323 dest->appendFrom(this, 0, dataSize());
324 dest->writeInt32(MARK_END);
325 };
326 bool isValid(void) {
327 return m_isValid;
328 }
329 private:
330 enum {
331 MARK_START = B_PACK_CHARS('B','T','B','S'),
332 MARK_END = B_PACK_CHARS('B','T','B','E'),
333 };
334 bool m_isValid;
335};
336
337class BinderLibTestEvent
338{
339 public:
340 BinderLibTestEvent(void)
341 : m_eventTriggered(false)
342 {
Yi Kong91635562018-06-07 14:38:36 -0700343 pthread_mutex_init(&m_waitMutex, nullptr);
344 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800345 }
346 int waitEvent(int timeout_s)
347 {
348 int ret;
349 pthread_mutex_lock(&m_waitMutex);
350 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800351 struct timespec ts;
352 clock_gettime(CLOCK_REALTIME, &ts);
353 ts.tv_sec += timeout_s;
354 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800355 }
356 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
357 pthread_mutex_unlock(&m_waitMutex);
358 return ret;
359 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200360 pthread_t getTriggeringThread()
361 {
362 return m_triggeringThread;
363 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800364 protected:
365 void triggerEvent(void) {
366 pthread_mutex_lock(&m_waitMutex);
367 pthread_cond_signal(&m_waitCond);
368 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200369 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800370 pthread_mutex_unlock(&m_waitMutex);
371 };
372 private:
373 pthread_mutex_t m_waitMutex;
374 pthread_cond_t m_waitCond;
375 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200376 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800377};
378
379class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
380{
381 public:
382 BinderLibTestCallBack()
383 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700384 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800385 {
386 }
387 status_t getResult(void)
388 {
389 return m_result;
390 }
391
392 private:
393 virtual status_t onTransact(uint32_t code,
394 const Parcel& data, Parcel* reply,
395 uint32_t flags = 0)
396 {
397 (void)reply;
398 (void)flags;
399 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200400 case BINDER_LIB_TEST_CALL_BACK: {
401 status_t status = data.readInt32(&m_result);
402 if (status != NO_ERROR) {
403 m_result = status;
404 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800405 triggerEvent();
406 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200407 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700408 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
409 sp<IBinder> server;
410 int ret;
411 const uint8_t *buf = data.data();
412 size_t size = data.dataSize();
413 if (m_prev_end) {
414 /* 64-bit kernel needs at most 8 bytes to align buffer end */
415 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
416 } else {
417 EXPECT_TRUE(IsPageAligned((void *)buf));
418 }
419
420 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
421
422 if (size > 0) {
423 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
424 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
425 data, reply);
426 EXPECT_EQ(NO_ERROR, ret);
427 }
428 return NO_ERROR;
429 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800430 default:
431 return UNKNOWN_TRANSACTION;
432 }
433 }
434
435 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700436 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800437};
438
439class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
440{
441 private:
442 virtual void binderDied(const wp<IBinder>& who) {
443 (void)who;
444 triggerEvent();
445 };
446};
447
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700448TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
449 // EXPECT_DEATH works by forking the process
450 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
451}
452
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000453TEST_F(BinderLibTest, AddManagerToManager) {
454 sp<IServiceManager> sm = defaultServiceManager();
455 sp<IBinder> binder = IInterface::asBinder(sm);
456 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
457}
458
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500459TEST_F(BinderLibTest, WasParceled) {
460 auto binder = sp<BBinder>::make();
461 EXPECT_FALSE(binder->wasParceled());
462 Parcel data;
463 data.writeStrongBinder(binder);
464 EXPECT_TRUE(binder->wasParceled());
465}
466
Riley Andrews06b01ad2014-12-18 12:10:08 -0800467TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800468 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700469 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
470 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800471}
472
Steven Moreland80844f72020-12-12 02:06:08 +0000473TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000474 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700475 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
476 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000477}
478
Steven Morelandf183fdd2020-10-27 00:12:12 +0000479TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000480 Parcel data, reply;
481 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700482 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
483 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000484}
485
Marco Ballesio7ee17572020-09-08 10:30:03 -0700486TEST_F(BinderLibTest, Freeze) {
Marco Ballesio7ee17572020-09-08 10:30:03 -0700487 Parcel data, reply, replypid;
Li Li6f059292021-09-10 09:59:30 -0700488 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
Marco Ballesio7ee17572020-09-08 10:30:03 -0700489
Li Li6f059292021-09-10 09:59:30 -0700490 // Pass test on devices where the cgroup v2 freezer is not supported
Marco Ballesio7ee17572020-09-08 10:30:03 -0700491 if (freezer_file.fail()) {
492 GTEST_SKIP();
493 return;
494 }
495
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700496 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700497 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700498 for (int i = 0; i < 10; i++) {
499 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
500 }
Li Li6f059292021-09-10 09:59:30 -0700501
502 // Pass test on devices where BINDER_FREEZE ioctl is not supported
503 int ret = IPCThreadState::self()->freeze(pid, false, 0);
504 if (ret != 0) {
505 GTEST_SKIP();
506 return;
507 }
508
509 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000510
511 // b/268232063 - succeeds ~0.08% of the time
512 {
513 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
514 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
515 }
516
Li Li6f059292021-09-10 09:59:30 -0700517 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700518 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700519
Li Li4e678b92021-09-14 12:14:42 -0700520 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700521
522 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
523 &async_received));
524
525 EXPECT_EQ(sync_received, 1);
526 EXPECT_EQ(async_received, 0);
527
Li Li4e678b92021-09-14 12:14:42 -0700528 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700529 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
530}
531
Riley Andrews06b01ad2014-12-18 12:10:08 -0800532TEST_F(BinderLibTest, SetError) {
533 int32_t testValue[] = { 0, -123, 123 };
534 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800535 Parcel data, reply;
536 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700537 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
538 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800539 }
540}
541
542TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700543 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800544}
545
546TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800547 int32_t ptrsize;
548 Parcel data, reply;
549 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700550 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700551 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
552 StatusEq(NO_ERROR));
553 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800554 RecordProperty("TestPtrSize", sizeof(void *));
555 RecordProperty("ServerPtrSize", sizeof(void *));
556}
557
558TEST_F(BinderLibTest, IndirectGetId2)
559{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800560 int32_t id;
561 int32_t count;
562 Parcel data, reply;
563 int32_t serverId[3];
564
565 data.writeInt32(ARRAY_SIZE(serverId));
566 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
567 sp<IBinder> server;
568 BinderLibTestBundle datai;
569
570 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700571 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800572 data.writeStrongBinder(server);
573 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
574 datai.appendTo(&data);
575 }
576
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700577 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
578 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800579
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700580 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800581 EXPECT_EQ(0, id);
582
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700583 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700584 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800585
586 for (size_t i = 0; i < (size_t)count; i++) {
587 BinderLibTestBundle replyi(&reply);
588 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700589 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800590 EXPECT_EQ(serverId[i], id);
591 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
592 }
593
594 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
595}
596
597TEST_F(BinderLibTest, IndirectGetId3)
598{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800599 int32_t id;
600 int32_t count;
601 Parcel data, reply;
602 int32_t serverId[3];
603
604 data.writeInt32(ARRAY_SIZE(serverId));
605 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
606 sp<IBinder> server;
607 BinderLibTestBundle datai;
608 BinderLibTestBundle datai2;
609
610 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700611 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800612 data.writeStrongBinder(server);
613 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
614
615 datai.writeInt32(1);
616 datai.writeStrongBinder(m_server);
617 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
618 datai2.appendTo(&datai);
619
620 datai.appendTo(&data);
621 }
622
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700623 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
624 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800625
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700626 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800627 EXPECT_EQ(0, id);
628
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700629 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700630 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800631
632 for (size_t i = 0; i < (size_t)count; i++) {
633 int32_t counti;
634
635 BinderLibTestBundle replyi(&reply);
636 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700637 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800638 EXPECT_EQ(serverId[i], id);
639
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700640 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800641 EXPECT_EQ(1, counti);
642
643 BinderLibTestBundle replyi2(&replyi);
644 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700645 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800646 EXPECT_EQ(0, id);
647 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
648
649 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
650 }
651
652 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
653}
654
655TEST_F(BinderLibTest, CallBack)
656{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800657 Parcel data, reply;
658 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
659 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700660 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
661 StatusEq(NO_ERROR));
662 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
663 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800664}
665
Steven Moreland35626652021-05-15 01:32:04 +0000666TEST_F(BinderLibTest, BinderCallContextGuard) {
667 sp<IBinder> binder = addServer();
668 Parcel data, reply;
669 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
670 StatusEq(DEAD_OBJECT));
671}
672
Riley Andrews06b01ad2014-12-18 12:10:08 -0800673TEST_F(BinderLibTest, AddServer)
674{
675 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700676 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800677}
678
Riley Andrews06b01ad2014-12-18 12:10:08 -0800679TEST_F(BinderLibTest, DeathNotificationStrongRef)
680{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800681 sp<IBinder> sbinder;
682
683 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
684
685 {
686 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700687 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700688 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800689 sbinder = binder;
690 }
691 {
692 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700693 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
694 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800695 }
696 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700697 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
698 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800699}
700
701TEST_F(BinderLibTest, DeathNotificationMultiple)
702{
703 status_t ret;
704 const int clientcount = 2;
705 sp<IBinder> target;
706 sp<IBinder> linkedclient[clientcount];
707 sp<BinderLibTestCallBack> callBack[clientcount];
708 sp<IBinder> passiveclient[clientcount];
709
710 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700711 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800712 for (int i = 0; i < clientcount; i++) {
713 {
714 Parcel data, reply;
715
716 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700717 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800718 callBack[i] = new BinderLibTestCallBack();
719 data.writeStrongBinder(target);
720 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700721 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
722 &reply, TF_ONE_WAY),
723 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800724 }
725 {
726 Parcel data, reply;
727
728 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700729 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800730 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700731 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
732 &reply, TF_ONE_WAY),
733 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800734 }
735 }
736 {
737 Parcel data, reply;
738 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
739 EXPECT_EQ(0, ret);
740 }
741
742 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700743 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
744 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800745 }
746}
747
Martijn Coenenf7100e42017-07-31 12:14:09 +0200748TEST_F(BinderLibTest, DeathNotificationThread)
749{
750 status_t ret;
751 sp<BinderLibTestCallBack> callback;
752 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700753 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200754 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700755 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200756
757 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
758
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700759 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200760
761 {
762 Parcel data, reply;
763 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
764 EXPECT_EQ(0, ret);
765 }
766
767 /* Make sure it's dead */
768 testDeathRecipient->waitEvent(5);
769
770 /* Now, pass the ref to another process and ask that process to
771 * call linkToDeath() on it, and wait for a response. This tests
772 * two things:
773 * 1) You still get death notifications when calling linkToDeath()
774 * on a ref that is already dead when it was passed to you.
775 * 2) That death notifications are not directly pushed to the thread
776 * registering them, but to the threadpool (proc workqueue) instead.
777 *
778 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
779 * is blocked on a condition variable waiting for the death notification to be
780 * called; therefore, that thread is not available for handling proc work.
781 * So, if the death notification was pushed to the thread workqueue, the callback
782 * would never be called, and the test would timeout and fail.
783 *
784 * Note that we can't do this part of the test from this thread itself, because
785 * the binder driver would only push death notifications to the thread if
786 * it is a looper thread, which this thread is not.
787 *
788 * See b/23525545 for details.
789 */
790 {
791 Parcel data, reply;
792
793 callback = new BinderLibTestCallBack();
794 data.writeStrongBinder(target);
795 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700796 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
797 TF_ONE_WAY),
798 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200799 }
800
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700801 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
802 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200803}
804
Riley Andrews06b01ad2014-12-18 12:10:08 -0800805TEST_F(BinderLibTest, PassFile) {
806 int ret;
807 int pipefd[2];
808 uint8_t buf[1] = { 0 };
809 uint8_t write_value = 123;
810
811 ret = pipe2(pipefd, O_NONBLOCK);
812 ASSERT_EQ(0, ret);
813
814 {
815 Parcel data, reply;
816 uint8_t writebuf[1] = { write_value };
817
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700818 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800819
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700820 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800821
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700822 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800823
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700824 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
825 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800826 }
827
828 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700829 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800830 EXPECT_EQ(write_value, buf[0]);
831
832 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
833
834 ret = read(pipefd[0], buf, sizeof(buf));
835 EXPECT_EQ(0, ret);
836
837 close(pipefd[0]);
838}
839
Ryo Hashimotobf551892018-05-31 16:58:35 +0900840TEST_F(BinderLibTest, PassParcelFileDescriptor) {
841 const int datasize = 123;
842 std::vector<uint8_t> writebuf(datasize);
843 for (size_t i = 0; i < writebuf.size(); ++i) {
844 writebuf[i] = i;
845 }
846
847 android::base::unique_fd read_end, write_end;
848 {
849 int pipefd[2];
850 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
851 read_end.reset(pipefd[0]);
852 write_end.reset(pipefd[1]);
853 }
854 {
855 Parcel data;
856 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
857 write_end.reset();
858 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
859 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
860
861 Parcel reply;
862 EXPECT_EQ(NO_ERROR,
863 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
864 &reply));
865 }
866 std::vector<uint8_t> readbuf(datasize);
867 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
868 EXPECT_EQ(writebuf, readbuf);
869
870 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
871
872 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
873}
874
Riley Andrews06b01ad2014-12-18 12:10:08 -0800875TEST_F(BinderLibTest, PromoteLocal) {
876 sp<IBinder> strong = new BBinder();
877 wp<IBinder> weak = strong;
878 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700879 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800880 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700881 strong = nullptr;
882 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800883 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700884 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800885}
886
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700887TEST_F(BinderLibTest, LocalGetExtension) {
888 sp<BBinder> binder = new BBinder();
889 sp<IBinder> ext = new BBinder();
890 binder->setExtension(ext);
891 EXPECT_EQ(ext, binder->getExtension());
892}
893
894TEST_F(BinderLibTest, RemoteGetExtension) {
895 sp<IBinder> server = addServer();
896 ASSERT_TRUE(server != nullptr);
897
898 sp<IBinder> extension;
899 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
900 ASSERT_NE(nullptr, extension.get());
901
902 EXPECT_EQ(NO_ERROR, extension->pingBinder());
903}
904
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700905TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700906 Parcel data, reply;
907
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700908 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
909 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700910
911 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700912 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800913 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
914 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
915 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
916 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700917}
918
Connor O'Brien52be2c92016-09-20 14:18:08 -0700919TEST_F(BinderLibTest, FreedBinder) {
920 status_t ret;
921
922 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700923 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700924
925 __u32 freedHandle;
926 wp<IBinder> keepFreedBinder;
927 {
928 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700929 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
930 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700931 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
932 freedHandle = freed->handle;
933 /* Add a weak ref to the freed binder so the driver does not
934 * delete its reference to it - otherwise the transaction
935 * fails regardless of whether the driver is fixed.
936 */
Steven Morelande171d622019-07-17 16:06:01 -0700937 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700938 }
Steven Morelande171d622019-07-17 16:06:01 -0700939 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700940 {
941 Parcel data, reply;
942 data.writeStrongBinder(server);
943 /* Replace original handle with handle to the freed binder */
944 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
945 __u32 oldHandle = strong->handle;
946 strong->handle = freedHandle;
947 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
948 /* Returns DEAD_OBJECT (-32) if target crashes and
949 * FAILED_TRANSACTION if the driver rejects the invalid
950 * object.
951 */
952 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
953 /* Restore original handle so parcel destructor does not use
954 * the wrong handle.
955 */
956 strong->handle = oldHandle;
957 }
958}
959
Sherry Yang336cdd32017-07-24 14:12:27 -0700960TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700961 Parcel data, reply;
962 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
963 for (int i = 0; i < 2; i++) {
964 BinderLibTestBundle datai;
965 datai.appendFrom(&data, 0, data.dataSize());
966
967 data.freeData();
968 data.writeInt32(1);
969 data.writeStrongBinder(callBack);
970 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
971
972 datai.appendTo(&data);
973 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700974 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
975 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700976}
977
Martijn Coenen45b07b42017-08-09 12:07:45 +0200978TEST_F(BinderLibTest, OnewayQueueing)
979{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200980 Parcel data, data2;
981
982 sp<IBinder> pollServer = addPollServer();
983
984 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
985 data.writeStrongBinder(callBack);
986 data.writeInt32(500000); // delay in us before calling back
987
988 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
989 data2.writeStrongBinder(callBack2);
990 data2.writeInt32(0); // delay in us
991
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700992 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
993 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200994
995 // The delay ensures that this second transaction will end up on the async_todo list
996 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700997 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
998 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200999
1000 // The server will ensure that the two transactions are handled in the expected order;
1001 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001002 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1003 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001004
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001005 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1006 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001007}
1008
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001009TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1010{
1011 status_t ret;
1012 Parcel data, reply;
1013 data.writeInterfaceToken(binderLibTestServiceName);
1014 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1015 EXPECT_EQ(-1, reply.readInt32());
1016 EXPECT_EQ(NO_ERROR, ret);
1017}
1018
1019TEST_F(BinderLibTest, WorkSourceSet)
1020{
1021 status_t ret;
1022 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001023 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001024 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001025 data.writeInterfaceToken(binderLibTestServiceName);
1026 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1027 EXPECT_EQ(100, reply.readInt32());
1028 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001029 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1030 EXPECT_EQ(NO_ERROR, ret);
1031}
1032
1033TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1034{
1035 status_t ret;
1036 Parcel data, reply;
1037
1038 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1039 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1040
1041 data.writeInterfaceToken(binderLibTestServiceName);
1042 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1043 EXPECT_EQ(-1, reply.readInt32());
1044 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001045 EXPECT_EQ(NO_ERROR, ret);
1046}
1047
1048TEST_F(BinderLibTest, WorkSourceCleared)
1049{
1050 status_t ret;
1051 Parcel data, reply;
1052
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001053 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001054 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1055 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001056 data.writeInterfaceToken(binderLibTestServiceName);
1057 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1058
1059 EXPECT_EQ(-1, reply.readInt32());
1060 EXPECT_EQ(100, previousWorkSource);
1061 EXPECT_EQ(NO_ERROR, ret);
1062}
1063
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001064TEST_F(BinderLibTest, WorkSourceRestored)
1065{
1066 status_t ret;
1067 Parcel data, reply;
1068
1069 IPCThreadState::self()->setCallingWorkSourceUid(100);
1070 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1071 IPCThreadState::self()->restoreCallingWorkSource(token);
1072
1073 data.writeInterfaceToken(binderLibTestServiceName);
1074 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1075
1076 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001077 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001078 EXPECT_EQ(NO_ERROR, ret);
1079}
1080
Olivier Gaillard91a04802018-11-14 17:32:41 +00001081TEST_F(BinderLibTest, PropagateFlagSet)
1082{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001083 IPCThreadState::self()->clearPropagateWorkSource();
1084 IPCThreadState::self()->setCallingWorkSourceUid(100);
1085 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1086}
1087
1088TEST_F(BinderLibTest, PropagateFlagCleared)
1089{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001090 IPCThreadState::self()->setCallingWorkSourceUid(100);
1091 IPCThreadState::self()->clearPropagateWorkSource();
1092 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1093}
1094
1095TEST_F(BinderLibTest, PropagateFlagRestored)
1096{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001097 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1098 IPCThreadState::self()->restoreCallingWorkSource(token);
1099
1100 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1101}
1102
1103TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1104{
1105 IPCThreadState::self()->setCallingWorkSourceUid(100);
1106
1107 Parcel data, reply;
1108 status_t ret;
1109 data.writeInterfaceToken(binderLibTestServiceName);
1110 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1111
1112 Parcel data2, reply2;
1113 status_t ret2;
1114 data2.writeInterfaceToken(binderLibTestServiceName);
1115 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1116 EXPECT_EQ(100, reply2.readInt32());
1117 EXPECT_EQ(NO_ERROR, ret2);
1118}
1119
Steven Morelandbf1915b2020-07-16 22:43:02 +00001120TEST_F(BinderLibTest, SchedPolicySet) {
1121 sp<IBinder> server = addServer();
1122 ASSERT_TRUE(server != nullptr);
1123
1124 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001125 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1126 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001127
1128 int policy = reply.readInt32();
1129 int priority = reply.readInt32();
1130
1131 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1132 EXPECT_EQ(kSchedPriority, priority);
1133}
1134
Steven Morelandcf03cf12020-12-04 02:58:40 +00001135TEST_F(BinderLibTest, InheritRt) {
1136 sp<IBinder> server = addServer();
1137 ASSERT_TRUE(server != nullptr);
1138
1139 const struct sched_param param {
1140 .sched_priority = kSchedPriorityMore,
1141 };
1142 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1143
1144 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001145 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1146 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001147
1148 int policy = reply.readInt32();
1149 int priority = reply.readInt32();
1150
1151 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1152 EXPECT_EQ(kSchedPriorityMore, priority);
1153}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001154
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001155TEST_F(BinderLibTest, VectorSent) {
1156 Parcel data, reply;
1157 sp<IBinder> server = addServer();
1158 ASSERT_TRUE(server != nullptr);
1159
1160 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1161 data.writeUint64Vector(testValue);
1162
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001163 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001164 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001165 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001166 EXPECT_EQ(readValue, testValue);
1167}
1168
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001169TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1170 sp<IBinder> server = addServer();
1171 ASSERT_TRUE(server != nullptr);
1172
1173 Parcel reply;
1174 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1175 StatusEq(NO_ERROR));
1176 base::unique_fd fd;
1177 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1178
1179 const int result = fcntl(fd.get(), F_GETFL);
1180 ASSERT_NE(result, -1);
1181 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1182}
1183
Steven Moreland59b84442022-07-12 18:32:44 +00001184// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1185// This value is not exposed, but some code in the framework relies on being able to use
1186// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001187constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001188constexpr size_t kSizeBytesOverFull = 1'050'000;
1189
1190TEST_F(BinderLibTest, GargantuanVectorSent) {
1191 sp<IBinder> server = addServer();
1192 ASSERT_TRUE(server != nullptr);
1193
1194 for (size_t i = 0; i < 10; i++) {
1195 // a slight variation in size is used to consider certain possible caching implementations
1196 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1197
1198 Parcel data, reply;
1199 data.writeUint64Vector(testValue);
1200 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1201 << i;
1202 std::vector<uint64_t> readValue;
1203 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1204 EXPECT_EQ(readValue, testValue);
1205 }
1206}
1207
1208TEST_F(BinderLibTest, LimitExceededVectorSent) {
1209 sp<IBinder> server = addServer();
1210 ASSERT_TRUE(server != nullptr);
1211 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1212
1213 Parcel data, reply;
1214 data.writeUint64Vector(testValue);
1215 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1216 StatusEq(FAILED_TRANSACTION));
1217}
1218
Martijn Coenen82c75312019-07-24 15:18:30 +02001219TEST_F(BinderLibTest, BufRejected) {
1220 Parcel data, reply;
1221 uint32_t buf;
1222 sp<IBinder> server = addServer();
1223 ASSERT_TRUE(server != nullptr);
1224
1225 binder_buffer_object obj {
1226 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001227 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001228 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1229 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001230 };
1231 data.setDataCapacity(1024);
1232 // Write a bogus object at offset 0 to get an entry in the offset table
1233 data.writeFileDescriptor(0);
1234 EXPECT_EQ(data.objectsCount(), 1);
1235 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1236 // And now, overwrite it with the buffer object
1237 memcpy(parcelData, &obj, sizeof(obj));
1238 data.setDataSize(sizeof(obj));
1239
Steven Morelandf2e0a952021-11-01 18:17:23 -07001240 EXPECT_EQ(data.objectsCount(), 1);
1241
Martijn Coenen82c75312019-07-24 15:18:30 +02001242 // Either the kernel should reject this transaction (if it's correct), but
1243 // if it's not, the server implementation should return an error if it
1244 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001245 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001246 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001247}
1248
Steven Morelandf2e0a952021-11-01 18:17:23 -07001249TEST_F(BinderLibTest, WeakRejected) {
1250 Parcel data, reply;
1251 sp<IBinder> server = addServer();
1252 ASSERT_TRUE(server != nullptr);
1253
1254 auto binder = sp<BBinder>::make();
1255 wp<BBinder> wpBinder(binder);
1256 flat_binder_object obj{
1257 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1258 .flags = 0,
1259 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1260 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1261 };
1262 data.setDataCapacity(1024);
1263 // Write a bogus object at offset 0 to get an entry in the offset table
1264 data.writeFileDescriptor(0);
1265 EXPECT_EQ(data.objectsCount(), 1);
1266 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1267 // And now, overwrite it with the weak binder
1268 memcpy(parcelData, &obj, sizeof(obj));
1269 data.setDataSize(sizeof(obj));
1270
1271 // a previous bug caused other objects to be released an extra time, so we
1272 // test with an object that libbinder will actually try to release
1273 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1274
1275 EXPECT_EQ(data.objectsCount(), 2);
1276
1277 // send it many times, since previous error was memory corruption, make it
1278 // more likely that the server crashes
1279 for (size_t i = 0; i < 100; i++) {
1280 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1281 StatusEq(BAD_VALUE));
1282 }
1283
1284 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1285}
1286
Steven Moreland254e8ef2021-04-19 22:28:50 +00001287TEST_F(BinderLibTest, GotSid) {
1288 sp<IBinder> server = addServer();
1289
1290 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001291 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001292}
1293
Andrei Homescu1519b982022-06-09 02:04:44 +00001294struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1295 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1296
1297 // Flattenable protocol
1298 size_t getFlattenedSize() const {
1299 // Return a valid non-zero size here so we don't get an unintended
1300 // BAD_VALUE from Parcel::write
1301 return 16;
1302 }
1303 size_t getFdCount() const { return mFdCount; }
1304 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1305 for (size_t i = 0; i < count; i++) {
1306 fds[i] = STDIN_FILENO;
1307 }
1308 return NO_ERROR;
1309 }
1310 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1311 size_t & /*count*/) {
1312 /* This doesn't get called */
1313 return NO_ERROR;
1314 }
1315
1316 size_t mFdCount;
1317};
1318
1319TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1320 rlimit origNofile;
1321 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1322 ASSERT_EQ(0, ret);
1323
1324 // Restore the original file limits when the test finishes
1325 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1326
1327 rlimit testNofile = {1024, 1024};
1328 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1329 ASSERT_EQ(0, ret);
1330
1331 Parcel parcel;
1332 // Try to write more file descriptors than supported by the OS
1333 TooManyFdsFlattenable tooManyFds1(1024);
1334 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1335
1336 // Try to write more file descriptors than the internal limit
1337 TooManyFdsFlattenable tooManyFds2(1025);
1338 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1339}
1340
Jayant Chowdhary30700942022-01-31 14:12:40 -08001341TEST(ServiceNotifications, Unregister) {
1342 auto sm = defaultServiceManager();
1343 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1344 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1345 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1346 virtual ~LocalRegistrationCallbackImpl() {}
1347 };
1348 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1349
1350 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1351 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1352}
1353
Elie Kheirallah47431c12022-04-21 23:46:17 +00001354TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1355 Parcel data, reply;
1356 sp<IBinder> server = addServer();
1357 ASSERT_TRUE(server != nullptr);
1358 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1359 StatusEq(NO_ERROR));
1360 int32_t replyi = reply.readInt32();
1361 // Expect 16 threads: kKernelThreads = 15 + Pool thread == 16
1362 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
1363 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1364
1365 /*
1366 * This will use all threads in the pool expect the main pool thread.
1367 * The service should run fine without locking, and the thread count should
1368 * not exceed 16 (15 Max + pool thread).
1369 */
1370 std::vector<std::thread> ts;
Steven Morelandb17a5f02022-07-13 01:25:35 +00001371 for (size_t i = 0; i < kKernelThreads; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001372 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001373 Parcel local_reply;
1374 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1375 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001376 }));
1377 }
1378
Elie Kheirallah1c0581e2023-03-01 23:50:46 +00001379 data.writeInt32(500);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001380 // Give a chance for all threads to be used
1381 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1382
1383 for (auto &t : ts) {
1384 t.join();
1385 }
1386
1387 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1388 StatusEq(NO_ERROR));
1389 replyi = reply.readInt32();
Steven Morelandb17a5f02022-07-13 01:25:35 +00001390 EXPECT_EQ(replyi, kKernelThreads + 1);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001391}
1392
Devin Moore4354f712022-12-08 01:44:46 +00001393TEST_F(BinderLibTest, ThreadPoolStarted) {
1394 Parcel data, reply;
1395 sp<IBinder> server = addServer();
1396 ASSERT_TRUE(server != nullptr);
1397 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1398 EXPECT_TRUE(reply.readBool());
1399}
1400
Elie Kheirallah47431c12022-04-21 23:46:17 +00001401size_t epochMillis() {
1402 using std::chrono::duration_cast;
1403 using std::chrono::milliseconds;
1404 using std::chrono::seconds;
1405 using std::chrono::system_clock;
1406 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1407}
1408
1409TEST_F(BinderLibTest, HangingServices) {
1410 Parcel data, reply;
1411 sp<IBinder> server = addServer();
1412 ASSERT_TRUE(server != nullptr);
1413 int32_t delay = 1000; // ms
1414 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001415 // b/266537959 - must take before taking lock, since countdown is started in the remote
1416 // process there.
1417 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001418 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1419 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001420 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1421 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001422 Parcel local_reply;
1423 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1424 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001425 }));
1426 }
1427
1428 for (auto &t : ts) {
1429 t.join();
1430 }
1431 size_t epochMsAfter = epochMillis();
1432
1433 // deadlock occurred and threads only finished after 1s passed.
1434 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1435}
1436
Yifan Hong84bedeb2021-04-21 21:37:17 -07001437class BinderLibRpcTestBase : public BinderLibTest {
1438public:
1439 void SetUp() override {
1440 if (!base::GetBoolProperty("ro.debuggable", false)) {
1441 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1442 "non-debuggable builds.";
1443 }
1444 BinderLibTest::SetUp();
1445 }
1446
1447 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1448 auto rpcServer = RpcServer::make();
1449 EXPECT_NE(nullptr, rpcServer);
1450 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001451 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001452 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1453 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001454 return {};
1455 }
1456 return {rpcServer->releaseServer(), port};
1457 }
1458};
1459
Yifan Hong8b890852021-06-10 13:44:09 -07001460class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001461
Yifan Hongbd276552022-02-28 15:28:51 -08001462// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1463// If device is debuggable AND not on user builds, expects matcher.
1464// Otherwise expects INVALID_OPERATION.
1465// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1466static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1467 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1468 android::base::GetProperty("ro.build.type", "") != "user";
1469 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1470}
1471
Yifan Hong8b890852021-06-10 13:44:09 -07001472TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1473 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001474 ASSERT_TRUE(binder != nullptr);
1475 auto [socket, port] = CreateSocket();
1476 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001477 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1478 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001479}
1480
Yifan Hong8b890852021-06-10 13:44:09 -07001481// Tests for multiple RpcServer's on the same binder object.
1482TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1483 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001484 ASSERT_TRUE(binder != nullptr);
1485
1486 auto [socket1, port1] = CreateSocket();
1487 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001488 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001489 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1490 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001491
1492 auto [socket2, port2] = CreateSocket();
1493 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001494 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001495 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1496 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001497}
1498
Yifan Hong8b890852021-06-10 13:44:09 -07001499// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1500// local binders.
1501class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001502public:
1503 sp<IBinder> GetService() {
1504 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1505 }
1506 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1507 return info.param ? "remote" : "local";
1508 }
1509};
1510
Yifan Hong8b890852021-06-10 13:44:09 -07001511TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1512 auto binder = GetService();
1513 ASSERT_TRUE(binder != nullptr);
1514 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001515 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001516}
1517
1518TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001519 auto binder = GetService();
1520 ASSERT_TRUE(binder != nullptr);
1521 auto [socket, port] = CreateSocket();
1522 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001523 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1524 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001525}
Yifan Hong8b890852021-06-10 13:44:09 -07001526INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1527 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001528
Yifan Hong543edcd2021-05-18 19:47:30 -07001529class BinderLibTestService : public BBinder {
1530public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001531 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1532 : m_id(id),
1533 m_nextServerId(id + 1),
1534 m_serverStartRequested(false),
1535 m_callback(nullptr),
1536 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001537 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1538 pthread_cond_init(&m_serverWaitCond, nullptr);
1539 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001540 ~BinderLibTestService() {
1541 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1542 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001543
Yifan Hong543edcd2021-05-18 19:47:30 -07001544 void processPendingCall() {
1545 if (m_callback != nullptr) {
1546 Parcel data;
1547 data.writeInt32(NO_ERROR);
1548 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1549 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001550 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001551 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001552
Yifan Hong543edcd2021-05-18 19:47:30 -07001553 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1554 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001555 // TODO(b/182914638): also checks getCallingUid() for RPC
1556 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001557 return PERMISSION_DENIED;
1558 }
1559 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001560 case BINDER_LIB_TEST_REGISTER_SERVER: {
1561 int32_t id;
1562 sp<IBinder> binder;
1563 id = data.readInt32();
1564 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001565 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001566 return BAD_VALUE;
1567 }
1568
Yifan Hong543edcd2021-05-18 19:47:30 -07001569 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001570
1571 pthread_mutex_lock(&m_serverWaitMutex);
1572 if (m_serverStartRequested) {
1573 m_serverStartRequested = false;
1574 m_serverStarted = binder;
1575 pthread_cond_signal(&m_serverWaitCond);
1576 }
1577 pthread_mutex_unlock(&m_serverWaitMutex);
1578 return NO_ERROR;
1579 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001580 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001581 case BINDER_LIB_TEST_ADD_SERVER: {
1582 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001583 int serverid;
1584
1585 if (m_id != 0) {
1586 return INVALID_OPERATION;
1587 }
1588 pthread_mutex_lock(&m_serverWaitMutex);
1589 if (m_serverStartRequested) {
1590 ret = -EBUSY;
1591 } else {
1592 serverid = m_nextServerId++;
1593 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001594 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001595
1596 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001597 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001598 pthread_mutex_lock(&m_serverWaitMutex);
1599 }
1600 if (ret > 0) {
1601 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001602 struct timespec ts;
1603 clock_gettime(CLOCK_REALTIME, &ts);
1604 ts.tv_sec += 5;
1605 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001606 }
1607 if (m_serverStartRequested) {
1608 m_serverStartRequested = false;
1609 ret = -ETIMEDOUT;
1610 } else {
1611 reply->writeStrongBinder(m_serverStarted);
1612 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001613 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001614 ret = NO_ERROR;
1615 }
1616 } else if (ret >= 0) {
1617 m_serverStartRequested = false;
1618 ret = UNKNOWN_ERROR;
1619 }
1620 pthread_mutex_unlock(&m_serverWaitMutex);
1621 return ret;
1622 }
Steven Moreland35626652021-05-15 01:32:04 +00001623 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1624 IPCThreadState::SpGuard spGuard{
1625 .address = __builtin_frame_address(0),
1626 .context = "GuardInBinderTransaction",
1627 };
1628 const IPCThreadState::SpGuard *origGuard =
1629 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1630
1631 // if the guard works, this should abort
1632 (void)IPCThreadState::self()->getCallingPid();
1633
1634 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1635 return NO_ERROR;
1636 }
1637
Marco Ballesio7ee17572020-09-08 10:30:03 -07001638 case BINDER_LIB_TEST_GETPID:
1639 reply->writeInt32(getpid());
1640 return NO_ERROR;
1641 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1642 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001643 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001644 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001645 // oneway error codes should be ignored
1646 if (flags & TF_ONE_WAY) {
1647 return UNKNOWN_ERROR;
1648 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001649 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001650 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1651 // Note: this transaction is only designed for use with a
1652 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001653 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001654 // A callback was already pending; this means that
1655 // we received a second call while still processing
1656 // the first one. Fail the test.
1657 sp<IBinder> callback = data.readStrongBinder();
1658 Parcel data2;
1659 data2.writeInt32(UNKNOWN_ERROR);
1660
Yi Kong91635562018-06-07 14:38:36 -07001661 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001662 } else {
1663 m_callback = data.readStrongBinder();
1664 int32_t delayUs = data.readInt32();
1665 /*
1666 * It's necessary that we sleep here, so the next
1667 * transaction the caller makes will be queued to
1668 * the async queue.
1669 */
1670 usleep(delayUs);
1671
1672 /*
1673 * Now when we return, libbinder will tell the kernel
1674 * we are done with this transaction, and the kernel
1675 * can move the queued transaction to either the
1676 * thread todo worklist (for kernels without the fix),
1677 * or the proc todo worklist. In case of the former,
1678 * the next outbound call will pick up the pending
1679 * transaction, which leads to undesired reentrant
1680 * behavior. This is caught in the if() branch above.
1681 */
1682 }
1683
1684 return NO_ERROR;
1685 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001686 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1687 Parcel data2, reply2;
1688 sp<IBinder> binder;
1689 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001690 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001691 return BAD_VALUE;
1692 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001693 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001694 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1695 return NO_ERROR;
1696 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001697 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1698 reply->writeStrongBinder(this);
1699 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001700 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1701 reply->writeInt32(m_id);
1702 return NO_ERROR;
1703 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1704 int32_t count;
1705 uint32_t indirect_code;
1706 sp<IBinder> binder;
1707
1708 count = data.readInt32();
1709 reply->writeInt32(m_id);
1710 reply->writeInt32(count);
1711 for (int i = 0; i < count; i++) {
1712 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001713 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001714 return BAD_VALUE;
1715 }
1716 indirect_code = data.readInt32();
1717 BinderLibTestBundle data2(&data);
1718 if (!data2.isValid()) {
1719 return BAD_VALUE;
1720 }
1721 BinderLibTestBundle reply2;
1722 binder->transact(indirect_code, data2, &reply2);
1723 reply2.appendTo(reply);
1724 }
1725 return NO_ERROR;
1726 }
1727 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1728 reply->setError(data.readInt32());
1729 return NO_ERROR;
1730 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1731 reply->writeInt32(sizeof(void *));
1732 return NO_ERROR;
1733 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1734 return NO_ERROR;
1735 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1736 m_strongRef = data.readStrongBinder();
1737 return NO_ERROR;
1738 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1739 int ret;
1740 Parcel data2, reply2;
1741 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1742 sp<IBinder> target;
1743 sp<IBinder> callback;
1744
1745 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001746 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001747 return BAD_VALUE;
1748 }
1749 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001750 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001751 return BAD_VALUE;
1752 }
1753 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001754 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001755 data2.writeInt32(ret);
1756 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1757 return NO_ERROR;
1758 }
1759 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1760 int ret;
1761 int32_t size;
1762 const void *buf;
1763 int fd;
1764
1765 fd = data.readFileDescriptor();
1766 if (fd < 0) {
1767 return BAD_VALUE;
1768 }
1769 ret = data.readInt32(&size);
1770 if (ret != NO_ERROR) {
1771 return ret;
1772 }
1773 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001774 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001775 return BAD_VALUE;
1776 }
1777 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001778 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001779 return NO_ERROR;
1780 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001781 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1782 int ret;
1783 int32_t size;
1784 const void *buf;
1785 android::base::unique_fd fd;
1786
1787 ret = data.readUniqueParcelFileDescriptor(&fd);
1788 if (ret != NO_ERROR) {
1789 return ret;
1790 }
1791 ret = data.readInt32(&size);
1792 if (ret != NO_ERROR) {
1793 return ret;
1794 }
1795 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001796 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001797 return BAD_VALUE;
1798 }
1799 ret = write(fd.get(), buf, size);
1800 if (ret != size) return UNKNOWN_ERROR;
1801 return NO_ERROR;
1802 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001803 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1804 alarm(10);
1805 return NO_ERROR;
1806 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001807 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001808 ;
1809 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001810 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001811 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001812 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001813 return NO_ERROR;
1814 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001815 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1816 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001817 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001818 return NO_ERROR;
1819 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001820 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1821 int policy = 0;
1822 sched_param param;
1823 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1824 return UNKNOWN_ERROR;
1825 }
1826 reply->writeInt32(policy);
1827 reply->writeInt32(param.sched_priority);
1828 return NO_ERROR;
1829 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001830 case BINDER_LIB_TEST_ECHO_VECTOR: {
1831 std::vector<uint64_t> vector;
1832 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001833 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001834 reply->writeUint64Vector(vector);
1835 return NO_ERROR;
1836 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001837 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1838 std::array<int, 2> sockets;
1839 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1840 if (!created) {
1841 ALOGE("Could not create socket pair");
1842 return UNKNOWN_ERROR;
1843 }
1844
1845 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1846 if (result != 0) {
1847 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1848 return UNKNOWN_ERROR;
1849 }
1850 base::unique_fd out(sockets[0]);
1851 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1852 if (writeResult != NO_ERROR) {
1853 ALOGE("Could not write unique_fd");
1854 return writeResult;
1855 }
1856 close(sockets[1]); // we don't need the other side of the fd
1857 return NO_ERROR;
1858 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001859 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001860 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1861 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001862 case BINDER_LIB_TEST_CAN_GET_SID: {
1863 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1864 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001865 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1866 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1867 return NO_ERROR;
1868 }
Devin Moore4354f712022-12-08 01:44:46 +00001869 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1870 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1871 return NO_ERROR;
1872 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001873 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001874 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001875 return NO_ERROR;
1876 }
1877 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001878 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001879 return NO_ERROR;
1880 }
1881 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1882 int32_t ms = data.readInt32();
1883 return unlockInMs(ms);
1884 }
1885 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001886 m_blockMutex.lock();
1887 sp<BinderLibTestService> thisService = this;
1888 int32_t value = data.readInt32();
1889 // start local thread to unlock in 1s
1890 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001891 t.detach();
1892 return NO_ERROR;
1893 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001894 default:
1895 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001896 };
1897 }
1898
Elie Kheirallah47431c12022-04-21 23:46:17 +00001899 status_t unlockInMs(int32_t ms) {
1900 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001901 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001902 return NO_ERROR;
1903 }
1904
Yifan Hong543edcd2021-05-18 19:47:30 -07001905private:
1906 int32_t m_id;
1907 int32_t m_nextServerId;
1908 pthread_mutex_t m_serverWaitMutex;
1909 pthread_cond_t m_serverWaitCond;
1910 bool m_serverStartRequested;
1911 sp<IBinder> m_serverStarted;
1912 sp<IBinder> m_strongRef;
1913 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001914 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001915 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001916};
1917
Martijn Coenen45b07b42017-08-09 12:07:45 +02001918int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001919{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001920 binderLibTestServiceName += String16(binderserversuffix);
1921
Steven Moreland35626652021-05-15 01:32:04 +00001922 // Testing to make sure that calls that we are serving can use getCallin*
1923 // even though we don't here.
1924 IPCThreadState::SpGuard spGuard{
1925 .address = __builtin_frame_address(0),
1926 .context = "main server thread",
1927 };
1928 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1929
Riley Andrews06b01ad2014-12-18 12:10:08 -08001930 status_t ret;
1931 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001932 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001933 {
1934 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001935
Steven Morelandbf1915b2020-07-16 22:43:02 +00001936 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1937
Steven Morelandcf03cf12020-12-04 02:58:40 +00001938 testService->setInheritRt(true);
1939
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001940 /*
1941 * Normally would also contain functionality as well, but we are only
1942 * testing the extension mechanism.
1943 */
1944 testService->setExtension(new BBinder());
1945
Martijn Coenen82c75312019-07-24 15:18:30 +02001946 // Required for test "BufRejected'
1947 testService->setRequestingSid(true);
1948
Martijn Coenen45b07b42017-08-09 12:07:45 +02001949 /*
1950 * We need this below, but can't hold a sp<> because it prevents the
1951 * node from being cleaned up automatically. It's safe in this case
1952 * because of how the tests are written.
1953 */
1954 testServicePtr = testService.get();
1955
Riley Andrews06b01ad2014-12-18 12:10:08 -08001956 if (index == 0) {
1957 ret = sm->addService(binderLibTestServiceName, testService);
1958 } else {
1959 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1960 Parcel data, reply;
1961 data.writeInt32(index);
1962 data.writeStrongBinder(testService);
1963
1964 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1965 }
1966 }
1967 write(readypipefd, &ret, sizeof(ret));
1968 close(readypipefd);
1969 //printf("%s: ret %d\n", __func__, ret);
1970 if (ret)
1971 return 1;
1972 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001973 if (usePoll) {
1974 int fd;
1975 struct epoll_event ev;
1976 int epoll_fd;
1977 IPCThreadState::self()->setupPolling(&fd);
1978 if (fd < 0) {
1979 return 1;
1980 }
1981 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1982
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001983 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001984 if (epoll_fd == -1) {
1985 return 1;
1986 }
1987
1988 ev.events = EPOLLIN;
1989 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1990 return 1;
1991 }
1992
1993 while (1) {
1994 /*
1995 * We simulate a single-threaded process using the binder poll
1996 * interface; besides handling binder commands, it can also
1997 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001998 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001999 *
2000 * processPendingCall() will then issue that transaction.
2001 */
2002 struct epoll_event events[1];
2003 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2004 if (numEvents < 0) {
2005 if (errno == EINTR) {
2006 continue;
2007 }
2008 return 1;
2009 }
2010 if (numEvents > 0) {
2011 IPCThreadState::self()->handlePolledCommands();
2012 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2013 testServicePtr->processPendingCall();
2014 }
2015 }
2016 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002017 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002018 ProcessState::self()->startThreadPool();
2019 IPCThreadState::self()->joinThreadPool();
2020 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002021 //printf("%s: joinThreadPool returned\n", __func__);
2022 return 1; /* joinThreadPool should not return */
2023}
2024
2025int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07002026 ExitIfWrongAbi();
2027
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002028 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002029 binderservername = argv[2];
2030 } else {
2031 binderservername = argv[0];
2032 }
2033
Martijn Coenen45b07b42017-08-09 12:07:45 +02002034 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2035 binderserversuffix = argv[5];
2036 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002037 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002038 binderserversuffix = new char[16];
2039 snprintf(binderserversuffix, 16, "%d", getpid());
2040 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002041
2042 ::testing::InitGoogleTest(&argc, argv);
2043 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2044 ProcessState::self()->startThreadPool();
2045 return RUN_ALL_TESTS();
2046}