blob: 8806fcc8a94ac668ac225578b09ca9cbf89172d7 [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
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070030#include <android-base/logging.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070031#include <android-base/properties.h>
Yifan Hong28d6c352021-06-04 17:27:35 -070032#include <android-base/result-gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080033#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070034#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000035#include <binder/Functional.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080036#include <binder/IBinder.h>
37#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070039#include <binder/RpcServer.h>
40#include <binder/RpcSession.h>
Parth Sane81b4d5a2024-05-23 14:11:13 +000041#include <binder/Status.h>
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070042#include <binder/unique_fd.h>
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070043#include <input/BlockingQueue.h>
44#include <processgroup/processgroup.h>
Tomasz Wasilczyk300aa132023-10-26 15:00:04 -070045#include <utils/Flattenable.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080046
Steven Morelandcf03cf12020-12-04 02:58:40 +000047#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020048#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080049#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070050#include <sys/socket.h>
51#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020052
Steven Moreland6ba5a252021-05-04 22:49:00 +000053#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070054
Riley Andrews06b01ad2014-12-18 12:10:08 -080055#define ARRAY_SIZE(array) (sizeof array / sizeof array[0])
56
57using namespace android;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000058using namespace android::binder::impl;
Yifan Hong84bedeb2021-04-21 21:37:17 -070059using namespace std::string_literals;
60using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070061using android::base::testing::HasValue;
Parth Sane81b4d5a2024-05-23 14:11:13 +000062using android::binder::Status;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070063using android::binder::unique_fd;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070064using std::chrono_literals::operator""ms;
Yifan Hong84bedeb2021-04-21 21:37:17 -070065using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080066using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070067using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070068using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070069
70// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
71MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
72 *result_listener << statusToString(arg);
73 return expected == arg;
74}
Riley Andrews06b01ad2014-12-18 12:10:08 -080075
Sherry Yang336cdd32017-07-24 14:12:27 -070076static ::testing::AssertionResult IsPageAligned(void *buf) {
Vilas Bhat04e28c72024-02-12 21:47:15 +000077 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
Sherry Yang336cdd32017-07-24 14:12:27 -070078 return ::testing::AssertionSuccess();
79 else
80 return ::testing::AssertionFailure() << buf << " is not page aligned";
81}
82
Riley Andrews06b01ad2014-12-18 12:10:08 -080083static testing::Environment* binder_env;
84static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070085static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080086static char binderserverarg[] = "--binderserver";
87
Steven Morelandbf1915b2020-07-16 22:43:02 +000088static constexpr int kSchedPolicy = SCHED_RR;
89static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000090static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000091static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000092
Riley Andrews06b01ad2014-12-18 12:10:08 -080093static String16 binderLibTestServiceName = String16("test.binderLib");
94
95enum BinderLibTestTranscationCode {
96 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
97 BINDER_LIB_TEST_REGISTER_SERVER,
98 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020099 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +0000100 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800101 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -0700102 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200103 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800104 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700105 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800106 BINDER_LIB_TEST_GET_ID_TRANSACTION,
107 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
108 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
109 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
110 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
111 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
112 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900113 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800114 BINDER_LIB_TEST_EXIT_TRANSACTION,
115 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
116 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700117 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100118 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000119 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700120 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
121 BINDER_LIB_TEST_GETPID,
Jing Jibdbe29a2023-10-03 00:03:28 -0700122 BINDER_LIB_TEST_GETUID,
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700123 BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE,
124 BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800125 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700126 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700127 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000128 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000129 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
130 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000131 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000132 BINDER_LIB_TEST_LOCK_UNLOCK,
133 BINDER_LIB_TEST_PROCESS_LOCK,
134 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
135 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800136};
137
Martijn Coenen45b07b42017-08-09 12:07:45 +0200138pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800139{
140 int ret;
141 pid_t pid;
142 status_t status;
143 int pipefd[2];
144 char stri[16];
145 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200146 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800147 char *childargv[] = {
148 binderservername,
149 binderserverarg,
150 stri,
151 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200152 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700153 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700154 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800155 };
156
157 ret = pipe(pipefd);
158 if (ret < 0)
159 return ret;
160
161 snprintf(stri, sizeof(stri), "%d", arg2);
162 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200163 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800164
165 pid = fork();
166 if (pid == -1)
167 return pid;
168 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800169 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800170 close(pipefd[0]);
171 execv(binderservername, childargv);
172 status = -errno;
173 write(pipefd[1], &status, sizeof(status));
174 fprintf(stderr, "execv failed, %s\n", strerror(errno));
175 _exit(EXIT_FAILURE);
176 }
177 close(pipefd[1]);
178 ret = read(pipefd[0], &status, sizeof(status));
179 //printf("pipe read returned %d, status %d\n", ret, status);
180 close(pipefd[0]);
181 if (ret == sizeof(status)) {
182 ret = status;
183 } else {
184 kill(pid, SIGKILL);
185 if (ret >= 0) {
186 ret = NO_INIT;
187 }
188 }
189 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700190 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800191 return ret;
192 }
193 return pid;
194}
195
Yifan Hong84bedeb2021-04-21 21:37:17 -0700196android::base::Result<int32_t> GetId(sp<IBinder> service) {
197 using android::base::Error;
198 Parcel data, reply;
199 data.markForBinder(service);
200 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
201 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
202 if (status != OK)
203 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
204 int32_t result = 0;
205 status = reply.readInt32(&result);
206 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
207 return result;
208}
209
Riley Andrews06b01ad2014-12-18 12:10:08 -0800210class BinderLibTestEnv : public ::testing::Environment {
211 public:
212 BinderLibTestEnv() {}
213 sp<IBinder> getServer(void) {
214 return m_server;
215 }
216
217 private:
218 virtual void SetUp() {
219 m_serverpid = start_server_process(0);
220 //printf("m_serverpid %d\n", m_serverpid);
221 ASSERT_GT(m_serverpid, 0);
222
223 sp<IServiceManager> sm = defaultServiceManager();
224 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000225#pragma clang diagnostic push
226#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -0800227 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +0000228#pragma clang diagnostic pop
Yi Kong91635562018-06-07 14:38:36 -0700229 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800230 //printf("%s: pid %d, get service done\n", __func__, m_pid);
231 }
232 virtual void TearDown() {
233 status_t ret;
234 Parcel data, reply;
235 int exitStatus;
236 pid_t pid;
237
238 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700239 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800240 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
241 EXPECT_EQ(0, ret);
242 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
243 EXPECT_EQ(0, ret);
244 }
245 if (m_serverpid > 0) {
246 //printf("wait for %d\n", m_pids[i]);
247 pid = wait(&exitStatus);
248 EXPECT_EQ(m_serverpid, pid);
249 EXPECT_TRUE(WIFEXITED(exitStatus));
250 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
251 }
252 }
253
254 pid_t m_serverpid;
255 sp<IBinder> m_server;
256};
257
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700258class TestFrozenStateChangeCallback : public IBinder::FrozenStateChangeCallback {
259public:
260 BlockingQueue<std::pair<const wp<IBinder>, State>> events;
261
262 virtual void onStateChanged(const wp<IBinder>& who, State state) {
263 events.push(std::make_pair(who, state));
264 }
265
266 void ensureFrozenEventReceived() {
267 auto event = events.popWithTimeout(500ms);
268 ASSERT_TRUE(event.has_value());
269 EXPECT_EQ(State::FROZEN, event->second); // isFrozen should be true
270 EXPECT_EQ(0u, events.size());
271 }
272
273 void ensureUnfrozenEventReceived() {
274 auto event = events.popWithTimeout(500ms);
275 ASSERT_TRUE(event.has_value());
276 EXPECT_EQ(State::UNFROZEN, event->second); // isFrozen should be false
277 EXPECT_EQ(0u, events.size());
278 }
279
280 std::vector<bool> getAllAndClear() {
281 std::vector<bool> results;
282 while (true) {
283 auto event = events.popWithTimeout(0ms);
284 if (!event.has_value()) {
285 break;
286 }
287 results.push_back(event->second == State::FROZEN);
288 }
289 return results;
290 }
291
292 sp<IBinder> binder;
293};
294
Riley Andrews06b01ad2014-12-18 12:10:08 -0800295class BinderLibTest : public ::testing::Test {
296 public:
297 virtual void SetUp() {
298 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Parth Sane81b4d5a2024-05-23 14:11:13 +0000299 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800300 }
301 virtual void TearDown() {
302 }
303 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200304 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800305 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800306 int32_t id;
307 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800308
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700309 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800310
Elie Kheirallahb7246642022-05-03 18:01:43 +0000311 sp<IBinder> binder = reply.readStrongBinder();
312 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700313 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800314 if (idPtr)
315 *idPtr = id;
316 return binder;
317 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200318
Yi Kong91635562018-06-07 14:38:36 -0700319 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200320 {
321 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
322 }
323
Yi Kong91635562018-06-07 14:38:36 -0700324 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200325 {
326 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
327 }
328
Riley Andrews06b01ad2014-12-18 12:10:08 -0800329 void waitForReadData(int fd, int timeout_ms) {
330 int ret;
331 pollfd pfd = pollfd();
332
333 pfd.fd = fd;
334 pfd.events = POLLIN;
335 ret = poll(&pfd, 1, timeout_ms);
336 EXPECT_EQ(1, ret);
337 }
338
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700339 bool checkFreezeSupport() {
340 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
341 // Pass test on devices where the cgroup v2 freezer is not supported
342 if (freezer_file.fail()) {
343 return false;
344 }
345 return IPCThreadState::self()->freeze(getpid(), false, 0) == NO_ERROR;
346 }
347
348 bool checkFreezeAndNotificationSupport() {
349 if (!checkFreezeSupport()) {
350 return false;
351 }
352 return ProcessState::isDriverFeatureEnabled(
353 ProcessState::DriverFeature::FREEZE_NOTIFICATION);
354 }
355
356 bool getBinderPid(int32_t* pid, sp<IBinder> server) {
357 Parcel data, replypid;
358 if (server->transact(BINDER_LIB_TEST_GETPID, data, &replypid) != NO_ERROR) {
359 ALOGE("BINDER_LIB_TEST_GETPID failed");
360 return false;
361 }
362 *pid = replypid.readInt32();
363 if (*pid <= 0) {
364 ALOGE("pid should be greater than zero");
365 return false;
366 }
367 return true;
368 }
369
370 void freezeProcess(int32_t pid) {
371 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
372 }
373
374 void unfreezeProcess(int32_t pid) {
375 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
376 }
377
378 void removeCallbackAndValidateNoEvent(sp<IBinder> binder,
379 sp<TestFrozenStateChangeCallback> callback) {
380 EXPECT_THAT(binder->removeFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
381 EXPECT_EQ(0u, callback->events.size());
382 }
383
Riley Andrews06b01ad2014-12-18 12:10:08 -0800384 sp<IBinder> m_server;
385};
386
387class BinderLibTestBundle : public Parcel
388{
389 public:
390 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800391 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800392 int32_t mark;
393 int32_t bundleLen;
394 size_t pos;
395
396 if (source->readInt32(&mark))
397 return;
398 if (mark != MARK_START)
399 return;
400 if (source->readInt32(&bundleLen))
401 return;
402 pos = source->dataPosition();
403 if (Parcel::appendFrom(source, pos, bundleLen))
404 return;
405 source->setDataPosition(pos + bundleLen);
406 if (source->readInt32(&mark))
407 return;
408 if (mark != MARK_END)
409 return;
410 m_isValid = true;
411 setDataPosition(0);
412 }
413 void appendTo(Parcel *dest) {
414 dest->writeInt32(MARK_START);
415 dest->writeInt32(dataSize());
416 dest->appendFrom(this, 0, dataSize());
417 dest->writeInt32(MARK_END);
418 };
419 bool isValid(void) {
420 return m_isValid;
421 }
422 private:
423 enum {
424 MARK_START = B_PACK_CHARS('B','T','B','S'),
425 MARK_END = B_PACK_CHARS('B','T','B','E'),
426 };
427 bool m_isValid;
428};
429
430class BinderLibTestEvent
431{
432 public:
433 BinderLibTestEvent(void)
434 : m_eventTriggered(false)
435 {
Yi Kong91635562018-06-07 14:38:36 -0700436 pthread_mutex_init(&m_waitMutex, nullptr);
437 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800438 }
439 int waitEvent(int timeout_s)
440 {
441 int ret;
442 pthread_mutex_lock(&m_waitMutex);
443 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800444 struct timespec ts;
445 clock_gettime(CLOCK_REALTIME, &ts);
446 ts.tv_sec += timeout_s;
447 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800448 }
449 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
450 pthread_mutex_unlock(&m_waitMutex);
451 return ret;
452 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200453 pthread_t getTriggeringThread()
454 {
455 return m_triggeringThread;
456 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800457 protected:
458 void triggerEvent(void) {
459 pthread_mutex_lock(&m_waitMutex);
460 pthread_cond_signal(&m_waitCond);
461 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200462 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800463 pthread_mutex_unlock(&m_waitMutex);
464 };
465 private:
466 pthread_mutex_t m_waitMutex;
467 pthread_cond_t m_waitCond;
468 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200469 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800470};
471
472class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
473{
474 public:
475 BinderLibTestCallBack()
476 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700477 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800478 {
479 }
480 status_t getResult(void)
481 {
482 return m_result;
483 }
484
485 private:
486 virtual status_t onTransact(uint32_t code,
487 const Parcel& data, Parcel* reply,
488 uint32_t flags = 0)
489 {
490 (void)reply;
491 (void)flags;
492 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200493 case BINDER_LIB_TEST_CALL_BACK: {
494 status_t status = data.readInt32(&m_result);
495 if (status != NO_ERROR) {
496 m_result = status;
497 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800498 triggerEvent();
499 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200500 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700501 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
502 sp<IBinder> server;
503 int ret;
504 const uint8_t *buf = data.data();
505 size_t size = data.dataSize();
506 if (m_prev_end) {
507 /* 64-bit kernel needs at most 8 bytes to align buffer end */
508 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
509 } else {
510 EXPECT_TRUE(IsPageAligned((void *)buf));
511 }
512
513 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
514
515 if (size > 0) {
516 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
517 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
518 data, reply);
519 EXPECT_EQ(NO_ERROR, ret);
520 }
521 return NO_ERROR;
522 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800523 default:
524 return UNKNOWN_TRANSACTION;
525 }
526 }
527
528 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700529 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800530};
531
532class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
533{
534 private:
535 virtual void binderDied(const wp<IBinder>& who) {
536 (void)who;
537 triggerEvent();
538 };
539};
540
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700541TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
542 // EXPECT_DEATH works by forking the process
543 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
544}
545
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000546TEST_F(BinderLibTest, AddManagerToManager) {
547 sp<IServiceManager> sm = defaultServiceManager();
548 sp<IBinder> binder = IInterface::asBinder(sm);
549 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
550}
551
Parth Sane81b4d5a2024-05-23 14:11:13 +0000552TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
553 auto sm = defaultServiceManager();
554 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
555 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
556 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
557 virtual ~LocalRegistrationCallbackImpl() {}
558 };
559 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
560
561 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
562 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
563}
564
565TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
566 auto sm = defaultServiceManager();
567 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
568 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
569 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
570 virtual ~LocalRegistrationCallbackImpl() {}
571 };
572 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
573
574 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
575
576 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
577 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
578 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
579}
580
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500581TEST_F(BinderLibTest, WasParceled) {
582 auto binder = sp<BBinder>::make();
583 EXPECT_FALSE(binder->wasParceled());
584 Parcel data;
585 data.writeStrongBinder(binder);
586 EXPECT_TRUE(binder->wasParceled());
587}
588
Riley Andrews06b01ad2014-12-18 12:10:08 -0800589TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800590 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700591 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
592 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800593}
594
Steven Moreland80844f72020-12-12 02:06:08 +0000595TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000596 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700597 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
598 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000599}
600
Steven Morelandf183fdd2020-10-27 00:12:12 +0000601TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000602 Parcel data, reply;
603 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700604 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
605 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000606}
607
Marco Ballesio7ee17572020-09-08 10:30:03 -0700608TEST_F(BinderLibTest, Freeze) {
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700609 if (!checkFreezeSupport()) {
610 GTEST_SKIP() << "Skipping test for kernels that do not support proceess freezing";
Marco Ballesio7ee17572020-09-08 10:30:03 -0700611 return;
612 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700613 Parcel data, reply, replypid;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700614 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700615 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700616 for (int i = 0; i < 10; i++) {
617 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
618 }
Li Li6f059292021-09-10 09:59:30 -0700619
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700620 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Li Li6f059292021-09-10 09:59:30 -0700621 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000622
623 // b/268232063 - succeeds ~0.08% of the time
624 {
625 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
626 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
627 }
628
Li Li6f059292021-09-10 09:59:30 -0700629 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700630 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700631
Li Li4e678b92021-09-14 12:14:42 -0700632 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700633
634 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
635 &async_received));
636
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700637 EXPECT_EQ(sync_received, 1u);
638 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700639
Li Li4e678b92021-09-14 12:14:42 -0700640 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700641 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
642}
643
Riley Andrews06b01ad2014-12-18 12:10:08 -0800644TEST_F(BinderLibTest, SetError) {
645 int32_t testValue[] = { 0, -123, 123 };
646 for (size_t i = 0; i < ARRAY_SIZE(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800647 Parcel data, reply;
648 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700649 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
650 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800651 }
652}
653
654TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700655 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800656}
657
658TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800659 int32_t ptrsize;
660 Parcel data, reply;
661 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700662 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700663 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
664 StatusEq(NO_ERROR));
665 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800666 RecordProperty("TestPtrSize", sizeof(void *));
667 RecordProperty("ServerPtrSize", sizeof(void *));
668}
669
670TEST_F(BinderLibTest, IndirectGetId2)
671{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800672 int32_t id;
673 int32_t count;
674 Parcel data, reply;
675 int32_t serverId[3];
676
677 data.writeInt32(ARRAY_SIZE(serverId));
678 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
679 sp<IBinder> server;
680 BinderLibTestBundle datai;
681
682 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700683 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800684 data.writeStrongBinder(server);
685 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
686 datai.appendTo(&data);
687 }
688
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700689 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
690 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800691
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700692 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800693 EXPECT_EQ(0, id);
694
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700695 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700696 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800697
698 for (size_t i = 0; i < (size_t)count; i++) {
699 BinderLibTestBundle replyi(&reply);
700 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700701 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800702 EXPECT_EQ(serverId[i], id);
703 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
704 }
705
706 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
707}
708
709TEST_F(BinderLibTest, IndirectGetId3)
710{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800711 int32_t id;
712 int32_t count;
713 Parcel data, reply;
714 int32_t serverId[3];
715
716 data.writeInt32(ARRAY_SIZE(serverId));
717 for (size_t i = 0; i < ARRAY_SIZE(serverId); i++) {
718 sp<IBinder> server;
719 BinderLibTestBundle datai;
720 BinderLibTestBundle datai2;
721
722 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700723 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800724 data.writeStrongBinder(server);
725 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
726
727 datai.writeInt32(1);
728 datai.writeStrongBinder(m_server);
729 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
730 datai2.appendTo(&datai);
731
732 datai.appendTo(&data);
733 }
734
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700735 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
736 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800737
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700738 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800739 EXPECT_EQ(0, id);
740
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700741 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -0700742 EXPECT_EQ(ARRAY_SIZE(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800743
744 for (size_t i = 0; i < (size_t)count; i++) {
745 int32_t counti;
746
747 BinderLibTestBundle replyi(&reply);
748 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700749 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800750 EXPECT_EQ(serverId[i], id);
751
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700752 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800753 EXPECT_EQ(1, counti);
754
755 BinderLibTestBundle replyi2(&replyi);
756 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700757 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800758 EXPECT_EQ(0, id);
759 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
760
761 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
762 }
763
764 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
765}
766
767TEST_F(BinderLibTest, CallBack)
768{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800769 Parcel data, reply;
770 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
771 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700772 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
773 StatusEq(NO_ERROR));
774 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
775 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800776}
777
Steven Moreland35626652021-05-15 01:32:04 +0000778TEST_F(BinderLibTest, BinderCallContextGuard) {
779 sp<IBinder> binder = addServer();
780 Parcel data, reply;
781 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
782 StatusEq(DEAD_OBJECT));
783}
784
Riley Andrews06b01ad2014-12-18 12:10:08 -0800785TEST_F(BinderLibTest, AddServer)
786{
787 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700788 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800789}
790
Riley Andrews06b01ad2014-12-18 12:10:08 -0800791TEST_F(BinderLibTest, DeathNotificationStrongRef)
792{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800793 sp<IBinder> sbinder;
794
795 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
796
797 {
798 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700799 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700800 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800801 sbinder = binder;
802 }
803 {
804 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700805 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
806 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800807 }
808 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700809 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
810 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800811}
812
813TEST_F(BinderLibTest, DeathNotificationMultiple)
814{
815 status_t ret;
816 const int clientcount = 2;
817 sp<IBinder> target;
818 sp<IBinder> linkedclient[clientcount];
819 sp<BinderLibTestCallBack> callBack[clientcount];
820 sp<IBinder> passiveclient[clientcount];
821
822 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700823 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800824 for (int i = 0; i < clientcount; i++) {
825 {
826 Parcel data, reply;
827
828 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700829 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800830 callBack[i] = new BinderLibTestCallBack();
831 data.writeStrongBinder(target);
832 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700833 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
834 &reply, TF_ONE_WAY),
835 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800836 }
837 {
838 Parcel data, reply;
839
840 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700841 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800842 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700843 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
844 &reply, TF_ONE_WAY),
845 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800846 }
847 }
848 {
849 Parcel data, reply;
850 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
851 EXPECT_EQ(0, ret);
852 }
853
854 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700855 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
856 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800857 }
858}
859
Martijn Coenenf7100e42017-07-31 12:14:09 +0200860TEST_F(BinderLibTest, DeathNotificationThread)
861{
862 status_t ret;
863 sp<BinderLibTestCallBack> callback;
864 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700865 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200866 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700867 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200868
869 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
870
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700871 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200872
873 {
874 Parcel data, reply;
875 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
876 EXPECT_EQ(0, ret);
877 }
878
879 /* Make sure it's dead */
880 testDeathRecipient->waitEvent(5);
881
882 /* Now, pass the ref to another process and ask that process to
883 * call linkToDeath() on it, and wait for a response. This tests
884 * two things:
885 * 1) You still get death notifications when calling linkToDeath()
886 * on a ref that is already dead when it was passed to you.
887 * 2) That death notifications are not directly pushed to the thread
888 * registering them, but to the threadpool (proc workqueue) instead.
889 *
890 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
891 * is blocked on a condition variable waiting for the death notification to be
892 * called; therefore, that thread is not available for handling proc work.
893 * So, if the death notification was pushed to the thread workqueue, the callback
894 * would never be called, and the test would timeout and fail.
895 *
896 * Note that we can't do this part of the test from this thread itself, because
897 * the binder driver would only push death notifications to the thread if
898 * it is a looper thread, which this thread is not.
899 *
900 * See b/23525545 for details.
901 */
902 {
903 Parcel data, reply;
904
905 callback = new BinderLibTestCallBack();
906 data.writeStrongBinder(target);
907 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700908 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
909 TF_ONE_WAY),
910 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200911 }
912
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700913 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
914 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200915}
916
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700917TEST_F(BinderLibTest, ReturnErrorIfKernelDoesNotSupportFreezeNotification) {
918 if (ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::FREEZE_NOTIFICATION)) {
919 GTEST_SKIP() << "Skipping test for kernels that support FREEZE_NOTIFICATION";
920 return;
921 }
922 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
923 sp<IBinder> binder = addServer();
924 ASSERT_NE(nullptr, binder);
925 ASSERT_EQ(nullptr, binder->localBinder());
926 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(INVALID_OPERATION));
927}
928
929TEST_F(BinderLibTest, FrozenStateChangeNotificatiion) {
930 if (!checkFreezeAndNotificationSupport()) {
931 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
932 return;
933 }
934 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
935 sp<IBinder> binder = addServer();
936 ASSERT_NE(nullptr, binder);
937 int32_t pid;
938 ASSERT_TRUE(getBinderPid(&pid, binder));
939
940 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
941 // Expect current state (unfrozen) to be delivered immediately.
942 callback->ensureUnfrozenEventReceived();
943 // Check that the process hasn't died otherwise there's a risk of freezing
944 // the wrong process.
945 EXPECT_EQ(OK, binder->pingBinder());
946 freezeProcess(pid);
947 callback->ensureFrozenEventReceived();
948 unfreezeProcess(pid);
949 callback->ensureUnfrozenEventReceived();
950 removeCallbackAndValidateNoEvent(binder, callback);
951}
952
953TEST_F(BinderLibTest, AddFrozenCallbackWhenFrozen) {
954 if (!checkFreezeAndNotificationSupport()) {
955 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
956 return;
957 }
958 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
959 sp<IBinder> binder = addServer();
960 ASSERT_NE(nullptr, binder);
961 int32_t pid;
962 ASSERT_TRUE(getBinderPid(&pid, binder));
963
964 // Check that the process hasn't died otherwise there's a risk of freezing
965 // the wrong process.
966 EXPECT_EQ(OK, binder->pingBinder());
967 freezeProcess(pid);
968 // Add the callback while the target process is frozen.
969 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
970 callback->ensureFrozenEventReceived();
971 unfreezeProcess(pid);
972 callback->ensureUnfrozenEventReceived();
973 removeCallbackAndValidateNoEvent(binder, callback);
974
975 // Check that the process hasn't died otherwise there's a risk of freezing
976 // the wrong process.
977 EXPECT_EQ(OK, binder->pingBinder());
978 freezeProcess(pid);
979 unfreezeProcess(pid);
980 // Make sure no callback happens since the listener has been removed.
981 EXPECT_EQ(0u, callback->events.size());
982}
983
984TEST_F(BinderLibTest, NoFrozenNotificationAfterCallbackRemoval) {
985 if (!checkFreezeAndNotificationSupport()) {
986 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
987 return;
988 }
989 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
990 sp<IBinder> binder = addServer();
991 ASSERT_NE(nullptr, binder);
992 int32_t pid;
993 ASSERT_TRUE(getBinderPid(&pid, binder));
994
995 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
996 callback->ensureUnfrozenEventReceived();
997 removeCallbackAndValidateNoEvent(binder, callback);
998
999 // Make sure no callback happens after the listener is removed.
1000 freezeProcess(pid);
1001 unfreezeProcess(pid);
1002 EXPECT_EQ(0u, callback->events.size());
1003}
1004
1005TEST_F(BinderLibTest, MultipleFrozenStateChangeCallbacks) {
1006 if (!checkFreezeAndNotificationSupport()) {
1007 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1008 return;
1009 }
1010 sp<TestFrozenStateChangeCallback> callback1 = sp<TestFrozenStateChangeCallback>::make();
1011 sp<TestFrozenStateChangeCallback> callback2 = sp<TestFrozenStateChangeCallback>::make();
1012 sp<IBinder> binder = addServer();
1013 ASSERT_NE(nullptr, binder);
1014 int32_t pid;
1015 ASSERT_TRUE(getBinderPid(&pid, binder));
1016
1017 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback1), StatusEq(NO_ERROR));
1018 // Expect current state (unfrozen) to be delivered immediately.
1019 callback1->ensureUnfrozenEventReceived();
1020
1021 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback2), StatusEq(NO_ERROR));
1022 // Expect current state (unfrozen) to be delivered immediately.
1023 callback2->ensureUnfrozenEventReceived();
1024
1025 freezeProcess(pid);
1026 callback1->ensureFrozenEventReceived();
1027 callback2->ensureFrozenEventReceived();
1028
1029 removeCallbackAndValidateNoEvent(binder, callback1);
1030 unfreezeProcess(pid);
1031 EXPECT_EQ(0u, callback1->events.size());
1032 callback2->ensureUnfrozenEventReceived();
1033 removeCallbackAndValidateNoEvent(binder, callback2);
1034
1035 freezeProcess(pid);
1036 EXPECT_EQ(0u, callback2->events.size());
1037}
1038
1039TEST_F(BinderLibTest, RemoveThenAddFrozenStateChangeCallbacks) {
1040 if (!checkFreezeAndNotificationSupport()) {
1041 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1042 return;
1043 }
1044 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1045 sp<IBinder> binder = addServer();
1046 ASSERT_NE(nullptr, binder);
1047 int32_t pid;
1048 ASSERT_TRUE(getBinderPid(&pid, binder));
1049
1050 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1051 // Expect current state (unfrozen) to be delivered immediately.
1052 callback->ensureUnfrozenEventReceived();
1053 removeCallbackAndValidateNoEvent(binder, callback);
1054
1055 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1056 callback->ensureUnfrozenEventReceived();
1057}
1058
1059TEST_F(BinderLibTest, CoalesceFreezeCallbacksWhenListenerIsFrozen) {
1060 if (!checkFreezeAndNotificationSupport()) {
1061 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1062 return;
1063 }
1064 sp<IBinder> binder = addServer();
1065 sp<IBinder> listener = addServer();
1066 ASSERT_NE(nullptr, binder);
1067 ASSERT_NE(nullptr, listener);
1068 int32_t pid, listenerPid;
1069 ASSERT_TRUE(getBinderPid(&pid, binder));
1070 ASSERT_TRUE(getBinderPid(&listenerPid, listener));
1071
1072 // Ask the listener process to register for state change callbacks.
1073 {
1074 Parcel data, reply;
1075 data.writeStrongBinder(binder);
1076 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE, data,
1077 &reply),
1078 StatusEq(NO_ERROR));
1079 }
1080 // Freeze the listener process.
1081 freezeProcess(listenerPid);
1082 createProcessGroup(getuid(), listenerPid);
1083 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Frozen"}));
1084 // Repeatedly flip the target process between frozen and unfrozen states.
1085 for (int i = 0; i < 1000; i++) {
1086 usleep(50);
1087 unfreezeProcess(pid);
1088 usleep(50);
1089 freezeProcess(pid);
1090 }
1091 // Unfreeze the listener process. Now it should receive the frozen state
1092 // change notifications.
1093 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Unfrozen"}));
1094 unfreezeProcess(listenerPid);
1095 // Wait for 500ms to give the process enough time to wake up and handle
1096 // notifications.
1097 usleep(500 * 1000);
1098 {
1099 std::vector<bool> events;
1100 Parcel data, reply;
1101 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS, data, &reply),
1102 StatusEq(NO_ERROR));
1103 reply.readBoolVector(&events);
1104 // There should only be one single state change notifications delievered.
1105 ASSERT_EQ(1u, events.size());
1106 EXPECT_TRUE(events[0]);
1107 }
1108}
1109
Riley Andrews06b01ad2014-12-18 12:10:08 -08001110TEST_F(BinderLibTest, PassFile) {
1111 int ret;
1112 int pipefd[2];
1113 uint8_t buf[1] = { 0 };
1114 uint8_t write_value = 123;
1115
1116 ret = pipe2(pipefd, O_NONBLOCK);
1117 ASSERT_EQ(0, ret);
1118
1119 {
1120 Parcel data, reply;
1121 uint8_t writebuf[1] = { write_value };
1122
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001123 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001124
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001125 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001126
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001127 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001128
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001129 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
1130 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001131 }
1132
1133 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -07001134 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001135 EXPECT_EQ(write_value, buf[0]);
1136
1137 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
1138
1139 ret = read(pipefd[0], buf, sizeof(buf));
1140 EXPECT_EQ(0, ret);
1141
1142 close(pipefd[0]);
1143}
1144
Ryo Hashimotobf551892018-05-31 16:58:35 +09001145TEST_F(BinderLibTest, PassParcelFileDescriptor) {
1146 const int datasize = 123;
1147 std::vector<uint8_t> writebuf(datasize);
1148 for (size_t i = 0; i < writebuf.size(); ++i) {
1149 writebuf[i] = i;
1150 }
1151
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001152 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001153 {
1154 int pipefd[2];
1155 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
1156 read_end.reset(pipefd[0]);
1157 write_end.reset(pipefd[1]);
1158 }
1159 {
1160 Parcel data;
1161 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
1162 write_end.reset();
1163 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
1164 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
1165
1166 Parcel reply;
1167 EXPECT_EQ(NO_ERROR,
1168 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
1169 &reply));
1170 }
1171 std::vector<uint8_t> readbuf(datasize);
1172 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
1173 EXPECT_EQ(writebuf, readbuf);
1174
1175 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
1176
1177 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
1178}
1179
Riley Andrews06b01ad2014-12-18 12:10:08 -08001180TEST_F(BinderLibTest, PromoteLocal) {
1181 sp<IBinder> strong = new BBinder();
1182 wp<IBinder> weak = strong;
1183 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001184 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001185 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -07001186 strong = nullptr;
1187 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001188 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001189 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001190}
1191
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001192TEST_F(BinderLibTest, LocalGetExtension) {
1193 sp<BBinder> binder = new BBinder();
1194 sp<IBinder> ext = new BBinder();
1195 binder->setExtension(ext);
1196 EXPECT_EQ(ext, binder->getExtension());
1197}
1198
1199TEST_F(BinderLibTest, RemoteGetExtension) {
1200 sp<IBinder> server = addServer();
1201 ASSERT_TRUE(server != nullptr);
1202
1203 sp<IBinder> extension;
1204 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
1205 ASSERT_NE(nullptr, extension.get());
1206
1207 EXPECT_EQ(NO_ERROR, extension->pingBinder());
1208}
1209
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001210TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001211 Parcel data, reply;
1212
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001213 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
1214 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001215
1216 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -07001217 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +08001218 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
1219 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
1220 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
1221 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001222}
1223
Connor O'Brien52be2c92016-09-20 14:18:08 -07001224TEST_F(BinderLibTest, FreedBinder) {
1225 status_t ret;
1226
1227 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -07001228 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001229
1230 __u32 freedHandle;
1231 wp<IBinder> keepFreedBinder;
1232 {
1233 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001234 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1235 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -07001236 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
1237 freedHandle = freed->handle;
1238 /* Add a weak ref to the freed binder so the driver does not
1239 * delete its reference to it - otherwise the transaction
1240 * fails regardless of whether the driver is fixed.
1241 */
Steven Morelande171d622019-07-17 16:06:01 -07001242 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001243 }
Steven Morelande171d622019-07-17 16:06:01 -07001244 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001245 {
1246 Parcel data, reply;
1247 data.writeStrongBinder(server);
1248 /* Replace original handle with handle to the freed binder */
1249 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
1250 __u32 oldHandle = strong->handle;
1251 strong->handle = freedHandle;
1252 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
1253 /* Returns DEAD_OBJECT (-32) if target crashes and
1254 * FAILED_TRANSACTION if the driver rejects the invalid
1255 * object.
1256 */
1257 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
1258 /* Restore original handle so parcel destructor does not use
1259 * the wrong handle.
1260 */
1261 strong->handle = oldHandle;
1262 }
1263}
1264
Sherry Yang336cdd32017-07-24 14:12:27 -07001265TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -07001266 Parcel data, reply;
1267 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1268 for (int i = 0; i < 2; i++) {
1269 BinderLibTestBundle datai;
1270 datai.appendFrom(&data, 0, data.dataSize());
1271
1272 data.freeData();
1273 data.writeInt32(1);
1274 data.writeStrongBinder(callBack);
1275 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1276
1277 datai.appendTo(&data);
1278 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001279 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1280 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -07001281}
1282
Martijn Coenen45b07b42017-08-09 12:07:45 +02001283TEST_F(BinderLibTest, OnewayQueueing)
1284{
Martijn Coenen45b07b42017-08-09 12:07:45 +02001285 Parcel data, data2;
1286
1287 sp<IBinder> pollServer = addPollServer();
1288
1289 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1290 data.writeStrongBinder(callBack);
1291 data.writeInt32(500000); // delay in us before calling back
1292
1293 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1294 data2.writeStrongBinder(callBack2);
1295 data2.writeInt32(0); // delay in us
1296
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001297 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1298 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001299
1300 // The delay ensures that this second transaction will end up on the async_todo list
1301 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001302 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1303 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001304
1305 // The server will ensure that the two transactions are handled in the expected order;
1306 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001307 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1308 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001309
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001310 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1311 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001312}
1313
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001314TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1315{
1316 status_t ret;
1317 Parcel data, reply;
1318 data.writeInterfaceToken(binderLibTestServiceName);
1319 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1320 EXPECT_EQ(-1, reply.readInt32());
1321 EXPECT_EQ(NO_ERROR, ret);
1322}
1323
1324TEST_F(BinderLibTest, WorkSourceSet)
1325{
1326 status_t ret;
1327 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001328 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001329 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001330 data.writeInterfaceToken(binderLibTestServiceName);
1331 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1332 EXPECT_EQ(100, reply.readInt32());
1333 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001334 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1335 EXPECT_EQ(NO_ERROR, ret);
1336}
1337
1338TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1339{
1340 status_t ret;
1341 Parcel data, reply;
1342
1343 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1344 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1345
1346 data.writeInterfaceToken(binderLibTestServiceName);
1347 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1348 EXPECT_EQ(-1, reply.readInt32());
1349 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001350 EXPECT_EQ(NO_ERROR, ret);
1351}
1352
1353TEST_F(BinderLibTest, WorkSourceCleared)
1354{
1355 status_t ret;
1356 Parcel data, reply;
1357
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001358 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001359 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1360 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001361 data.writeInterfaceToken(binderLibTestServiceName);
1362 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1363
1364 EXPECT_EQ(-1, reply.readInt32());
1365 EXPECT_EQ(100, previousWorkSource);
1366 EXPECT_EQ(NO_ERROR, ret);
1367}
1368
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001369TEST_F(BinderLibTest, WorkSourceRestored)
1370{
1371 status_t ret;
1372 Parcel data, reply;
1373
1374 IPCThreadState::self()->setCallingWorkSourceUid(100);
1375 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1376 IPCThreadState::self()->restoreCallingWorkSource(token);
1377
1378 data.writeInterfaceToken(binderLibTestServiceName);
1379 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1380
1381 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001382 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001383 EXPECT_EQ(NO_ERROR, ret);
1384}
1385
Olivier Gaillard91a04802018-11-14 17:32:41 +00001386TEST_F(BinderLibTest, PropagateFlagSet)
1387{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001388 IPCThreadState::self()->clearPropagateWorkSource();
1389 IPCThreadState::self()->setCallingWorkSourceUid(100);
1390 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1391}
1392
1393TEST_F(BinderLibTest, PropagateFlagCleared)
1394{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001395 IPCThreadState::self()->setCallingWorkSourceUid(100);
1396 IPCThreadState::self()->clearPropagateWorkSource();
1397 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1398}
1399
1400TEST_F(BinderLibTest, PropagateFlagRestored)
1401{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001402 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1403 IPCThreadState::self()->restoreCallingWorkSource(token);
1404
1405 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1406}
1407
1408TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1409{
1410 IPCThreadState::self()->setCallingWorkSourceUid(100);
1411
1412 Parcel data, reply;
1413 status_t ret;
1414 data.writeInterfaceToken(binderLibTestServiceName);
1415 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001416 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001417
1418 Parcel data2, reply2;
1419 status_t ret2;
1420 data2.writeInterfaceToken(binderLibTestServiceName);
1421 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1422 EXPECT_EQ(100, reply2.readInt32());
1423 EXPECT_EQ(NO_ERROR, ret2);
1424}
1425
Steven Morelandbf1915b2020-07-16 22:43:02 +00001426TEST_F(BinderLibTest, SchedPolicySet) {
1427 sp<IBinder> server = addServer();
1428 ASSERT_TRUE(server != nullptr);
1429
1430 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001431 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1432 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001433
1434 int policy = reply.readInt32();
1435 int priority = reply.readInt32();
1436
1437 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1438 EXPECT_EQ(kSchedPriority, priority);
1439}
1440
Steven Morelandcf03cf12020-12-04 02:58:40 +00001441TEST_F(BinderLibTest, InheritRt) {
1442 sp<IBinder> server = addServer();
1443 ASSERT_TRUE(server != nullptr);
1444
1445 const struct sched_param param {
1446 .sched_priority = kSchedPriorityMore,
1447 };
1448 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1449
1450 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001451 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1452 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001453
1454 int policy = reply.readInt32();
1455 int priority = reply.readInt32();
1456
1457 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1458 EXPECT_EQ(kSchedPriorityMore, priority);
1459}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001460
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001461TEST_F(BinderLibTest, VectorSent) {
1462 Parcel data, reply;
1463 sp<IBinder> server = addServer();
1464 ASSERT_TRUE(server != nullptr);
1465
1466 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1467 data.writeUint64Vector(testValue);
1468
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001469 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001470 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001471 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001472 EXPECT_EQ(readValue, testValue);
1473}
1474
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001475TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1476 sp<IBinder> server = addServer();
1477 ASSERT_TRUE(server != nullptr);
1478
1479 Parcel reply;
1480 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1481 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001482 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001483 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1484
1485 const int result = fcntl(fd.get(), F_GETFL);
1486 ASSERT_NE(result, -1);
1487 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1488}
1489
Steven Moreland59b84442022-07-12 18:32:44 +00001490// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1491// This value is not exposed, but some code in the framework relies on being able to use
1492// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001493constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001494constexpr size_t kSizeBytesOverFull = 1'050'000;
1495
1496TEST_F(BinderLibTest, GargantuanVectorSent) {
1497 sp<IBinder> server = addServer();
1498 ASSERT_TRUE(server != nullptr);
1499
1500 for (size_t i = 0; i < 10; i++) {
1501 // a slight variation in size is used to consider certain possible caching implementations
1502 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1503
1504 Parcel data, reply;
1505 data.writeUint64Vector(testValue);
1506 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1507 << i;
1508 std::vector<uint64_t> readValue;
1509 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1510 EXPECT_EQ(readValue, testValue);
1511 }
1512}
1513
1514TEST_F(BinderLibTest, LimitExceededVectorSent) {
1515 sp<IBinder> server = addServer();
1516 ASSERT_TRUE(server != nullptr);
1517 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1518
1519 Parcel data, reply;
1520 data.writeUint64Vector(testValue);
1521 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1522 StatusEq(FAILED_TRANSACTION));
1523}
1524
Martijn Coenen82c75312019-07-24 15:18:30 +02001525TEST_F(BinderLibTest, BufRejected) {
1526 Parcel data, reply;
1527 uint32_t buf;
1528 sp<IBinder> server = addServer();
1529 ASSERT_TRUE(server != nullptr);
1530
1531 binder_buffer_object obj {
1532 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001533 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001534 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1535 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001536 };
1537 data.setDataCapacity(1024);
1538 // Write a bogus object at offset 0 to get an entry in the offset table
1539 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001540 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001541 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1542 // And now, overwrite it with the buffer object
1543 memcpy(parcelData, &obj, sizeof(obj));
1544 data.setDataSize(sizeof(obj));
1545
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001546 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001547
Martijn Coenen82c75312019-07-24 15:18:30 +02001548 // Either the kernel should reject this transaction (if it's correct), but
1549 // if it's not, the server implementation should return an error if it
1550 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001551 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001552 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001553}
1554
Steven Morelandf2e0a952021-11-01 18:17:23 -07001555TEST_F(BinderLibTest, WeakRejected) {
1556 Parcel data, reply;
1557 sp<IBinder> server = addServer();
1558 ASSERT_TRUE(server != nullptr);
1559
1560 auto binder = sp<BBinder>::make();
1561 wp<BBinder> wpBinder(binder);
1562 flat_binder_object obj{
1563 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1564 .flags = 0,
1565 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1566 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1567 };
1568 data.setDataCapacity(1024);
1569 // Write a bogus object at offset 0 to get an entry in the offset table
1570 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001571 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001572 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1573 // And now, overwrite it with the weak binder
1574 memcpy(parcelData, &obj, sizeof(obj));
1575 data.setDataSize(sizeof(obj));
1576
1577 // a previous bug caused other objects to be released an extra time, so we
1578 // test with an object that libbinder will actually try to release
1579 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1580
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001581 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001582
1583 // send it many times, since previous error was memory corruption, make it
1584 // more likely that the server crashes
1585 for (size_t i = 0; i < 100; i++) {
1586 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1587 StatusEq(BAD_VALUE));
1588 }
1589
1590 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1591}
1592
Steven Moreland254e8ef2021-04-19 22:28:50 +00001593TEST_F(BinderLibTest, GotSid) {
1594 sp<IBinder> server = addServer();
1595
1596 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001597 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001598}
1599
Andrei Homescu1519b982022-06-09 02:04:44 +00001600struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1601 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1602
1603 // Flattenable protocol
1604 size_t getFlattenedSize() const {
1605 // Return a valid non-zero size here so we don't get an unintended
1606 // BAD_VALUE from Parcel::write
1607 return 16;
1608 }
1609 size_t getFdCount() const { return mFdCount; }
1610 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1611 for (size_t i = 0; i < count; i++) {
1612 fds[i] = STDIN_FILENO;
1613 }
1614 return NO_ERROR;
1615 }
1616 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1617 size_t & /*count*/) {
1618 /* This doesn't get called */
1619 return NO_ERROR;
1620 }
1621
1622 size_t mFdCount;
1623};
1624
1625TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1626 rlimit origNofile;
1627 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1628 ASSERT_EQ(0, ret);
1629
1630 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001631 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001632
1633 rlimit testNofile = {1024, 1024};
1634 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1635 ASSERT_EQ(0, ret);
1636
1637 Parcel parcel;
1638 // Try to write more file descriptors than supported by the OS
1639 TooManyFdsFlattenable tooManyFds1(1024);
1640 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1641
1642 // Try to write more file descriptors than the internal limit
1643 TooManyFdsFlattenable tooManyFds2(1025);
1644 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1645}
1646
Jayant Chowdhary30700942022-01-31 14:12:40 -08001647TEST(ServiceNotifications, Unregister) {
1648 auto sm = defaultServiceManager();
1649 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1650 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1651 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1652 virtual ~LocalRegistrationCallbackImpl() {}
1653 };
1654 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1655
1656 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1657 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1658}
1659
Elie Kheirallah47431c12022-04-21 23:46:17 +00001660TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1661 Parcel data, reply;
1662 sp<IBinder> server = addServer();
1663 ASSERT_TRUE(server != nullptr);
1664 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1665 StatusEq(NO_ERROR));
1666 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001667 // see getThreadPoolMaxTotalThreadCount for why there is a race
1668 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1669
Elie Kheirallah47431c12022-04-21 23:46:17 +00001670 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1671
1672 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001673 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1674 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1675 * started threads from setThreadPoolMaxThreadCount
1676 *
1677 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001678 */
1679 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001680 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001681 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001682 Parcel local_reply;
1683 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1684 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001685 }));
1686 }
1687
Steven Moreland3e9debc2023-06-15 00:35:29 +00001688 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1689 // the time, the below call will pre-empt them (presumably because we have the
1690 // scheduler timeslice already + scheduler hint).
1691 sleep(1);
1692
1693 data.writeInt32(1000);
1694 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001695 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1696
1697 for (auto &t : ts) {
1698 t.join();
1699 }
1700
1701 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1702 StatusEq(NO_ERROR));
1703 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001704 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001705}
1706
Devin Moore4354f712022-12-08 01:44:46 +00001707TEST_F(BinderLibTest, ThreadPoolStarted) {
1708 Parcel data, reply;
1709 sp<IBinder> server = addServer();
1710 ASSERT_TRUE(server != nullptr);
1711 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1712 EXPECT_TRUE(reply.readBool());
1713}
1714
Elie Kheirallah47431c12022-04-21 23:46:17 +00001715size_t epochMillis() {
1716 using std::chrono::duration_cast;
1717 using std::chrono::milliseconds;
1718 using std::chrono::seconds;
1719 using std::chrono::system_clock;
1720 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1721}
1722
1723TEST_F(BinderLibTest, HangingServices) {
1724 Parcel data, reply;
1725 sp<IBinder> server = addServer();
1726 ASSERT_TRUE(server != nullptr);
1727 int32_t delay = 1000; // ms
1728 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001729 // b/266537959 - must take before taking lock, since countdown is started in the remote
1730 // process there.
1731 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001732 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1733 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001734 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1735 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001736 Parcel local_reply;
1737 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1738 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001739 }));
1740 }
1741
1742 for (auto &t : ts) {
1743 t.join();
1744 }
1745 size_t epochMsAfter = epochMillis();
1746
1747 // deadlock occurred and threads only finished after 1s passed.
1748 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1749}
1750
Jing Jibbe9ae62023-10-07 15:26:02 -07001751TEST_F(BinderLibTest, BinderProxyCount) {
1752 Parcel data, reply;
1753 sp<IBinder> server = addServer();
1754 ASSERT_NE(server, nullptr);
1755
1756 uint32_t initialCount = BpBinder::getBinderProxyCount();
1757 size_t iterations = 100;
1758 {
1759 uint32_t count = initialCount;
1760 std::vector<sp<IBinder> > proxies;
1761 sp<IBinder> proxy;
1762 // Create binder proxies and verify the count.
1763 for (size_t i = 0; i < iterations; i++) {
1764 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1765 StatusEq(NO_ERROR));
1766 proxies.push_back(reply.readStrongBinder());
1767 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1768 }
1769 // Remove every other one and verify the count.
1770 auto it = proxies.begin();
1771 for (size_t i = 0; it != proxies.end(); i++) {
1772 if (i % 2 == 0) {
1773 it = proxies.erase(it);
1774 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1775 }
1776 }
1777 }
1778 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1779}
1780
Jing Jibdbe29a2023-10-03 00:03:28 -07001781static constexpr int kBpCountHighWatermark = 20;
1782static constexpr int kBpCountLowWatermark = 10;
1783static constexpr int kBpCountWarningWatermark = 15;
1784static constexpr int kInvalidUid = -1;
1785
1786TEST_F(BinderLibTest, BinderProxyCountCallback) {
1787 Parcel data, reply;
1788 sp<IBinder> server = addServer();
1789 ASSERT_NE(server, nullptr);
1790
1791 BpBinder::enableCountByUid();
1792 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1793 int32_t uid = reply.readInt32();
1794 ASSERT_NE(uid, kInvalidUid);
1795
1796 uint32_t initialCount = BpBinder::getBinderProxyCount();
1797 {
1798 uint32_t count = initialCount;
1799 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1800 kBpCountLowWatermark,
1801 kBpCountWarningWatermark);
1802 int limitCallbackUid = kInvalidUid;
1803 int warningCallbackUid = kInvalidUid;
1804 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1805 [&](int uid) { warningCallbackUid = uid; });
1806
1807 std::vector<sp<IBinder> > proxies;
1808 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1809 warningCallbackUid = limitCallbackUid = kInvalidUid;
1810 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1811 StatusEq(NO_ERROR));
1812 proxies.push_back(reply.readStrongBinder());
1813 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1814 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1815 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1816 };
1817 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1818 warningCallbackUid = limitCallbackUid = kInvalidUid;
1819 proxies.pop_back();
1820 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1821 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1822 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1823 };
1824
1825 // Test the increment/decrement of the binder proxies.
1826 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1827 createProxyOnce(kInvalidUid, kInvalidUid);
1828 }
1829 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1830 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1831 createProxyOnce(kInvalidUid, kInvalidUid);
1832 }
1833 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1834 createProxyOnce(kInvalidUid, kInvalidUid);
1835 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1836 removeProxyOnce(kInvalidUid, kInvalidUid);
1837 }
1838 createProxyOnce(kInvalidUid, kInvalidUid);
1839
1840 // Go down below the low watermark.
1841 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1842 removeProxyOnce(kInvalidUid, kInvalidUid);
1843 }
1844 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1845 createProxyOnce(kInvalidUid, kInvalidUid);
1846 }
1847 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1848 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1849 createProxyOnce(kInvalidUid, kInvalidUid);
1850 }
1851 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1852 createProxyOnce(kInvalidUid, kInvalidUid);
1853 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1854 removeProxyOnce(kInvalidUid, kInvalidUid);
1855 }
1856 createProxyOnce(kInvalidUid, kInvalidUid);
1857 }
1858 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1859}
1860
Yifan Hong84bedeb2021-04-21 21:37:17 -07001861class BinderLibRpcTestBase : public BinderLibTest {
1862public:
1863 void SetUp() override {
1864 if (!base::GetBoolProperty("ro.debuggable", false)) {
1865 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1866 "non-debuggable builds.";
1867 }
1868 BinderLibTest::SetUp();
1869 }
1870
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001871 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001872 auto rpcServer = RpcServer::make();
1873 EXPECT_NE(nullptr, rpcServer);
1874 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001875 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001876 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1877 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001878 return {};
1879 }
1880 return {rpcServer->releaseServer(), port};
1881 }
1882};
1883
Yifan Hong8b890852021-06-10 13:44:09 -07001884class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001885
Yifan Hongbd276552022-02-28 15:28:51 -08001886// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1887// If device is debuggable AND not on user builds, expects matcher.
1888// Otherwise expects INVALID_OPERATION.
1889// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1890static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1891 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1892 android::base::GetProperty("ro.build.type", "") != "user";
1893 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1894}
1895
Yifan Hong8b890852021-06-10 13:44:09 -07001896TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1897 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001898 ASSERT_TRUE(binder != nullptr);
1899 auto [socket, port] = CreateSocket();
1900 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001901 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1902 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001903}
1904
Yifan Hong8b890852021-06-10 13:44:09 -07001905// Tests for multiple RpcServer's on the same binder object.
1906TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1907 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001908 ASSERT_TRUE(binder != nullptr);
1909
1910 auto [socket1, port1] = CreateSocket();
1911 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001912 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001913 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1914 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001915
1916 auto [socket2, port2] = CreateSocket();
1917 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001918 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001919 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1920 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001921}
1922
Yifan Hong8b890852021-06-10 13:44:09 -07001923// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1924// local binders.
1925class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001926public:
1927 sp<IBinder> GetService() {
1928 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1929 }
1930 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1931 return info.param ? "remote" : "local";
1932 }
1933};
1934
Yifan Hong8b890852021-06-10 13:44:09 -07001935TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1936 auto binder = GetService();
1937 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001938 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001939 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001940}
1941
1942TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001943 auto binder = GetService();
1944 ASSERT_TRUE(binder != nullptr);
1945 auto [socket, port] = CreateSocket();
1946 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001947 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1948 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001949}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001950INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1951 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001952
Yifan Hong543edcd2021-05-18 19:47:30 -07001953class BinderLibTestService : public BBinder {
1954public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001955 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1956 : m_id(id),
1957 m_nextServerId(id + 1),
1958 m_serverStartRequested(false),
1959 m_callback(nullptr),
1960 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001961 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1962 pthread_cond_init(&m_serverWaitCond, nullptr);
1963 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001964 ~BinderLibTestService() {
1965 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1966 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001967
Yifan Hong543edcd2021-05-18 19:47:30 -07001968 void processPendingCall() {
1969 if (m_callback != nullptr) {
1970 Parcel data;
1971 data.writeInt32(NO_ERROR);
1972 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1973 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001974 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001975 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001976
Yifan Hong543edcd2021-05-18 19:47:30 -07001977 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1978 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001979 // TODO(b/182914638): also checks getCallingUid() for RPC
1980 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001981 return PERMISSION_DENIED;
1982 }
1983 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001984 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001985 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001986 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001987 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001988 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001989 return BAD_VALUE;
1990 }
1991
Yifan Hong543edcd2021-05-18 19:47:30 -07001992 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001993
1994 pthread_mutex_lock(&m_serverWaitMutex);
1995 if (m_serverStartRequested) {
1996 m_serverStartRequested = false;
1997 m_serverStarted = binder;
1998 pthread_cond_signal(&m_serverWaitCond);
1999 }
2000 pthread_mutex_unlock(&m_serverWaitMutex);
2001 return NO_ERROR;
2002 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002003 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08002004 case BINDER_LIB_TEST_ADD_SERVER: {
2005 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002006 int serverid;
2007
2008 if (m_id != 0) {
2009 return INVALID_OPERATION;
2010 }
2011 pthread_mutex_lock(&m_serverWaitMutex);
2012 if (m_serverStartRequested) {
2013 ret = -EBUSY;
2014 } else {
2015 serverid = m_nextServerId++;
2016 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002017 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002018
2019 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002020 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002021 pthread_mutex_lock(&m_serverWaitMutex);
2022 }
2023 if (ret > 0) {
2024 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002025 struct timespec ts;
2026 clock_gettime(CLOCK_REALTIME, &ts);
2027 ts.tv_sec += 5;
2028 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002029 }
2030 if (m_serverStartRequested) {
2031 m_serverStartRequested = false;
2032 ret = -ETIMEDOUT;
2033 } else {
2034 reply->writeStrongBinder(m_serverStarted);
2035 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07002036 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002037 ret = NO_ERROR;
2038 }
2039 } else if (ret >= 0) {
2040 m_serverStartRequested = false;
2041 ret = UNKNOWN_ERROR;
2042 }
2043 pthread_mutex_unlock(&m_serverWaitMutex);
2044 return ret;
2045 }
Steven Moreland35626652021-05-15 01:32:04 +00002046 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
2047 IPCThreadState::SpGuard spGuard{
2048 .address = __builtin_frame_address(0),
2049 .context = "GuardInBinderTransaction",
2050 };
2051 const IPCThreadState::SpGuard *origGuard =
2052 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2053
2054 // if the guard works, this should abort
2055 (void)IPCThreadState::self()->getCallingPid();
2056
2057 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
2058 return NO_ERROR;
2059 }
2060
Marco Ballesio7ee17572020-09-08 10:30:03 -07002061 case BINDER_LIB_TEST_GETPID:
2062 reply->writeInt32(getpid());
2063 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07002064 case BINDER_LIB_TEST_GETUID:
2065 reply->writeInt32(getuid());
2066 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07002067 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
2068 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00002069 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08002070 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00002071 // oneway error codes should be ignored
2072 if (flags & TF_ONE_WAY) {
2073 return UNKNOWN_ERROR;
2074 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002075 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002076 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
2077 // Note: this transaction is only designed for use with a
2078 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07002079 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02002080 // A callback was already pending; this means that
2081 // we received a second call while still processing
2082 // the first one. Fail the test.
2083 sp<IBinder> callback = data.readStrongBinder();
2084 Parcel data2;
2085 data2.writeInt32(UNKNOWN_ERROR);
2086
Yi Kong91635562018-06-07 14:38:36 -07002087 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002088 } else {
2089 m_callback = data.readStrongBinder();
2090 int32_t delayUs = data.readInt32();
2091 /*
2092 * It's necessary that we sleep here, so the next
2093 * transaction the caller makes will be queued to
2094 * the async queue.
2095 */
2096 usleep(delayUs);
2097
2098 /*
2099 * Now when we return, libbinder will tell the kernel
2100 * we are done with this transaction, and the kernel
2101 * can move the queued transaction to either the
2102 * thread todo worklist (for kernels without the fix),
2103 * or the proc todo worklist. In case of the former,
2104 * the next outbound call will pick up the pending
2105 * transaction, which leads to undesired reentrant
2106 * behavior. This is caught in the if() branch above.
2107 */
2108 }
2109
2110 return NO_ERROR;
2111 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002112 case BINDER_LIB_TEST_NOP_CALL_BACK: {
2113 Parcel data2, reply2;
2114 sp<IBinder> binder;
2115 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002116 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002117 return BAD_VALUE;
2118 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02002119 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002120 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2121 return NO_ERROR;
2122 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07002123 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
2124 reply->writeStrongBinder(this);
2125 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002126 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
2127 reply->writeInt32(m_id);
2128 return NO_ERROR;
2129 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
2130 int32_t count;
2131 uint32_t indirect_code;
2132 sp<IBinder> binder;
2133
2134 count = data.readInt32();
2135 reply->writeInt32(m_id);
2136 reply->writeInt32(count);
2137 for (int i = 0; i < count; i++) {
2138 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002139 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002140 return BAD_VALUE;
2141 }
2142 indirect_code = data.readInt32();
2143 BinderLibTestBundle data2(&data);
2144 if (!data2.isValid()) {
2145 return BAD_VALUE;
2146 }
2147 BinderLibTestBundle reply2;
2148 binder->transact(indirect_code, data2, &reply2);
2149 reply2.appendTo(reply);
2150 }
2151 return NO_ERROR;
2152 }
2153 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
2154 reply->setError(data.readInt32());
2155 return NO_ERROR;
2156 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
2157 reply->writeInt32(sizeof(void *));
2158 return NO_ERROR;
2159 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
2160 return NO_ERROR;
2161 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
2162 m_strongRef = data.readStrongBinder();
2163 return NO_ERROR;
2164 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
2165 int ret;
2166 Parcel data2, reply2;
2167 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
2168 sp<IBinder> target;
2169 sp<IBinder> callback;
2170
2171 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002172 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002173 return BAD_VALUE;
2174 }
2175 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002176 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002177 return BAD_VALUE;
2178 }
2179 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07002180 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002181 data2.writeInt32(ret);
2182 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2183 return NO_ERROR;
2184 }
2185 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
2186 int ret;
2187 int32_t size;
2188 const void *buf;
2189 int fd;
2190
2191 fd = data.readFileDescriptor();
2192 if (fd < 0) {
2193 return BAD_VALUE;
2194 }
2195 ret = data.readInt32(&size);
2196 if (ret != NO_ERROR) {
2197 return ret;
2198 }
2199 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07002200 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002201 return BAD_VALUE;
2202 }
2203 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07002204 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002205 return NO_ERROR;
2206 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09002207 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
2208 int ret;
2209 int32_t size;
2210 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002211 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09002212
2213 ret = data.readUniqueParcelFileDescriptor(&fd);
2214 if (ret != NO_ERROR) {
2215 return ret;
2216 }
2217 ret = data.readInt32(&size);
2218 if (ret != NO_ERROR) {
2219 return ret;
2220 }
2221 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07002222 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09002223 return BAD_VALUE;
2224 }
2225 ret = write(fd.get(), buf, size);
2226 if (ret != size) return UNKNOWN_ERROR;
2227 return NO_ERROR;
2228 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002229 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
2230 alarm(10);
2231 return NO_ERROR;
2232 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07002233 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002234 ;
2235 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002236 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07002237 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07002238 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002239 return NO_ERROR;
2240 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002241 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
2242 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00002243 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002244 return NO_ERROR;
2245 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00002246 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
2247 int policy = 0;
2248 sched_param param;
2249 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
2250 return UNKNOWN_ERROR;
2251 }
2252 reply->writeInt32(policy);
2253 reply->writeInt32(param.sched_priority);
2254 return NO_ERROR;
2255 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002256 case BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE: {
2257 sp<IBinder> binder = data.readStrongBinder();
2258 frozenStateChangeCallback = sp<TestFrozenStateChangeCallback>::make();
2259 // Hold an strong pointer to the binder object so it doesn't go
2260 // away.
2261 frozenStateChangeCallback->binder = binder;
2262 int ret = binder->addFrozenStateChangeCallback(frozenStateChangeCallback);
2263 if (ret != NO_ERROR) {
2264 return ret;
2265 }
2266 auto event = frozenStateChangeCallback->events.popWithTimeout(10ms);
2267 if (!event.has_value()) {
2268 return NOT_ENOUGH_DATA;
2269 }
2270 return NO_ERROR;
2271 }
2272 case BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS: {
2273 reply->writeBoolVector(frozenStateChangeCallback->getAllAndClear());
2274 return NO_ERROR;
2275 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002276 case BINDER_LIB_TEST_ECHO_VECTOR: {
2277 std::vector<uint64_t> vector;
2278 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07002279 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002280 reply->writeUint64Vector(vector);
2281 return NO_ERROR;
2282 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002283 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
2284 std::array<int, 2> sockets;
2285 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
2286 if (!created) {
2287 ALOGE("Could not create socket pair");
2288 return UNKNOWN_ERROR;
2289 }
2290
2291 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2292 if (result != 0) {
2293 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2294 return UNKNOWN_ERROR;
2295 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002296 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002297 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2298 if (writeResult != NO_ERROR) {
2299 ALOGE("Could not write unique_fd");
2300 return writeResult;
2301 }
2302 close(sockets[1]); // we don't need the other side of the fd
2303 return NO_ERROR;
2304 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07002305 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02002306 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2307 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00002308 case BINDER_LIB_TEST_CAN_GET_SID: {
2309 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2310 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002311 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2312 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2313 return NO_ERROR;
2314 }
Devin Moore4354f712022-12-08 01:44:46 +00002315 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2316 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2317 return NO_ERROR;
2318 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002319 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002320 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002321 return NO_ERROR;
2322 }
2323 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002324 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002325 return NO_ERROR;
2326 }
2327 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2328 int32_t ms = data.readInt32();
2329 return unlockInMs(ms);
2330 }
2331 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002332 m_blockMutex.lock();
2333 sp<BinderLibTestService> thisService = this;
2334 int32_t value = data.readInt32();
2335 // start local thread to unlock in 1s
2336 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002337 t.detach();
2338 return NO_ERROR;
2339 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002340 default:
2341 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002342 };
2343 }
2344
Elie Kheirallah47431c12022-04-21 23:46:17 +00002345 status_t unlockInMs(int32_t ms) {
2346 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002347 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002348 return NO_ERROR;
2349 }
2350
Yifan Hong543edcd2021-05-18 19:47:30 -07002351private:
2352 int32_t m_id;
2353 int32_t m_nextServerId;
2354 pthread_mutex_t m_serverWaitMutex;
2355 pthread_cond_t m_serverWaitCond;
2356 bool m_serverStartRequested;
2357 sp<IBinder> m_serverStarted;
2358 sp<IBinder> m_strongRef;
2359 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002360 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002361 std::mutex m_blockMutex;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002362 sp<TestFrozenStateChangeCallback> frozenStateChangeCallback;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002363};
2364
Martijn Coenen45b07b42017-08-09 12:07:45 +02002365int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002366{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002367 binderLibTestServiceName += String16(binderserversuffix);
2368
Steven Moreland35626652021-05-15 01:32:04 +00002369 // Testing to make sure that calls that we are serving can use getCallin*
2370 // even though we don't here.
2371 IPCThreadState::SpGuard spGuard{
2372 .address = __builtin_frame_address(0),
2373 .context = "main server thread",
2374 };
2375 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2376
Riley Andrews06b01ad2014-12-18 12:10:08 -08002377 status_t ret;
2378 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02002379 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002380 {
2381 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002382
Steven Morelandbf1915b2020-07-16 22:43:02 +00002383 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2384
Steven Morelandcf03cf12020-12-04 02:58:40 +00002385 testService->setInheritRt(true);
2386
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002387 /*
2388 * Normally would also contain functionality as well, but we are only
2389 * testing the extension mechanism.
2390 */
2391 testService->setExtension(new BBinder());
2392
Martijn Coenen82c75312019-07-24 15:18:30 +02002393 // Required for test "BufRejected'
2394 testService->setRequestingSid(true);
2395
Martijn Coenen45b07b42017-08-09 12:07:45 +02002396 /*
2397 * We need this below, but can't hold a sp<> because it prevents the
2398 * node from being cleaned up automatically. It's safe in this case
2399 * because of how the tests are written.
2400 */
2401 testServicePtr = testService.get();
2402
Riley Andrews06b01ad2014-12-18 12:10:08 -08002403 if (index == 0) {
2404 ret = sm->addService(binderLibTestServiceName, testService);
2405 } else {
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002406#pragma clang diagnostic push
2407#pragma clang diagnostic ignored "-Wdeprecated-declarations"
Riley Andrews06b01ad2014-12-18 12:10:08 -08002408 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002409#pragma clang diagnostic pop
Riley Andrews06b01ad2014-12-18 12:10:08 -08002410 Parcel data, reply;
2411 data.writeInt32(index);
2412 data.writeStrongBinder(testService);
2413
2414 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2415 }
2416 }
2417 write(readypipefd, &ret, sizeof(ret));
2418 close(readypipefd);
2419 //printf("%s: ret %d\n", __func__, ret);
2420 if (ret)
2421 return 1;
2422 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002423 if (usePoll) {
2424 int fd;
2425 struct epoll_event ev;
2426 int epoll_fd;
2427 IPCThreadState::self()->setupPolling(&fd);
2428 if (fd < 0) {
2429 return 1;
2430 }
2431 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2432
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002433 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002434 if (epoll_fd == -1) {
2435 return 1;
2436 }
2437
2438 ev.events = EPOLLIN;
2439 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2440 return 1;
2441 }
2442
2443 while (1) {
2444 /*
2445 * We simulate a single-threaded process using the binder poll
2446 * interface; besides handling binder commands, it can also
2447 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002448 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002449 *
2450 * processPendingCall() will then issue that transaction.
2451 */
2452 struct epoll_event events[1];
2453 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2454 if (numEvents < 0) {
2455 if (errno == EINTR) {
2456 continue;
2457 }
2458 return 1;
2459 }
2460 if (numEvents > 0) {
2461 IPCThreadState::self()->handlePolledCommands();
2462 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2463 testServicePtr->processPendingCall();
2464 }
2465 }
2466 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002467 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002468 ProcessState::self()->startThreadPool();
2469 IPCThreadState::self()->joinThreadPool();
2470 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002471 //printf("%s: joinThreadPool returned\n", __func__);
2472 return 1; /* joinThreadPool should not return */
2473}
2474
Steven Moreland68275d72023-04-21 22:12:45 +00002475int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002476 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002477 binderservername = argv[2];
2478 } else {
2479 binderservername = argv[0];
2480 }
2481
Martijn Coenen45b07b42017-08-09 12:07:45 +02002482 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2483 binderserversuffix = argv[5];
2484 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002485 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002486 binderserversuffix = new char[16];
2487 snprintf(binderserversuffix, 16, "%d", getpid());
2488 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002489
2490 ::testing::InitGoogleTest(&argc, argv);
2491 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2492 ProcessState::self()->startThreadPool();
2493 return RUN_ALL_TESTS();
2494}