blob: f7498c497bc46e644b0eab3f7e6347ff29dda528 [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));
510 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
511 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700512 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700513
Li Li4e678b92021-09-14 12:14:42 -0700514 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700515
516 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
517 &async_received));
518
519 EXPECT_EQ(sync_received, 1);
520 EXPECT_EQ(async_received, 0);
521
Li Li4e678b92021-09-14 12:14:42 -0700522 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700523 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
524}
525
Riley Andrews06b01ad2014-12-18 12:10:08 -0800526TEST_F(BinderLibTest, SetError) {
527 int32_t testValue[] = { 0, -123, 123 };
528 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800529 Parcel data, reply;
530 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700531 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
532 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800533 }
534}
535
536TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700537 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800538}
539
540TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800541 int32_t ptrsize;
542 Parcel data, reply;
543 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700544 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700545 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
546 StatusEq(NO_ERROR));
547 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800548 RecordProperty("TestPtrSize", sizeof(void *));
549 RecordProperty("ServerPtrSize", sizeof(void *));
550}
551
552TEST_F(BinderLibTest, IndirectGetId2)
553{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800554 int32_t id;
555 int32_t count;
556 Parcel data, reply;
557 int32_t serverId[3];
558
559 data.writeInt32(ARRAY_SIZE(serverId));
560 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
561 sp<IBinder> server;
562 BinderLibTestBundle datai;
563
564 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700565 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800566 data.writeStrongBinder(server);
567 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
568 datai.appendTo(&data);
569 }
570
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700571 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
572 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800573
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700574 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800575 EXPECT_EQ(0, id);
576
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700577 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700578 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800579
580 for (size_t i = 0; i < (size_t)count; i++) {
581 BinderLibTestBundle replyi(&reply);
582 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700583 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800584 EXPECT_EQ(serverId[i], id);
585 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
586 }
587
588 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
589}
590
591TEST_F(BinderLibTest, IndirectGetId3)
592{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800593 int32_t id;
594 int32_t count;
595 Parcel data, reply;
596 int32_t serverId[3];
597
598 data.writeInt32(ARRAY_SIZE(serverId));
599 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
600 sp<IBinder> server;
601 BinderLibTestBundle datai;
602 BinderLibTestBundle datai2;
603
604 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700605 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800606 data.writeStrongBinder(server);
607 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
608
609 datai.writeInt32(1);
610 datai.writeStrongBinder(m_server);
611 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
612 datai2.appendTo(&datai);
613
614 datai.appendTo(&data);
615 }
616
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700617 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
618 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800619
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700620 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800621 EXPECT_EQ(0, id);
622
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700623 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700624 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800625
626 for (size_t i = 0; i < (size_t)count; i++) {
627 int32_t counti;
628
629 BinderLibTestBundle replyi(&reply);
630 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700631 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800632 EXPECT_EQ(serverId[i], id);
633
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700634 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800635 EXPECT_EQ(1, counti);
636
637 BinderLibTestBundle replyi2(&replyi);
638 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700639 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800640 EXPECT_EQ(0, id);
641 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
642
643 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
644 }
645
646 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
647}
648
649TEST_F(BinderLibTest, CallBack)
650{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800651 Parcel data, reply;
652 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
653 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700654 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
655 StatusEq(NO_ERROR));
656 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
657 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800658}
659
Steven Moreland35626652021-05-15 01:32:04 +0000660TEST_F(BinderLibTest, BinderCallContextGuard) {
661 sp<IBinder> binder = addServer();
662 Parcel data, reply;
663 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
664 StatusEq(DEAD_OBJECT));
665}
666
Riley Andrews06b01ad2014-12-18 12:10:08 -0800667TEST_F(BinderLibTest, AddServer)
668{
669 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700670 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800671}
672
Riley Andrews06b01ad2014-12-18 12:10:08 -0800673TEST_F(BinderLibTest, DeathNotificationStrongRef)
674{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800675 sp<IBinder> sbinder;
676
677 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
678
679 {
680 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700681 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700682 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800683 sbinder = binder;
684 }
685 {
686 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700687 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
688 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800689 }
690 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700691 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
692 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800693}
694
695TEST_F(BinderLibTest, DeathNotificationMultiple)
696{
697 status_t ret;
698 const int clientcount = 2;
699 sp<IBinder> target;
700 sp<IBinder> linkedclient[clientcount];
701 sp<BinderLibTestCallBack> callBack[clientcount];
702 sp<IBinder> passiveclient[clientcount];
703
704 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700705 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800706 for (int i = 0; i < clientcount; i++) {
707 {
708 Parcel data, reply;
709
710 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700711 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800712 callBack[i] = new BinderLibTestCallBack();
713 data.writeStrongBinder(target);
714 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700715 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
716 &reply, TF_ONE_WAY),
717 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800718 }
719 {
720 Parcel data, reply;
721
722 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700723 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800724 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700725 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
726 &reply, TF_ONE_WAY),
727 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800728 }
729 }
730 {
731 Parcel data, reply;
732 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
733 EXPECT_EQ(0, ret);
734 }
735
736 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700737 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
738 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800739 }
740}
741
Martijn Coenenf7100e42017-07-31 12:14:09 +0200742TEST_F(BinderLibTest, DeathNotificationThread)
743{
744 status_t ret;
745 sp<BinderLibTestCallBack> callback;
746 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700747 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200748 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700749 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200750
751 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
752
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700753 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200754
755 {
756 Parcel data, reply;
757 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
758 EXPECT_EQ(0, ret);
759 }
760
761 /* Make sure it's dead */
762 testDeathRecipient->waitEvent(5);
763
764 /* Now, pass the ref to another process and ask that process to
765 * call linkToDeath() on it, and wait for a response. This tests
766 * two things:
767 * 1) You still get death notifications when calling linkToDeath()
768 * on a ref that is already dead when it was passed to you.
769 * 2) That death notifications are not directly pushed to the thread
770 * registering them, but to the threadpool (proc workqueue) instead.
771 *
772 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
773 * is blocked on a condition variable waiting for the death notification to be
774 * called; therefore, that thread is not available for handling proc work.
775 * So, if the death notification was pushed to the thread workqueue, the callback
776 * would never be called, and the test would timeout and fail.
777 *
778 * Note that we can't do this part of the test from this thread itself, because
779 * the binder driver would only push death notifications to the thread if
780 * it is a looper thread, which this thread is not.
781 *
782 * See b/23525545 for details.
783 */
784 {
785 Parcel data, reply;
786
787 callback = new BinderLibTestCallBack();
788 data.writeStrongBinder(target);
789 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700790 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
791 TF_ONE_WAY),
792 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200793 }
794
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700795 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
796 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200797}
798
Riley Andrews06b01ad2014-12-18 12:10:08 -0800799TEST_F(BinderLibTest, PassFile) {
800 int ret;
801 int pipefd[2];
802 uint8_t buf[1] = { 0 };
803 uint8_t write_value = 123;
804
805 ret = pipe2(pipefd, O_NONBLOCK);
806 ASSERT_EQ(0, ret);
807
808 {
809 Parcel data, reply;
810 uint8_t writebuf[1] = { write_value };
811
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700812 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800813
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700814 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800815
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700816 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800817
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700818 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
819 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800820 }
821
822 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700823 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800824 EXPECT_EQ(write_value, buf[0]);
825
826 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
827
828 ret = read(pipefd[0], buf, sizeof(buf));
829 EXPECT_EQ(0, ret);
830
831 close(pipefd[0]);
832}
833
Ryo Hashimotobf551892018-05-31 16:58:35 +0900834TEST_F(BinderLibTest, PassParcelFileDescriptor) {
835 const int datasize = 123;
836 std::vector<uint8_t> writebuf(datasize);
837 for (size_t i = 0; i < writebuf.size(); ++i) {
838 writebuf[i] = i;
839 }
840
841 android::base::unique_fd read_end, write_end;
842 {
843 int pipefd[2];
844 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
845 read_end.reset(pipefd[0]);
846 write_end.reset(pipefd[1]);
847 }
848 {
849 Parcel data;
850 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
851 write_end.reset();
852 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
853 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
854
855 Parcel reply;
856 EXPECT_EQ(NO_ERROR,
857 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
858 &reply));
859 }
860 std::vector<uint8_t> readbuf(datasize);
861 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
862 EXPECT_EQ(writebuf, readbuf);
863
864 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
865
866 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
867}
868
Riley Andrews06b01ad2014-12-18 12:10:08 -0800869TEST_F(BinderLibTest, PromoteLocal) {
870 sp<IBinder> strong = new BBinder();
871 wp<IBinder> weak = strong;
872 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700873 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800874 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -0700875 strong = nullptr;
876 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800877 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -0700878 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800879}
880
Steven Morelandb8ad08d2019-08-09 14:42:56 -0700881TEST_F(BinderLibTest, LocalGetExtension) {
882 sp<BBinder> binder = new BBinder();
883 sp<IBinder> ext = new BBinder();
884 binder->setExtension(ext);
885 EXPECT_EQ(ext, binder->getExtension());
886}
887
888TEST_F(BinderLibTest, RemoteGetExtension) {
889 sp<IBinder> server = addServer();
890 ASSERT_TRUE(server != nullptr);
891
892 sp<IBinder> extension;
893 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
894 ASSERT_NE(nullptr, extension.get());
895
896 EXPECT_EQ(NO_ERROR, extension->pingBinder());
897}
898
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700899TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700900 Parcel data, reply;
901
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700902 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
903 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700904
905 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -0700906 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +0800907 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
908 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
909 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
910 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700911}
912
Connor O'Brien52be2c92016-09-20 14:18:08 -0700913TEST_F(BinderLibTest, FreedBinder) {
914 status_t ret;
915
916 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700917 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -0700918
919 __u32 freedHandle;
920 wp<IBinder> keepFreedBinder;
921 {
922 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700923 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
924 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -0700925 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
926 freedHandle = freed->handle;
927 /* Add a weak ref to the freed binder so the driver does not
928 * delete its reference to it - otherwise the transaction
929 * fails regardless of whether the driver is fixed.
930 */
Steven Morelande171d622019-07-17 16:06:01 -0700931 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700932 }
Steven Morelande171d622019-07-17 16:06:01 -0700933 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -0700934 {
935 Parcel data, reply;
936 data.writeStrongBinder(server);
937 /* Replace original handle with handle to the freed binder */
938 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
939 __u32 oldHandle = strong->handle;
940 strong->handle = freedHandle;
941 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
942 /* Returns DEAD_OBJECT (-32) if target crashes and
943 * FAILED_TRANSACTION if the driver rejects the invalid
944 * object.
945 */
946 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
947 /* Restore original handle so parcel destructor does not use
948 * the wrong handle.
949 */
950 strong->handle = oldHandle;
951 }
952}
953
Sherry Yang336cdd32017-07-24 14:12:27 -0700954TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -0700955 Parcel data, reply;
956 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
957 for (int i = 0; i < 2; i++) {
958 BinderLibTestBundle datai;
959 datai.appendFrom(&data, 0, data.dataSize());
960
961 data.freeData();
962 data.writeInt32(1);
963 data.writeStrongBinder(callBack);
964 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
965
966 datai.appendTo(&data);
967 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700968 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
969 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -0700970}
971
Martijn Coenen45b07b42017-08-09 12:07:45 +0200972TEST_F(BinderLibTest, OnewayQueueing)
973{
Martijn Coenen45b07b42017-08-09 12:07:45 +0200974 Parcel data, data2;
975
976 sp<IBinder> pollServer = addPollServer();
977
978 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
979 data.writeStrongBinder(callBack);
980 data.writeInt32(500000); // delay in us before calling back
981
982 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
983 data2.writeStrongBinder(callBack2);
984 data2.writeInt32(0); // delay in us
985
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700986 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
987 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200988
989 // The delay ensures that this second transaction will end up on the async_todo list
990 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700991 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
992 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200993
994 // The server will ensure that the two transactions are handled in the expected order;
995 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700996 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
997 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +0200998
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700999 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1000 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001001}
1002
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001003TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1004{
1005 status_t ret;
1006 Parcel data, reply;
1007 data.writeInterfaceToken(binderLibTestServiceName);
1008 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1009 EXPECT_EQ(-1, reply.readInt32());
1010 EXPECT_EQ(NO_ERROR, ret);
1011}
1012
1013TEST_F(BinderLibTest, WorkSourceSet)
1014{
1015 status_t ret;
1016 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001017 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001018 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001019 data.writeInterfaceToken(binderLibTestServiceName);
1020 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1021 EXPECT_EQ(100, reply.readInt32());
1022 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001023 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1024 EXPECT_EQ(NO_ERROR, ret);
1025}
1026
1027TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1028{
1029 status_t ret;
1030 Parcel data, reply;
1031
1032 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1033 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1034
1035 data.writeInterfaceToken(binderLibTestServiceName);
1036 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1037 EXPECT_EQ(-1, reply.readInt32());
1038 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001039 EXPECT_EQ(NO_ERROR, ret);
1040}
1041
1042TEST_F(BinderLibTest, WorkSourceCleared)
1043{
1044 status_t ret;
1045 Parcel data, reply;
1046
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001047 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001048 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1049 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001050 data.writeInterfaceToken(binderLibTestServiceName);
1051 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1052
1053 EXPECT_EQ(-1, reply.readInt32());
1054 EXPECT_EQ(100, previousWorkSource);
1055 EXPECT_EQ(NO_ERROR, ret);
1056}
1057
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001058TEST_F(BinderLibTest, WorkSourceRestored)
1059{
1060 status_t ret;
1061 Parcel data, reply;
1062
1063 IPCThreadState::self()->setCallingWorkSourceUid(100);
1064 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1065 IPCThreadState::self()->restoreCallingWorkSource(token);
1066
1067 data.writeInterfaceToken(binderLibTestServiceName);
1068 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1069
1070 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001071 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001072 EXPECT_EQ(NO_ERROR, ret);
1073}
1074
Olivier Gaillard91a04802018-11-14 17:32:41 +00001075TEST_F(BinderLibTest, PropagateFlagSet)
1076{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001077 IPCThreadState::self()->clearPropagateWorkSource();
1078 IPCThreadState::self()->setCallingWorkSourceUid(100);
1079 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1080}
1081
1082TEST_F(BinderLibTest, PropagateFlagCleared)
1083{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001084 IPCThreadState::self()->setCallingWorkSourceUid(100);
1085 IPCThreadState::self()->clearPropagateWorkSource();
1086 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1087}
1088
1089TEST_F(BinderLibTest, PropagateFlagRestored)
1090{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001091 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1092 IPCThreadState::self()->restoreCallingWorkSource(token);
1093
1094 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1095}
1096
1097TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1098{
1099 IPCThreadState::self()->setCallingWorkSourceUid(100);
1100
1101 Parcel data, reply;
1102 status_t ret;
1103 data.writeInterfaceToken(binderLibTestServiceName);
1104 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1105
1106 Parcel data2, reply2;
1107 status_t ret2;
1108 data2.writeInterfaceToken(binderLibTestServiceName);
1109 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1110 EXPECT_EQ(100, reply2.readInt32());
1111 EXPECT_EQ(NO_ERROR, ret2);
1112}
1113
Steven Morelandbf1915b2020-07-16 22:43:02 +00001114TEST_F(BinderLibTest, SchedPolicySet) {
1115 sp<IBinder> server = addServer();
1116 ASSERT_TRUE(server != nullptr);
1117
1118 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001119 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1120 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001121
1122 int policy = reply.readInt32();
1123 int priority = reply.readInt32();
1124
1125 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1126 EXPECT_EQ(kSchedPriority, priority);
1127}
1128
Steven Morelandcf03cf12020-12-04 02:58:40 +00001129TEST_F(BinderLibTest, InheritRt) {
1130 sp<IBinder> server = addServer();
1131 ASSERT_TRUE(server != nullptr);
1132
1133 const struct sched_param param {
1134 .sched_priority = kSchedPriorityMore,
1135 };
1136 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1137
1138 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001139 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1140 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001141
1142 int policy = reply.readInt32();
1143 int priority = reply.readInt32();
1144
1145 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1146 EXPECT_EQ(kSchedPriorityMore, priority);
1147}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001148
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001149TEST_F(BinderLibTest, VectorSent) {
1150 Parcel data, reply;
1151 sp<IBinder> server = addServer();
1152 ASSERT_TRUE(server != nullptr);
1153
1154 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1155 data.writeUint64Vector(testValue);
1156
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001157 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001158 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001159 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001160 EXPECT_EQ(readValue, testValue);
1161}
1162
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001163TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1164 sp<IBinder> server = addServer();
1165 ASSERT_TRUE(server != nullptr);
1166
1167 Parcel reply;
1168 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1169 StatusEq(NO_ERROR));
1170 base::unique_fd fd;
1171 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1172
1173 const int result = fcntl(fd.get(), F_GETFL);
1174 ASSERT_NE(result, -1);
1175 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1176}
1177
Steven Moreland59b84442022-07-12 18:32:44 +00001178// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1179// This value is not exposed, but some code in the framework relies on being able to use
1180// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001181constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001182constexpr size_t kSizeBytesOverFull = 1'050'000;
1183
1184TEST_F(BinderLibTest, GargantuanVectorSent) {
1185 sp<IBinder> server = addServer();
1186 ASSERT_TRUE(server != nullptr);
1187
1188 for (size_t i = 0; i < 10; i++) {
1189 // a slight variation in size is used to consider certain possible caching implementations
1190 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1191
1192 Parcel data, reply;
1193 data.writeUint64Vector(testValue);
1194 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1195 << i;
1196 std::vector<uint64_t> readValue;
1197 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1198 EXPECT_EQ(readValue, testValue);
1199 }
1200}
1201
1202TEST_F(BinderLibTest, LimitExceededVectorSent) {
1203 sp<IBinder> server = addServer();
1204 ASSERT_TRUE(server != nullptr);
1205 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1206
1207 Parcel data, reply;
1208 data.writeUint64Vector(testValue);
1209 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1210 StatusEq(FAILED_TRANSACTION));
1211}
1212
Martijn Coenen82c75312019-07-24 15:18:30 +02001213TEST_F(BinderLibTest, BufRejected) {
1214 Parcel data, reply;
1215 uint32_t buf;
1216 sp<IBinder> server = addServer();
1217 ASSERT_TRUE(server != nullptr);
1218
1219 binder_buffer_object obj {
1220 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001221 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001222 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1223 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001224 };
1225 data.setDataCapacity(1024);
1226 // Write a bogus object at offset 0 to get an entry in the offset table
1227 data.writeFileDescriptor(0);
1228 EXPECT_EQ(data.objectsCount(), 1);
1229 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1230 // And now, overwrite it with the buffer object
1231 memcpy(parcelData, &obj, sizeof(obj));
1232 data.setDataSize(sizeof(obj));
1233
Steven Morelandf2e0a952021-11-01 18:17:23 -07001234 EXPECT_EQ(data.objectsCount(), 1);
1235
Martijn Coenen82c75312019-07-24 15:18:30 +02001236 // Either the kernel should reject this transaction (if it's correct), but
1237 // if it's not, the server implementation should return an error if it
1238 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001239 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001240 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001241}
1242
Steven Morelandf2e0a952021-11-01 18:17:23 -07001243TEST_F(BinderLibTest, WeakRejected) {
1244 Parcel data, reply;
1245 sp<IBinder> server = addServer();
1246 ASSERT_TRUE(server != nullptr);
1247
1248 auto binder = sp<BBinder>::make();
1249 wp<BBinder> wpBinder(binder);
1250 flat_binder_object obj{
1251 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1252 .flags = 0,
1253 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1254 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1255 };
1256 data.setDataCapacity(1024);
1257 // Write a bogus object at offset 0 to get an entry in the offset table
1258 data.writeFileDescriptor(0);
1259 EXPECT_EQ(data.objectsCount(), 1);
1260 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1261 // And now, overwrite it with the weak binder
1262 memcpy(parcelData, &obj, sizeof(obj));
1263 data.setDataSize(sizeof(obj));
1264
1265 // a previous bug caused other objects to be released an extra time, so we
1266 // test with an object that libbinder will actually try to release
1267 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1268
1269 EXPECT_EQ(data.objectsCount(), 2);
1270
1271 // send it many times, since previous error was memory corruption, make it
1272 // more likely that the server crashes
1273 for (size_t i = 0; i < 100; i++) {
1274 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1275 StatusEq(BAD_VALUE));
1276 }
1277
1278 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1279}
1280
Steven Moreland254e8ef2021-04-19 22:28:50 +00001281TEST_F(BinderLibTest, GotSid) {
1282 sp<IBinder> server = addServer();
1283
1284 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001285 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001286}
1287
Andrei Homescu1519b982022-06-09 02:04:44 +00001288struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1289 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1290
1291 // Flattenable protocol
1292 size_t getFlattenedSize() const {
1293 // Return a valid non-zero size here so we don't get an unintended
1294 // BAD_VALUE from Parcel::write
1295 return 16;
1296 }
1297 size_t getFdCount() const { return mFdCount; }
1298 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1299 for (size_t i = 0; i < count; i++) {
1300 fds[i] = STDIN_FILENO;
1301 }
1302 return NO_ERROR;
1303 }
1304 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1305 size_t & /*count*/) {
1306 /* This doesn't get called */
1307 return NO_ERROR;
1308 }
1309
1310 size_t mFdCount;
1311};
1312
1313TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1314 rlimit origNofile;
1315 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1316 ASSERT_EQ(0, ret);
1317
1318 // Restore the original file limits when the test finishes
1319 base::ScopeGuard guardUnguard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
1320
1321 rlimit testNofile = {1024, 1024};
1322 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1323 ASSERT_EQ(0, ret);
1324
1325 Parcel parcel;
1326 // Try to write more file descriptors than supported by the OS
1327 TooManyFdsFlattenable tooManyFds1(1024);
1328 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1329
1330 // Try to write more file descriptors than the internal limit
1331 TooManyFdsFlattenable tooManyFds2(1025);
1332 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1333}
1334
Jayant Chowdhary30700942022-01-31 14:12:40 -08001335TEST(ServiceNotifications, Unregister) {
1336 auto sm = defaultServiceManager();
1337 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1338 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1339 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1340 virtual ~LocalRegistrationCallbackImpl() {}
1341 };
1342 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1343
1344 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1345 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1346}
1347
Elie Kheirallah47431c12022-04-21 23:46:17 +00001348TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1349 Parcel data, reply;
1350 sp<IBinder> server = addServer();
1351 ASSERT_TRUE(server != nullptr);
1352 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1353 StatusEq(NO_ERROR));
1354 int32_t replyi = reply.readInt32();
1355 // Expect 16 threads: kKernelThreads = 15 + Pool thread == 16
1356 EXPECT_TRUE(replyi == kKernelThreads || replyi == kKernelThreads + 1);
1357 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1358
1359 /*
1360 * This will use all threads in the pool expect the main pool thread.
1361 * The service should run fine without locking, and the thread count should
1362 * not exceed 16 (15 Max + pool thread).
1363 */
1364 std::vector<std::thread> ts;
Steven Morelandb17a5f02022-07-13 01:25:35 +00001365 for (size_t i = 0; i < kKernelThreads; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001366 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001367 Parcel local_reply;
1368 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1369 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001370 }));
1371 }
1372
Steven Morelandb17a5f02022-07-13 01:25:35 +00001373 data.writeInt32(100);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001374 // Give a chance for all threads to be used
1375 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1376
1377 for (auto &t : ts) {
1378 t.join();
1379 }
1380
1381 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1382 StatusEq(NO_ERROR));
1383 replyi = reply.readInt32();
Steven Morelandb17a5f02022-07-13 01:25:35 +00001384 EXPECT_EQ(replyi, kKernelThreads + 1);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001385}
1386
Devin Moore4354f712022-12-08 01:44:46 +00001387TEST_F(BinderLibTest, ThreadPoolStarted) {
1388 Parcel data, reply;
1389 sp<IBinder> server = addServer();
1390 ASSERT_TRUE(server != nullptr);
1391 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1392 EXPECT_TRUE(reply.readBool());
1393}
1394
Elie Kheirallah47431c12022-04-21 23:46:17 +00001395size_t epochMillis() {
1396 using std::chrono::duration_cast;
1397 using std::chrono::milliseconds;
1398 using std::chrono::seconds;
1399 using std::chrono::system_clock;
1400 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1401}
1402
1403TEST_F(BinderLibTest, HangingServices) {
1404 Parcel data, reply;
1405 sp<IBinder> server = addServer();
1406 ASSERT_TRUE(server != nullptr);
1407 int32_t delay = 1000; // ms
1408 data.writeInt32(delay);
1409 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1410 std::vector<std::thread> ts;
1411 size_t epochMsBefore = epochMillis();
1412 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1413 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001414 Parcel local_reply;
1415 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1416 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001417 }));
1418 }
1419
1420 for (auto &t : ts) {
1421 t.join();
1422 }
1423 size_t epochMsAfter = epochMillis();
1424
1425 // deadlock occurred and threads only finished after 1s passed.
1426 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1427}
1428
Yifan Hong84bedeb2021-04-21 21:37:17 -07001429class BinderLibRpcTestBase : public BinderLibTest {
1430public:
1431 void SetUp() override {
1432 if (!base::GetBoolProperty("ro.debuggable", false)) {
1433 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1434 "non-debuggable builds.";
1435 }
1436 BinderLibTest::SetUp();
1437 }
1438
1439 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1440 auto rpcServer = RpcServer::make();
1441 EXPECT_NE(nullptr, rpcServer);
1442 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001443 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001444 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1445 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001446 return {};
1447 }
1448 return {rpcServer->releaseServer(), port};
1449 }
1450};
1451
Yifan Hong8b890852021-06-10 13:44:09 -07001452class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001453
Yifan Hongbd276552022-02-28 15:28:51 -08001454// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1455// If device is debuggable AND not on user builds, expects matcher.
1456// Otherwise expects INVALID_OPERATION.
1457// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1458static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1459 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1460 android::base::GetProperty("ro.build.type", "") != "user";
1461 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1462}
1463
Yifan Hong8b890852021-06-10 13:44:09 -07001464TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1465 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001466 ASSERT_TRUE(binder != nullptr);
1467 auto [socket, port] = CreateSocket();
1468 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001469 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1470 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001471}
1472
Yifan Hong8b890852021-06-10 13:44:09 -07001473// Tests for multiple RpcServer's on the same binder object.
1474TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1475 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001476 ASSERT_TRUE(binder != nullptr);
1477
1478 auto [socket1, port1] = CreateSocket();
1479 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001480 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001481 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1482 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001483
1484 auto [socket2, port2] = CreateSocket();
1485 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001486 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001487 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1488 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001489}
1490
Yifan Hong8b890852021-06-10 13:44:09 -07001491// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1492// local binders.
1493class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001494public:
1495 sp<IBinder> GetService() {
1496 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1497 }
1498 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1499 return info.param ? "remote" : "local";
1500 }
1501};
1502
Yifan Hong8b890852021-06-10 13:44:09 -07001503TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1504 auto binder = GetService();
1505 ASSERT_TRUE(binder != nullptr);
1506 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001507 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001508}
1509
1510TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001511 auto binder = GetService();
1512 ASSERT_TRUE(binder != nullptr);
1513 auto [socket, port] = CreateSocket();
1514 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001515 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1516 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001517}
Yifan Hong8b890852021-06-10 13:44:09 -07001518INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1519 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001520
Yifan Hong543edcd2021-05-18 19:47:30 -07001521class BinderLibTestService : public BBinder {
1522public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001523 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1524 : m_id(id),
1525 m_nextServerId(id + 1),
1526 m_serverStartRequested(false),
1527 m_callback(nullptr),
1528 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001529 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1530 pthread_cond_init(&m_serverWaitCond, nullptr);
1531 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001532 ~BinderLibTestService() {
1533 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1534 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001535
Yifan Hong543edcd2021-05-18 19:47:30 -07001536 void processPendingCall() {
1537 if (m_callback != nullptr) {
1538 Parcel data;
1539 data.writeInt32(NO_ERROR);
1540 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1541 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001542 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001543 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001544
Yifan Hong543edcd2021-05-18 19:47:30 -07001545 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1546 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001547 // TODO(b/182914638): also checks getCallingUid() for RPC
1548 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001549 return PERMISSION_DENIED;
1550 }
1551 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001552 case BINDER_LIB_TEST_REGISTER_SERVER: {
1553 int32_t id;
1554 sp<IBinder> binder;
1555 id = data.readInt32();
1556 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001557 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001558 return BAD_VALUE;
1559 }
1560
Yifan Hong543edcd2021-05-18 19:47:30 -07001561 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001562
1563 pthread_mutex_lock(&m_serverWaitMutex);
1564 if (m_serverStartRequested) {
1565 m_serverStartRequested = false;
1566 m_serverStarted = binder;
1567 pthread_cond_signal(&m_serverWaitCond);
1568 }
1569 pthread_mutex_unlock(&m_serverWaitMutex);
1570 return NO_ERROR;
1571 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001572 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001573 case BINDER_LIB_TEST_ADD_SERVER: {
1574 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001575 int serverid;
1576
1577 if (m_id != 0) {
1578 return INVALID_OPERATION;
1579 }
1580 pthread_mutex_lock(&m_serverWaitMutex);
1581 if (m_serverStartRequested) {
1582 ret = -EBUSY;
1583 } else {
1584 serverid = m_nextServerId++;
1585 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001586 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001587
1588 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001589 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001590 pthread_mutex_lock(&m_serverWaitMutex);
1591 }
1592 if (ret > 0) {
1593 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001594 struct timespec ts;
1595 clock_gettime(CLOCK_REALTIME, &ts);
1596 ts.tv_sec += 5;
1597 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001598 }
1599 if (m_serverStartRequested) {
1600 m_serverStartRequested = false;
1601 ret = -ETIMEDOUT;
1602 } else {
1603 reply->writeStrongBinder(m_serverStarted);
1604 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001605 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001606 ret = NO_ERROR;
1607 }
1608 } else if (ret >= 0) {
1609 m_serverStartRequested = false;
1610 ret = UNKNOWN_ERROR;
1611 }
1612 pthread_mutex_unlock(&m_serverWaitMutex);
1613 return ret;
1614 }
Steven Moreland35626652021-05-15 01:32:04 +00001615 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1616 IPCThreadState::SpGuard spGuard{
1617 .address = __builtin_frame_address(0),
1618 .context = "GuardInBinderTransaction",
1619 };
1620 const IPCThreadState::SpGuard *origGuard =
1621 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1622
1623 // if the guard works, this should abort
1624 (void)IPCThreadState::self()->getCallingPid();
1625
1626 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1627 return NO_ERROR;
1628 }
1629
Marco Ballesio7ee17572020-09-08 10:30:03 -07001630 case BINDER_LIB_TEST_GETPID:
1631 reply->writeInt32(getpid());
1632 return NO_ERROR;
1633 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1634 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001635 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001636 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001637 // oneway error codes should be ignored
1638 if (flags & TF_ONE_WAY) {
1639 return UNKNOWN_ERROR;
1640 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001641 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001642 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1643 // Note: this transaction is only designed for use with a
1644 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001645 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001646 // A callback was already pending; this means that
1647 // we received a second call while still processing
1648 // the first one. Fail the test.
1649 sp<IBinder> callback = data.readStrongBinder();
1650 Parcel data2;
1651 data2.writeInt32(UNKNOWN_ERROR);
1652
Yi Kong91635562018-06-07 14:38:36 -07001653 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001654 } else {
1655 m_callback = data.readStrongBinder();
1656 int32_t delayUs = data.readInt32();
1657 /*
1658 * It's necessary that we sleep here, so the next
1659 * transaction the caller makes will be queued to
1660 * the async queue.
1661 */
1662 usleep(delayUs);
1663
1664 /*
1665 * Now when we return, libbinder will tell the kernel
1666 * we are done with this transaction, and the kernel
1667 * can move the queued transaction to either the
1668 * thread todo worklist (for kernels without the fix),
1669 * or the proc todo worklist. In case of the former,
1670 * the next outbound call will pick up the pending
1671 * transaction, which leads to undesired reentrant
1672 * behavior. This is caught in the if() branch above.
1673 */
1674 }
1675
1676 return NO_ERROR;
1677 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001678 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1679 Parcel data2, reply2;
1680 sp<IBinder> binder;
1681 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001682 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001683 return BAD_VALUE;
1684 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001685 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001686 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1687 return NO_ERROR;
1688 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001689 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1690 reply->writeStrongBinder(this);
1691 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001692 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1693 reply->writeInt32(m_id);
1694 return NO_ERROR;
1695 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1696 int32_t count;
1697 uint32_t indirect_code;
1698 sp<IBinder> binder;
1699
1700 count = data.readInt32();
1701 reply->writeInt32(m_id);
1702 reply->writeInt32(count);
1703 for (int i = 0; i < count; i++) {
1704 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001705 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001706 return BAD_VALUE;
1707 }
1708 indirect_code = data.readInt32();
1709 BinderLibTestBundle data2(&data);
1710 if (!data2.isValid()) {
1711 return BAD_VALUE;
1712 }
1713 BinderLibTestBundle reply2;
1714 binder->transact(indirect_code, data2, &reply2);
1715 reply2.appendTo(reply);
1716 }
1717 return NO_ERROR;
1718 }
1719 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1720 reply->setError(data.readInt32());
1721 return NO_ERROR;
1722 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1723 reply->writeInt32(sizeof(void *));
1724 return NO_ERROR;
1725 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1726 return NO_ERROR;
1727 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1728 m_strongRef = data.readStrongBinder();
1729 return NO_ERROR;
1730 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1731 int ret;
1732 Parcel data2, reply2;
1733 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1734 sp<IBinder> target;
1735 sp<IBinder> callback;
1736
1737 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001738 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001739 return BAD_VALUE;
1740 }
1741 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001742 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001743 return BAD_VALUE;
1744 }
1745 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001746 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001747 data2.writeInt32(ret);
1748 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1749 return NO_ERROR;
1750 }
1751 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1752 int ret;
1753 int32_t size;
1754 const void *buf;
1755 int fd;
1756
1757 fd = data.readFileDescriptor();
1758 if (fd < 0) {
1759 return BAD_VALUE;
1760 }
1761 ret = data.readInt32(&size);
1762 if (ret != NO_ERROR) {
1763 return ret;
1764 }
1765 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001766 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001767 return BAD_VALUE;
1768 }
1769 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001770 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001771 return NO_ERROR;
1772 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001773 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1774 int ret;
1775 int32_t size;
1776 const void *buf;
1777 android::base::unique_fd fd;
1778
1779 ret = data.readUniqueParcelFileDescriptor(&fd);
1780 if (ret != NO_ERROR) {
1781 return ret;
1782 }
1783 ret = data.readInt32(&size);
1784 if (ret != NO_ERROR) {
1785 return ret;
1786 }
1787 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001788 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001789 return BAD_VALUE;
1790 }
1791 ret = write(fd.get(), buf, size);
1792 if (ret != size) return UNKNOWN_ERROR;
1793 return NO_ERROR;
1794 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001795 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1796 alarm(10);
1797 return NO_ERROR;
1798 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001799 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001800 ;
1801 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001802 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001803 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001804 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001805 return NO_ERROR;
1806 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001807 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1808 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001809 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001810 return NO_ERROR;
1811 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001812 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1813 int policy = 0;
1814 sched_param param;
1815 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1816 return UNKNOWN_ERROR;
1817 }
1818 reply->writeInt32(policy);
1819 reply->writeInt32(param.sched_priority);
1820 return NO_ERROR;
1821 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001822 case BINDER_LIB_TEST_ECHO_VECTOR: {
1823 std::vector<uint64_t> vector;
1824 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001825 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001826 reply->writeUint64Vector(vector);
1827 return NO_ERROR;
1828 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001829 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1830 std::array<int, 2> sockets;
1831 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1832 if (!created) {
1833 ALOGE("Could not create socket pair");
1834 return UNKNOWN_ERROR;
1835 }
1836
1837 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1838 if (result != 0) {
1839 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1840 return UNKNOWN_ERROR;
1841 }
1842 base::unique_fd out(sockets[0]);
1843 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1844 if (writeResult != NO_ERROR) {
1845 ALOGE("Could not write unique_fd");
1846 return writeResult;
1847 }
1848 close(sockets[1]); // we don't need the other side of the fd
1849 return NO_ERROR;
1850 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001851 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001852 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1853 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001854 case BINDER_LIB_TEST_CAN_GET_SID: {
1855 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1856 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001857 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1858 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1859 return NO_ERROR;
1860 }
Devin Moore4354f712022-12-08 01:44:46 +00001861 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1862 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1863 return NO_ERROR;
1864 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001865 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001866 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001867 return NO_ERROR;
1868 }
1869 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001870 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001871 return NO_ERROR;
1872 }
1873 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1874 int32_t ms = data.readInt32();
1875 return unlockInMs(ms);
1876 }
1877 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001878 m_blockMutex.lock();
1879 sp<BinderLibTestService> thisService = this;
1880 int32_t value = data.readInt32();
1881 // start local thread to unlock in 1s
1882 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001883 t.detach();
1884 return NO_ERROR;
1885 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001886 default:
1887 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001888 };
1889 }
1890
Elie Kheirallah47431c12022-04-21 23:46:17 +00001891 status_t unlockInMs(int32_t ms) {
1892 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001893 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001894 return NO_ERROR;
1895 }
1896
Yifan Hong543edcd2021-05-18 19:47:30 -07001897private:
1898 int32_t m_id;
1899 int32_t m_nextServerId;
1900 pthread_mutex_t m_serverWaitMutex;
1901 pthread_cond_t m_serverWaitCond;
1902 bool m_serverStartRequested;
1903 sp<IBinder> m_serverStarted;
1904 sp<IBinder> m_strongRef;
1905 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001906 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001907 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001908};
1909
Martijn Coenen45b07b42017-08-09 12:07:45 +02001910int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001911{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001912 binderLibTestServiceName += String16(binderserversuffix);
1913
Steven Moreland35626652021-05-15 01:32:04 +00001914 // Testing to make sure that calls that we are serving can use getCallin*
1915 // even though we don't here.
1916 IPCThreadState::SpGuard spGuard{
1917 .address = __builtin_frame_address(0),
1918 .context = "main server thread",
1919 };
1920 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1921
Riley Andrews06b01ad2014-12-18 12:10:08 -08001922 status_t ret;
1923 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001924 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001925 {
1926 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001927
Steven Morelandbf1915b2020-07-16 22:43:02 +00001928 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1929
Steven Morelandcf03cf12020-12-04 02:58:40 +00001930 testService->setInheritRt(true);
1931
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001932 /*
1933 * Normally would also contain functionality as well, but we are only
1934 * testing the extension mechanism.
1935 */
1936 testService->setExtension(new BBinder());
1937
Martijn Coenen82c75312019-07-24 15:18:30 +02001938 // Required for test "BufRejected'
1939 testService->setRequestingSid(true);
1940
Martijn Coenen45b07b42017-08-09 12:07:45 +02001941 /*
1942 * We need this below, but can't hold a sp<> because it prevents the
1943 * node from being cleaned up automatically. It's safe in this case
1944 * because of how the tests are written.
1945 */
1946 testServicePtr = testService.get();
1947
Riley Andrews06b01ad2014-12-18 12:10:08 -08001948 if (index == 0) {
1949 ret = sm->addService(binderLibTestServiceName, testService);
1950 } else {
1951 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1952 Parcel data, reply;
1953 data.writeInt32(index);
1954 data.writeStrongBinder(testService);
1955
1956 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1957 }
1958 }
1959 write(readypipefd, &ret, sizeof(ret));
1960 close(readypipefd);
1961 //printf("%s: ret %d\n", __func__, ret);
1962 if (ret)
1963 return 1;
1964 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001965 if (usePoll) {
1966 int fd;
1967 struct epoll_event ev;
1968 int epoll_fd;
1969 IPCThreadState::self()->setupPolling(&fd);
1970 if (fd < 0) {
1971 return 1;
1972 }
1973 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1974
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001975 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001976 if (epoll_fd == -1) {
1977 return 1;
1978 }
1979
1980 ev.events = EPOLLIN;
1981 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1982 return 1;
1983 }
1984
1985 while (1) {
1986 /*
1987 * We simulate a single-threaded process using the binder poll
1988 * interface; besides handling binder commands, it can also
1989 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001990 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001991 *
1992 * processPendingCall() will then issue that transaction.
1993 */
1994 struct epoll_event events[1];
1995 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1996 if (numEvents < 0) {
1997 if (errno == EINTR) {
1998 continue;
1999 }
2000 return 1;
2001 }
2002 if (numEvents > 0) {
2003 IPCThreadState::self()->handlePolledCommands();
2004 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2005 testServicePtr->processPendingCall();
2006 }
2007 }
2008 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002009 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002010 ProcessState::self()->startThreadPool();
2011 IPCThreadState::self()->joinThreadPool();
2012 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002013 //printf("%s: joinThreadPool returned\n", __func__);
2014 return 1; /* joinThreadPool should not return */
2015}
2016
2017int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07002018 ExitIfWrongAbi();
2019
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002020 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002021 binderservername = argv[2];
2022 } else {
2023 binderservername = argv[0];
2024 }
2025
Martijn Coenen45b07b42017-08-09 12:07:45 +02002026 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2027 binderserversuffix = argv[5];
2028 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002029 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002030 binderserversuffix = new char[16];
2031 snprintf(binderserversuffix, 16, "%d", getpid());
2032 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002033
2034 ::testing::InitGoogleTest(&argc, argv);
2035 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2036 ProcessState::self()->startThreadPool();
2037 return RUN_ALL_TESTS();
2038}