blob: 955c65020516f349de1979d1174a2989cad95fd0 [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);
Steven Moreland436a1102023-01-24 21:48:11 +00001409 // b/266537959 - must take before taking lock, since countdown is started in the remote
1410 // process there.
1411 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001412 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1413 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001414 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1415 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001416 Parcel local_reply;
1417 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1418 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001419 }));
1420 }
1421
1422 for (auto &t : ts) {
1423 t.join();
1424 }
1425 size_t epochMsAfter = epochMillis();
1426
1427 // deadlock occurred and threads only finished after 1s passed.
1428 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1429}
1430
Yifan Hong84bedeb2021-04-21 21:37:17 -07001431class BinderLibRpcTestBase : public BinderLibTest {
1432public:
1433 void SetUp() override {
1434 if (!base::GetBoolProperty("ro.debuggable", false)) {
1435 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1436 "non-debuggable builds.";
1437 }
1438 BinderLibTest::SetUp();
1439 }
1440
1441 std::tuple<android::base::unique_fd, unsigned int> CreateSocket() {
1442 auto rpcServer = RpcServer::make();
1443 EXPECT_NE(nullptr, rpcServer);
1444 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001445 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001446 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1447 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001448 return {};
1449 }
1450 return {rpcServer->releaseServer(), port};
1451 }
1452};
1453
Yifan Hong8b890852021-06-10 13:44:09 -07001454class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001455
Yifan Hongbd276552022-02-28 15:28:51 -08001456// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1457// If device is debuggable AND not on user builds, expects matcher.
1458// Otherwise expects INVALID_OPERATION.
1459// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1460static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1461 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1462 android::base::GetProperty("ro.build.type", "") != "user";
1463 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1464}
1465
Yifan Hong8b890852021-06-10 13:44:09 -07001466TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1467 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001468 ASSERT_TRUE(binder != nullptr);
1469 auto [socket, port] = CreateSocket();
1470 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001471 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1472 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001473}
1474
Yifan Hong8b890852021-06-10 13:44:09 -07001475// Tests for multiple RpcServer's on the same binder object.
1476TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1477 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001478 ASSERT_TRUE(binder != nullptr);
1479
1480 auto [socket1, port1] = CreateSocket();
1481 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001482 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001483 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1484 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001485
1486 auto [socket2, port2] = CreateSocket();
1487 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001488 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001489 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1490 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001491}
1492
Yifan Hong8b890852021-06-10 13:44:09 -07001493// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1494// local binders.
1495class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001496public:
1497 sp<IBinder> GetService() {
1498 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1499 }
1500 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1501 return info.param ? "remote" : "local";
1502 }
1503};
1504
Yifan Hong8b890852021-06-10 13:44:09 -07001505TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1506 auto binder = GetService();
1507 ASSERT_TRUE(binder != nullptr);
1508 EXPECT_THAT(binder->setRpcClientDebug(android::base::unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001509 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001510}
1511
1512TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001513 auto binder = GetService();
1514 ASSERT_TRUE(binder != nullptr);
1515 auto [socket, port] = CreateSocket();
1516 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001517 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1518 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001519}
Yifan Hong8b890852021-06-10 13:44:09 -07001520INSTANTIATE_TEST_CASE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1521 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001522
Yifan Hong543edcd2021-05-18 19:47:30 -07001523class BinderLibTestService : public BBinder {
1524public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001525 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1526 : m_id(id),
1527 m_nextServerId(id + 1),
1528 m_serverStartRequested(false),
1529 m_callback(nullptr),
1530 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001531 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1532 pthread_cond_init(&m_serverWaitCond, nullptr);
1533 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001534 ~BinderLibTestService() {
1535 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1536 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001537
Yifan Hong543edcd2021-05-18 19:47:30 -07001538 void processPendingCall() {
1539 if (m_callback != nullptr) {
1540 Parcel data;
1541 data.writeInt32(NO_ERROR);
1542 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1543 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001544 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001545 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001546
Yifan Hong543edcd2021-05-18 19:47:30 -07001547 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1548 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001549 // TODO(b/182914638): also checks getCallingUid() for RPC
1550 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001551 return PERMISSION_DENIED;
1552 }
1553 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001554 case BINDER_LIB_TEST_REGISTER_SERVER: {
1555 int32_t id;
1556 sp<IBinder> binder;
1557 id = data.readInt32();
1558 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001559 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001560 return BAD_VALUE;
1561 }
1562
Yifan Hong543edcd2021-05-18 19:47:30 -07001563 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001564
1565 pthread_mutex_lock(&m_serverWaitMutex);
1566 if (m_serverStartRequested) {
1567 m_serverStartRequested = false;
1568 m_serverStarted = binder;
1569 pthread_cond_signal(&m_serverWaitCond);
1570 }
1571 pthread_mutex_unlock(&m_serverWaitMutex);
1572 return NO_ERROR;
1573 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001574 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08001575 case BINDER_LIB_TEST_ADD_SERVER: {
1576 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001577 int serverid;
1578
1579 if (m_id != 0) {
1580 return INVALID_OPERATION;
1581 }
1582 pthread_mutex_lock(&m_serverWaitMutex);
1583 if (m_serverStartRequested) {
1584 ret = -EBUSY;
1585 } else {
1586 serverid = m_nextServerId++;
1587 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001588 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001589
1590 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001591 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001592 pthread_mutex_lock(&m_serverWaitMutex);
1593 }
1594 if (ret > 0) {
1595 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001596 struct timespec ts;
1597 clock_gettime(CLOCK_REALTIME, &ts);
1598 ts.tv_sec += 5;
1599 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001600 }
1601 if (m_serverStartRequested) {
1602 m_serverStartRequested = false;
1603 ret = -ETIMEDOUT;
1604 } else {
1605 reply->writeStrongBinder(m_serverStarted);
1606 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07001607 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001608 ret = NO_ERROR;
1609 }
1610 } else if (ret >= 0) {
1611 m_serverStartRequested = false;
1612 ret = UNKNOWN_ERROR;
1613 }
1614 pthread_mutex_unlock(&m_serverWaitMutex);
1615 return ret;
1616 }
Steven Moreland35626652021-05-15 01:32:04 +00001617 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
1618 IPCThreadState::SpGuard spGuard{
1619 .address = __builtin_frame_address(0),
1620 .context = "GuardInBinderTransaction",
1621 };
1622 const IPCThreadState::SpGuard *origGuard =
1623 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1624
1625 // if the guard works, this should abort
1626 (void)IPCThreadState::self()->getCallingPid();
1627
1628 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
1629 return NO_ERROR;
1630 }
1631
Marco Ballesio7ee17572020-09-08 10:30:03 -07001632 case BINDER_LIB_TEST_GETPID:
1633 reply->writeInt32(getpid());
1634 return NO_ERROR;
1635 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
1636 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00001637 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08001638 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00001639 // oneway error codes should be ignored
1640 if (flags & TF_ONE_WAY) {
1641 return UNKNOWN_ERROR;
1642 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001643 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001644 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
1645 // Note: this transaction is only designed for use with a
1646 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07001647 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02001648 // A callback was already pending; this means that
1649 // we received a second call while still processing
1650 // the first one. Fail the test.
1651 sp<IBinder> callback = data.readStrongBinder();
1652 Parcel data2;
1653 data2.writeInt32(UNKNOWN_ERROR);
1654
Yi Kong91635562018-06-07 14:38:36 -07001655 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001656 } else {
1657 m_callback = data.readStrongBinder();
1658 int32_t delayUs = data.readInt32();
1659 /*
1660 * It's necessary that we sleep here, so the next
1661 * transaction the caller makes will be queued to
1662 * the async queue.
1663 */
1664 usleep(delayUs);
1665
1666 /*
1667 * Now when we return, libbinder will tell the kernel
1668 * we are done with this transaction, and the kernel
1669 * can move the queued transaction to either the
1670 * thread todo worklist (for kernels without the fix),
1671 * or the proc todo worklist. In case of the former,
1672 * the next outbound call will pick up the pending
1673 * transaction, which leads to undesired reentrant
1674 * behavior. This is caught in the if() branch above.
1675 */
1676 }
1677
1678 return NO_ERROR;
1679 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001680 case BINDER_LIB_TEST_NOP_CALL_BACK: {
1681 Parcel data2, reply2;
1682 sp<IBinder> binder;
1683 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001684 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001685 return BAD_VALUE;
1686 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02001687 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001688 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1689 return NO_ERROR;
1690 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001691 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
1692 reply->writeStrongBinder(this);
1693 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001694 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
1695 reply->writeInt32(m_id);
1696 return NO_ERROR;
1697 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
1698 int32_t count;
1699 uint32_t indirect_code;
1700 sp<IBinder> binder;
1701
1702 count = data.readInt32();
1703 reply->writeInt32(m_id);
1704 reply->writeInt32(count);
1705 for (int i = 0; i < count; i++) {
1706 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001707 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001708 return BAD_VALUE;
1709 }
1710 indirect_code = data.readInt32();
1711 BinderLibTestBundle data2(&data);
1712 if (!data2.isValid()) {
1713 return BAD_VALUE;
1714 }
1715 BinderLibTestBundle reply2;
1716 binder->transact(indirect_code, data2, &reply2);
1717 reply2.appendTo(reply);
1718 }
1719 return NO_ERROR;
1720 }
1721 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
1722 reply->setError(data.readInt32());
1723 return NO_ERROR;
1724 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
1725 reply->writeInt32(sizeof(void *));
1726 return NO_ERROR;
1727 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
1728 return NO_ERROR;
1729 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
1730 m_strongRef = data.readStrongBinder();
1731 return NO_ERROR;
1732 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
1733 int ret;
1734 Parcel data2, reply2;
1735 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
1736 sp<IBinder> target;
1737 sp<IBinder> callback;
1738
1739 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001740 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001741 return BAD_VALUE;
1742 }
1743 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001744 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001745 return BAD_VALUE;
1746 }
1747 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07001748 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001749 data2.writeInt32(ret);
1750 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
1751 return NO_ERROR;
1752 }
1753 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
1754 int ret;
1755 int32_t size;
1756 const void *buf;
1757 int fd;
1758
1759 fd = data.readFileDescriptor();
1760 if (fd < 0) {
1761 return BAD_VALUE;
1762 }
1763 ret = data.readInt32(&size);
1764 if (ret != NO_ERROR) {
1765 return ret;
1766 }
1767 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07001768 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001769 return BAD_VALUE;
1770 }
1771 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07001772 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001773 return NO_ERROR;
1774 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09001775 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
1776 int ret;
1777 int32_t size;
1778 const void *buf;
1779 android::base::unique_fd fd;
1780
1781 ret = data.readUniqueParcelFileDescriptor(&fd);
1782 if (ret != NO_ERROR) {
1783 return ret;
1784 }
1785 ret = data.readInt32(&size);
1786 if (ret != NO_ERROR) {
1787 return ret;
1788 }
1789 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07001790 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09001791 return BAD_VALUE;
1792 }
1793 ret = write(fd.get(), buf, size);
1794 if (ret != size) return UNKNOWN_ERROR;
1795 return NO_ERROR;
1796 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001797 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
1798 alarm(10);
1799 return NO_ERROR;
1800 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07001801 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001802 ;
1803 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001804 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07001805 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07001806 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001807 return NO_ERROR;
1808 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001809 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
1810 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001811 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001812 return NO_ERROR;
1813 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00001814 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
1815 int policy = 0;
1816 sched_param param;
1817 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
1818 return UNKNOWN_ERROR;
1819 }
1820 reply->writeInt32(policy);
1821 reply->writeInt32(param.sched_priority);
1822 return NO_ERROR;
1823 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001824 case BINDER_LIB_TEST_ECHO_VECTOR: {
1825 std::vector<uint64_t> vector;
1826 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07001827 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001828 reply->writeUint64Vector(vector);
1829 return NO_ERROR;
1830 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001831 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
1832 std::array<int, 2> sockets;
1833 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
1834 if (!created) {
1835 ALOGE("Could not create socket pair");
1836 return UNKNOWN_ERROR;
1837 }
1838
1839 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
1840 if (result != 0) {
1841 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
1842 return UNKNOWN_ERROR;
1843 }
1844 base::unique_fd out(sockets[0]);
1845 status_t writeResult = reply->writeUniqueFileDescriptor(out);
1846 if (writeResult != NO_ERROR) {
1847 ALOGE("Could not write unique_fd");
1848 return writeResult;
1849 }
1850 close(sockets[1]); // we don't need the other side of the fd
1851 return NO_ERROR;
1852 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07001853 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02001854 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
1855 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00001856 case BINDER_LIB_TEST_CAN_GET_SID: {
1857 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
1858 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001859 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
1860 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
1861 return NO_ERROR;
1862 }
Devin Moore4354f712022-12-08 01:44:46 +00001863 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
1864 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
1865 return NO_ERROR;
1866 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00001867 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001868 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001869 return NO_ERROR;
1870 }
1871 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001872 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001873 return NO_ERROR;
1874 }
1875 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
1876 int32_t ms = data.readInt32();
1877 return unlockInMs(ms);
1878 }
1879 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001880 m_blockMutex.lock();
1881 sp<BinderLibTestService> thisService = this;
1882 int32_t value = data.readInt32();
1883 // start local thread to unlock in 1s
1884 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00001885 t.detach();
1886 return NO_ERROR;
1887 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08001888 default:
1889 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07001890 };
1891 }
1892
Elie Kheirallah47431c12022-04-21 23:46:17 +00001893 status_t unlockInMs(int32_t ms) {
1894 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001895 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001896 return NO_ERROR;
1897 }
1898
Yifan Hong543edcd2021-05-18 19:47:30 -07001899private:
1900 int32_t m_id;
1901 int32_t m_nextServerId;
1902 pthread_mutex_t m_serverWaitMutex;
1903 pthread_cond_t m_serverWaitCond;
1904 bool m_serverStartRequested;
1905 sp<IBinder> m_serverStarted;
1906 sp<IBinder> m_strongRef;
1907 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07001908 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00001909 std::mutex m_blockMutex;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001910};
1911
Martijn Coenen45b07b42017-08-09 12:07:45 +02001912int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08001913{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07001914 binderLibTestServiceName += String16(binderserversuffix);
1915
Steven Moreland35626652021-05-15 01:32:04 +00001916 // Testing to make sure that calls that we are serving can use getCallin*
1917 // even though we don't here.
1918 IPCThreadState::SpGuard spGuard{
1919 .address = __builtin_frame_address(0),
1920 .context = "main server thread",
1921 };
1922 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
1923
Riley Andrews06b01ad2014-12-18 12:10:08 -08001924 status_t ret;
1925 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02001926 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001927 {
1928 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001929
Steven Morelandbf1915b2020-07-16 22:43:02 +00001930 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
1931
Steven Morelandcf03cf12020-12-04 02:58:40 +00001932 testService->setInheritRt(true);
1933
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001934 /*
1935 * Normally would also contain functionality as well, but we are only
1936 * testing the extension mechanism.
1937 */
1938 testService->setExtension(new BBinder());
1939
Martijn Coenen82c75312019-07-24 15:18:30 +02001940 // Required for test "BufRejected'
1941 testService->setRequestingSid(true);
1942
Martijn Coenen45b07b42017-08-09 12:07:45 +02001943 /*
1944 * We need this below, but can't hold a sp<> because it prevents the
1945 * node from being cleaned up automatically. It's safe in this case
1946 * because of how the tests are written.
1947 */
1948 testServicePtr = testService.get();
1949
Riley Andrews06b01ad2014-12-18 12:10:08 -08001950 if (index == 0) {
1951 ret = sm->addService(binderLibTestServiceName, testService);
1952 } else {
1953 sp<IBinder> server = sm->getService(binderLibTestServiceName);
1954 Parcel data, reply;
1955 data.writeInt32(index);
1956 data.writeStrongBinder(testService);
1957
1958 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
1959 }
1960 }
1961 write(readypipefd, &ret, sizeof(ret));
1962 close(readypipefd);
1963 //printf("%s: ret %d\n", __func__, ret);
1964 if (ret)
1965 return 1;
1966 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001967 if (usePoll) {
1968 int fd;
1969 struct epoll_event ev;
1970 int epoll_fd;
1971 IPCThreadState::self()->setupPolling(&fd);
1972 if (fd < 0) {
1973 return 1;
1974 }
1975 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
1976
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08001977 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02001978 if (epoll_fd == -1) {
1979 return 1;
1980 }
1981
1982 ev.events = EPOLLIN;
1983 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
1984 return 1;
1985 }
1986
1987 while (1) {
1988 /*
1989 * We simulate a single-threaded process using the binder poll
1990 * interface; besides handling binder commands, it can also
1991 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07001992 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02001993 *
1994 * processPendingCall() will then issue that transaction.
1995 */
1996 struct epoll_event events[1];
1997 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
1998 if (numEvents < 0) {
1999 if (errno == EINTR) {
2000 continue;
2001 }
2002 return 1;
2003 }
2004 if (numEvents > 0) {
2005 IPCThreadState::self()->handlePolledCommands();
2006 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2007 testServicePtr->processPendingCall();
2008 }
2009 }
2010 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002011 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002012 ProcessState::self()->startThreadPool();
2013 IPCThreadState::self()->joinThreadPool();
2014 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002015 //printf("%s: joinThreadPool returned\n", __func__);
2016 return 1; /* joinThreadPool should not return */
2017}
2018
2019int main(int argc, char **argv) {
Steven Morelandf9f3de22020-05-06 17:14:39 -07002020 ExitIfWrongAbi();
2021
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002022 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002023 binderservername = argv[2];
2024 } else {
2025 binderservername = argv[0];
2026 }
2027
Martijn Coenen45b07b42017-08-09 12:07:45 +02002028 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2029 binderserversuffix = argv[5];
2030 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002031 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002032 binderserversuffix = new char[16];
2033 snprintf(binderserversuffix, 16, "%d", getpid());
2034 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002035
2036 ::testing::InitGoogleTest(&argc, argv);
2037 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2038 ProcessState::self()->startThreadPool();
2039 return RUN_ALL_TESTS();
2040}