blob: e56b7cf00407fba0c71178908d1c958f110c4244 [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
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -070053#include "../Utils.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000054#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070055
Riley Andrews06b01ad2014-12-18 12:10:08 -080056using namespace android;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000057using namespace android::binder::impl;
Yifan Hong84bedeb2021-04-21 21:37:17 -070058using namespace std::string_literals;
59using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070060using android::base::testing::HasValue;
Parth Sane81b4d5a2024-05-23 14:11:13 +000061using android::binder::Status;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070062using android::binder::unique_fd;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070063using std::chrono_literals::operator""ms;
Yifan Hong84bedeb2021-04-21 21:37:17 -070064using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080065using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070066using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070067using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070068
69// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
70MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
71 *result_listener << statusToString(arg);
72 return expected == arg;
73}
Riley Andrews06b01ad2014-12-18 12:10:08 -080074
Sherry Yang336cdd32017-07-24 14:12:27 -070075static ::testing::AssertionResult IsPageAligned(void *buf) {
Vilas Bhat04e28c72024-02-12 21:47:15 +000076 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
Sherry Yang336cdd32017-07-24 14:12:27 -070077 return ::testing::AssertionSuccess();
78 else
79 return ::testing::AssertionFailure() << buf << " is not page aligned";
80}
81
Riley Andrews06b01ad2014-12-18 12:10:08 -080082static testing::Environment* binder_env;
83static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070084static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080085static char binderserverarg[] = "--binderserver";
86
Steven Morelandbf1915b2020-07-16 22:43:02 +000087static constexpr int kSchedPolicy = SCHED_RR;
88static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000089static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000090static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000091
Riley Andrews06b01ad2014-12-18 12:10:08 -080092static String16 binderLibTestServiceName = String16("test.binderLib");
93
94enum BinderLibTestTranscationCode {
95 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
96 BINDER_LIB_TEST_REGISTER_SERVER,
97 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020098 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000099 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800100 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -0700101 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200102 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800103 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700104 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800105 BINDER_LIB_TEST_GET_ID_TRANSACTION,
106 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
107 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
108 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
109 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
110 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
111 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900112 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800113 BINDER_LIB_TEST_EXIT_TRANSACTION,
114 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
115 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700116 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100117 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000118 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700119 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
120 BINDER_LIB_TEST_GETPID,
Jing Jibdbe29a2023-10-03 00:03:28 -0700121 BINDER_LIB_TEST_GETUID,
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700122 BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE,
123 BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800124 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700125 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700126 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000127 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000128 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
129 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000130 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000131 BINDER_LIB_TEST_LOCK_UNLOCK,
132 BINDER_LIB_TEST_PROCESS_LOCK,
133 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
134 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800135};
136
Martijn Coenen45b07b42017-08-09 12:07:45 +0200137pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800138{
139 int ret;
140 pid_t pid;
141 status_t status;
142 int pipefd[2];
143 char stri[16];
144 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200145 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800146 char *childargv[] = {
147 binderservername,
148 binderserverarg,
149 stri,
150 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200151 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700152 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700153 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800154 };
155
156 ret = pipe(pipefd);
157 if (ret < 0)
158 return ret;
159
160 snprintf(stri, sizeof(stri), "%d", arg2);
161 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200162 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800163
164 pid = fork();
165 if (pid == -1)
166 return pid;
167 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800168 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800169 close(pipefd[0]);
170 execv(binderservername, childargv);
171 status = -errno;
172 write(pipefd[1], &status, sizeof(status));
173 fprintf(stderr, "execv failed, %s\n", strerror(errno));
174 _exit(EXIT_FAILURE);
175 }
176 close(pipefd[1]);
177 ret = read(pipefd[0], &status, sizeof(status));
178 //printf("pipe read returned %d, status %d\n", ret, status);
179 close(pipefd[0]);
180 if (ret == sizeof(status)) {
181 ret = status;
182 } else {
183 kill(pid, SIGKILL);
184 if (ret >= 0) {
185 ret = NO_INIT;
186 }
187 }
188 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700189 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800190 return ret;
191 }
192 return pid;
193}
194
Yifan Hong84bedeb2021-04-21 21:37:17 -0700195android::base::Result<int32_t> GetId(sp<IBinder> service) {
196 using android::base::Error;
197 Parcel data, reply;
198 data.markForBinder(service);
199 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
200 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
201 if (status != OK)
202 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
203 int32_t result = 0;
204 status = reply.readInt32(&result);
205 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
206 return result;
207}
208
Riley Andrews06b01ad2014-12-18 12:10:08 -0800209class BinderLibTestEnv : public ::testing::Environment {
210 public:
211 BinderLibTestEnv() {}
212 sp<IBinder> getServer(void) {
213 return m_server;
214 }
215
216 private:
217 virtual void SetUp() {
218 m_serverpid = start_server_process(0);
219 //printf("m_serverpid %d\n", m_serverpid);
220 ASSERT_GT(m_serverpid, 0);
221
222 sp<IServiceManager> sm = defaultServiceManager();
Parth Sanedc207542024-11-14 11:49:08 +0000223 // disable caching during addService.
224 sm->enableAddServiceCache(false);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800225 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700226 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -0800227 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700228 LIBBINDER_IGNORE_END()
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);
Parth Sanedc207542024-11-14 11:49:08 +0000300 sp<IServiceManager> sm = defaultServiceManager();
301 // disable caching during addService.
302 sm->enableAddServiceCache(false);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800303 }
304 virtual void TearDown() {
305 }
306 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200307 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800308 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800309 int32_t id;
310 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800311
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700312 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800313
Elie Kheirallahb7246642022-05-03 18:01:43 +0000314 sp<IBinder> binder = reply.readStrongBinder();
315 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700316 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800317 if (idPtr)
318 *idPtr = id;
319 return binder;
320 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200321
Yi Kong91635562018-06-07 14:38:36 -0700322 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200323 {
324 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
325 }
326
Yi Kong91635562018-06-07 14:38:36 -0700327 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200328 {
329 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
330 }
331
Riley Andrews06b01ad2014-12-18 12:10:08 -0800332 void waitForReadData(int fd, int timeout_ms) {
333 int ret;
334 pollfd pfd = pollfd();
335
336 pfd.fd = fd;
337 pfd.events = POLLIN;
338 ret = poll(&pfd, 1, timeout_ms);
339 EXPECT_EQ(1, ret);
340 }
341
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700342 bool checkFreezeSupport() {
343 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
344 // Pass test on devices where the cgroup v2 freezer is not supported
345 if (freezer_file.fail()) {
346 return false;
347 }
348 return IPCThreadState::self()->freeze(getpid(), false, 0) == NO_ERROR;
349 }
350
351 bool checkFreezeAndNotificationSupport() {
352 if (!checkFreezeSupport()) {
353 return false;
354 }
355 return ProcessState::isDriverFeatureEnabled(
356 ProcessState::DriverFeature::FREEZE_NOTIFICATION);
357 }
358
359 bool getBinderPid(int32_t* pid, sp<IBinder> server) {
360 Parcel data, replypid;
361 if (server->transact(BINDER_LIB_TEST_GETPID, data, &replypid) != NO_ERROR) {
362 ALOGE("BINDER_LIB_TEST_GETPID failed");
363 return false;
364 }
365 *pid = replypid.readInt32();
366 if (*pid <= 0) {
367 ALOGE("pid should be greater than zero");
368 return false;
369 }
370 return true;
371 }
372
373 void freezeProcess(int32_t pid) {
374 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
375 }
376
377 void unfreezeProcess(int32_t pid) {
378 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
379 }
380
381 void removeCallbackAndValidateNoEvent(sp<IBinder> binder,
382 sp<TestFrozenStateChangeCallback> callback) {
383 EXPECT_THAT(binder->removeFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
384 EXPECT_EQ(0u, callback->events.size());
385 }
386
Riley Andrews06b01ad2014-12-18 12:10:08 -0800387 sp<IBinder> m_server;
388};
389
390class BinderLibTestBundle : public Parcel
391{
392 public:
393 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800394 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800395 int32_t mark;
396 int32_t bundleLen;
397 size_t pos;
398
399 if (source->readInt32(&mark))
400 return;
401 if (mark != MARK_START)
402 return;
403 if (source->readInt32(&bundleLen))
404 return;
405 pos = source->dataPosition();
406 if (Parcel::appendFrom(source, pos, bundleLen))
407 return;
408 source->setDataPosition(pos + bundleLen);
409 if (source->readInt32(&mark))
410 return;
411 if (mark != MARK_END)
412 return;
413 m_isValid = true;
414 setDataPosition(0);
415 }
416 void appendTo(Parcel *dest) {
417 dest->writeInt32(MARK_START);
418 dest->writeInt32(dataSize());
419 dest->appendFrom(this, 0, dataSize());
420 dest->writeInt32(MARK_END);
421 };
422 bool isValid(void) {
423 return m_isValid;
424 }
425 private:
426 enum {
427 MARK_START = B_PACK_CHARS('B','T','B','S'),
428 MARK_END = B_PACK_CHARS('B','T','B','E'),
429 };
430 bool m_isValid;
431};
432
433class BinderLibTestEvent
434{
435 public:
436 BinderLibTestEvent(void)
437 : m_eventTriggered(false)
438 {
Yi Kong91635562018-06-07 14:38:36 -0700439 pthread_mutex_init(&m_waitMutex, nullptr);
440 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800441 }
442 int waitEvent(int timeout_s)
443 {
444 int ret;
445 pthread_mutex_lock(&m_waitMutex);
446 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800447 struct timespec ts;
448 clock_gettime(CLOCK_REALTIME, &ts);
449 ts.tv_sec += timeout_s;
450 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800451 }
452 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
453 pthread_mutex_unlock(&m_waitMutex);
454 return ret;
455 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200456 pthread_t getTriggeringThread()
457 {
458 return m_triggeringThread;
459 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800460 protected:
461 void triggerEvent(void) {
462 pthread_mutex_lock(&m_waitMutex);
463 pthread_cond_signal(&m_waitCond);
464 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200465 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800466 pthread_mutex_unlock(&m_waitMutex);
467 };
468 private:
469 pthread_mutex_t m_waitMutex;
470 pthread_cond_t m_waitCond;
471 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200472 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800473};
474
475class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
476{
477 public:
478 BinderLibTestCallBack()
479 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700480 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800481 {
482 }
483 status_t getResult(void)
484 {
485 return m_result;
486 }
487
488 private:
489 virtual status_t onTransact(uint32_t code,
490 const Parcel& data, Parcel* reply,
491 uint32_t flags = 0)
492 {
493 (void)reply;
494 (void)flags;
495 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200496 case BINDER_LIB_TEST_CALL_BACK: {
497 status_t status = data.readInt32(&m_result);
498 if (status != NO_ERROR) {
499 m_result = status;
500 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800501 triggerEvent();
502 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200503 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700504 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
505 sp<IBinder> server;
506 int ret;
507 const uint8_t *buf = data.data();
508 size_t size = data.dataSize();
509 if (m_prev_end) {
510 /* 64-bit kernel needs at most 8 bytes to align buffer end */
511 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
512 } else {
513 EXPECT_TRUE(IsPageAligned((void *)buf));
514 }
515
516 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
517
518 if (size > 0) {
519 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
520 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
521 data, reply);
522 EXPECT_EQ(NO_ERROR, ret);
523 }
524 return NO_ERROR;
525 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800526 default:
527 return UNKNOWN_TRANSACTION;
528 }
529 }
530
531 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700532 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800533};
534
535class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
536{
537 private:
538 virtual void binderDied(const wp<IBinder>& who) {
539 (void)who;
540 triggerEvent();
541 };
542};
543
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700544TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
545 // EXPECT_DEATH works by forking the process
546 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
547}
548
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000549TEST_F(BinderLibTest, AddManagerToManager) {
550 sp<IServiceManager> sm = defaultServiceManager();
551 sp<IBinder> binder = IInterface::asBinder(sm);
552 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
553}
554
Parth Sane81b4d5a2024-05-23 14:11:13 +0000555TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
556 auto sm = defaultServiceManager();
557 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
558 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
559 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
560 virtual ~LocalRegistrationCallbackImpl() {}
561 };
562 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
563
564 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
565 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
566}
567
568TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
569 auto sm = defaultServiceManager();
570 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
571 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
572 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
573 virtual ~LocalRegistrationCallbackImpl() {}
574 };
575 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
576
577 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
578
579 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
580 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
581 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
582}
583
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500584TEST_F(BinderLibTest, WasParceled) {
585 auto binder = sp<BBinder>::make();
586 EXPECT_FALSE(binder->wasParceled());
587 Parcel data;
588 data.writeStrongBinder(binder);
589 EXPECT_TRUE(binder->wasParceled());
590}
591
Riley Andrews06b01ad2014-12-18 12:10:08 -0800592TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800593 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700594 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
595 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800596}
597
Steven Moreland80844f72020-12-12 02:06:08 +0000598TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000599 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700600 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
601 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000602}
603
Steven Morelandf183fdd2020-10-27 00:12:12 +0000604TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000605 Parcel data, reply;
606 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700607 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
608 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000609}
610
Marco Ballesio7ee17572020-09-08 10:30:03 -0700611TEST_F(BinderLibTest, Freeze) {
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700612 if (!checkFreezeSupport()) {
613 GTEST_SKIP() << "Skipping test for kernels that do not support proceess freezing";
Marco Ballesio7ee17572020-09-08 10:30:03 -0700614 return;
615 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700616 Parcel data, reply, replypid;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700617 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700618 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700619 for (int i = 0; i < 10; i++) {
620 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
621 }
Li Li6f059292021-09-10 09:59:30 -0700622
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700623 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Li Li6f059292021-09-10 09:59:30 -0700624 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000625
626 // b/268232063 - succeeds ~0.08% of the time
627 {
628 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
629 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
630 }
631
Li Li6f059292021-09-10 09:59:30 -0700632 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700633 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700634
Li Li4e678b92021-09-14 12:14:42 -0700635 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700636
637 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
638 &async_received));
639
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700640 EXPECT_EQ(sync_received, 1u);
641 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700642
Li Li4e678b92021-09-14 12:14:42 -0700643 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700644 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
645}
646
Riley Andrews06b01ad2014-12-18 12:10:08 -0800647TEST_F(BinderLibTest, SetError) {
648 int32_t testValue[] = { 0, -123, 123 };
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700649 for (size_t i = 0; i < countof(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800650 Parcel data, reply;
651 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700652 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
653 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800654 }
655}
656
657TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700658 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800659}
660
661TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800662 int32_t ptrsize;
663 Parcel data, reply;
664 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700665 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700666 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
667 StatusEq(NO_ERROR));
668 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800669 RecordProperty("TestPtrSize", sizeof(void *));
670 RecordProperty("ServerPtrSize", sizeof(void *));
671}
672
673TEST_F(BinderLibTest, IndirectGetId2)
674{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800675 int32_t id;
676 int32_t count;
677 Parcel data, reply;
678 int32_t serverId[3];
679
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700680 data.writeInt32(countof(serverId));
681 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800682 sp<IBinder> server;
683 BinderLibTestBundle datai;
684
685 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700686 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800687 data.writeStrongBinder(server);
688 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
689 datai.appendTo(&data);
690 }
691
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700692 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
693 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800694
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700695 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800696 EXPECT_EQ(0, id);
697
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700698 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700699 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800700
701 for (size_t i = 0; i < (size_t)count; i++) {
702 BinderLibTestBundle replyi(&reply);
703 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700704 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800705 EXPECT_EQ(serverId[i], id);
706 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
707 }
708
709 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
710}
711
712TEST_F(BinderLibTest, IndirectGetId3)
713{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800714 int32_t id;
715 int32_t count;
716 Parcel data, reply;
717 int32_t serverId[3];
718
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700719 data.writeInt32(countof(serverId));
720 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800721 sp<IBinder> server;
722 BinderLibTestBundle datai;
723 BinderLibTestBundle datai2;
724
725 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700726 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800727 data.writeStrongBinder(server);
728 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
729
730 datai.writeInt32(1);
731 datai.writeStrongBinder(m_server);
732 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
733 datai2.appendTo(&datai);
734
735 datai.appendTo(&data);
736 }
737
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700738 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
739 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800740
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700741 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800742 EXPECT_EQ(0, id);
743
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700744 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700745 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800746
747 for (size_t i = 0; i < (size_t)count; i++) {
748 int32_t counti;
749
750 BinderLibTestBundle replyi(&reply);
751 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700752 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800753 EXPECT_EQ(serverId[i], id);
754
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700755 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800756 EXPECT_EQ(1, counti);
757
758 BinderLibTestBundle replyi2(&replyi);
759 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700760 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800761 EXPECT_EQ(0, id);
762 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
763
764 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
765 }
766
767 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
768}
769
770TEST_F(BinderLibTest, CallBack)
771{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800772 Parcel data, reply;
773 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
774 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700775 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
776 StatusEq(NO_ERROR));
777 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
778 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800779}
780
Steven Moreland35626652021-05-15 01:32:04 +0000781TEST_F(BinderLibTest, BinderCallContextGuard) {
782 sp<IBinder> binder = addServer();
783 Parcel data, reply;
784 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
785 StatusEq(DEAD_OBJECT));
786}
787
Riley Andrews06b01ad2014-12-18 12:10:08 -0800788TEST_F(BinderLibTest, AddServer)
789{
790 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700791 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800792}
793
Riley Andrews06b01ad2014-12-18 12:10:08 -0800794TEST_F(BinderLibTest, DeathNotificationStrongRef)
795{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800796 sp<IBinder> sbinder;
797
798 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
799
800 {
801 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700802 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700803 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800804 sbinder = binder;
805 }
806 {
807 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700808 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
809 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800810 }
811 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700812 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
813 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800814}
815
816TEST_F(BinderLibTest, DeathNotificationMultiple)
817{
818 status_t ret;
819 const int clientcount = 2;
820 sp<IBinder> target;
821 sp<IBinder> linkedclient[clientcount];
822 sp<BinderLibTestCallBack> callBack[clientcount];
823 sp<IBinder> passiveclient[clientcount];
824
825 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700826 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800827 for (int i = 0; i < clientcount; i++) {
828 {
829 Parcel data, reply;
830
831 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700832 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800833 callBack[i] = new BinderLibTestCallBack();
834 data.writeStrongBinder(target);
835 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700836 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
837 &reply, TF_ONE_WAY),
838 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800839 }
840 {
841 Parcel data, reply;
842
843 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700844 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800845 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700846 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
847 &reply, TF_ONE_WAY),
848 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800849 }
850 }
851 {
852 Parcel data, reply;
853 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
854 EXPECT_EQ(0, ret);
855 }
856
857 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700858 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
859 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800860 }
861}
862
Martijn Coenenf7100e42017-07-31 12:14:09 +0200863TEST_F(BinderLibTest, DeathNotificationThread)
864{
865 status_t ret;
866 sp<BinderLibTestCallBack> callback;
867 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700868 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200869 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700870 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200871
872 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
873
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700874 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200875
876 {
877 Parcel data, reply;
878 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
879 EXPECT_EQ(0, ret);
880 }
881
882 /* Make sure it's dead */
883 testDeathRecipient->waitEvent(5);
884
885 /* Now, pass the ref to another process and ask that process to
886 * call linkToDeath() on it, and wait for a response. This tests
887 * two things:
888 * 1) You still get death notifications when calling linkToDeath()
889 * on a ref that is already dead when it was passed to you.
890 * 2) That death notifications are not directly pushed to the thread
891 * registering them, but to the threadpool (proc workqueue) instead.
892 *
893 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
894 * is blocked on a condition variable waiting for the death notification to be
895 * called; therefore, that thread is not available for handling proc work.
896 * So, if the death notification was pushed to the thread workqueue, the callback
897 * would never be called, and the test would timeout and fail.
898 *
899 * Note that we can't do this part of the test from this thread itself, because
900 * the binder driver would only push death notifications to the thread if
901 * it is a looper thread, which this thread is not.
902 *
903 * See b/23525545 for details.
904 */
905 {
906 Parcel data, reply;
907
908 callback = new BinderLibTestCallBack();
909 data.writeStrongBinder(target);
910 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700911 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
912 TF_ONE_WAY),
913 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200914 }
915
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700916 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
917 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200918}
919
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700920TEST_F(BinderLibTest, ReturnErrorIfKernelDoesNotSupportFreezeNotification) {
921 if (ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::FREEZE_NOTIFICATION)) {
922 GTEST_SKIP() << "Skipping test for kernels that support FREEZE_NOTIFICATION";
923 return;
924 }
925 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
926 sp<IBinder> binder = addServer();
927 ASSERT_NE(nullptr, binder);
928 ASSERT_EQ(nullptr, binder->localBinder());
929 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(INVALID_OPERATION));
930}
931
932TEST_F(BinderLibTest, FrozenStateChangeNotificatiion) {
933 if (!checkFreezeAndNotificationSupport()) {
934 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
935 return;
936 }
937 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
938 sp<IBinder> binder = addServer();
939 ASSERT_NE(nullptr, binder);
940 int32_t pid;
941 ASSERT_TRUE(getBinderPid(&pid, binder));
942
943 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
944 // Expect current state (unfrozen) to be delivered immediately.
945 callback->ensureUnfrozenEventReceived();
946 // Check that the process hasn't died otherwise there's a risk of freezing
947 // the wrong process.
948 EXPECT_EQ(OK, binder->pingBinder());
949 freezeProcess(pid);
950 callback->ensureFrozenEventReceived();
951 unfreezeProcess(pid);
952 callback->ensureUnfrozenEventReceived();
953 removeCallbackAndValidateNoEvent(binder, callback);
954}
955
956TEST_F(BinderLibTest, AddFrozenCallbackWhenFrozen) {
957 if (!checkFreezeAndNotificationSupport()) {
958 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
959 return;
960 }
961 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
962 sp<IBinder> binder = addServer();
963 ASSERT_NE(nullptr, binder);
964 int32_t pid;
965 ASSERT_TRUE(getBinderPid(&pid, binder));
966
967 // Check that the process hasn't died otherwise there's a risk of freezing
968 // the wrong process.
969 EXPECT_EQ(OK, binder->pingBinder());
970 freezeProcess(pid);
971 // Add the callback while the target process is frozen.
972 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
973 callback->ensureFrozenEventReceived();
974 unfreezeProcess(pid);
975 callback->ensureUnfrozenEventReceived();
976 removeCallbackAndValidateNoEvent(binder, callback);
977
978 // Check that the process hasn't died otherwise there's a risk of freezing
979 // the wrong process.
980 EXPECT_EQ(OK, binder->pingBinder());
981 freezeProcess(pid);
982 unfreezeProcess(pid);
983 // Make sure no callback happens since the listener has been removed.
984 EXPECT_EQ(0u, callback->events.size());
985}
986
987TEST_F(BinderLibTest, NoFrozenNotificationAfterCallbackRemoval) {
988 if (!checkFreezeAndNotificationSupport()) {
989 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
990 return;
991 }
992 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
993 sp<IBinder> binder = addServer();
994 ASSERT_NE(nullptr, binder);
995 int32_t pid;
996 ASSERT_TRUE(getBinderPid(&pid, binder));
997
998 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
999 callback->ensureUnfrozenEventReceived();
1000 removeCallbackAndValidateNoEvent(binder, callback);
1001
1002 // Make sure no callback happens after the listener is removed.
1003 freezeProcess(pid);
1004 unfreezeProcess(pid);
1005 EXPECT_EQ(0u, callback->events.size());
1006}
1007
1008TEST_F(BinderLibTest, MultipleFrozenStateChangeCallbacks) {
1009 if (!checkFreezeAndNotificationSupport()) {
1010 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1011 return;
1012 }
1013 sp<TestFrozenStateChangeCallback> callback1 = sp<TestFrozenStateChangeCallback>::make();
1014 sp<TestFrozenStateChangeCallback> callback2 = sp<TestFrozenStateChangeCallback>::make();
1015 sp<IBinder> binder = addServer();
1016 ASSERT_NE(nullptr, binder);
1017 int32_t pid;
1018 ASSERT_TRUE(getBinderPid(&pid, binder));
1019
1020 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback1), StatusEq(NO_ERROR));
1021 // Expect current state (unfrozen) to be delivered immediately.
1022 callback1->ensureUnfrozenEventReceived();
1023
1024 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback2), StatusEq(NO_ERROR));
1025 // Expect current state (unfrozen) to be delivered immediately.
1026 callback2->ensureUnfrozenEventReceived();
1027
1028 freezeProcess(pid);
1029 callback1->ensureFrozenEventReceived();
1030 callback2->ensureFrozenEventReceived();
1031
1032 removeCallbackAndValidateNoEvent(binder, callback1);
1033 unfreezeProcess(pid);
1034 EXPECT_EQ(0u, callback1->events.size());
1035 callback2->ensureUnfrozenEventReceived();
1036 removeCallbackAndValidateNoEvent(binder, callback2);
1037
1038 freezeProcess(pid);
1039 EXPECT_EQ(0u, callback2->events.size());
1040}
1041
1042TEST_F(BinderLibTest, RemoveThenAddFrozenStateChangeCallbacks) {
1043 if (!checkFreezeAndNotificationSupport()) {
1044 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1045 return;
1046 }
1047 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1048 sp<IBinder> binder = addServer();
1049 ASSERT_NE(nullptr, binder);
1050 int32_t pid;
1051 ASSERT_TRUE(getBinderPid(&pid, binder));
1052
1053 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1054 // Expect current state (unfrozen) to be delivered immediately.
1055 callback->ensureUnfrozenEventReceived();
1056 removeCallbackAndValidateNoEvent(binder, callback);
1057
1058 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1059 callback->ensureUnfrozenEventReceived();
1060}
1061
1062TEST_F(BinderLibTest, CoalesceFreezeCallbacksWhenListenerIsFrozen) {
1063 if (!checkFreezeAndNotificationSupport()) {
1064 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1065 return;
1066 }
1067 sp<IBinder> binder = addServer();
1068 sp<IBinder> listener = addServer();
1069 ASSERT_NE(nullptr, binder);
1070 ASSERT_NE(nullptr, listener);
1071 int32_t pid, listenerPid;
1072 ASSERT_TRUE(getBinderPid(&pid, binder));
1073 ASSERT_TRUE(getBinderPid(&listenerPid, listener));
1074
1075 // Ask the listener process to register for state change callbacks.
1076 {
1077 Parcel data, reply;
1078 data.writeStrongBinder(binder);
1079 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE, data,
1080 &reply),
1081 StatusEq(NO_ERROR));
1082 }
1083 // Freeze the listener process.
1084 freezeProcess(listenerPid);
1085 createProcessGroup(getuid(), listenerPid);
1086 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Frozen"}));
1087 // Repeatedly flip the target process between frozen and unfrozen states.
1088 for (int i = 0; i < 1000; i++) {
1089 usleep(50);
1090 unfreezeProcess(pid);
1091 usleep(50);
1092 freezeProcess(pid);
1093 }
1094 // Unfreeze the listener process. Now it should receive the frozen state
1095 // change notifications.
1096 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Unfrozen"}));
1097 unfreezeProcess(listenerPid);
1098 // Wait for 500ms to give the process enough time to wake up and handle
1099 // notifications.
1100 usleep(500 * 1000);
1101 {
1102 std::vector<bool> events;
1103 Parcel data, reply;
1104 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS, data, &reply),
1105 StatusEq(NO_ERROR));
1106 reply.readBoolVector(&events);
1107 // There should only be one single state change notifications delievered.
1108 ASSERT_EQ(1u, events.size());
1109 EXPECT_TRUE(events[0]);
1110 }
1111}
1112
Riley Andrews06b01ad2014-12-18 12:10:08 -08001113TEST_F(BinderLibTest, PassFile) {
1114 int ret;
1115 int pipefd[2];
1116 uint8_t buf[1] = { 0 };
1117 uint8_t write_value = 123;
1118
1119 ret = pipe2(pipefd, O_NONBLOCK);
1120 ASSERT_EQ(0, ret);
1121
1122 {
1123 Parcel data, reply;
1124 uint8_t writebuf[1] = { write_value };
1125
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001126 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001127
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001128 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001129
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001130 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001131
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001132 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
1133 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001134 }
1135
1136 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -07001137 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001138 EXPECT_EQ(write_value, buf[0]);
1139
1140 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
1141
1142 ret = read(pipefd[0], buf, sizeof(buf));
1143 EXPECT_EQ(0, ret);
1144
1145 close(pipefd[0]);
1146}
1147
Ryo Hashimotobf551892018-05-31 16:58:35 +09001148TEST_F(BinderLibTest, PassParcelFileDescriptor) {
1149 const int datasize = 123;
1150 std::vector<uint8_t> writebuf(datasize);
1151 for (size_t i = 0; i < writebuf.size(); ++i) {
1152 writebuf[i] = i;
1153 }
1154
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001155 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001156 {
1157 int pipefd[2];
1158 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
1159 read_end.reset(pipefd[0]);
1160 write_end.reset(pipefd[1]);
1161 }
1162 {
1163 Parcel data;
1164 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
1165 write_end.reset();
1166 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
1167 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
1168
1169 Parcel reply;
1170 EXPECT_EQ(NO_ERROR,
1171 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
1172 &reply));
1173 }
1174 std::vector<uint8_t> readbuf(datasize);
1175 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
1176 EXPECT_EQ(writebuf, readbuf);
1177
1178 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
1179
1180 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
1181}
1182
Riley Andrews06b01ad2014-12-18 12:10:08 -08001183TEST_F(BinderLibTest, PromoteLocal) {
1184 sp<IBinder> strong = new BBinder();
1185 wp<IBinder> weak = strong;
1186 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001187 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001188 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -07001189 strong = nullptr;
1190 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001191 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001192 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001193}
1194
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001195TEST_F(BinderLibTest, LocalGetExtension) {
1196 sp<BBinder> binder = new BBinder();
1197 sp<IBinder> ext = new BBinder();
1198 binder->setExtension(ext);
1199 EXPECT_EQ(ext, binder->getExtension());
1200}
1201
1202TEST_F(BinderLibTest, RemoteGetExtension) {
1203 sp<IBinder> server = addServer();
1204 ASSERT_TRUE(server != nullptr);
1205
1206 sp<IBinder> extension;
1207 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
1208 ASSERT_NE(nullptr, extension.get());
1209
1210 EXPECT_EQ(NO_ERROR, extension->pingBinder());
1211}
1212
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001213TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001214 Parcel data, reply;
1215
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001216 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
1217 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001218
1219 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -07001220 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +08001221 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
1222 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
1223 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
1224 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001225}
1226
Connor O'Brien52be2c92016-09-20 14:18:08 -07001227TEST_F(BinderLibTest, FreedBinder) {
1228 status_t ret;
1229
1230 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -07001231 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001232
1233 __u32 freedHandle;
1234 wp<IBinder> keepFreedBinder;
1235 {
1236 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001237 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1238 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -07001239 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
1240 freedHandle = freed->handle;
1241 /* Add a weak ref to the freed binder so the driver does not
1242 * delete its reference to it - otherwise the transaction
1243 * fails regardless of whether the driver is fixed.
1244 */
Steven Morelande171d622019-07-17 16:06:01 -07001245 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001246 }
Steven Morelande171d622019-07-17 16:06:01 -07001247 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001248 {
1249 Parcel data, reply;
1250 data.writeStrongBinder(server);
1251 /* Replace original handle with handle to the freed binder */
1252 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
1253 __u32 oldHandle = strong->handle;
1254 strong->handle = freedHandle;
1255 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
1256 /* Returns DEAD_OBJECT (-32) if target crashes and
1257 * FAILED_TRANSACTION if the driver rejects the invalid
1258 * object.
1259 */
1260 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
1261 /* Restore original handle so parcel destructor does not use
1262 * the wrong handle.
1263 */
1264 strong->handle = oldHandle;
1265 }
1266}
1267
Sherry Yang336cdd32017-07-24 14:12:27 -07001268TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -07001269 Parcel data, reply;
1270 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1271 for (int i = 0; i < 2; i++) {
1272 BinderLibTestBundle datai;
1273 datai.appendFrom(&data, 0, data.dataSize());
1274
1275 data.freeData();
1276 data.writeInt32(1);
1277 data.writeStrongBinder(callBack);
1278 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1279
1280 datai.appendTo(&data);
1281 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001282 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1283 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -07001284}
1285
Martijn Coenen45b07b42017-08-09 12:07:45 +02001286TEST_F(BinderLibTest, OnewayQueueing)
1287{
Martijn Coenen45b07b42017-08-09 12:07:45 +02001288 Parcel data, data2;
1289
1290 sp<IBinder> pollServer = addPollServer();
1291
1292 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1293 data.writeStrongBinder(callBack);
1294 data.writeInt32(500000); // delay in us before calling back
1295
1296 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1297 data2.writeStrongBinder(callBack2);
1298 data2.writeInt32(0); // delay in us
1299
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001300 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1301 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001302
1303 // The delay ensures that this second transaction will end up on the async_todo list
1304 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001305 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1306 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001307
1308 // The server will ensure that the two transactions are handled in the expected order;
1309 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001310 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1311 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001312
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001313 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1314 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001315}
1316
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001317TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1318{
1319 status_t ret;
1320 Parcel data, reply;
1321 data.writeInterfaceToken(binderLibTestServiceName);
1322 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1323 EXPECT_EQ(-1, reply.readInt32());
1324 EXPECT_EQ(NO_ERROR, ret);
1325}
1326
1327TEST_F(BinderLibTest, WorkSourceSet)
1328{
1329 status_t ret;
1330 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001331 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001332 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001333 data.writeInterfaceToken(binderLibTestServiceName);
1334 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1335 EXPECT_EQ(100, reply.readInt32());
1336 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001337 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1338 EXPECT_EQ(NO_ERROR, ret);
1339}
1340
1341TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1342{
1343 status_t ret;
1344 Parcel data, reply;
1345
1346 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1347 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1348
1349 data.writeInterfaceToken(binderLibTestServiceName);
1350 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1351 EXPECT_EQ(-1, reply.readInt32());
1352 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001353 EXPECT_EQ(NO_ERROR, ret);
1354}
1355
1356TEST_F(BinderLibTest, WorkSourceCleared)
1357{
1358 status_t ret;
1359 Parcel data, reply;
1360
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001361 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001362 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1363 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001364 data.writeInterfaceToken(binderLibTestServiceName);
1365 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1366
1367 EXPECT_EQ(-1, reply.readInt32());
1368 EXPECT_EQ(100, previousWorkSource);
1369 EXPECT_EQ(NO_ERROR, ret);
1370}
1371
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001372TEST_F(BinderLibTest, WorkSourceRestored)
1373{
1374 status_t ret;
1375 Parcel data, reply;
1376
1377 IPCThreadState::self()->setCallingWorkSourceUid(100);
1378 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1379 IPCThreadState::self()->restoreCallingWorkSource(token);
1380
1381 data.writeInterfaceToken(binderLibTestServiceName);
1382 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1383
1384 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001385 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001386 EXPECT_EQ(NO_ERROR, ret);
1387}
1388
Olivier Gaillard91a04802018-11-14 17:32:41 +00001389TEST_F(BinderLibTest, PropagateFlagSet)
1390{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001391 IPCThreadState::self()->clearPropagateWorkSource();
1392 IPCThreadState::self()->setCallingWorkSourceUid(100);
1393 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1394}
1395
1396TEST_F(BinderLibTest, PropagateFlagCleared)
1397{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001398 IPCThreadState::self()->setCallingWorkSourceUid(100);
1399 IPCThreadState::self()->clearPropagateWorkSource();
1400 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1401}
1402
1403TEST_F(BinderLibTest, PropagateFlagRestored)
1404{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001405 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1406 IPCThreadState::self()->restoreCallingWorkSource(token);
1407
1408 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1409}
1410
1411TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1412{
1413 IPCThreadState::self()->setCallingWorkSourceUid(100);
1414
1415 Parcel data, reply;
1416 status_t ret;
1417 data.writeInterfaceToken(binderLibTestServiceName);
1418 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001419 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001420
1421 Parcel data2, reply2;
1422 status_t ret2;
1423 data2.writeInterfaceToken(binderLibTestServiceName);
1424 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1425 EXPECT_EQ(100, reply2.readInt32());
1426 EXPECT_EQ(NO_ERROR, ret2);
1427}
1428
Steven Morelandbf1915b2020-07-16 22:43:02 +00001429TEST_F(BinderLibTest, SchedPolicySet) {
1430 sp<IBinder> server = addServer();
1431 ASSERT_TRUE(server != nullptr);
1432
1433 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001434 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1435 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001436
1437 int policy = reply.readInt32();
1438 int priority = reply.readInt32();
1439
1440 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1441 EXPECT_EQ(kSchedPriority, priority);
1442}
1443
Steven Morelandcf03cf12020-12-04 02:58:40 +00001444TEST_F(BinderLibTest, InheritRt) {
1445 sp<IBinder> server = addServer();
1446 ASSERT_TRUE(server != nullptr);
1447
1448 const struct sched_param param {
1449 .sched_priority = kSchedPriorityMore,
1450 };
1451 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1452
1453 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001454 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1455 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001456
1457 int policy = reply.readInt32();
1458 int priority = reply.readInt32();
1459
1460 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1461 EXPECT_EQ(kSchedPriorityMore, priority);
1462}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001463
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001464TEST_F(BinderLibTest, VectorSent) {
1465 Parcel data, reply;
1466 sp<IBinder> server = addServer();
1467 ASSERT_TRUE(server != nullptr);
1468
1469 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1470 data.writeUint64Vector(testValue);
1471
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001472 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001473 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001474 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001475 EXPECT_EQ(readValue, testValue);
1476}
1477
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001478TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1479 sp<IBinder> server = addServer();
1480 ASSERT_TRUE(server != nullptr);
1481
1482 Parcel reply;
1483 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1484 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001485 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001486 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1487
1488 const int result = fcntl(fd.get(), F_GETFL);
1489 ASSERT_NE(result, -1);
1490 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1491}
1492
Steven Moreland59b84442022-07-12 18:32:44 +00001493// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1494// This value is not exposed, but some code in the framework relies on being able to use
1495// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001496constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001497constexpr size_t kSizeBytesOverFull = 1'050'000;
1498
1499TEST_F(BinderLibTest, GargantuanVectorSent) {
1500 sp<IBinder> server = addServer();
1501 ASSERT_TRUE(server != nullptr);
1502
1503 for (size_t i = 0; i < 10; i++) {
1504 // a slight variation in size is used to consider certain possible caching implementations
1505 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1506
1507 Parcel data, reply;
1508 data.writeUint64Vector(testValue);
1509 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1510 << i;
1511 std::vector<uint64_t> readValue;
1512 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1513 EXPECT_EQ(readValue, testValue);
1514 }
1515}
1516
1517TEST_F(BinderLibTest, LimitExceededVectorSent) {
1518 sp<IBinder> server = addServer();
1519 ASSERT_TRUE(server != nullptr);
1520 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1521
1522 Parcel data, reply;
1523 data.writeUint64Vector(testValue);
1524 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1525 StatusEq(FAILED_TRANSACTION));
1526}
1527
Martijn Coenen82c75312019-07-24 15:18:30 +02001528TEST_F(BinderLibTest, BufRejected) {
1529 Parcel data, reply;
1530 uint32_t buf;
1531 sp<IBinder> server = addServer();
1532 ASSERT_TRUE(server != nullptr);
1533
1534 binder_buffer_object obj {
1535 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001536 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001537 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1538 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001539 };
1540 data.setDataCapacity(1024);
1541 // Write a bogus object at offset 0 to get an entry in the offset table
1542 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001543 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001544 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1545 // And now, overwrite it with the buffer object
1546 memcpy(parcelData, &obj, sizeof(obj));
1547 data.setDataSize(sizeof(obj));
1548
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001549 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001550
Martijn Coenen82c75312019-07-24 15:18:30 +02001551 // Either the kernel should reject this transaction (if it's correct), but
1552 // if it's not, the server implementation should return an error if it
1553 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001554 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001555 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001556}
1557
Steven Morelandf2e0a952021-11-01 18:17:23 -07001558TEST_F(BinderLibTest, WeakRejected) {
1559 Parcel data, reply;
1560 sp<IBinder> server = addServer();
1561 ASSERT_TRUE(server != nullptr);
1562
1563 auto binder = sp<BBinder>::make();
1564 wp<BBinder> wpBinder(binder);
1565 flat_binder_object obj{
1566 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1567 .flags = 0,
1568 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1569 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1570 };
1571 data.setDataCapacity(1024);
1572 // Write a bogus object at offset 0 to get an entry in the offset table
1573 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001574 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001575 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1576 // And now, overwrite it with the weak binder
1577 memcpy(parcelData, &obj, sizeof(obj));
1578 data.setDataSize(sizeof(obj));
1579
1580 // a previous bug caused other objects to be released an extra time, so we
1581 // test with an object that libbinder will actually try to release
1582 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1583
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001584 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001585
1586 // send it many times, since previous error was memory corruption, make it
1587 // more likely that the server crashes
1588 for (size_t i = 0; i < 100; i++) {
1589 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1590 StatusEq(BAD_VALUE));
1591 }
1592
1593 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1594}
1595
Steven Moreland254e8ef2021-04-19 22:28:50 +00001596TEST_F(BinderLibTest, GotSid) {
1597 sp<IBinder> server = addServer();
1598
1599 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001600 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001601}
1602
Andrei Homescu1519b982022-06-09 02:04:44 +00001603struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1604 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1605
1606 // Flattenable protocol
1607 size_t getFlattenedSize() const {
1608 // Return a valid non-zero size here so we don't get an unintended
1609 // BAD_VALUE from Parcel::write
1610 return 16;
1611 }
1612 size_t getFdCount() const { return mFdCount; }
1613 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1614 for (size_t i = 0; i < count; i++) {
1615 fds[i] = STDIN_FILENO;
1616 }
1617 return NO_ERROR;
1618 }
1619 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1620 size_t & /*count*/) {
1621 /* This doesn't get called */
1622 return NO_ERROR;
1623 }
1624
1625 size_t mFdCount;
1626};
1627
1628TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1629 rlimit origNofile;
1630 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1631 ASSERT_EQ(0, ret);
1632
1633 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001634 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001635
1636 rlimit testNofile = {1024, 1024};
1637 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1638 ASSERT_EQ(0, ret);
1639
1640 Parcel parcel;
1641 // Try to write more file descriptors than supported by the OS
1642 TooManyFdsFlattenable tooManyFds1(1024);
1643 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1644
1645 // Try to write more file descriptors than the internal limit
1646 TooManyFdsFlattenable tooManyFds2(1025);
1647 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1648}
1649
Jayant Chowdhary30700942022-01-31 14:12:40 -08001650TEST(ServiceNotifications, Unregister) {
1651 auto sm = defaultServiceManager();
Parth Sanedc207542024-11-14 11:49:08 +00001652 sm->enableAddServiceCache(false);
Jayant Chowdhary30700942022-01-31 14:12:40 -08001653 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1654 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1655 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1656 virtual ~LocalRegistrationCallbackImpl() {}
1657 };
1658 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1659
1660 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1661 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1662}
1663
Elie Kheirallah47431c12022-04-21 23:46:17 +00001664TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1665 Parcel data, reply;
1666 sp<IBinder> server = addServer();
1667 ASSERT_TRUE(server != nullptr);
1668 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1669 StatusEq(NO_ERROR));
1670 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001671 // see getThreadPoolMaxTotalThreadCount for why there is a race
1672 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1673
Elie Kheirallah47431c12022-04-21 23:46:17 +00001674 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1675
1676 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001677 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1678 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1679 * started threads from setThreadPoolMaxThreadCount
1680 *
1681 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001682 */
1683 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001684 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001685 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001686 Parcel local_reply;
1687 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1688 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001689 }));
1690 }
1691
Steven Moreland3e9debc2023-06-15 00:35:29 +00001692 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1693 // the time, the below call will pre-empt them (presumably because we have the
1694 // scheduler timeslice already + scheduler hint).
1695 sleep(1);
1696
1697 data.writeInt32(1000);
1698 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001699 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1700
1701 for (auto &t : ts) {
1702 t.join();
1703 }
1704
1705 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1706 StatusEq(NO_ERROR));
1707 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001708 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001709}
1710
Devin Moore4354f712022-12-08 01:44:46 +00001711TEST_F(BinderLibTest, ThreadPoolStarted) {
1712 Parcel data, reply;
1713 sp<IBinder> server = addServer();
1714 ASSERT_TRUE(server != nullptr);
1715 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1716 EXPECT_TRUE(reply.readBool());
1717}
1718
Elie Kheirallah47431c12022-04-21 23:46:17 +00001719size_t epochMillis() {
1720 using std::chrono::duration_cast;
1721 using std::chrono::milliseconds;
1722 using std::chrono::seconds;
1723 using std::chrono::system_clock;
1724 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1725}
1726
1727TEST_F(BinderLibTest, HangingServices) {
1728 Parcel data, reply;
1729 sp<IBinder> server = addServer();
1730 ASSERT_TRUE(server != nullptr);
1731 int32_t delay = 1000; // ms
1732 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001733 // b/266537959 - must take before taking lock, since countdown is started in the remote
1734 // process there.
1735 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001736 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1737 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001738 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1739 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001740 Parcel local_reply;
1741 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1742 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001743 }));
1744 }
1745
1746 for (auto &t : ts) {
1747 t.join();
1748 }
1749 size_t epochMsAfter = epochMillis();
1750
1751 // deadlock occurred and threads only finished after 1s passed.
1752 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1753}
1754
Jing Jibbe9ae62023-10-07 15:26:02 -07001755TEST_F(BinderLibTest, BinderProxyCount) {
1756 Parcel data, reply;
1757 sp<IBinder> server = addServer();
1758 ASSERT_NE(server, nullptr);
1759
1760 uint32_t initialCount = BpBinder::getBinderProxyCount();
1761 size_t iterations = 100;
1762 {
1763 uint32_t count = initialCount;
1764 std::vector<sp<IBinder> > proxies;
1765 sp<IBinder> proxy;
1766 // Create binder proxies and verify the count.
1767 for (size_t i = 0; i < iterations; i++) {
1768 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1769 StatusEq(NO_ERROR));
1770 proxies.push_back(reply.readStrongBinder());
1771 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1772 }
1773 // Remove every other one and verify the count.
1774 auto it = proxies.begin();
1775 for (size_t i = 0; it != proxies.end(); i++) {
1776 if (i % 2 == 0) {
1777 it = proxies.erase(it);
1778 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1779 }
1780 }
1781 }
1782 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1783}
1784
Jing Jibdbe29a2023-10-03 00:03:28 -07001785static constexpr int kBpCountHighWatermark = 20;
1786static constexpr int kBpCountLowWatermark = 10;
1787static constexpr int kBpCountWarningWatermark = 15;
1788static constexpr int kInvalidUid = -1;
1789
1790TEST_F(BinderLibTest, BinderProxyCountCallback) {
1791 Parcel data, reply;
1792 sp<IBinder> server = addServer();
1793 ASSERT_NE(server, nullptr);
1794
1795 BpBinder::enableCountByUid();
1796 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1797 int32_t uid = reply.readInt32();
1798 ASSERT_NE(uid, kInvalidUid);
1799
1800 uint32_t initialCount = BpBinder::getBinderProxyCount();
1801 {
1802 uint32_t count = initialCount;
1803 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1804 kBpCountLowWatermark,
1805 kBpCountWarningWatermark);
1806 int limitCallbackUid = kInvalidUid;
1807 int warningCallbackUid = kInvalidUid;
1808 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1809 [&](int uid) { warningCallbackUid = uid; });
1810
1811 std::vector<sp<IBinder> > proxies;
1812 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1813 warningCallbackUid = limitCallbackUid = kInvalidUid;
1814 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1815 StatusEq(NO_ERROR));
1816 proxies.push_back(reply.readStrongBinder());
1817 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1818 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1819 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1820 };
1821 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1822 warningCallbackUid = limitCallbackUid = kInvalidUid;
1823 proxies.pop_back();
1824 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1825 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1826 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1827 };
1828
1829 // Test the increment/decrement of the binder proxies.
1830 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1831 createProxyOnce(kInvalidUid, kInvalidUid);
1832 }
1833 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1834 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1835 createProxyOnce(kInvalidUid, kInvalidUid);
1836 }
1837 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1838 createProxyOnce(kInvalidUid, kInvalidUid);
1839 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1840 removeProxyOnce(kInvalidUid, kInvalidUid);
1841 }
1842 createProxyOnce(kInvalidUid, kInvalidUid);
1843
1844 // Go down below the low watermark.
1845 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1846 removeProxyOnce(kInvalidUid, kInvalidUid);
1847 }
1848 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1849 createProxyOnce(kInvalidUid, kInvalidUid);
1850 }
1851 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1852 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1853 createProxyOnce(kInvalidUid, kInvalidUid);
1854 }
1855 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1856 createProxyOnce(kInvalidUid, kInvalidUid);
1857 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1858 removeProxyOnce(kInvalidUid, kInvalidUid);
1859 }
1860 createProxyOnce(kInvalidUid, kInvalidUid);
1861 }
1862 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1863}
1864
Yifan Hong84bedeb2021-04-21 21:37:17 -07001865class BinderLibRpcTestBase : public BinderLibTest {
1866public:
1867 void SetUp() override {
1868 if (!base::GetBoolProperty("ro.debuggable", false)) {
1869 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1870 "non-debuggable builds.";
1871 }
1872 BinderLibTest::SetUp();
1873 }
1874
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001875 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001876 auto rpcServer = RpcServer::make();
1877 EXPECT_NE(nullptr, rpcServer);
1878 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001879 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001880 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1881 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001882 return {};
1883 }
1884 return {rpcServer->releaseServer(), port};
1885 }
1886};
1887
Yifan Hong8b890852021-06-10 13:44:09 -07001888class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001889
Yifan Hongbd276552022-02-28 15:28:51 -08001890// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1891// If device is debuggable AND not on user builds, expects matcher.
1892// Otherwise expects INVALID_OPERATION.
1893// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1894static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1895 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1896 android::base::GetProperty("ro.build.type", "") != "user";
1897 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1898}
1899
Yifan Hong8b890852021-06-10 13:44:09 -07001900TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1901 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001902 ASSERT_TRUE(binder != nullptr);
1903 auto [socket, port] = CreateSocket();
1904 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001905 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1906 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001907}
1908
Yifan Hong8b890852021-06-10 13:44:09 -07001909// Tests for multiple RpcServer's on the same binder object.
1910TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1911 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001912 ASSERT_TRUE(binder != nullptr);
1913
1914 auto [socket1, port1] = CreateSocket();
1915 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001916 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001917 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1918 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001919
1920 auto [socket2, port2] = CreateSocket();
1921 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001922 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001923 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1924 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001925}
1926
Yifan Hong8b890852021-06-10 13:44:09 -07001927// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1928// local binders.
1929class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001930public:
1931 sp<IBinder> GetService() {
1932 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1933 }
1934 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1935 return info.param ? "remote" : "local";
1936 }
1937};
1938
Yifan Hong8b890852021-06-10 13:44:09 -07001939TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1940 auto binder = GetService();
1941 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001942 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001943 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001944}
1945
1946TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001947 auto binder = GetService();
1948 ASSERT_TRUE(binder != nullptr);
1949 auto [socket, port] = CreateSocket();
1950 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001951 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1952 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001953}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001954INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1955 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001956
Yifan Hong543edcd2021-05-18 19:47:30 -07001957class BinderLibTestService : public BBinder {
1958public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001959 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1960 : m_id(id),
1961 m_nextServerId(id + 1),
1962 m_serverStartRequested(false),
1963 m_callback(nullptr),
1964 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001965 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1966 pthread_cond_init(&m_serverWaitCond, nullptr);
1967 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001968 ~BinderLibTestService() {
1969 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1970 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001971
Yifan Hong543edcd2021-05-18 19:47:30 -07001972 void processPendingCall() {
1973 if (m_callback != nullptr) {
1974 Parcel data;
1975 data.writeInt32(NO_ERROR);
1976 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1977 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001978 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001979 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001980
Yifan Hong543edcd2021-05-18 19:47:30 -07001981 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1982 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001983 // TODO(b/182914638): also checks getCallingUid() for RPC
1984 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001985 return PERMISSION_DENIED;
1986 }
1987 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001988 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001989 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001990 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001991 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001992 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001993 return BAD_VALUE;
1994 }
1995
Yifan Hong543edcd2021-05-18 19:47:30 -07001996 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001997
1998 pthread_mutex_lock(&m_serverWaitMutex);
1999 if (m_serverStartRequested) {
2000 m_serverStartRequested = false;
2001 m_serverStarted = binder;
2002 pthread_cond_signal(&m_serverWaitCond);
2003 }
2004 pthread_mutex_unlock(&m_serverWaitMutex);
2005 return NO_ERROR;
2006 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002007 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08002008 case BINDER_LIB_TEST_ADD_SERVER: {
2009 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002010 int serverid;
2011
2012 if (m_id != 0) {
2013 return INVALID_OPERATION;
2014 }
2015 pthread_mutex_lock(&m_serverWaitMutex);
2016 if (m_serverStartRequested) {
2017 ret = -EBUSY;
2018 } else {
2019 serverid = m_nextServerId++;
2020 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002021 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002022
2023 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002024 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002025 pthread_mutex_lock(&m_serverWaitMutex);
2026 }
2027 if (ret > 0) {
2028 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002029 struct timespec ts;
2030 clock_gettime(CLOCK_REALTIME, &ts);
2031 ts.tv_sec += 5;
2032 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002033 }
2034 if (m_serverStartRequested) {
2035 m_serverStartRequested = false;
2036 ret = -ETIMEDOUT;
2037 } else {
2038 reply->writeStrongBinder(m_serverStarted);
2039 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07002040 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002041 ret = NO_ERROR;
2042 }
2043 } else if (ret >= 0) {
2044 m_serverStartRequested = false;
2045 ret = UNKNOWN_ERROR;
2046 }
2047 pthread_mutex_unlock(&m_serverWaitMutex);
2048 return ret;
2049 }
Steven Moreland35626652021-05-15 01:32:04 +00002050 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
2051 IPCThreadState::SpGuard spGuard{
2052 .address = __builtin_frame_address(0),
2053 .context = "GuardInBinderTransaction",
2054 };
2055 const IPCThreadState::SpGuard *origGuard =
2056 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2057
2058 // if the guard works, this should abort
2059 (void)IPCThreadState::self()->getCallingPid();
2060
2061 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
2062 return NO_ERROR;
2063 }
2064
Marco Ballesio7ee17572020-09-08 10:30:03 -07002065 case BINDER_LIB_TEST_GETPID:
2066 reply->writeInt32(getpid());
2067 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07002068 case BINDER_LIB_TEST_GETUID:
2069 reply->writeInt32(getuid());
2070 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07002071 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
2072 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00002073 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08002074 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00002075 // oneway error codes should be ignored
2076 if (flags & TF_ONE_WAY) {
2077 return UNKNOWN_ERROR;
2078 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002079 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002080 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
2081 // Note: this transaction is only designed for use with a
2082 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07002083 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02002084 // A callback was already pending; this means that
2085 // we received a second call while still processing
2086 // the first one. Fail the test.
2087 sp<IBinder> callback = data.readStrongBinder();
2088 Parcel data2;
2089 data2.writeInt32(UNKNOWN_ERROR);
2090
Yi Kong91635562018-06-07 14:38:36 -07002091 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002092 } else {
2093 m_callback = data.readStrongBinder();
2094 int32_t delayUs = data.readInt32();
2095 /*
2096 * It's necessary that we sleep here, so the next
2097 * transaction the caller makes will be queued to
2098 * the async queue.
2099 */
2100 usleep(delayUs);
2101
2102 /*
2103 * Now when we return, libbinder will tell the kernel
2104 * we are done with this transaction, and the kernel
2105 * can move the queued transaction to either the
2106 * thread todo worklist (for kernels without the fix),
2107 * or the proc todo worklist. In case of the former,
2108 * the next outbound call will pick up the pending
2109 * transaction, which leads to undesired reentrant
2110 * behavior. This is caught in the if() branch above.
2111 */
2112 }
2113
2114 return NO_ERROR;
2115 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002116 case BINDER_LIB_TEST_NOP_CALL_BACK: {
2117 Parcel data2, reply2;
2118 sp<IBinder> binder;
2119 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002120 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002121 return BAD_VALUE;
2122 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02002123 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002124 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2125 return NO_ERROR;
2126 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07002127 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
2128 reply->writeStrongBinder(this);
2129 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002130 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
2131 reply->writeInt32(m_id);
2132 return NO_ERROR;
2133 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
2134 int32_t count;
2135 uint32_t indirect_code;
2136 sp<IBinder> binder;
2137
2138 count = data.readInt32();
2139 reply->writeInt32(m_id);
2140 reply->writeInt32(count);
2141 for (int i = 0; i < count; i++) {
2142 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002143 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002144 return BAD_VALUE;
2145 }
2146 indirect_code = data.readInt32();
2147 BinderLibTestBundle data2(&data);
2148 if (!data2.isValid()) {
2149 return BAD_VALUE;
2150 }
2151 BinderLibTestBundle reply2;
2152 binder->transact(indirect_code, data2, &reply2);
2153 reply2.appendTo(reply);
2154 }
2155 return NO_ERROR;
2156 }
2157 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
2158 reply->setError(data.readInt32());
2159 return NO_ERROR;
2160 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
2161 reply->writeInt32(sizeof(void *));
2162 return NO_ERROR;
2163 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
2164 return NO_ERROR;
2165 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
2166 m_strongRef = data.readStrongBinder();
2167 return NO_ERROR;
2168 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
2169 int ret;
2170 Parcel data2, reply2;
2171 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
2172 sp<IBinder> target;
2173 sp<IBinder> callback;
2174
2175 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002176 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002177 return BAD_VALUE;
2178 }
2179 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002180 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002181 return BAD_VALUE;
2182 }
2183 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07002184 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002185 data2.writeInt32(ret);
2186 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2187 return NO_ERROR;
2188 }
2189 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
2190 int ret;
2191 int32_t size;
2192 const void *buf;
2193 int fd;
2194
2195 fd = data.readFileDescriptor();
2196 if (fd < 0) {
2197 return BAD_VALUE;
2198 }
2199 ret = data.readInt32(&size);
2200 if (ret != NO_ERROR) {
2201 return ret;
2202 }
2203 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07002204 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002205 return BAD_VALUE;
2206 }
2207 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07002208 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002209 return NO_ERROR;
2210 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09002211 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
2212 int ret;
2213 int32_t size;
2214 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002215 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09002216
2217 ret = data.readUniqueParcelFileDescriptor(&fd);
2218 if (ret != NO_ERROR) {
2219 return ret;
2220 }
2221 ret = data.readInt32(&size);
2222 if (ret != NO_ERROR) {
2223 return ret;
2224 }
2225 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07002226 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09002227 return BAD_VALUE;
2228 }
2229 ret = write(fd.get(), buf, size);
2230 if (ret != size) return UNKNOWN_ERROR;
2231 return NO_ERROR;
2232 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002233 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
2234 alarm(10);
2235 return NO_ERROR;
2236 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07002237 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002238 ;
2239 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002240 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07002241 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07002242 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002243 return NO_ERROR;
2244 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002245 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
2246 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00002247 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002248 return NO_ERROR;
2249 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00002250 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
2251 int policy = 0;
2252 sched_param param;
2253 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
2254 return UNKNOWN_ERROR;
2255 }
2256 reply->writeInt32(policy);
2257 reply->writeInt32(param.sched_priority);
2258 return NO_ERROR;
2259 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002260 case BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE: {
2261 sp<IBinder> binder = data.readStrongBinder();
2262 frozenStateChangeCallback = sp<TestFrozenStateChangeCallback>::make();
2263 // Hold an strong pointer to the binder object so it doesn't go
2264 // away.
2265 frozenStateChangeCallback->binder = binder;
2266 int ret = binder->addFrozenStateChangeCallback(frozenStateChangeCallback);
2267 if (ret != NO_ERROR) {
2268 return ret;
2269 }
Yu-Ting Tsengc08e4712024-10-10 17:51:44 -07002270 auto event = frozenStateChangeCallback->events.popWithTimeout(1000ms);
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002271 if (!event.has_value()) {
2272 return NOT_ENOUGH_DATA;
2273 }
2274 return NO_ERROR;
2275 }
2276 case BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS: {
2277 reply->writeBoolVector(frozenStateChangeCallback->getAllAndClear());
2278 return NO_ERROR;
2279 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002280 case BINDER_LIB_TEST_ECHO_VECTOR: {
2281 std::vector<uint64_t> vector;
2282 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07002283 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002284 reply->writeUint64Vector(vector);
2285 return NO_ERROR;
2286 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002287 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
2288 std::array<int, 2> sockets;
2289 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
2290 if (!created) {
2291 ALOGE("Could not create socket pair");
2292 return UNKNOWN_ERROR;
2293 }
2294
2295 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2296 if (result != 0) {
2297 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2298 return UNKNOWN_ERROR;
2299 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002300 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002301 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2302 if (writeResult != NO_ERROR) {
2303 ALOGE("Could not write unique_fd");
2304 return writeResult;
2305 }
2306 close(sockets[1]); // we don't need the other side of the fd
2307 return NO_ERROR;
2308 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07002309 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02002310 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2311 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00002312 case BINDER_LIB_TEST_CAN_GET_SID: {
2313 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2314 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002315 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2316 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2317 return NO_ERROR;
2318 }
Devin Moore4354f712022-12-08 01:44:46 +00002319 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2320 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2321 return NO_ERROR;
2322 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002323 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002324 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002325 return NO_ERROR;
2326 }
2327 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002328 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002329 return NO_ERROR;
2330 }
2331 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2332 int32_t ms = data.readInt32();
2333 return unlockInMs(ms);
2334 }
2335 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002336 m_blockMutex.lock();
2337 sp<BinderLibTestService> thisService = this;
2338 int32_t value = data.readInt32();
2339 // start local thread to unlock in 1s
2340 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002341 t.detach();
2342 return NO_ERROR;
2343 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002344 default:
2345 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002346 };
2347 }
2348
Elie Kheirallah47431c12022-04-21 23:46:17 +00002349 status_t unlockInMs(int32_t ms) {
2350 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002351 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002352 return NO_ERROR;
2353 }
2354
Yifan Hong543edcd2021-05-18 19:47:30 -07002355private:
2356 int32_t m_id;
2357 int32_t m_nextServerId;
2358 pthread_mutex_t m_serverWaitMutex;
2359 pthread_cond_t m_serverWaitCond;
2360 bool m_serverStartRequested;
2361 sp<IBinder> m_serverStarted;
2362 sp<IBinder> m_strongRef;
2363 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002364 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002365 std::mutex m_blockMutex;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002366 sp<TestFrozenStateChangeCallback> frozenStateChangeCallback;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002367};
2368
Martijn Coenen45b07b42017-08-09 12:07:45 +02002369int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002370{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002371 binderLibTestServiceName += String16(binderserversuffix);
2372
Steven Moreland35626652021-05-15 01:32:04 +00002373 // Testing to make sure that calls that we are serving can use getCallin*
2374 // even though we don't here.
2375 IPCThreadState::SpGuard spGuard{
2376 .address = __builtin_frame_address(0),
2377 .context = "main server thread",
2378 };
2379 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2380
Riley Andrews06b01ad2014-12-18 12:10:08 -08002381 status_t ret;
2382 sp<IServiceManager> sm = defaultServiceManager();
Parth Sanedc207542024-11-14 11:49:08 +00002383 sm->enableAddServiceCache(false);
2384
Martijn Coenen45b07b42017-08-09 12:07:45 +02002385 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002386 {
2387 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002388
Steven Morelandbf1915b2020-07-16 22:43:02 +00002389 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2390
Steven Morelandcf03cf12020-12-04 02:58:40 +00002391 testService->setInheritRt(true);
2392
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002393 /*
2394 * Normally would also contain functionality as well, but we are only
2395 * testing the extension mechanism.
2396 */
2397 testService->setExtension(new BBinder());
2398
Martijn Coenen82c75312019-07-24 15:18:30 +02002399 // Required for test "BufRejected'
2400 testService->setRequestingSid(true);
2401
Martijn Coenen45b07b42017-08-09 12:07:45 +02002402 /*
2403 * We need this below, but can't hold a sp<> because it prevents the
2404 * node from being cleaned up automatically. It's safe in this case
2405 * because of how the tests are written.
2406 */
2407 testServicePtr = testService.get();
2408
Riley Andrews06b01ad2014-12-18 12:10:08 -08002409 if (index == 0) {
2410 ret = sm->addService(binderLibTestServiceName, testService);
2411 } else {
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002412 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -08002413 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002414 LIBBINDER_IGNORE_END()
Riley Andrews06b01ad2014-12-18 12:10:08 -08002415 Parcel data, reply;
2416 data.writeInt32(index);
2417 data.writeStrongBinder(testService);
2418
2419 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2420 }
2421 }
2422 write(readypipefd, &ret, sizeof(ret));
2423 close(readypipefd);
2424 //printf("%s: ret %d\n", __func__, ret);
2425 if (ret)
2426 return 1;
2427 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002428 if (usePoll) {
2429 int fd;
2430 struct epoll_event ev;
2431 int epoll_fd;
2432 IPCThreadState::self()->setupPolling(&fd);
2433 if (fd < 0) {
2434 return 1;
2435 }
2436 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2437
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002438 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002439 if (epoll_fd == -1) {
2440 return 1;
2441 }
2442
2443 ev.events = EPOLLIN;
2444 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2445 return 1;
2446 }
2447
2448 while (1) {
2449 /*
2450 * We simulate a single-threaded process using the binder poll
2451 * interface; besides handling binder commands, it can also
2452 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002453 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002454 *
2455 * processPendingCall() will then issue that transaction.
2456 */
2457 struct epoll_event events[1];
2458 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2459 if (numEvents < 0) {
2460 if (errno == EINTR) {
2461 continue;
2462 }
2463 return 1;
2464 }
2465 if (numEvents > 0) {
2466 IPCThreadState::self()->handlePolledCommands();
2467 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2468 testServicePtr->processPendingCall();
2469 }
2470 }
2471 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002472 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002473 ProcessState::self()->startThreadPool();
2474 IPCThreadState::self()->joinThreadPool();
2475 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002476 //printf("%s: joinThreadPool returned\n", __func__);
2477 return 1; /* joinThreadPool should not return */
2478}
2479
Steven Moreland68275d72023-04-21 22:12:45 +00002480int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002481 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002482 binderservername = argv[2];
2483 } else {
2484 binderservername = argv[0];
2485 }
2486
Martijn Coenen45b07b42017-08-09 12:07:45 +02002487 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2488 binderserversuffix = argv[5];
2489 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002490 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002491 binderserversuffix = new char[16];
2492 snprintf(binderserversuffix, 16, "%d", getpid());
2493 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002494
2495 ::testing::InitGoogleTest(&argc, argv);
2496 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2497 ProcessState::self()->startThreadPool();
2498 return RUN_ALL_TESTS();
2499}