blob: 9e92f95416e7ec3d87e64e0bc32750bcd0aacefe [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>
Frederick Maylef2163b82024-09-30 17:42:45 -070049#include <sys/mman.h>
Steven Morelandda048352020-02-19 13:25:53 -080050#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070051#include <sys/socket.h>
52#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020053
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -070054#include "../Utils.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000055#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070056
Riley Andrews06b01ad2014-12-18 12:10:08 -080057using namespace android;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000058using namespace android::binder::impl;
Yifan Hong84bedeb2021-04-21 21:37:17 -070059using namespace std::string_literals;
60using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070061using android::base::testing::HasValue;
Parth Sane81b4d5a2024-05-23 14:11:13 +000062using android::binder::Status;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070063using android::binder::unique_fd;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070064using std::chrono_literals::operator""ms;
Yifan Hong84bedeb2021-04-21 21:37:17 -070065using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080066using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070067using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070068using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070069
70// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
71MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
72 *result_listener << statusToString(arg);
73 return expected == arg;
74}
Riley Andrews06b01ad2014-12-18 12:10:08 -080075
Sherry Yang336cdd32017-07-24 14:12:27 -070076static ::testing::AssertionResult IsPageAligned(void *buf) {
Vilas Bhat04e28c72024-02-12 21:47:15 +000077 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
Sherry Yang336cdd32017-07-24 14:12:27 -070078 return ::testing::AssertionSuccess();
79 else
80 return ::testing::AssertionFailure() << buf << " is not page aligned";
81}
82
Riley Andrews06b01ad2014-12-18 12:10:08 -080083static testing::Environment* binder_env;
84static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070085static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080086static char binderserverarg[] = "--binderserver";
87
Steven Morelandbf1915b2020-07-16 22:43:02 +000088static constexpr int kSchedPolicy = SCHED_RR;
89static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000090static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000091static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000092
Riley Andrews06b01ad2014-12-18 12:10:08 -080093static String16 binderLibTestServiceName = String16("test.binderLib");
94
95enum BinderLibTestTranscationCode {
96 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
97 BINDER_LIB_TEST_REGISTER_SERVER,
98 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020099 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +0000100 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800101 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -0700102 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200103 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800104 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700105 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800106 BINDER_LIB_TEST_GET_ID_TRANSACTION,
107 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
108 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
109 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
110 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
111 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
112 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900113 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Frederick Maylef2163b82024-09-30 17:42:45 -0700114 BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION,
115 BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800116 BINDER_LIB_TEST_EXIT_TRANSACTION,
117 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
118 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700119 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100120 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000121 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700122 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
123 BINDER_LIB_TEST_GETPID,
Jing Jibdbe29a2023-10-03 00:03:28 -0700124 BINDER_LIB_TEST_GETUID,
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700125 BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE,
126 BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800127 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700128 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700129 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000130 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000131 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
132 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000133 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000134 BINDER_LIB_TEST_LOCK_UNLOCK,
135 BINDER_LIB_TEST_PROCESS_LOCK,
136 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
137 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800138};
139
Martijn Coenen45b07b42017-08-09 12:07:45 +0200140pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800141{
142 int ret;
143 pid_t pid;
144 status_t status;
145 int pipefd[2];
146 char stri[16];
147 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200148 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800149 char *childargv[] = {
150 binderservername,
151 binderserverarg,
152 stri,
153 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200154 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700155 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700156 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800157 };
158
159 ret = pipe(pipefd);
160 if (ret < 0)
161 return ret;
162
163 snprintf(stri, sizeof(stri), "%d", arg2);
164 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200165 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800166
167 pid = fork();
168 if (pid == -1)
169 return pid;
170 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800171 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800172 close(pipefd[0]);
173 execv(binderservername, childargv);
174 status = -errno;
175 write(pipefd[1], &status, sizeof(status));
176 fprintf(stderr, "execv failed, %s\n", strerror(errno));
177 _exit(EXIT_FAILURE);
178 }
179 close(pipefd[1]);
180 ret = read(pipefd[0], &status, sizeof(status));
181 //printf("pipe read returned %d, status %d\n", ret, status);
182 close(pipefd[0]);
183 if (ret == sizeof(status)) {
184 ret = status;
185 } else {
186 kill(pid, SIGKILL);
187 if (ret >= 0) {
188 ret = NO_INIT;
189 }
190 }
191 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700192 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800193 return ret;
194 }
195 return pid;
196}
197
Yifan Hong84bedeb2021-04-21 21:37:17 -0700198android::base::Result<int32_t> GetId(sp<IBinder> service) {
199 using android::base::Error;
200 Parcel data, reply;
201 data.markForBinder(service);
202 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
203 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
204 if (status != OK)
205 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
206 int32_t result = 0;
207 status = reply.readInt32(&result);
208 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
209 return result;
210}
211
Riley Andrews06b01ad2014-12-18 12:10:08 -0800212class BinderLibTestEnv : public ::testing::Environment {
213 public:
214 BinderLibTestEnv() {}
215 sp<IBinder> getServer(void) {
216 return m_server;
217 }
218
219 private:
220 virtual void SetUp() {
221 m_serverpid = start_server_process(0);
222 //printf("m_serverpid %d\n", m_serverpid);
223 ASSERT_GT(m_serverpid, 0);
224
225 sp<IServiceManager> sm = defaultServiceManager();
Parth Sanedc207542024-11-14 11:49:08 +0000226 // disable caching during addService.
227 sm->enableAddServiceCache(false);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800228 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700229 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -0800230 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700231 LIBBINDER_IGNORE_END()
Yi Kong91635562018-06-07 14:38:36 -0700232 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800233 //printf("%s: pid %d, get service done\n", __func__, m_pid);
234 }
235 virtual void TearDown() {
236 status_t ret;
237 Parcel data, reply;
238 int exitStatus;
239 pid_t pid;
240
241 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700242 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800243 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
244 EXPECT_EQ(0, ret);
245 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
246 EXPECT_EQ(0, ret);
247 }
248 if (m_serverpid > 0) {
249 //printf("wait for %d\n", m_pids[i]);
250 pid = wait(&exitStatus);
251 EXPECT_EQ(m_serverpid, pid);
252 EXPECT_TRUE(WIFEXITED(exitStatus));
253 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
254 }
255 }
256
257 pid_t m_serverpid;
258 sp<IBinder> m_server;
259};
260
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700261class TestFrozenStateChangeCallback : public IBinder::FrozenStateChangeCallback {
262public:
263 BlockingQueue<std::pair<const wp<IBinder>, State>> events;
264
265 virtual void onStateChanged(const wp<IBinder>& who, State state) {
266 events.push(std::make_pair(who, state));
267 }
268
269 void ensureFrozenEventReceived() {
270 auto event = events.popWithTimeout(500ms);
271 ASSERT_TRUE(event.has_value());
272 EXPECT_EQ(State::FROZEN, event->second); // isFrozen should be true
273 EXPECT_EQ(0u, events.size());
274 }
275
276 void ensureUnfrozenEventReceived() {
277 auto event = events.popWithTimeout(500ms);
278 ASSERT_TRUE(event.has_value());
279 EXPECT_EQ(State::UNFROZEN, event->second); // isFrozen should be false
280 EXPECT_EQ(0u, events.size());
281 }
282
283 std::vector<bool> getAllAndClear() {
284 std::vector<bool> results;
285 while (true) {
286 auto event = events.popWithTimeout(0ms);
287 if (!event.has_value()) {
288 break;
289 }
290 results.push_back(event->second == State::FROZEN);
291 }
292 return results;
293 }
294
295 sp<IBinder> binder;
296};
297
Riley Andrews06b01ad2014-12-18 12:10:08 -0800298class BinderLibTest : public ::testing::Test {
299 public:
300 virtual void SetUp() {
301 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Parth Sane81b4d5a2024-05-23 14:11:13 +0000302 IPCThreadState::self()->restoreCallingWorkSource(0);
Parth Sanedc207542024-11-14 11:49:08 +0000303 sp<IServiceManager> sm = defaultServiceManager();
304 // disable caching during addService.
305 sm->enableAddServiceCache(false);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800306 }
307 virtual void TearDown() {
308 }
309 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200310 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800311 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800312 int32_t id;
313 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800314
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700315 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800316
Elie Kheirallahb7246642022-05-03 18:01:43 +0000317 sp<IBinder> binder = reply.readStrongBinder();
318 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700319 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800320 if (idPtr)
321 *idPtr = id;
322 return binder;
323 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200324
Yi Kong91635562018-06-07 14:38:36 -0700325 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200326 {
327 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
328 }
329
Yi Kong91635562018-06-07 14:38:36 -0700330 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200331 {
332 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
333 }
334
Riley Andrews06b01ad2014-12-18 12:10:08 -0800335 void waitForReadData(int fd, int timeout_ms) {
336 int ret;
337 pollfd pfd = pollfd();
338
339 pfd.fd = fd;
340 pfd.events = POLLIN;
341 ret = poll(&pfd, 1, timeout_ms);
342 EXPECT_EQ(1, ret);
343 }
344
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700345 bool checkFreezeSupport() {
346 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
347 // Pass test on devices where the cgroup v2 freezer is not supported
348 if (freezer_file.fail()) {
349 return false;
350 }
351 return IPCThreadState::self()->freeze(getpid(), false, 0) == NO_ERROR;
352 }
353
354 bool checkFreezeAndNotificationSupport() {
355 if (!checkFreezeSupport()) {
356 return false;
357 }
358 return ProcessState::isDriverFeatureEnabled(
359 ProcessState::DriverFeature::FREEZE_NOTIFICATION);
360 }
361
362 bool getBinderPid(int32_t* pid, sp<IBinder> server) {
363 Parcel data, replypid;
364 if (server->transact(BINDER_LIB_TEST_GETPID, data, &replypid) != NO_ERROR) {
365 ALOGE("BINDER_LIB_TEST_GETPID failed");
366 return false;
367 }
368 *pid = replypid.readInt32();
369 if (*pid <= 0) {
370 ALOGE("pid should be greater than zero");
371 return false;
372 }
373 return true;
374 }
375
376 void freezeProcess(int32_t pid) {
377 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
378 }
379
380 void unfreezeProcess(int32_t pid) {
381 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
382 }
383
384 void removeCallbackAndValidateNoEvent(sp<IBinder> binder,
385 sp<TestFrozenStateChangeCallback> callback) {
386 EXPECT_THAT(binder->removeFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
387 EXPECT_EQ(0u, callback->events.size());
388 }
389
Riley Andrews06b01ad2014-12-18 12:10:08 -0800390 sp<IBinder> m_server;
391};
392
393class BinderLibTestBundle : public Parcel
394{
395 public:
396 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800397 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800398 int32_t mark;
399 int32_t bundleLen;
400 size_t pos;
401
402 if (source->readInt32(&mark))
403 return;
404 if (mark != MARK_START)
405 return;
406 if (source->readInt32(&bundleLen))
407 return;
408 pos = source->dataPosition();
409 if (Parcel::appendFrom(source, pos, bundleLen))
410 return;
411 source->setDataPosition(pos + bundleLen);
412 if (source->readInt32(&mark))
413 return;
414 if (mark != MARK_END)
415 return;
416 m_isValid = true;
417 setDataPosition(0);
418 }
419 void appendTo(Parcel *dest) {
420 dest->writeInt32(MARK_START);
421 dest->writeInt32(dataSize());
422 dest->appendFrom(this, 0, dataSize());
423 dest->writeInt32(MARK_END);
424 };
425 bool isValid(void) {
426 return m_isValid;
427 }
428 private:
429 enum {
430 MARK_START = B_PACK_CHARS('B','T','B','S'),
431 MARK_END = B_PACK_CHARS('B','T','B','E'),
432 };
433 bool m_isValid;
434};
435
436class BinderLibTestEvent
437{
438 public:
439 BinderLibTestEvent(void)
440 : m_eventTriggered(false)
441 {
Yi Kong91635562018-06-07 14:38:36 -0700442 pthread_mutex_init(&m_waitMutex, nullptr);
443 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800444 }
445 int waitEvent(int timeout_s)
446 {
447 int ret;
448 pthread_mutex_lock(&m_waitMutex);
449 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800450 struct timespec ts;
451 clock_gettime(CLOCK_REALTIME, &ts);
452 ts.tv_sec += timeout_s;
453 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800454 }
455 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
456 pthread_mutex_unlock(&m_waitMutex);
457 return ret;
458 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200459 pthread_t getTriggeringThread()
460 {
461 return m_triggeringThread;
462 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800463 protected:
464 void triggerEvent(void) {
465 pthread_mutex_lock(&m_waitMutex);
466 pthread_cond_signal(&m_waitCond);
467 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200468 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800469 pthread_mutex_unlock(&m_waitMutex);
470 };
471 private:
472 pthread_mutex_t m_waitMutex;
473 pthread_cond_t m_waitCond;
474 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200475 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800476};
477
478class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
479{
480 public:
481 BinderLibTestCallBack()
482 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700483 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800484 {
485 }
486 status_t getResult(void)
487 {
488 return m_result;
489 }
490
491 private:
492 virtual status_t onTransact(uint32_t code,
493 const Parcel& data, Parcel* reply,
494 uint32_t flags = 0)
495 {
496 (void)reply;
497 (void)flags;
498 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200499 case BINDER_LIB_TEST_CALL_BACK: {
500 status_t status = data.readInt32(&m_result);
501 if (status != NO_ERROR) {
502 m_result = status;
503 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800504 triggerEvent();
505 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200506 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700507 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
508 sp<IBinder> server;
509 int ret;
510 const uint8_t *buf = data.data();
511 size_t size = data.dataSize();
512 if (m_prev_end) {
513 /* 64-bit kernel needs at most 8 bytes to align buffer end */
514 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
515 } else {
516 EXPECT_TRUE(IsPageAligned((void *)buf));
517 }
518
519 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
520
521 if (size > 0) {
522 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
523 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
524 data, reply);
525 EXPECT_EQ(NO_ERROR, ret);
526 }
527 return NO_ERROR;
528 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800529 default:
530 return UNKNOWN_TRANSACTION;
531 }
532 }
533
534 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700535 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800536};
537
538class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
539{
540 private:
541 virtual void binderDied(const wp<IBinder>& who) {
542 (void)who;
543 triggerEvent();
544 };
545};
546
Frederick Maylef2163b82024-09-30 17:42:45 -0700547ssize_t countFds() {
548 return std::distance(std::filesystem::directory_iterator("/proc/self/fd"),
549 std::filesystem::directory_iterator{});
550}
551
552struct FdLeakDetector {
553 int startCount;
554
555 FdLeakDetector() {
556 // This log statement is load bearing. We have to log something before
557 // counting FDs to make sure the logging system is initialized, otherwise
558 // the sockets it opens will look like a leak.
559 ALOGW("FdLeakDetector counting FDs.");
560 startCount = countFds();
561 }
562 ~FdLeakDetector() {
563 int endCount = countFds();
564 if (startCount != endCount) {
565 ADD_FAILURE() << "fd count changed (" << startCount << " -> " << endCount
566 << ") fd leak?";
567 }
568 }
569};
570
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700571TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
572 // EXPECT_DEATH works by forking the process
573 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
574}
575
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000576TEST_F(BinderLibTest, AddManagerToManager) {
577 sp<IServiceManager> sm = defaultServiceManager();
578 sp<IBinder> binder = IInterface::asBinder(sm);
579 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
580}
581
Parth Sane81b4d5a2024-05-23 14:11:13 +0000582TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
583 auto sm = defaultServiceManager();
584 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
585 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
586 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
587 virtual ~LocalRegistrationCallbackImpl() {}
588 };
589 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
590
591 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
592 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
593}
594
595TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
596 auto sm = defaultServiceManager();
597 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
598 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
599 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
600 virtual ~LocalRegistrationCallbackImpl() {}
601 };
602 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
603
604 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
605
606 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
607 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
608 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
609}
610
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500611TEST_F(BinderLibTest, WasParceled) {
612 auto binder = sp<BBinder>::make();
613 EXPECT_FALSE(binder->wasParceled());
614 Parcel data;
615 data.writeStrongBinder(binder);
616 EXPECT_TRUE(binder->wasParceled());
617}
618
Riley Andrews06b01ad2014-12-18 12:10:08 -0800619TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800620 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700621 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
622 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800623}
624
Steven Moreland80844f72020-12-12 02:06:08 +0000625TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000626 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700627 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
628 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000629}
630
Steven Morelandf183fdd2020-10-27 00:12:12 +0000631TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000632 Parcel data, reply;
633 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700634 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
635 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000636}
637
Marco Ballesio7ee17572020-09-08 10:30:03 -0700638TEST_F(BinderLibTest, Freeze) {
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700639 if (!checkFreezeSupport()) {
640 GTEST_SKIP() << "Skipping test for kernels that do not support proceess freezing";
Marco Ballesio7ee17572020-09-08 10:30:03 -0700641 return;
642 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700643 Parcel data, reply, replypid;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700644 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700645 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700646 for (int i = 0; i < 10; i++) {
647 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
648 }
Li Li6f059292021-09-10 09:59:30 -0700649
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700650 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Li Li6f059292021-09-10 09:59:30 -0700651 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000652
653 // b/268232063 - succeeds ~0.08% of the time
654 {
655 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
656 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
657 }
658
Li Li6f059292021-09-10 09:59:30 -0700659 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700660 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700661
Li Li4e678b92021-09-14 12:14:42 -0700662 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700663
664 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
665 &async_received));
666
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700667 EXPECT_EQ(sync_received, 1u);
668 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700669
Li Li4e678b92021-09-14 12:14:42 -0700670 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700671 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
672}
673
Riley Andrews06b01ad2014-12-18 12:10:08 -0800674TEST_F(BinderLibTest, SetError) {
675 int32_t testValue[] = { 0, -123, 123 };
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700676 for (size_t i = 0; i < countof(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800677 Parcel data, reply;
678 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700679 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
680 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800681 }
682}
683
684TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700685 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800686}
687
688TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800689 int32_t ptrsize;
690 Parcel data, reply;
691 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700692 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700693 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
694 StatusEq(NO_ERROR));
695 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800696 RecordProperty("TestPtrSize", sizeof(void *));
697 RecordProperty("ServerPtrSize", sizeof(void *));
698}
699
700TEST_F(BinderLibTest, IndirectGetId2)
701{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800702 int32_t id;
703 int32_t count;
704 Parcel data, reply;
705 int32_t serverId[3];
706
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700707 data.writeInt32(countof(serverId));
708 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800709 sp<IBinder> server;
710 BinderLibTestBundle datai;
711
712 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700713 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800714 data.writeStrongBinder(server);
715 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
716 datai.appendTo(&data);
717 }
718
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700719 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
720 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800721
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700722 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800723 EXPECT_EQ(0, id);
724
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700725 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700726 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800727
728 for (size_t i = 0; i < (size_t)count; i++) {
729 BinderLibTestBundle replyi(&reply);
730 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700731 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800732 EXPECT_EQ(serverId[i], id);
733 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
734 }
735
736 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
737}
738
739TEST_F(BinderLibTest, IndirectGetId3)
740{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800741 int32_t id;
742 int32_t count;
743 Parcel data, reply;
744 int32_t serverId[3];
745
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700746 data.writeInt32(countof(serverId));
747 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800748 sp<IBinder> server;
749 BinderLibTestBundle datai;
750 BinderLibTestBundle datai2;
751
752 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700753 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800754 data.writeStrongBinder(server);
755 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
756
757 datai.writeInt32(1);
758 datai.writeStrongBinder(m_server);
759 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
760 datai2.appendTo(&datai);
761
762 datai.appendTo(&data);
763 }
764
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700765 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
766 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800767
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700768 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800769 EXPECT_EQ(0, id);
770
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700771 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700772 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800773
774 for (size_t i = 0; i < (size_t)count; i++) {
775 int32_t counti;
776
777 BinderLibTestBundle replyi(&reply);
778 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700779 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800780 EXPECT_EQ(serverId[i], id);
781
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700782 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800783 EXPECT_EQ(1, counti);
784
785 BinderLibTestBundle replyi2(&replyi);
786 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700787 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800788 EXPECT_EQ(0, id);
789 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
790
791 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
792 }
793
794 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
795}
796
797TEST_F(BinderLibTest, CallBack)
798{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800799 Parcel data, reply;
800 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
801 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700802 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
803 StatusEq(NO_ERROR));
804 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
805 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800806}
807
Steven Moreland35626652021-05-15 01:32:04 +0000808TEST_F(BinderLibTest, BinderCallContextGuard) {
809 sp<IBinder> binder = addServer();
810 Parcel data, reply;
811 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
812 StatusEq(DEAD_OBJECT));
813}
814
Riley Andrews06b01ad2014-12-18 12:10:08 -0800815TEST_F(BinderLibTest, AddServer)
816{
817 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700818 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800819}
820
Riley Andrews06b01ad2014-12-18 12:10:08 -0800821TEST_F(BinderLibTest, DeathNotificationStrongRef)
822{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800823 sp<IBinder> sbinder;
824
825 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
826
827 {
828 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700829 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700830 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800831 sbinder = binder;
832 }
833 {
834 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700835 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
836 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800837 }
838 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700839 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
840 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800841}
842
843TEST_F(BinderLibTest, DeathNotificationMultiple)
844{
845 status_t ret;
846 const int clientcount = 2;
847 sp<IBinder> target;
848 sp<IBinder> linkedclient[clientcount];
849 sp<BinderLibTestCallBack> callBack[clientcount];
850 sp<IBinder> passiveclient[clientcount];
851
852 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700853 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800854 for (int i = 0; i < clientcount; i++) {
855 {
856 Parcel data, reply;
857
858 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700859 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800860 callBack[i] = new BinderLibTestCallBack();
861 data.writeStrongBinder(target);
862 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700863 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
864 &reply, TF_ONE_WAY),
865 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800866 }
867 {
868 Parcel data, reply;
869
870 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700871 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800872 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700873 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
874 &reply, TF_ONE_WAY),
875 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800876 }
877 }
878 {
879 Parcel data, reply;
880 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
881 EXPECT_EQ(0, ret);
882 }
883
884 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700885 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
886 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800887 }
888}
889
Martijn Coenenf7100e42017-07-31 12:14:09 +0200890TEST_F(BinderLibTest, DeathNotificationThread)
891{
892 status_t ret;
893 sp<BinderLibTestCallBack> callback;
894 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700895 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200896 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700897 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200898
899 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
900
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700901 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200902
903 {
904 Parcel data, reply;
905 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
906 EXPECT_EQ(0, ret);
907 }
908
909 /* Make sure it's dead */
910 testDeathRecipient->waitEvent(5);
911
912 /* Now, pass the ref to another process and ask that process to
913 * call linkToDeath() on it, and wait for a response. This tests
914 * two things:
915 * 1) You still get death notifications when calling linkToDeath()
916 * on a ref that is already dead when it was passed to you.
917 * 2) That death notifications are not directly pushed to the thread
918 * registering them, but to the threadpool (proc workqueue) instead.
919 *
920 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
921 * is blocked on a condition variable waiting for the death notification to be
922 * called; therefore, that thread is not available for handling proc work.
923 * So, if the death notification was pushed to the thread workqueue, the callback
924 * would never be called, and the test would timeout and fail.
925 *
926 * Note that we can't do this part of the test from this thread itself, because
927 * the binder driver would only push death notifications to the thread if
928 * it is a looper thread, which this thread is not.
929 *
930 * See b/23525545 for details.
931 */
932 {
933 Parcel data, reply;
934
935 callback = new BinderLibTestCallBack();
936 data.writeStrongBinder(target);
937 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700938 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
939 TF_ONE_WAY),
940 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200941 }
942
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700943 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
944 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200945}
946
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700947TEST_F(BinderLibTest, ReturnErrorIfKernelDoesNotSupportFreezeNotification) {
948 if (ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::FREEZE_NOTIFICATION)) {
949 GTEST_SKIP() << "Skipping test for kernels that support FREEZE_NOTIFICATION";
950 return;
951 }
952 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
953 sp<IBinder> binder = addServer();
954 ASSERT_NE(nullptr, binder);
955 ASSERT_EQ(nullptr, binder->localBinder());
956 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(INVALID_OPERATION));
957}
958
959TEST_F(BinderLibTest, FrozenStateChangeNotificatiion) {
960 if (!checkFreezeAndNotificationSupport()) {
961 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
962 return;
963 }
964 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
965 sp<IBinder> binder = addServer();
966 ASSERT_NE(nullptr, binder);
967 int32_t pid;
968 ASSERT_TRUE(getBinderPid(&pid, binder));
969
970 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
971 // Expect current state (unfrozen) to be delivered immediately.
972 callback->ensureUnfrozenEventReceived();
973 // Check that the process hasn't died otherwise there's a risk of freezing
974 // the wrong process.
975 EXPECT_EQ(OK, binder->pingBinder());
976 freezeProcess(pid);
977 callback->ensureFrozenEventReceived();
978 unfreezeProcess(pid);
979 callback->ensureUnfrozenEventReceived();
980 removeCallbackAndValidateNoEvent(binder, callback);
981}
982
983TEST_F(BinderLibTest, AddFrozenCallbackWhenFrozen) {
984 if (!checkFreezeAndNotificationSupport()) {
985 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
986 return;
987 }
988 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
989 sp<IBinder> binder = addServer();
990 ASSERT_NE(nullptr, binder);
991 int32_t pid;
992 ASSERT_TRUE(getBinderPid(&pid, binder));
993
994 // Check that the process hasn't died otherwise there's a risk of freezing
995 // the wrong process.
996 EXPECT_EQ(OK, binder->pingBinder());
997 freezeProcess(pid);
998 // Add the callback while the target process is frozen.
999 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1000 callback->ensureFrozenEventReceived();
1001 unfreezeProcess(pid);
1002 callback->ensureUnfrozenEventReceived();
1003 removeCallbackAndValidateNoEvent(binder, callback);
1004
1005 // Check that the process hasn't died otherwise there's a risk of freezing
1006 // the wrong process.
1007 EXPECT_EQ(OK, binder->pingBinder());
1008 freezeProcess(pid);
1009 unfreezeProcess(pid);
1010 // Make sure no callback happens since the listener has been removed.
1011 EXPECT_EQ(0u, callback->events.size());
1012}
1013
1014TEST_F(BinderLibTest, NoFrozenNotificationAfterCallbackRemoval) {
1015 if (!checkFreezeAndNotificationSupport()) {
1016 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1017 return;
1018 }
1019 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1020 sp<IBinder> binder = addServer();
1021 ASSERT_NE(nullptr, binder);
1022 int32_t pid;
1023 ASSERT_TRUE(getBinderPid(&pid, binder));
1024
1025 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1026 callback->ensureUnfrozenEventReceived();
1027 removeCallbackAndValidateNoEvent(binder, callback);
1028
1029 // Make sure no callback happens after the listener is removed.
1030 freezeProcess(pid);
1031 unfreezeProcess(pid);
1032 EXPECT_EQ(0u, callback->events.size());
1033}
1034
1035TEST_F(BinderLibTest, MultipleFrozenStateChangeCallbacks) {
1036 if (!checkFreezeAndNotificationSupport()) {
1037 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1038 return;
1039 }
1040 sp<TestFrozenStateChangeCallback> callback1 = sp<TestFrozenStateChangeCallback>::make();
1041 sp<TestFrozenStateChangeCallback> callback2 = sp<TestFrozenStateChangeCallback>::make();
1042 sp<IBinder> binder = addServer();
1043 ASSERT_NE(nullptr, binder);
1044 int32_t pid;
1045 ASSERT_TRUE(getBinderPid(&pid, binder));
1046
1047 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback1), StatusEq(NO_ERROR));
1048 // Expect current state (unfrozen) to be delivered immediately.
1049 callback1->ensureUnfrozenEventReceived();
1050
1051 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback2), StatusEq(NO_ERROR));
1052 // Expect current state (unfrozen) to be delivered immediately.
1053 callback2->ensureUnfrozenEventReceived();
1054
1055 freezeProcess(pid);
1056 callback1->ensureFrozenEventReceived();
1057 callback2->ensureFrozenEventReceived();
1058
1059 removeCallbackAndValidateNoEvent(binder, callback1);
1060 unfreezeProcess(pid);
1061 EXPECT_EQ(0u, callback1->events.size());
1062 callback2->ensureUnfrozenEventReceived();
1063 removeCallbackAndValidateNoEvent(binder, callback2);
1064
1065 freezeProcess(pid);
1066 EXPECT_EQ(0u, callback2->events.size());
1067}
1068
1069TEST_F(BinderLibTest, RemoveThenAddFrozenStateChangeCallbacks) {
1070 if (!checkFreezeAndNotificationSupport()) {
1071 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1072 return;
1073 }
1074 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1075 sp<IBinder> binder = addServer();
1076 ASSERT_NE(nullptr, binder);
1077 int32_t pid;
1078 ASSERT_TRUE(getBinderPid(&pid, binder));
1079
1080 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1081 // Expect current state (unfrozen) to be delivered immediately.
1082 callback->ensureUnfrozenEventReceived();
1083 removeCallbackAndValidateNoEvent(binder, callback);
1084
1085 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1086 callback->ensureUnfrozenEventReceived();
1087}
1088
1089TEST_F(BinderLibTest, CoalesceFreezeCallbacksWhenListenerIsFrozen) {
1090 if (!checkFreezeAndNotificationSupport()) {
1091 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1092 return;
1093 }
1094 sp<IBinder> binder = addServer();
1095 sp<IBinder> listener = addServer();
1096 ASSERT_NE(nullptr, binder);
1097 ASSERT_NE(nullptr, listener);
1098 int32_t pid, listenerPid;
1099 ASSERT_TRUE(getBinderPid(&pid, binder));
1100 ASSERT_TRUE(getBinderPid(&listenerPid, listener));
1101
1102 // Ask the listener process to register for state change callbacks.
1103 {
1104 Parcel data, reply;
1105 data.writeStrongBinder(binder);
1106 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE, data,
1107 &reply),
1108 StatusEq(NO_ERROR));
1109 }
1110 // Freeze the listener process.
1111 freezeProcess(listenerPid);
1112 createProcessGroup(getuid(), listenerPid);
1113 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Frozen"}));
1114 // Repeatedly flip the target process between frozen and unfrozen states.
1115 for (int i = 0; i < 1000; i++) {
1116 usleep(50);
1117 unfreezeProcess(pid);
1118 usleep(50);
1119 freezeProcess(pid);
1120 }
1121 // Unfreeze the listener process. Now it should receive the frozen state
1122 // change notifications.
1123 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Unfrozen"}));
1124 unfreezeProcess(listenerPid);
1125 // Wait for 500ms to give the process enough time to wake up and handle
1126 // notifications.
1127 usleep(500 * 1000);
1128 {
1129 std::vector<bool> events;
1130 Parcel data, reply;
1131 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS, data, &reply),
1132 StatusEq(NO_ERROR));
1133 reply.readBoolVector(&events);
1134 // There should only be one single state change notifications delievered.
1135 ASSERT_EQ(1u, events.size());
1136 EXPECT_TRUE(events[0]);
1137 }
1138}
1139
Riley Andrews06b01ad2014-12-18 12:10:08 -08001140TEST_F(BinderLibTest, PassFile) {
1141 int ret;
1142 int pipefd[2];
1143 uint8_t buf[1] = { 0 };
1144 uint8_t write_value = 123;
1145
1146 ret = pipe2(pipefd, O_NONBLOCK);
1147 ASSERT_EQ(0, ret);
1148
1149 {
1150 Parcel data, reply;
1151 uint8_t writebuf[1] = { write_value };
1152
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001153 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001154
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001155 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001156
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001157 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001158
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001159 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
1160 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001161 }
1162
1163 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -07001164 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001165 EXPECT_EQ(write_value, buf[0]);
1166
1167 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
1168
1169 ret = read(pipefd[0], buf, sizeof(buf));
1170 EXPECT_EQ(0, ret);
1171
1172 close(pipefd[0]);
1173}
1174
Ryo Hashimotobf551892018-05-31 16:58:35 +09001175TEST_F(BinderLibTest, PassParcelFileDescriptor) {
1176 const int datasize = 123;
1177 std::vector<uint8_t> writebuf(datasize);
1178 for (size_t i = 0; i < writebuf.size(); ++i) {
1179 writebuf[i] = i;
1180 }
1181
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001182 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001183 {
1184 int pipefd[2];
1185 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
1186 read_end.reset(pipefd[0]);
1187 write_end.reset(pipefd[1]);
1188 }
1189 {
1190 Parcel data;
1191 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
1192 write_end.reset();
1193 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
1194 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
1195
1196 Parcel reply;
1197 EXPECT_EQ(NO_ERROR,
1198 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
1199 &reply));
1200 }
1201 std::vector<uint8_t> readbuf(datasize);
1202 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
1203 EXPECT_EQ(writebuf, readbuf);
1204
1205 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
1206
1207 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
1208}
1209
Frederick Maylef2163b82024-09-30 17:42:45 -07001210TEST_F(BinderLibTest, RecvOwnedFileDescriptors) {
1211 FdLeakDetector fd_leak_detector;
1212
1213 Parcel data;
1214 Parcel reply;
1215 EXPECT_EQ(NO_ERROR,
1216 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1217 &reply));
1218 unique_fd a, b;
1219 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1220 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1221}
1222
1223// Used to trigger fdsan error (b/239222407).
1224TEST_F(BinderLibTest, RecvOwnedFileDescriptorsAndWriteInt) {
1225 GTEST_SKIP() << "triggers fdsan false positive: b/370824489";
1226
1227 FdLeakDetector fd_leak_detector;
1228
1229 Parcel data;
1230 Parcel reply;
1231 EXPECT_EQ(NO_ERROR,
1232 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1233 &reply));
1234 reply.setDataPosition(reply.dataSize());
1235 reply.writeInt32(0);
1236 reply.setDataPosition(0);
1237 unique_fd a, b;
1238 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1239 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1240}
1241
1242// Used to trigger fdsan error (b/239222407).
1243TEST_F(BinderLibTest, RecvOwnedFileDescriptorsAndTruncate) {
1244 GTEST_SKIP() << "triggers fdsan false positive: b/370824489";
1245
1246 FdLeakDetector fd_leak_detector;
1247
1248 Parcel data;
1249 Parcel reply;
1250 EXPECT_EQ(NO_ERROR,
1251 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1252 &reply));
1253 reply.setDataSize(reply.dataSize() - sizeof(flat_binder_object));
1254 unique_fd a, b;
1255 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1256 EXPECT_EQ(BAD_TYPE, reply.readUniqueFileDescriptor(&b));
1257}
1258
1259TEST_F(BinderLibTest, RecvUnownedFileDescriptors) {
1260 FdLeakDetector fd_leak_detector;
1261
1262 Parcel data;
1263 Parcel reply;
1264 EXPECT_EQ(NO_ERROR,
1265 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1266 &reply));
1267 unique_fd a, b;
1268 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1269 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1270}
1271
1272// Used to trigger fdsan error (b/239222407).
1273TEST_F(BinderLibTest, RecvUnownedFileDescriptorsAndWriteInt) {
1274 FdLeakDetector fd_leak_detector;
1275
1276 Parcel data;
1277 Parcel reply;
1278 EXPECT_EQ(NO_ERROR,
1279 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1280 &reply));
1281 reply.setDataPosition(reply.dataSize());
1282 reply.writeInt32(0);
1283 reply.setDataPosition(0);
1284 unique_fd a, b;
1285 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1286 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1287}
1288
1289// Used to trigger fdsan error (b/239222407).
1290TEST_F(BinderLibTest, RecvUnownedFileDescriptorsAndTruncate) {
1291 FdLeakDetector fd_leak_detector;
1292
1293 Parcel data;
1294 Parcel reply;
1295 EXPECT_EQ(NO_ERROR,
1296 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1297 &reply));
1298 reply.setDataSize(reply.dataSize() - sizeof(flat_binder_object));
1299 unique_fd a, b;
1300 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1301 EXPECT_EQ(BAD_TYPE, reply.readUniqueFileDescriptor(&b));
1302}
1303
Riley Andrews06b01ad2014-12-18 12:10:08 -08001304TEST_F(BinderLibTest, PromoteLocal) {
1305 sp<IBinder> strong = new BBinder();
1306 wp<IBinder> weak = strong;
1307 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001308 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001309 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -07001310 strong = nullptr;
1311 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001312 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001313 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001314}
1315
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001316TEST_F(BinderLibTest, LocalGetExtension) {
1317 sp<BBinder> binder = new BBinder();
1318 sp<IBinder> ext = new BBinder();
1319 binder->setExtension(ext);
1320 EXPECT_EQ(ext, binder->getExtension());
1321}
1322
1323TEST_F(BinderLibTest, RemoteGetExtension) {
1324 sp<IBinder> server = addServer();
1325 ASSERT_TRUE(server != nullptr);
1326
1327 sp<IBinder> extension;
1328 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
1329 ASSERT_NE(nullptr, extension.get());
1330
1331 EXPECT_EQ(NO_ERROR, extension->pingBinder());
1332}
1333
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001334TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001335 Parcel data, reply;
1336
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001337 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
1338 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001339
1340 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -07001341 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +08001342 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
1343 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
1344 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
1345 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001346}
1347
Connor O'Brien52be2c92016-09-20 14:18:08 -07001348TEST_F(BinderLibTest, FreedBinder) {
1349 status_t ret;
1350
1351 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -07001352 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001353
1354 __u32 freedHandle;
1355 wp<IBinder> keepFreedBinder;
1356 {
1357 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001358 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1359 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -07001360 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
1361 freedHandle = freed->handle;
1362 /* Add a weak ref to the freed binder so the driver does not
1363 * delete its reference to it - otherwise the transaction
1364 * fails regardless of whether the driver is fixed.
1365 */
Steven Morelande171d622019-07-17 16:06:01 -07001366 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001367 }
Steven Morelande171d622019-07-17 16:06:01 -07001368 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001369 {
1370 Parcel data, reply;
1371 data.writeStrongBinder(server);
1372 /* Replace original handle with handle to the freed binder */
1373 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
1374 __u32 oldHandle = strong->handle;
1375 strong->handle = freedHandle;
1376 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
1377 /* Returns DEAD_OBJECT (-32) if target crashes and
1378 * FAILED_TRANSACTION if the driver rejects the invalid
1379 * object.
1380 */
1381 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
1382 /* Restore original handle so parcel destructor does not use
1383 * the wrong handle.
1384 */
1385 strong->handle = oldHandle;
1386 }
1387}
1388
Sherry Yang336cdd32017-07-24 14:12:27 -07001389TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -07001390 Parcel data, reply;
1391 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1392 for (int i = 0; i < 2; i++) {
1393 BinderLibTestBundle datai;
1394 datai.appendFrom(&data, 0, data.dataSize());
1395
1396 data.freeData();
1397 data.writeInt32(1);
1398 data.writeStrongBinder(callBack);
1399 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1400
1401 datai.appendTo(&data);
1402 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001403 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1404 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -07001405}
1406
Martijn Coenen45b07b42017-08-09 12:07:45 +02001407TEST_F(BinderLibTest, OnewayQueueing)
1408{
Martijn Coenen45b07b42017-08-09 12:07:45 +02001409 Parcel data, data2;
1410
1411 sp<IBinder> pollServer = addPollServer();
1412
1413 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1414 data.writeStrongBinder(callBack);
1415 data.writeInt32(500000); // delay in us before calling back
1416
1417 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1418 data2.writeStrongBinder(callBack2);
1419 data2.writeInt32(0); // delay in us
1420
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001421 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1422 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001423
1424 // The delay ensures that this second transaction will end up on the async_todo list
1425 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001426 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1427 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001428
1429 // The server will ensure that the two transactions are handled in the expected order;
1430 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001431 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1432 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001433
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001434 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1435 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001436}
1437
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001438TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1439{
1440 status_t ret;
1441 Parcel data, reply;
1442 data.writeInterfaceToken(binderLibTestServiceName);
1443 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1444 EXPECT_EQ(-1, reply.readInt32());
1445 EXPECT_EQ(NO_ERROR, ret);
1446}
1447
1448TEST_F(BinderLibTest, WorkSourceSet)
1449{
1450 status_t ret;
1451 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001452 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001453 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001454 data.writeInterfaceToken(binderLibTestServiceName);
1455 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1456 EXPECT_EQ(100, reply.readInt32());
1457 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001458 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1459 EXPECT_EQ(NO_ERROR, ret);
1460}
1461
1462TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1463{
1464 status_t ret;
1465 Parcel data, reply;
1466
1467 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1468 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1469
1470 data.writeInterfaceToken(binderLibTestServiceName);
1471 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1472 EXPECT_EQ(-1, reply.readInt32());
1473 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001474 EXPECT_EQ(NO_ERROR, ret);
1475}
1476
1477TEST_F(BinderLibTest, WorkSourceCleared)
1478{
1479 status_t ret;
1480 Parcel data, reply;
1481
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001482 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001483 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1484 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001485 data.writeInterfaceToken(binderLibTestServiceName);
1486 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1487
1488 EXPECT_EQ(-1, reply.readInt32());
1489 EXPECT_EQ(100, previousWorkSource);
1490 EXPECT_EQ(NO_ERROR, ret);
1491}
1492
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001493TEST_F(BinderLibTest, WorkSourceRestored)
1494{
1495 status_t ret;
1496 Parcel data, reply;
1497
1498 IPCThreadState::self()->setCallingWorkSourceUid(100);
1499 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1500 IPCThreadState::self()->restoreCallingWorkSource(token);
1501
1502 data.writeInterfaceToken(binderLibTestServiceName);
1503 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1504
1505 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001506 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001507 EXPECT_EQ(NO_ERROR, ret);
1508}
1509
Olivier Gaillard91a04802018-11-14 17:32:41 +00001510TEST_F(BinderLibTest, PropagateFlagSet)
1511{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001512 IPCThreadState::self()->clearPropagateWorkSource();
1513 IPCThreadState::self()->setCallingWorkSourceUid(100);
1514 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1515}
1516
1517TEST_F(BinderLibTest, PropagateFlagCleared)
1518{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001519 IPCThreadState::self()->setCallingWorkSourceUid(100);
1520 IPCThreadState::self()->clearPropagateWorkSource();
1521 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1522}
1523
1524TEST_F(BinderLibTest, PropagateFlagRestored)
1525{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001526 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1527 IPCThreadState::self()->restoreCallingWorkSource(token);
1528
1529 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1530}
1531
1532TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1533{
1534 IPCThreadState::self()->setCallingWorkSourceUid(100);
1535
1536 Parcel data, reply;
1537 status_t ret;
1538 data.writeInterfaceToken(binderLibTestServiceName);
1539 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001540 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001541
1542 Parcel data2, reply2;
1543 status_t ret2;
1544 data2.writeInterfaceToken(binderLibTestServiceName);
1545 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1546 EXPECT_EQ(100, reply2.readInt32());
1547 EXPECT_EQ(NO_ERROR, ret2);
1548}
1549
Steven Morelandbf1915b2020-07-16 22:43:02 +00001550TEST_F(BinderLibTest, SchedPolicySet) {
1551 sp<IBinder> server = addServer();
1552 ASSERT_TRUE(server != nullptr);
1553
1554 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001555 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1556 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001557
1558 int policy = reply.readInt32();
1559 int priority = reply.readInt32();
1560
1561 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1562 EXPECT_EQ(kSchedPriority, priority);
1563}
1564
Steven Morelandcf03cf12020-12-04 02:58:40 +00001565TEST_F(BinderLibTest, InheritRt) {
1566 sp<IBinder> server = addServer();
1567 ASSERT_TRUE(server != nullptr);
1568
1569 const struct sched_param param {
1570 .sched_priority = kSchedPriorityMore,
1571 };
1572 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1573
1574 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001575 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1576 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001577
1578 int policy = reply.readInt32();
1579 int priority = reply.readInt32();
1580
1581 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1582 EXPECT_EQ(kSchedPriorityMore, priority);
1583}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001584
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001585TEST_F(BinderLibTest, VectorSent) {
1586 Parcel data, reply;
1587 sp<IBinder> server = addServer();
1588 ASSERT_TRUE(server != nullptr);
1589
1590 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1591 data.writeUint64Vector(testValue);
1592
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001593 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001594 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001595 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001596 EXPECT_EQ(readValue, testValue);
1597}
1598
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001599TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1600 sp<IBinder> server = addServer();
1601 ASSERT_TRUE(server != nullptr);
1602
1603 Parcel reply;
1604 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1605 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001606 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001607 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1608
1609 const int result = fcntl(fd.get(), F_GETFL);
1610 ASSERT_NE(result, -1);
1611 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1612}
1613
Steven Moreland59b84442022-07-12 18:32:44 +00001614// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1615// This value is not exposed, but some code in the framework relies on being able to use
1616// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001617constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001618constexpr size_t kSizeBytesOverFull = 1'050'000;
1619
1620TEST_F(BinderLibTest, GargantuanVectorSent) {
1621 sp<IBinder> server = addServer();
1622 ASSERT_TRUE(server != nullptr);
1623
1624 for (size_t i = 0; i < 10; i++) {
1625 // a slight variation in size is used to consider certain possible caching implementations
1626 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1627
1628 Parcel data, reply;
1629 data.writeUint64Vector(testValue);
1630 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1631 << i;
1632 std::vector<uint64_t> readValue;
1633 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1634 EXPECT_EQ(readValue, testValue);
1635 }
1636}
1637
1638TEST_F(BinderLibTest, LimitExceededVectorSent) {
1639 sp<IBinder> server = addServer();
1640 ASSERT_TRUE(server != nullptr);
1641 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1642
1643 Parcel data, reply;
1644 data.writeUint64Vector(testValue);
1645 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1646 StatusEq(FAILED_TRANSACTION));
1647}
1648
Martijn Coenen82c75312019-07-24 15:18:30 +02001649TEST_F(BinderLibTest, BufRejected) {
1650 Parcel data, reply;
1651 uint32_t buf;
1652 sp<IBinder> server = addServer();
1653 ASSERT_TRUE(server != nullptr);
1654
1655 binder_buffer_object obj {
1656 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001657 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001658 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1659 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001660 };
1661 data.setDataCapacity(1024);
1662 // Write a bogus object at offset 0 to get an entry in the offset table
1663 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001664 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001665 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1666 // And now, overwrite it with the buffer object
1667 memcpy(parcelData, &obj, sizeof(obj));
1668 data.setDataSize(sizeof(obj));
1669
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001670 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001671
Martijn Coenen82c75312019-07-24 15:18:30 +02001672 // Either the kernel should reject this transaction (if it's correct), but
1673 // if it's not, the server implementation should return an error if it
1674 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001675 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001676 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001677}
1678
Steven Morelandf2e0a952021-11-01 18:17:23 -07001679TEST_F(BinderLibTest, WeakRejected) {
1680 Parcel data, reply;
1681 sp<IBinder> server = addServer();
1682 ASSERT_TRUE(server != nullptr);
1683
1684 auto binder = sp<BBinder>::make();
1685 wp<BBinder> wpBinder(binder);
1686 flat_binder_object obj{
1687 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1688 .flags = 0,
1689 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1690 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1691 };
1692 data.setDataCapacity(1024);
1693 // Write a bogus object at offset 0 to get an entry in the offset table
1694 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001695 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001696 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1697 // And now, overwrite it with the weak binder
1698 memcpy(parcelData, &obj, sizeof(obj));
1699 data.setDataSize(sizeof(obj));
1700
1701 // a previous bug caused other objects to be released an extra time, so we
1702 // test with an object that libbinder will actually try to release
1703 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1704
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001705 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001706
1707 // send it many times, since previous error was memory corruption, make it
1708 // more likely that the server crashes
1709 for (size_t i = 0; i < 100; i++) {
1710 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1711 StatusEq(BAD_VALUE));
1712 }
1713
1714 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1715}
1716
Steven Moreland254e8ef2021-04-19 22:28:50 +00001717TEST_F(BinderLibTest, GotSid) {
1718 sp<IBinder> server = addServer();
1719
1720 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001721 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001722}
1723
Andrei Homescu1519b982022-06-09 02:04:44 +00001724struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1725 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1726
1727 // Flattenable protocol
1728 size_t getFlattenedSize() const {
1729 // Return a valid non-zero size here so we don't get an unintended
1730 // BAD_VALUE from Parcel::write
1731 return 16;
1732 }
1733 size_t getFdCount() const { return mFdCount; }
1734 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1735 for (size_t i = 0; i < count; i++) {
1736 fds[i] = STDIN_FILENO;
1737 }
1738 return NO_ERROR;
1739 }
1740 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1741 size_t & /*count*/) {
1742 /* This doesn't get called */
1743 return NO_ERROR;
1744 }
1745
1746 size_t mFdCount;
1747};
1748
1749TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1750 rlimit origNofile;
1751 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1752 ASSERT_EQ(0, ret);
1753
1754 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001755 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001756
1757 rlimit testNofile = {1024, 1024};
1758 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1759 ASSERT_EQ(0, ret);
1760
1761 Parcel parcel;
1762 // Try to write more file descriptors than supported by the OS
1763 TooManyFdsFlattenable tooManyFds1(1024);
1764 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1765
1766 // Try to write more file descriptors than the internal limit
1767 TooManyFdsFlattenable tooManyFds2(1025);
1768 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1769}
1770
Jayant Chowdhary30700942022-01-31 14:12:40 -08001771TEST(ServiceNotifications, Unregister) {
1772 auto sm = defaultServiceManager();
Parth Sanedc207542024-11-14 11:49:08 +00001773 sm->enableAddServiceCache(false);
Jayant Chowdhary30700942022-01-31 14:12:40 -08001774 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1775 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1776 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1777 virtual ~LocalRegistrationCallbackImpl() {}
1778 };
1779 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1780
1781 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1782 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1783}
1784
Elie Kheirallah47431c12022-04-21 23:46:17 +00001785TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1786 Parcel data, reply;
1787 sp<IBinder> server = addServer();
1788 ASSERT_TRUE(server != nullptr);
1789 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1790 StatusEq(NO_ERROR));
1791 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001792 // see getThreadPoolMaxTotalThreadCount for why there is a race
1793 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1794
Elie Kheirallah47431c12022-04-21 23:46:17 +00001795 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1796
1797 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001798 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1799 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1800 * started threads from setThreadPoolMaxThreadCount
1801 *
1802 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001803 */
1804 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001805 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001806 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001807 Parcel local_reply;
1808 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1809 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001810 }));
1811 }
1812
Steven Moreland3e9debc2023-06-15 00:35:29 +00001813 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1814 // the time, the below call will pre-empt them (presumably because we have the
1815 // scheduler timeslice already + scheduler hint).
1816 sleep(1);
1817
1818 data.writeInt32(1000);
1819 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001820 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1821
1822 for (auto &t : ts) {
1823 t.join();
1824 }
1825
1826 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1827 StatusEq(NO_ERROR));
1828 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001829 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001830}
1831
Devin Moore4354f712022-12-08 01:44:46 +00001832TEST_F(BinderLibTest, ThreadPoolStarted) {
1833 Parcel data, reply;
1834 sp<IBinder> server = addServer();
1835 ASSERT_TRUE(server != nullptr);
1836 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1837 EXPECT_TRUE(reply.readBool());
1838}
1839
Elie Kheirallah47431c12022-04-21 23:46:17 +00001840size_t epochMillis() {
1841 using std::chrono::duration_cast;
1842 using std::chrono::milliseconds;
1843 using std::chrono::seconds;
1844 using std::chrono::system_clock;
1845 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1846}
1847
1848TEST_F(BinderLibTest, HangingServices) {
1849 Parcel data, reply;
1850 sp<IBinder> server = addServer();
1851 ASSERT_TRUE(server != nullptr);
1852 int32_t delay = 1000; // ms
1853 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001854 // b/266537959 - must take before taking lock, since countdown is started in the remote
1855 // process there.
1856 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001857 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1858 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001859 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1860 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001861 Parcel local_reply;
1862 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1863 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001864 }));
1865 }
1866
1867 for (auto &t : ts) {
1868 t.join();
1869 }
1870 size_t epochMsAfter = epochMillis();
1871
1872 // deadlock occurred and threads only finished after 1s passed.
1873 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1874}
1875
Jing Jibbe9ae62023-10-07 15:26:02 -07001876TEST_F(BinderLibTest, BinderProxyCount) {
1877 Parcel data, reply;
1878 sp<IBinder> server = addServer();
1879 ASSERT_NE(server, nullptr);
1880
1881 uint32_t initialCount = BpBinder::getBinderProxyCount();
1882 size_t iterations = 100;
1883 {
1884 uint32_t count = initialCount;
1885 std::vector<sp<IBinder> > proxies;
1886 sp<IBinder> proxy;
1887 // Create binder proxies and verify the count.
1888 for (size_t i = 0; i < iterations; i++) {
1889 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1890 StatusEq(NO_ERROR));
1891 proxies.push_back(reply.readStrongBinder());
1892 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1893 }
1894 // Remove every other one and verify the count.
1895 auto it = proxies.begin();
1896 for (size_t i = 0; it != proxies.end(); i++) {
1897 if (i % 2 == 0) {
1898 it = proxies.erase(it);
1899 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1900 }
1901 }
1902 }
1903 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1904}
1905
Jing Jibdbe29a2023-10-03 00:03:28 -07001906static constexpr int kBpCountHighWatermark = 20;
1907static constexpr int kBpCountLowWatermark = 10;
1908static constexpr int kBpCountWarningWatermark = 15;
1909static constexpr int kInvalidUid = -1;
1910
1911TEST_F(BinderLibTest, BinderProxyCountCallback) {
1912 Parcel data, reply;
1913 sp<IBinder> server = addServer();
1914 ASSERT_NE(server, nullptr);
1915
1916 BpBinder::enableCountByUid();
1917 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1918 int32_t uid = reply.readInt32();
1919 ASSERT_NE(uid, kInvalidUid);
1920
1921 uint32_t initialCount = BpBinder::getBinderProxyCount();
1922 {
1923 uint32_t count = initialCount;
1924 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1925 kBpCountLowWatermark,
1926 kBpCountWarningWatermark);
1927 int limitCallbackUid = kInvalidUid;
1928 int warningCallbackUid = kInvalidUid;
1929 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1930 [&](int uid) { warningCallbackUid = uid; });
1931
1932 std::vector<sp<IBinder> > proxies;
1933 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1934 warningCallbackUid = limitCallbackUid = kInvalidUid;
1935 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1936 StatusEq(NO_ERROR));
1937 proxies.push_back(reply.readStrongBinder());
1938 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1939 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1940 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1941 };
1942 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1943 warningCallbackUid = limitCallbackUid = kInvalidUid;
1944 proxies.pop_back();
1945 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1946 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1947 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1948 };
1949
1950 // Test the increment/decrement of the binder proxies.
1951 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1952 createProxyOnce(kInvalidUid, kInvalidUid);
1953 }
1954 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1955 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1956 createProxyOnce(kInvalidUid, kInvalidUid);
1957 }
1958 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1959 createProxyOnce(kInvalidUid, kInvalidUid);
1960 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1961 removeProxyOnce(kInvalidUid, kInvalidUid);
1962 }
1963 createProxyOnce(kInvalidUid, kInvalidUid);
1964
1965 // Go down below the low watermark.
1966 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1967 removeProxyOnce(kInvalidUid, kInvalidUid);
1968 }
1969 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1970 createProxyOnce(kInvalidUid, kInvalidUid);
1971 }
1972 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1973 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1974 createProxyOnce(kInvalidUid, kInvalidUid);
1975 }
1976 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1977 createProxyOnce(kInvalidUid, kInvalidUid);
1978 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1979 removeProxyOnce(kInvalidUid, kInvalidUid);
1980 }
1981 createProxyOnce(kInvalidUid, kInvalidUid);
1982 }
1983 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1984}
1985
Yifan Hong84bedeb2021-04-21 21:37:17 -07001986class BinderLibRpcTestBase : public BinderLibTest {
1987public:
1988 void SetUp() override {
1989 if (!base::GetBoolProperty("ro.debuggable", false)) {
1990 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1991 "non-debuggable builds.";
1992 }
1993 BinderLibTest::SetUp();
1994 }
1995
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001996 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001997 auto rpcServer = RpcServer::make();
1998 EXPECT_NE(nullptr, rpcServer);
1999 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07002000 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07002001 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
2002 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07002003 return {};
2004 }
2005 return {rpcServer->releaseServer(), port};
2006 }
2007};
2008
Yifan Hong8b890852021-06-10 13:44:09 -07002009class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07002010
Yifan Hongbd276552022-02-28 15:28:51 -08002011// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
2012// If device is debuggable AND not on user builds, expects matcher.
2013// Otherwise expects INVALID_OPERATION.
2014// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
2015static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
2016 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
2017 android::base::GetProperty("ro.build.type", "") != "user";
2018 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
2019}
2020
Yifan Hong8b890852021-06-10 13:44:09 -07002021TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
2022 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07002023 ASSERT_TRUE(binder != nullptr);
2024 auto [socket, port] = CreateSocket();
2025 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08002026 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
2027 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002028}
2029
Yifan Hong8b890852021-06-10 13:44:09 -07002030// Tests for multiple RpcServer's on the same binder object.
2031TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
2032 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07002033 ASSERT_TRUE(binder != nullptr);
2034
2035 auto [socket1, port1] = CreateSocket();
2036 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07002037 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08002038 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
2039 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002040
2041 auto [socket2, port2] = CreateSocket();
2042 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07002043 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08002044 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
2045 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002046}
2047
Yifan Hong8b890852021-06-10 13:44:09 -07002048// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
2049// local binders.
2050class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07002051public:
2052 sp<IBinder> GetService() {
2053 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
2054 }
2055 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
2056 return info.param ? "remote" : "local";
2057 }
2058};
2059
Yifan Hong8b890852021-06-10 13:44:09 -07002060TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
2061 auto binder = GetService();
2062 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002063 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08002064 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07002065}
2066
2067TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07002068 auto binder = GetService();
2069 ASSERT_TRUE(binder != nullptr);
2070 auto [socket, port] = CreateSocket();
2071 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08002072 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
2073 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002074}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002075INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
2076 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07002077
Yifan Hong543edcd2021-05-18 19:47:30 -07002078class BinderLibTestService : public BBinder {
2079public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07002080 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
2081 : m_id(id),
2082 m_nextServerId(id + 1),
2083 m_serverStartRequested(false),
2084 m_callback(nullptr),
2085 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07002086 pthread_mutex_init(&m_serverWaitMutex, nullptr);
2087 pthread_cond_init(&m_serverWaitCond, nullptr);
2088 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07002089 ~BinderLibTestService() {
2090 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
2091 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002092
Yifan Hong543edcd2021-05-18 19:47:30 -07002093 void processPendingCall() {
2094 if (m_callback != nullptr) {
2095 Parcel data;
2096 data.writeInt32(NO_ERROR);
2097 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
2098 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002099 }
Yifan Hong543edcd2021-05-18 19:47:30 -07002100 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002101
Yifan Hong543edcd2021-05-18 19:47:30 -07002102 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
2103 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07002104 // TODO(b/182914638): also checks getCallingUid() for RPC
2105 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07002106 return PERMISSION_DENIED;
2107 }
2108 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002109 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002110 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002111 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08002112 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002113 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002114 return BAD_VALUE;
2115 }
2116
Yifan Hong543edcd2021-05-18 19:47:30 -07002117 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002118
2119 pthread_mutex_lock(&m_serverWaitMutex);
2120 if (m_serverStartRequested) {
2121 m_serverStartRequested = false;
2122 m_serverStarted = binder;
2123 pthread_cond_signal(&m_serverWaitCond);
2124 }
2125 pthread_mutex_unlock(&m_serverWaitMutex);
2126 return NO_ERROR;
2127 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002128 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08002129 case BINDER_LIB_TEST_ADD_SERVER: {
2130 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002131 int serverid;
2132
2133 if (m_id != 0) {
2134 return INVALID_OPERATION;
2135 }
2136 pthread_mutex_lock(&m_serverWaitMutex);
2137 if (m_serverStartRequested) {
2138 ret = -EBUSY;
2139 } else {
2140 serverid = m_nextServerId++;
2141 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002142 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002143
2144 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002145 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002146 pthread_mutex_lock(&m_serverWaitMutex);
2147 }
2148 if (ret > 0) {
2149 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002150 struct timespec ts;
2151 clock_gettime(CLOCK_REALTIME, &ts);
2152 ts.tv_sec += 5;
2153 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002154 }
2155 if (m_serverStartRequested) {
2156 m_serverStartRequested = false;
2157 ret = -ETIMEDOUT;
2158 } else {
2159 reply->writeStrongBinder(m_serverStarted);
2160 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07002161 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002162 ret = NO_ERROR;
2163 }
2164 } else if (ret >= 0) {
2165 m_serverStartRequested = false;
2166 ret = UNKNOWN_ERROR;
2167 }
2168 pthread_mutex_unlock(&m_serverWaitMutex);
2169 return ret;
2170 }
Steven Moreland35626652021-05-15 01:32:04 +00002171 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
2172 IPCThreadState::SpGuard spGuard{
2173 .address = __builtin_frame_address(0),
2174 .context = "GuardInBinderTransaction",
2175 };
2176 const IPCThreadState::SpGuard *origGuard =
2177 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2178
2179 // if the guard works, this should abort
2180 (void)IPCThreadState::self()->getCallingPid();
2181
2182 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
2183 return NO_ERROR;
2184 }
2185
Marco Ballesio7ee17572020-09-08 10:30:03 -07002186 case BINDER_LIB_TEST_GETPID:
2187 reply->writeInt32(getpid());
2188 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07002189 case BINDER_LIB_TEST_GETUID:
2190 reply->writeInt32(getuid());
2191 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07002192 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
2193 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00002194 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08002195 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00002196 // oneway error codes should be ignored
2197 if (flags & TF_ONE_WAY) {
2198 return UNKNOWN_ERROR;
2199 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002200 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002201 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
2202 // Note: this transaction is only designed for use with a
2203 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07002204 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02002205 // A callback was already pending; this means that
2206 // we received a second call while still processing
2207 // the first one. Fail the test.
2208 sp<IBinder> callback = data.readStrongBinder();
2209 Parcel data2;
2210 data2.writeInt32(UNKNOWN_ERROR);
2211
Yi Kong91635562018-06-07 14:38:36 -07002212 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002213 } else {
2214 m_callback = data.readStrongBinder();
2215 int32_t delayUs = data.readInt32();
2216 /*
2217 * It's necessary that we sleep here, so the next
2218 * transaction the caller makes will be queued to
2219 * the async queue.
2220 */
2221 usleep(delayUs);
2222
2223 /*
2224 * Now when we return, libbinder will tell the kernel
2225 * we are done with this transaction, and the kernel
2226 * can move the queued transaction to either the
2227 * thread todo worklist (for kernels without the fix),
2228 * or the proc todo worklist. In case of the former,
2229 * the next outbound call will pick up the pending
2230 * transaction, which leads to undesired reentrant
2231 * behavior. This is caught in the if() branch above.
2232 */
2233 }
2234
2235 return NO_ERROR;
2236 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002237 case BINDER_LIB_TEST_NOP_CALL_BACK: {
2238 Parcel data2, reply2;
2239 sp<IBinder> binder;
2240 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002241 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002242 return BAD_VALUE;
2243 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02002244 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002245 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2246 return NO_ERROR;
2247 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07002248 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
2249 reply->writeStrongBinder(this);
2250 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002251 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
2252 reply->writeInt32(m_id);
2253 return NO_ERROR;
2254 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
2255 int32_t count;
2256 uint32_t indirect_code;
2257 sp<IBinder> binder;
2258
2259 count = data.readInt32();
2260 reply->writeInt32(m_id);
2261 reply->writeInt32(count);
2262 for (int i = 0; i < count; i++) {
2263 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002264 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002265 return BAD_VALUE;
2266 }
2267 indirect_code = data.readInt32();
2268 BinderLibTestBundle data2(&data);
2269 if (!data2.isValid()) {
2270 return BAD_VALUE;
2271 }
2272 BinderLibTestBundle reply2;
2273 binder->transact(indirect_code, data2, &reply2);
2274 reply2.appendTo(reply);
2275 }
2276 return NO_ERROR;
2277 }
2278 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
2279 reply->setError(data.readInt32());
2280 return NO_ERROR;
2281 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
2282 reply->writeInt32(sizeof(void *));
2283 return NO_ERROR;
2284 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
2285 return NO_ERROR;
2286 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
2287 m_strongRef = data.readStrongBinder();
2288 return NO_ERROR;
2289 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
2290 int ret;
2291 Parcel data2, reply2;
2292 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
2293 sp<IBinder> target;
2294 sp<IBinder> callback;
2295
2296 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002297 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002298 return BAD_VALUE;
2299 }
2300 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002301 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002302 return BAD_VALUE;
2303 }
2304 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07002305 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002306 data2.writeInt32(ret);
2307 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2308 return NO_ERROR;
2309 }
2310 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
2311 int ret;
2312 int32_t size;
2313 const void *buf;
2314 int fd;
2315
2316 fd = data.readFileDescriptor();
2317 if (fd < 0) {
2318 return BAD_VALUE;
2319 }
2320 ret = data.readInt32(&size);
2321 if (ret != NO_ERROR) {
2322 return ret;
2323 }
2324 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07002325 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002326 return BAD_VALUE;
2327 }
2328 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07002329 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002330 return NO_ERROR;
2331 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09002332 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
2333 int ret;
2334 int32_t size;
2335 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002336 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09002337
2338 ret = data.readUniqueParcelFileDescriptor(&fd);
2339 if (ret != NO_ERROR) {
2340 return ret;
2341 }
2342 ret = data.readInt32(&size);
2343 if (ret != NO_ERROR) {
2344 return ret;
2345 }
2346 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07002347 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09002348 return BAD_VALUE;
2349 }
2350 ret = write(fd.get(), buf, size);
2351 if (ret != size) return UNKNOWN_ERROR;
2352 return NO_ERROR;
2353 }
Frederick Maylef2163b82024-09-30 17:42:45 -07002354 case BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION: {
2355 unique_fd fd1(memfd_create("memfd1", MFD_CLOEXEC));
2356 if (!fd1.ok()) {
2357 PLOGE("memfd_create failed");
2358 return UNKNOWN_ERROR;
2359 }
2360 unique_fd fd2(memfd_create("memfd2", MFD_CLOEXEC));
2361 if (!fd2.ok()) {
2362 PLOGE("memfd_create failed");
2363 return UNKNOWN_ERROR;
2364 }
2365 status_t ret;
2366 ret = reply->writeFileDescriptor(fd1.release(), true);
2367 if (ret != NO_ERROR) {
2368 return ret;
2369 }
2370 ret = reply->writeFileDescriptor(fd2.release(), true);
2371 if (ret != NO_ERROR) {
2372 return ret;
2373 }
2374 return NO_ERROR;
2375 }
2376 case BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION: {
2377 status_t ret;
2378 ret = reply->writeFileDescriptor(STDOUT_FILENO, false);
2379 if (ret != NO_ERROR) {
2380 return ret;
2381 }
2382 ret = reply->writeFileDescriptor(STDERR_FILENO, false);
2383 if (ret != NO_ERROR) {
2384 return ret;
2385 }
2386 return NO_ERROR;
2387 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002388 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
2389 alarm(10);
2390 return NO_ERROR;
2391 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07002392 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002393 ;
2394 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002395 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07002396 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07002397 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002398 return NO_ERROR;
2399 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002400 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
2401 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00002402 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002403 return NO_ERROR;
2404 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00002405 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
2406 int policy = 0;
2407 sched_param param;
2408 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
2409 return UNKNOWN_ERROR;
2410 }
2411 reply->writeInt32(policy);
2412 reply->writeInt32(param.sched_priority);
2413 return NO_ERROR;
2414 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002415 case BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE: {
2416 sp<IBinder> binder = data.readStrongBinder();
2417 frozenStateChangeCallback = sp<TestFrozenStateChangeCallback>::make();
2418 // Hold an strong pointer to the binder object so it doesn't go
2419 // away.
2420 frozenStateChangeCallback->binder = binder;
2421 int ret = binder->addFrozenStateChangeCallback(frozenStateChangeCallback);
2422 if (ret != NO_ERROR) {
2423 return ret;
2424 }
Yu-Ting Tsengc08e4712024-10-10 17:51:44 -07002425 auto event = frozenStateChangeCallback->events.popWithTimeout(1000ms);
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002426 if (!event.has_value()) {
2427 return NOT_ENOUGH_DATA;
2428 }
2429 return NO_ERROR;
2430 }
2431 case BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS: {
2432 reply->writeBoolVector(frozenStateChangeCallback->getAllAndClear());
2433 return NO_ERROR;
2434 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002435 case BINDER_LIB_TEST_ECHO_VECTOR: {
2436 std::vector<uint64_t> vector;
2437 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07002438 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002439 reply->writeUint64Vector(vector);
2440 return NO_ERROR;
2441 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002442 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
2443 std::array<int, 2> sockets;
2444 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
2445 if (!created) {
2446 ALOGE("Could not create socket pair");
2447 return UNKNOWN_ERROR;
2448 }
2449
2450 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2451 if (result != 0) {
2452 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2453 return UNKNOWN_ERROR;
2454 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002455 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002456 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2457 if (writeResult != NO_ERROR) {
2458 ALOGE("Could not write unique_fd");
2459 return writeResult;
2460 }
2461 close(sockets[1]); // we don't need the other side of the fd
2462 return NO_ERROR;
2463 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07002464 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02002465 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2466 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00002467 case BINDER_LIB_TEST_CAN_GET_SID: {
2468 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2469 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002470 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2471 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2472 return NO_ERROR;
2473 }
Devin Moore4354f712022-12-08 01:44:46 +00002474 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2475 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2476 return NO_ERROR;
2477 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002478 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002479 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002480 return NO_ERROR;
2481 }
2482 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002483 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002484 return NO_ERROR;
2485 }
2486 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2487 int32_t ms = data.readInt32();
2488 return unlockInMs(ms);
2489 }
2490 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002491 m_blockMutex.lock();
2492 sp<BinderLibTestService> thisService = this;
2493 int32_t value = data.readInt32();
2494 // start local thread to unlock in 1s
2495 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002496 t.detach();
2497 return NO_ERROR;
2498 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002499 default:
2500 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002501 };
2502 }
2503
Elie Kheirallah47431c12022-04-21 23:46:17 +00002504 status_t unlockInMs(int32_t ms) {
2505 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002506 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002507 return NO_ERROR;
2508 }
2509
Yifan Hong543edcd2021-05-18 19:47:30 -07002510private:
2511 int32_t m_id;
2512 int32_t m_nextServerId;
2513 pthread_mutex_t m_serverWaitMutex;
2514 pthread_cond_t m_serverWaitCond;
2515 bool m_serverStartRequested;
2516 sp<IBinder> m_serverStarted;
2517 sp<IBinder> m_strongRef;
2518 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002519 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002520 std::mutex m_blockMutex;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002521 sp<TestFrozenStateChangeCallback> frozenStateChangeCallback;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002522};
2523
Martijn Coenen45b07b42017-08-09 12:07:45 +02002524int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002525{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002526 binderLibTestServiceName += String16(binderserversuffix);
2527
Steven Moreland35626652021-05-15 01:32:04 +00002528 // Testing to make sure that calls that we are serving can use getCallin*
2529 // even though we don't here.
2530 IPCThreadState::SpGuard spGuard{
2531 .address = __builtin_frame_address(0),
2532 .context = "main server thread",
2533 };
2534 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2535
Riley Andrews06b01ad2014-12-18 12:10:08 -08002536 status_t ret;
2537 sp<IServiceManager> sm = defaultServiceManager();
Parth Sanedc207542024-11-14 11:49:08 +00002538 sm->enableAddServiceCache(false);
2539
Martijn Coenen45b07b42017-08-09 12:07:45 +02002540 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002541 {
2542 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002543
Steven Morelandbf1915b2020-07-16 22:43:02 +00002544 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2545
Steven Morelandcf03cf12020-12-04 02:58:40 +00002546 testService->setInheritRt(true);
2547
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002548 /*
2549 * Normally would also contain functionality as well, but we are only
2550 * testing the extension mechanism.
2551 */
2552 testService->setExtension(new BBinder());
2553
Martijn Coenen82c75312019-07-24 15:18:30 +02002554 // Required for test "BufRejected'
2555 testService->setRequestingSid(true);
2556
Martijn Coenen45b07b42017-08-09 12:07:45 +02002557 /*
2558 * We need this below, but can't hold a sp<> because it prevents the
2559 * node from being cleaned up automatically. It's safe in this case
2560 * because of how the tests are written.
2561 */
2562 testServicePtr = testService.get();
2563
Riley Andrews06b01ad2014-12-18 12:10:08 -08002564 if (index == 0) {
2565 ret = sm->addService(binderLibTestServiceName, testService);
2566 } else {
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002567 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -08002568 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002569 LIBBINDER_IGNORE_END()
Riley Andrews06b01ad2014-12-18 12:10:08 -08002570 Parcel data, reply;
2571 data.writeInt32(index);
2572 data.writeStrongBinder(testService);
2573
2574 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2575 }
2576 }
2577 write(readypipefd, &ret, sizeof(ret));
2578 close(readypipefd);
2579 //printf("%s: ret %d\n", __func__, ret);
2580 if (ret)
2581 return 1;
2582 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002583 if (usePoll) {
2584 int fd;
2585 struct epoll_event ev;
2586 int epoll_fd;
2587 IPCThreadState::self()->setupPolling(&fd);
2588 if (fd < 0) {
2589 return 1;
2590 }
2591 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2592
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002593 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002594 if (epoll_fd == -1) {
2595 return 1;
2596 }
2597
2598 ev.events = EPOLLIN;
2599 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2600 return 1;
2601 }
2602
2603 while (1) {
2604 /*
2605 * We simulate a single-threaded process using the binder poll
2606 * interface; besides handling binder commands, it can also
2607 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002608 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002609 *
2610 * processPendingCall() will then issue that transaction.
2611 */
2612 struct epoll_event events[1];
2613 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2614 if (numEvents < 0) {
2615 if (errno == EINTR) {
2616 continue;
2617 }
2618 return 1;
2619 }
2620 if (numEvents > 0) {
2621 IPCThreadState::self()->handlePolledCommands();
2622 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2623 testServicePtr->processPendingCall();
2624 }
2625 }
2626 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002627 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002628 ProcessState::self()->startThreadPool();
2629 IPCThreadState::self()->joinThreadPool();
2630 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002631 //printf("%s: joinThreadPool returned\n", __func__);
2632 return 1; /* joinThreadPool should not return */
2633}
2634
Steven Moreland68275d72023-04-21 22:12:45 +00002635int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002636 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002637 binderservername = argv[2];
2638 } else {
2639 binderservername = argv[0];
2640 }
2641
Martijn Coenen45b07b42017-08-09 12:07:45 +02002642 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2643 binderserversuffix = argv[5];
2644 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002645 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002646 binderserversuffix = new char[16];
2647 snprintf(binderserversuffix, 16, "%d", getpid());
2648 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002649
2650 ::testing::InitGoogleTest(&argc, argv);
2651 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2652 ProcessState::self()->startThreadPool();
2653 return RUN_ALL_TESTS();
2654}