blob: e152763be1dbb7029c6daf2a8572134c149966cc [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 Mayle884d1a52024-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 Mayle884d1a52024-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();
226 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700227 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -0800228 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700229 LIBBINDER_IGNORE_END()
Yi Kong91635562018-06-07 14:38:36 -0700230 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800231 //printf("%s: pid %d, get service done\n", __func__, m_pid);
232 }
233 virtual void TearDown() {
234 status_t ret;
235 Parcel data, reply;
236 int exitStatus;
237 pid_t pid;
238
239 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700240 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800241 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
242 EXPECT_EQ(0, ret);
243 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
244 EXPECT_EQ(0, ret);
245 }
246 if (m_serverpid > 0) {
247 //printf("wait for %d\n", m_pids[i]);
248 pid = wait(&exitStatus);
249 EXPECT_EQ(m_serverpid, pid);
250 EXPECT_TRUE(WIFEXITED(exitStatus));
251 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
252 }
253 }
254
255 pid_t m_serverpid;
256 sp<IBinder> m_server;
257};
258
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700259class TestFrozenStateChangeCallback : public IBinder::FrozenStateChangeCallback {
260public:
261 BlockingQueue<std::pair<const wp<IBinder>, State>> events;
262
263 virtual void onStateChanged(const wp<IBinder>& who, State state) {
264 events.push(std::make_pair(who, state));
265 }
266
267 void ensureFrozenEventReceived() {
268 auto event = events.popWithTimeout(500ms);
269 ASSERT_TRUE(event.has_value());
270 EXPECT_EQ(State::FROZEN, event->second); // isFrozen should be true
271 EXPECT_EQ(0u, events.size());
272 }
273
274 void ensureUnfrozenEventReceived() {
275 auto event = events.popWithTimeout(500ms);
276 ASSERT_TRUE(event.has_value());
277 EXPECT_EQ(State::UNFROZEN, event->second); // isFrozen should be false
278 EXPECT_EQ(0u, events.size());
279 }
280
281 std::vector<bool> getAllAndClear() {
282 std::vector<bool> results;
283 while (true) {
284 auto event = events.popWithTimeout(0ms);
285 if (!event.has_value()) {
286 break;
287 }
288 results.push_back(event->second == State::FROZEN);
289 }
290 return results;
291 }
292
293 sp<IBinder> binder;
294};
295
Riley Andrews06b01ad2014-12-18 12:10:08 -0800296class BinderLibTest : public ::testing::Test {
297 public:
298 virtual void SetUp() {
299 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Parth Sane81b4d5a2024-05-23 14:11:13 +0000300 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800301 }
302 virtual void TearDown() {
303 }
304 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200305 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800306 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800307 int32_t id;
308 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800309
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700310 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800311
Elie Kheirallahb7246642022-05-03 18:01:43 +0000312 sp<IBinder> binder = reply.readStrongBinder();
313 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700314 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800315 if (idPtr)
316 *idPtr = id;
317 return binder;
318 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200319
Yi Kong91635562018-06-07 14:38:36 -0700320 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200321 {
322 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
323 }
324
Yi Kong91635562018-06-07 14:38:36 -0700325 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200326 {
327 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
328 }
329
Riley Andrews06b01ad2014-12-18 12:10:08 -0800330 void waitForReadData(int fd, int timeout_ms) {
331 int ret;
332 pollfd pfd = pollfd();
333
334 pfd.fd = fd;
335 pfd.events = POLLIN;
336 ret = poll(&pfd, 1, timeout_ms);
337 EXPECT_EQ(1, ret);
338 }
339
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700340 bool checkFreezeSupport() {
341 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
342 // Pass test on devices where the cgroup v2 freezer is not supported
343 if (freezer_file.fail()) {
344 return false;
345 }
346 return IPCThreadState::self()->freeze(getpid(), false, 0) == NO_ERROR;
347 }
348
349 bool checkFreezeAndNotificationSupport() {
350 if (!checkFreezeSupport()) {
351 return false;
352 }
353 return ProcessState::isDriverFeatureEnabled(
354 ProcessState::DriverFeature::FREEZE_NOTIFICATION);
355 }
356
357 bool getBinderPid(int32_t* pid, sp<IBinder> server) {
358 Parcel data, replypid;
359 if (server->transact(BINDER_LIB_TEST_GETPID, data, &replypid) != NO_ERROR) {
360 ALOGE("BINDER_LIB_TEST_GETPID failed");
361 return false;
362 }
363 *pid = replypid.readInt32();
364 if (*pid <= 0) {
365 ALOGE("pid should be greater than zero");
366 return false;
367 }
368 return true;
369 }
370
371 void freezeProcess(int32_t pid) {
372 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
373 }
374
375 void unfreezeProcess(int32_t pid) {
376 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
377 }
378
379 void removeCallbackAndValidateNoEvent(sp<IBinder> binder,
380 sp<TestFrozenStateChangeCallback> callback) {
381 EXPECT_THAT(binder->removeFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
382 EXPECT_EQ(0u, callback->events.size());
383 }
384
Riley Andrews06b01ad2014-12-18 12:10:08 -0800385 sp<IBinder> m_server;
386};
387
388class BinderLibTestBundle : public Parcel
389{
390 public:
391 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800392 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800393 int32_t mark;
394 int32_t bundleLen;
395 size_t pos;
396
397 if (source->readInt32(&mark))
398 return;
399 if (mark != MARK_START)
400 return;
401 if (source->readInt32(&bundleLen))
402 return;
403 pos = source->dataPosition();
404 if (Parcel::appendFrom(source, pos, bundleLen))
405 return;
406 source->setDataPosition(pos + bundleLen);
407 if (source->readInt32(&mark))
408 return;
409 if (mark != MARK_END)
410 return;
411 m_isValid = true;
412 setDataPosition(0);
413 }
414 void appendTo(Parcel *dest) {
415 dest->writeInt32(MARK_START);
416 dest->writeInt32(dataSize());
417 dest->appendFrom(this, 0, dataSize());
418 dest->writeInt32(MARK_END);
419 };
420 bool isValid(void) {
421 return m_isValid;
422 }
423 private:
424 enum {
425 MARK_START = B_PACK_CHARS('B','T','B','S'),
426 MARK_END = B_PACK_CHARS('B','T','B','E'),
427 };
428 bool m_isValid;
429};
430
431class BinderLibTestEvent
432{
433 public:
434 BinderLibTestEvent(void)
435 : m_eventTriggered(false)
436 {
Yi Kong91635562018-06-07 14:38:36 -0700437 pthread_mutex_init(&m_waitMutex, nullptr);
438 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800439 }
440 int waitEvent(int timeout_s)
441 {
442 int ret;
443 pthread_mutex_lock(&m_waitMutex);
444 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800445 struct timespec ts;
446 clock_gettime(CLOCK_REALTIME, &ts);
447 ts.tv_sec += timeout_s;
448 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800449 }
450 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
451 pthread_mutex_unlock(&m_waitMutex);
452 return ret;
453 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200454 pthread_t getTriggeringThread()
455 {
456 return m_triggeringThread;
457 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800458 protected:
459 void triggerEvent(void) {
460 pthread_mutex_lock(&m_waitMutex);
461 pthread_cond_signal(&m_waitCond);
462 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200463 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800464 pthread_mutex_unlock(&m_waitMutex);
465 };
466 private:
467 pthread_mutex_t m_waitMutex;
468 pthread_cond_t m_waitCond;
469 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200470 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800471};
472
473class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
474{
475 public:
476 BinderLibTestCallBack()
477 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700478 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800479 {
480 }
481 status_t getResult(void)
482 {
483 return m_result;
484 }
485
486 private:
487 virtual status_t onTransact(uint32_t code,
488 const Parcel& data, Parcel* reply,
489 uint32_t flags = 0)
490 {
491 (void)reply;
492 (void)flags;
493 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200494 case BINDER_LIB_TEST_CALL_BACK: {
495 status_t status = data.readInt32(&m_result);
496 if (status != NO_ERROR) {
497 m_result = status;
498 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800499 triggerEvent();
500 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200501 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700502 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
503 sp<IBinder> server;
504 int ret;
505 const uint8_t *buf = data.data();
506 size_t size = data.dataSize();
507 if (m_prev_end) {
508 /* 64-bit kernel needs at most 8 bytes to align buffer end */
509 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
510 } else {
511 EXPECT_TRUE(IsPageAligned((void *)buf));
512 }
513
514 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
515
516 if (size > 0) {
517 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
518 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
519 data, reply);
520 EXPECT_EQ(NO_ERROR, ret);
521 }
522 return NO_ERROR;
523 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800524 default:
525 return UNKNOWN_TRANSACTION;
526 }
527 }
528
529 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700530 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800531};
532
533class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
534{
535 private:
536 virtual void binderDied(const wp<IBinder>& who) {
537 (void)who;
538 triggerEvent();
539 };
540};
541
Frederick Mayle884d1a52024-09-30 17:42:45 -0700542ssize_t countFds() {
543 return std::distance(std::filesystem::directory_iterator("/proc/self/fd"),
544 std::filesystem::directory_iterator{});
545}
546
547struct FdLeakDetector {
548 int startCount;
549
550 FdLeakDetector() {
551 // This log statement is load bearing. We have to log something before
552 // counting FDs to make sure the logging system is initialized, otherwise
553 // the sockets it opens will look like a leak.
554 ALOGW("FdLeakDetector counting FDs.");
555 startCount = countFds();
556 }
557 ~FdLeakDetector() {
558 int endCount = countFds();
559 if (startCount != endCount) {
560 ADD_FAILURE() << "fd count changed (" << startCount << " -> " << endCount
561 << ") fd leak?";
562 }
563 }
564};
565
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700566TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
567 // EXPECT_DEATH works by forking the process
568 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
569}
570
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000571TEST_F(BinderLibTest, AddManagerToManager) {
572 sp<IServiceManager> sm = defaultServiceManager();
573 sp<IBinder> binder = IInterface::asBinder(sm);
574 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
575}
576
Parth Sane81b4d5a2024-05-23 14:11:13 +0000577TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
578 auto sm = defaultServiceManager();
579 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
580 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
581 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
582 virtual ~LocalRegistrationCallbackImpl() {}
583 };
584 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
585
586 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
587 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
588}
589
590TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
591 auto sm = defaultServiceManager();
592 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
593 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
594 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
595 virtual ~LocalRegistrationCallbackImpl() {}
596 };
597 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
598
599 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
600
601 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
602 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
603 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
604}
605
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500606TEST_F(BinderLibTest, WasParceled) {
607 auto binder = sp<BBinder>::make();
608 EXPECT_FALSE(binder->wasParceled());
609 Parcel data;
610 data.writeStrongBinder(binder);
611 EXPECT_TRUE(binder->wasParceled());
612}
613
Riley Andrews06b01ad2014-12-18 12:10:08 -0800614TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800615 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700616 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
617 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800618}
619
Steven Moreland80844f72020-12-12 02:06:08 +0000620TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000621 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700622 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
623 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000624}
625
Steven Morelandf183fdd2020-10-27 00:12:12 +0000626TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000627 Parcel data, reply;
628 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700629 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
630 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000631}
632
Marco Ballesio7ee17572020-09-08 10:30:03 -0700633TEST_F(BinderLibTest, Freeze) {
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700634 if (!checkFreezeSupport()) {
635 GTEST_SKIP() << "Skipping test for kernels that do not support proceess freezing";
Marco Ballesio7ee17572020-09-08 10:30:03 -0700636 return;
637 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700638 Parcel data, reply, replypid;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700639 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700640 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700641 for (int i = 0; i < 10; i++) {
642 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
643 }
Li Li6f059292021-09-10 09:59:30 -0700644
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700645 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Li Li6f059292021-09-10 09:59:30 -0700646 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000647
648 // b/268232063 - succeeds ~0.08% of the time
649 {
650 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
651 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
652 }
653
Li Li6f059292021-09-10 09:59:30 -0700654 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700655 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700656
Li Li4e678b92021-09-14 12:14:42 -0700657 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700658
659 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
660 &async_received));
661
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700662 EXPECT_EQ(sync_received, 1u);
663 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700664
Li Li4e678b92021-09-14 12:14:42 -0700665 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700666 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
667}
668
Riley Andrews06b01ad2014-12-18 12:10:08 -0800669TEST_F(BinderLibTest, SetError) {
670 int32_t testValue[] = { 0, -123, 123 };
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700671 for (size_t i = 0; i < countof(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800672 Parcel data, reply;
673 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700674 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
675 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800676 }
677}
678
679TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700680 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800681}
682
683TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800684 int32_t ptrsize;
685 Parcel data, reply;
686 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700687 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700688 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
689 StatusEq(NO_ERROR));
690 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800691 RecordProperty("TestPtrSize", sizeof(void *));
692 RecordProperty("ServerPtrSize", sizeof(void *));
693}
694
695TEST_F(BinderLibTest, IndirectGetId2)
696{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800697 int32_t id;
698 int32_t count;
699 Parcel data, reply;
700 int32_t serverId[3];
701
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700702 data.writeInt32(countof(serverId));
703 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800704 sp<IBinder> server;
705 BinderLibTestBundle datai;
706
707 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700708 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800709 data.writeStrongBinder(server);
710 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
711 datai.appendTo(&data);
712 }
713
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700714 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
715 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800716
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700717 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800718 EXPECT_EQ(0, id);
719
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700720 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700721 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800722
723 for (size_t i = 0; i < (size_t)count; i++) {
724 BinderLibTestBundle replyi(&reply);
725 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700726 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800727 EXPECT_EQ(serverId[i], id);
728 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
729 }
730
731 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
732}
733
734TEST_F(BinderLibTest, IndirectGetId3)
735{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800736 int32_t id;
737 int32_t count;
738 Parcel data, reply;
739 int32_t serverId[3];
740
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700741 data.writeInt32(countof(serverId));
742 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800743 sp<IBinder> server;
744 BinderLibTestBundle datai;
745 BinderLibTestBundle datai2;
746
747 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700748 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800749 data.writeStrongBinder(server);
750 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
751
752 datai.writeInt32(1);
753 datai.writeStrongBinder(m_server);
754 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
755 datai2.appendTo(&datai);
756
757 datai.appendTo(&data);
758 }
759
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700760 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
761 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800762
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700763 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800764 EXPECT_EQ(0, id);
765
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700766 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700767 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800768
769 for (size_t i = 0; i < (size_t)count; i++) {
770 int32_t counti;
771
772 BinderLibTestBundle replyi(&reply);
773 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700774 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800775 EXPECT_EQ(serverId[i], id);
776
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700777 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800778 EXPECT_EQ(1, counti);
779
780 BinderLibTestBundle replyi2(&replyi);
781 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700782 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800783 EXPECT_EQ(0, id);
784 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
785
786 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
787 }
788
789 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
790}
791
792TEST_F(BinderLibTest, CallBack)
793{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800794 Parcel data, reply;
795 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
796 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700797 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
798 StatusEq(NO_ERROR));
799 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
800 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800801}
802
Steven Moreland35626652021-05-15 01:32:04 +0000803TEST_F(BinderLibTest, BinderCallContextGuard) {
804 sp<IBinder> binder = addServer();
805 Parcel data, reply;
806 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
807 StatusEq(DEAD_OBJECT));
808}
809
Riley Andrews06b01ad2014-12-18 12:10:08 -0800810TEST_F(BinderLibTest, AddServer)
811{
812 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700813 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800814}
815
Riley Andrews06b01ad2014-12-18 12:10:08 -0800816TEST_F(BinderLibTest, DeathNotificationStrongRef)
817{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800818 sp<IBinder> sbinder;
819
820 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
821
822 {
823 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700824 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700825 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800826 sbinder = binder;
827 }
828 {
829 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700830 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
831 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800832 }
833 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700834 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
835 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800836}
837
838TEST_F(BinderLibTest, DeathNotificationMultiple)
839{
840 status_t ret;
841 const int clientcount = 2;
842 sp<IBinder> target;
843 sp<IBinder> linkedclient[clientcount];
844 sp<BinderLibTestCallBack> callBack[clientcount];
845 sp<IBinder> passiveclient[clientcount];
846
847 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700848 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800849 for (int i = 0; i < clientcount; i++) {
850 {
851 Parcel data, reply;
852
853 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700854 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800855 callBack[i] = new BinderLibTestCallBack();
856 data.writeStrongBinder(target);
857 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700858 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
859 &reply, TF_ONE_WAY),
860 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800861 }
862 {
863 Parcel data, reply;
864
865 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700866 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800867 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700868 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
869 &reply, TF_ONE_WAY),
870 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800871 }
872 }
873 {
874 Parcel data, reply;
875 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
876 EXPECT_EQ(0, ret);
877 }
878
879 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700880 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
881 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800882 }
883}
884
Martijn Coenenf7100e42017-07-31 12:14:09 +0200885TEST_F(BinderLibTest, DeathNotificationThread)
886{
887 status_t ret;
888 sp<BinderLibTestCallBack> callback;
889 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700890 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200891 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700892 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200893
894 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
895
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700896 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200897
898 {
899 Parcel data, reply;
900 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
901 EXPECT_EQ(0, ret);
902 }
903
904 /* Make sure it's dead */
905 testDeathRecipient->waitEvent(5);
906
907 /* Now, pass the ref to another process and ask that process to
908 * call linkToDeath() on it, and wait for a response. This tests
909 * two things:
910 * 1) You still get death notifications when calling linkToDeath()
911 * on a ref that is already dead when it was passed to you.
912 * 2) That death notifications are not directly pushed to the thread
913 * registering them, but to the threadpool (proc workqueue) instead.
914 *
915 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
916 * is blocked on a condition variable waiting for the death notification to be
917 * called; therefore, that thread is not available for handling proc work.
918 * So, if the death notification was pushed to the thread workqueue, the callback
919 * would never be called, and the test would timeout and fail.
920 *
921 * Note that we can't do this part of the test from this thread itself, because
922 * the binder driver would only push death notifications to the thread if
923 * it is a looper thread, which this thread is not.
924 *
925 * See b/23525545 for details.
926 */
927 {
928 Parcel data, reply;
929
930 callback = new BinderLibTestCallBack();
931 data.writeStrongBinder(target);
932 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700933 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
934 TF_ONE_WAY),
935 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200936 }
937
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700938 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
939 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200940}
941
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700942TEST_F(BinderLibTest, ReturnErrorIfKernelDoesNotSupportFreezeNotification) {
943 if (ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::FREEZE_NOTIFICATION)) {
944 GTEST_SKIP() << "Skipping test for kernels that support FREEZE_NOTIFICATION";
945 return;
946 }
947 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
948 sp<IBinder> binder = addServer();
949 ASSERT_NE(nullptr, binder);
950 ASSERT_EQ(nullptr, binder->localBinder());
951 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(INVALID_OPERATION));
952}
953
954TEST_F(BinderLibTest, FrozenStateChangeNotificatiion) {
955 if (!checkFreezeAndNotificationSupport()) {
956 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
957 return;
958 }
959 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
960 sp<IBinder> binder = addServer();
961 ASSERT_NE(nullptr, binder);
962 int32_t pid;
963 ASSERT_TRUE(getBinderPid(&pid, binder));
964
965 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
966 // Expect current state (unfrozen) to be delivered immediately.
967 callback->ensureUnfrozenEventReceived();
968 // Check that the process hasn't died otherwise there's a risk of freezing
969 // the wrong process.
970 EXPECT_EQ(OK, binder->pingBinder());
971 freezeProcess(pid);
972 callback->ensureFrozenEventReceived();
973 unfreezeProcess(pid);
974 callback->ensureUnfrozenEventReceived();
975 removeCallbackAndValidateNoEvent(binder, callback);
976}
977
978TEST_F(BinderLibTest, AddFrozenCallbackWhenFrozen) {
979 if (!checkFreezeAndNotificationSupport()) {
980 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
981 return;
982 }
983 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
984 sp<IBinder> binder = addServer();
985 ASSERT_NE(nullptr, binder);
986 int32_t pid;
987 ASSERT_TRUE(getBinderPid(&pid, binder));
988
989 // Check that the process hasn't died otherwise there's a risk of freezing
990 // the wrong process.
991 EXPECT_EQ(OK, binder->pingBinder());
992 freezeProcess(pid);
993 // Add the callback while the target process is frozen.
994 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
995 callback->ensureFrozenEventReceived();
996 unfreezeProcess(pid);
997 callback->ensureUnfrozenEventReceived();
998 removeCallbackAndValidateNoEvent(binder, callback);
999
1000 // Check that the process hasn't died otherwise there's a risk of freezing
1001 // the wrong process.
1002 EXPECT_EQ(OK, binder->pingBinder());
1003 freezeProcess(pid);
1004 unfreezeProcess(pid);
1005 // Make sure no callback happens since the listener has been removed.
1006 EXPECT_EQ(0u, callback->events.size());
1007}
1008
1009TEST_F(BinderLibTest, NoFrozenNotificationAfterCallbackRemoval) {
1010 if (!checkFreezeAndNotificationSupport()) {
1011 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1012 return;
1013 }
1014 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1015 sp<IBinder> binder = addServer();
1016 ASSERT_NE(nullptr, binder);
1017 int32_t pid;
1018 ASSERT_TRUE(getBinderPid(&pid, binder));
1019
1020 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1021 callback->ensureUnfrozenEventReceived();
1022 removeCallbackAndValidateNoEvent(binder, callback);
1023
1024 // Make sure no callback happens after the listener is removed.
1025 freezeProcess(pid);
1026 unfreezeProcess(pid);
1027 EXPECT_EQ(0u, callback->events.size());
1028}
1029
1030TEST_F(BinderLibTest, MultipleFrozenStateChangeCallbacks) {
1031 if (!checkFreezeAndNotificationSupport()) {
1032 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1033 return;
1034 }
1035 sp<TestFrozenStateChangeCallback> callback1 = sp<TestFrozenStateChangeCallback>::make();
1036 sp<TestFrozenStateChangeCallback> callback2 = sp<TestFrozenStateChangeCallback>::make();
1037 sp<IBinder> binder = addServer();
1038 ASSERT_NE(nullptr, binder);
1039 int32_t pid;
1040 ASSERT_TRUE(getBinderPid(&pid, binder));
1041
1042 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback1), StatusEq(NO_ERROR));
1043 // Expect current state (unfrozen) to be delivered immediately.
1044 callback1->ensureUnfrozenEventReceived();
1045
1046 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback2), StatusEq(NO_ERROR));
1047 // Expect current state (unfrozen) to be delivered immediately.
1048 callback2->ensureUnfrozenEventReceived();
1049
1050 freezeProcess(pid);
1051 callback1->ensureFrozenEventReceived();
1052 callback2->ensureFrozenEventReceived();
1053
1054 removeCallbackAndValidateNoEvent(binder, callback1);
1055 unfreezeProcess(pid);
1056 EXPECT_EQ(0u, callback1->events.size());
1057 callback2->ensureUnfrozenEventReceived();
1058 removeCallbackAndValidateNoEvent(binder, callback2);
1059
1060 freezeProcess(pid);
1061 EXPECT_EQ(0u, callback2->events.size());
1062}
1063
1064TEST_F(BinderLibTest, RemoveThenAddFrozenStateChangeCallbacks) {
1065 if (!checkFreezeAndNotificationSupport()) {
1066 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1067 return;
1068 }
1069 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1070 sp<IBinder> binder = addServer();
1071 ASSERT_NE(nullptr, binder);
1072 int32_t pid;
1073 ASSERT_TRUE(getBinderPid(&pid, binder));
1074
1075 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1076 // Expect current state (unfrozen) to be delivered immediately.
1077 callback->ensureUnfrozenEventReceived();
1078 removeCallbackAndValidateNoEvent(binder, callback);
1079
1080 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1081 callback->ensureUnfrozenEventReceived();
1082}
1083
1084TEST_F(BinderLibTest, CoalesceFreezeCallbacksWhenListenerIsFrozen) {
1085 if (!checkFreezeAndNotificationSupport()) {
1086 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1087 return;
1088 }
1089 sp<IBinder> binder = addServer();
1090 sp<IBinder> listener = addServer();
1091 ASSERT_NE(nullptr, binder);
1092 ASSERT_NE(nullptr, listener);
1093 int32_t pid, listenerPid;
1094 ASSERT_TRUE(getBinderPid(&pid, binder));
1095 ASSERT_TRUE(getBinderPid(&listenerPid, listener));
1096
1097 // Ask the listener process to register for state change callbacks.
1098 {
1099 Parcel data, reply;
1100 data.writeStrongBinder(binder);
1101 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE, data,
1102 &reply),
1103 StatusEq(NO_ERROR));
1104 }
1105 // Freeze the listener process.
1106 freezeProcess(listenerPid);
1107 createProcessGroup(getuid(), listenerPid);
1108 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Frozen"}));
1109 // Repeatedly flip the target process between frozen and unfrozen states.
1110 for (int i = 0; i < 1000; i++) {
1111 usleep(50);
1112 unfreezeProcess(pid);
1113 usleep(50);
1114 freezeProcess(pid);
1115 }
1116 // Unfreeze the listener process. Now it should receive the frozen state
1117 // change notifications.
1118 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Unfrozen"}));
1119 unfreezeProcess(listenerPid);
1120 // Wait for 500ms to give the process enough time to wake up and handle
1121 // notifications.
1122 usleep(500 * 1000);
1123 {
1124 std::vector<bool> events;
1125 Parcel data, reply;
1126 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS, data, &reply),
1127 StatusEq(NO_ERROR));
1128 reply.readBoolVector(&events);
1129 // There should only be one single state change notifications delievered.
1130 ASSERT_EQ(1u, events.size());
1131 EXPECT_TRUE(events[0]);
1132 }
1133}
1134
Riley Andrews06b01ad2014-12-18 12:10:08 -08001135TEST_F(BinderLibTest, PassFile) {
1136 int ret;
1137 int pipefd[2];
1138 uint8_t buf[1] = { 0 };
1139 uint8_t write_value = 123;
1140
1141 ret = pipe2(pipefd, O_NONBLOCK);
1142 ASSERT_EQ(0, ret);
1143
1144 {
1145 Parcel data, reply;
1146 uint8_t writebuf[1] = { write_value };
1147
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001148 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001149
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001150 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001151
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001152 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001153
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001154 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
1155 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001156 }
1157
1158 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -07001159 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001160 EXPECT_EQ(write_value, buf[0]);
1161
1162 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
1163
1164 ret = read(pipefd[0], buf, sizeof(buf));
1165 EXPECT_EQ(0, ret);
1166
1167 close(pipefd[0]);
1168}
1169
Ryo Hashimotobf551892018-05-31 16:58:35 +09001170TEST_F(BinderLibTest, PassParcelFileDescriptor) {
1171 const int datasize = 123;
1172 std::vector<uint8_t> writebuf(datasize);
1173 for (size_t i = 0; i < writebuf.size(); ++i) {
1174 writebuf[i] = i;
1175 }
1176
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001177 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001178 {
1179 int pipefd[2];
1180 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
1181 read_end.reset(pipefd[0]);
1182 write_end.reset(pipefd[1]);
1183 }
1184 {
1185 Parcel data;
1186 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
1187 write_end.reset();
1188 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
1189 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
1190
1191 Parcel reply;
1192 EXPECT_EQ(NO_ERROR,
1193 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
1194 &reply));
1195 }
1196 std::vector<uint8_t> readbuf(datasize);
1197 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
1198 EXPECT_EQ(writebuf, readbuf);
1199
1200 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
1201
1202 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
1203}
1204
Frederick Mayle884d1a52024-09-30 17:42:45 -07001205TEST_F(BinderLibTest, RecvOwnedFileDescriptors) {
1206 FdLeakDetector fd_leak_detector;
1207
1208 Parcel data;
1209 Parcel reply;
1210 EXPECT_EQ(NO_ERROR,
1211 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1212 &reply));
1213 unique_fd a, b;
1214 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1215 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1216}
1217
1218// Used to trigger fdsan error (b/239222407).
1219TEST_F(BinderLibTest, RecvOwnedFileDescriptorsAndWriteInt) {
1220 GTEST_SKIP() << "triggers fdsan false positive: b/370824489";
1221
1222 FdLeakDetector fd_leak_detector;
1223
1224 Parcel data;
1225 Parcel reply;
1226 EXPECT_EQ(NO_ERROR,
1227 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1228 &reply));
1229 reply.setDataPosition(reply.dataSize());
1230 reply.writeInt32(0);
1231 reply.setDataPosition(0);
1232 unique_fd a, b;
1233 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1234 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1235}
1236
1237// Used to trigger fdsan error (b/239222407).
1238TEST_F(BinderLibTest, RecvOwnedFileDescriptorsAndTruncate) {
1239 GTEST_SKIP() << "triggers fdsan false positive: b/370824489";
1240
1241 FdLeakDetector fd_leak_detector;
1242
1243 Parcel data;
1244 Parcel reply;
1245 EXPECT_EQ(NO_ERROR,
1246 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION, data,
1247 &reply));
1248 reply.setDataSize(reply.dataSize() - sizeof(flat_binder_object));
1249 unique_fd a, b;
1250 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1251 EXPECT_EQ(BAD_TYPE, reply.readUniqueFileDescriptor(&b));
1252}
1253
1254TEST_F(BinderLibTest, RecvUnownedFileDescriptors) {
1255 FdLeakDetector fd_leak_detector;
1256
1257 Parcel data;
1258 Parcel reply;
1259 EXPECT_EQ(NO_ERROR,
1260 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1261 &reply));
1262 unique_fd a, b;
1263 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1264 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1265}
1266
1267// Used to trigger fdsan error (b/239222407).
1268TEST_F(BinderLibTest, RecvUnownedFileDescriptorsAndWriteInt) {
1269 FdLeakDetector fd_leak_detector;
1270
1271 Parcel data;
1272 Parcel reply;
1273 EXPECT_EQ(NO_ERROR,
1274 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1275 &reply));
1276 reply.setDataPosition(reply.dataSize());
1277 reply.writeInt32(0);
1278 reply.setDataPosition(0);
1279 unique_fd a, b;
1280 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1281 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&b));
1282}
1283
1284// Used to trigger fdsan error (b/239222407).
1285TEST_F(BinderLibTest, RecvUnownedFileDescriptorsAndTruncate) {
1286 FdLeakDetector fd_leak_detector;
1287
1288 Parcel data;
1289 Parcel reply;
1290 EXPECT_EQ(NO_ERROR,
1291 m_server->transact(BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION, data,
1292 &reply));
1293 reply.setDataSize(reply.dataSize() - sizeof(flat_binder_object));
1294 unique_fd a, b;
1295 EXPECT_EQ(OK, reply.readUniqueFileDescriptor(&a));
1296 EXPECT_EQ(BAD_TYPE, reply.readUniqueFileDescriptor(&b));
1297}
1298
Riley Andrews06b01ad2014-12-18 12:10:08 -08001299TEST_F(BinderLibTest, PromoteLocal) {
1300 sp<IBinder> strong = new BBinder();
1301 wp<IBinder> weak = strong;
1302 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001303 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001304 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -07001305 strong = nullptr;
1306 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001307 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001308 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001309}
1310
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001311TEST_F(BinderLibTest, LocalGetExtension) {
1312 sp<BBinder> binder = new BBinder();
1313 sp<IBinder> ext = new BBinder();
1314 binder->setExtension(ext);
1315 EXPECT_EQ(ext, binder->getExtension());
1316}
1317
1318TEST_F(BinderLibTest, RemoteGetExtension) {
1319 sp<IBinder> server = addServer();
1320 ASSERT_TRUE(server != nullptr);
1321
1322 sp<IBinder> extension;
1323 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
1324 ASSERT_NE(nullptr, extension.get());
1325
1326 EXPECT_EQ(NO_ERROR, extension->pingBinder());
1327}
1328
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001329TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001330 Parcel data, reply;
1331
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001332 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
1333 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001334
1335 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -07001336 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +08001337 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
1338 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
1339 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
1340 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001341}
1342
Connor O'Brien52be2c92016-09-20 14:18:08 -07001343TEST_F(BinderLibTest, FreedBinder) {
1344 status_t ret;
1345
1346 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -07001347 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001348
1349 __u32 freedHandle;
1350 wp<IBinder> keepFreedBinder;
1351 {
1352 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001353 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1354 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -07001355 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
1356 freedHandle = freed->handle;
1357 /* Add a weak ref to the freed binder so the driver does not
1358 * delete its reference to it - otherwise the transaction
1359 * fails regardless of whether the driver is fixed.
1360 */
Steven Morelande171d622019-07-17 16:06:01 -07001361 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001362 }
Steven Morelande171d622019-07-17 16:06:01 -07001363 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001364 {
1365 Parcel data, reply;
1366 data.writeStrongBinder(server);
1367 /* Replace original handle with handle to the freed binder */
1368 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
1369 __u32 oldHandle = strong->handle;
1370 strong->handle = freedHandle;
1371 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
1372 /* Returns DEAD_OBJECT (-32) if target crashes and
1373 * FAILED_TRANSACTION if the driver rejects the invalid
1374 * object.
1375 */
1376 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
1377 /* Restore original handle so parcel destructor does not use
1378 * the wrong handle.
1379 */
1380 strong->handle = oldHandle;
1381 }
1382}
1383
Sherry Yang336cdd32017-07-24 14:12:27 -07001384TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -07001385 Parcel data, reply;
1386 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1387 for (int i = 0; i < 2; i++) {
1388 BinderLibTestBundle datai;
1389 datai.appendFrom(&data, 0, data.dataSize());
1390
1391 data.freeData();
1392 data.writeInt32(1);
1393 data.writeStrongBinder(callBack);
1394 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1395
1396 datai.appendTo(&data);
1397 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001398 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1399 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -07001400}
1401
Martijn Coenen45b07b42017-08-09 12:07:45 +02001402TEST_F(BinderLibTest, OnewayQueueing)
1403{
Martijn Coenen45b07b42017-08-09 12:07:45 +02001404 Parcel data, data2;
1405
1406 sp<IBinder> pollServer = addPollServer();
1407
1408 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1409 data.writeStrongBinder(callBack);
1410 data.writeInt32(500000); // delay in us before calling back
1411
1412 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1413 data2.writeStrongBinder(callBack2);
1414 data2.writeInt32(0); // delay in us
1415
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001416 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1417 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001418
1419 // The delay ensures that this second transaction will end up on the async_todo list
1420 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001421 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1422 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001423
1424 // The server will ensure that the two transactions are handled in the expected order;
1425 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001426 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1427 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001428
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001429 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1430 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001431}
1432
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001433TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1434{
1435 status_t ret;
1436 Parcel data, reply;
1437 data.writeInterfaceToken(binderLibTestServiceName);
1438 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1439 EXPECT_EQ(-1, reply.readInt32());
1440 EXPECT_EQ(NO_ERROR, ret);
1441}
1442
1443TEST_F(BinderLibTest, WorkSourceSet)
1444{
1445 status_t ret;
1446 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001447 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001448 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001449 data.writeInterfaceToken(binderLibTestServiceName);
1450 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1451 EXPECT_EQ(100, reply.readInt32());
1452 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001453 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1454 EXPECT_EQ(NO_ERROR, ret);
1455}
1456
1457TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1458{
1459 status_t ret;
1460 Parcel data, reply;
1461
1462 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1463 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1464
1465 data.writeInterfaceToken(binderLibTestServiceName);
1466 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1467 EXPECT_EQ(-1, reply.readInt32());
1468 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001469 EXPECT_EQ(NO_ERROR, ret);
1470}
1471
1472TEST_F(BinderLibTest, WorkSourceCleared)
1473{
1474 status_t ret;
1475 Parcel data, reply;
1476
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001477 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001478 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1479 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001480 data.writeInterfaceToken(binderLibTestServiceName);
1481 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1482
1483 EXPECT_EQ(-1, reply.readInt32());
1484 EXPECT_EQ(100, previousWorkSource);
1485 EXPECT_EQ(NO_ERROR, ret);
1486}
1487
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001488TEST_F(BinderLibTest, WorkSourceRestored)
1489{
1490 status_t ret;
1491 Parcel data, reply;
1492
1493 IPCThreadState::self()->setCallingWorkSourceUid(100);
1494 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1495 IPCThreadState::self()->restoreCallingWorkSource(token);
1496
1497 data.writeInterfaceToken(binderLibTestServiceName);
1498 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1499
1500 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001501 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001502 EXPECT_EQ(NO_ERROR, ret);
1503}
1504
Olivier Gaillard91a04802018-11-14 17:32:41 +00001505TEST_F(BinderLibTest, PropagateFlagSet)
1506{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001507 IPCThreadState::self()->clearPropagateWorkSource();
1508 IPCThreadState::self()->setCallingWorkSourceUid(100);
1509 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1510}
1511
1512TEST_F(BinderLibTest, PropagateFlagCleared)
1513{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001514 IPCThreadState::self()->setCallingWorkSourceUid(100);
1515 IPCThreadState::self()->clearPropagateWorkSource();
1516 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1517}
1518
1519TEST_F(BinderLibTest, PropagateFlagRestored)
1520{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001521 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1522 IPCThreadState::self()->restoreCallingWorkSource(token);
1523
1524 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1525}
1526
1527TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1528{
1529 IPCThreadState::self()->setCallingWorkSourceUid(100);
1530
1531 Parcel data, reply;
1532 status_t ret;
1533 data.writeInterfaceToken(binderLibTestServiceName);
1534 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001535 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001536
1537 Parcel data2, reply2;
1538 status_t ret2;
1539 data2.writeInterfaceToken(binderLibTestServiceName);
1540 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1541 EXPECT_EQ(100, reply2.readInt32());
1542 EXPECT_EQ(NO_ERROR, ret2);
1543}
1544
Steven Morelandbf1915b2020-07-16 22:43:02 +00001545TEST_F(BinderLibTest, SchedPolicySet) {
1546 sp<IBinder> server = addServer();
1547 ASSERT_TRUE(server != nullptr);
1548
1549 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001550 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1551 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001552
1553 int policy = reply.readInt32();
1554 int priority = reply.readInt32();
1555
1556 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1557 EXPECT_EQ(kSchedPriority, priority);
1558}
1559
Steven Morelandcf03cf12020-12-04 02:58:40 +00001560TEST_F(BinderLibTest, InheritRt) {
1561 sp<IBinder> server = addServer();
1562 ASSERT_TRUE(server != nullptr);
1563
1564 const struct sched_param param {
1565 .sched_priority = kSchedPriorityMore,
1566 };
1567 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1568
1569 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001570 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1571 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001572
1573 int policy = reply.readInt32();
1574 int priority = reply.readInt32();
1575
1576 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1577 EXPECT_EQ(kSchedPriorityMore, priority);
1578}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001579
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001580TEST_F(BinderLibTest, VectorSent) {
1581 Parcel data, reply;
1582 sp<IBinder> server = addServer();
1583 ASSERT_TRUE(server != nullptr);
1584
1585 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1586 data.writeUint64Vector(testValue);
1587
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001588 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001589 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001590 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001591 EXPECT_EQ(readValue, testValue);
1592}
1593
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001594TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1595 sp<IBinder> server = addServer();
1596 ASSERT_TRUE(server != nullptr);
1597
1598 Parcel reply;
1599 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1600 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001601 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001602 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1603
1604 const int result = fcntl(fd.get(), F_GETFL);
1605 ASSERT_NE(result, -1);
1606 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1607}
1608
Steven Moreland59b84442022-07-12 18:32:44 +00001609// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1610// This value is not exposed, but some code in the framework relies on being able to use
1611// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001612constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001613constexpr size_t kSizeBytesOverFull = 1'050'000;
1614
1615TEST_F(BinderLibTest, GargantuanVectorSent) {
1616 sp<IBinder> server = addServer();
1617 ASSERT_TRUE(server != nullptr);
1618
1619 for (size_t i = 0; i < 10; i++) {
1620 // a slight variation in size is used to consider certain possible caching implementations
1621 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1622
1623 Parcel data, reply;
1624 data.writeUint64Vector(testValue);
1625 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1626 << i;
1627 std::vector<uint64_t> readValue;
1628 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1629 EXPECT_EQ(readValue, testValue);
1630 }
1631}
1632
1633TEST_F(BinderLibTest, LimitExceededVectorSent) {
1634 sp<IBinder> server = addServer();
1635 ASSERT_TRUE(server != nullptr);
1636 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1637
1638 Parcel data, reply;
1639 data.writeUint64Vector(testValue);
1640 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1641 StatusEq(FAILED_TRANSACTION));
1642}
1643
Martijn Coenen82c75312019-07-24 15:18:30 +02001644TEST_F(BinderLibTest, BufRejected) {
1645 Parcel data, reply;
1646 uint32_t buf;
1647 sp<IBinder> server = addServer();
1648 ASSERT_TRUE(server != nullptr);
1649
1650 binder_buffer_object obj {
1651 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001652 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001653 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1654 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001655 };
1656 data.setDataCapacity(1024);
1657 // Write a bogus object at offset 0 to get an entry in the offset table
1658 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001659 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001660 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1661 // And now, overwrite it with the buffer object
1662 memcpy(parcelData, &obj, sizeof(obj));
1663 data.setDataSize(sizeof(obj));
1664
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001665 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001666
Martijn Coenen82c75312019-07-24 15:18:30 +02001667 // Either the kernel should reject this transaction (if it's correct), but
1668 // if it's not, the server implementation should return an error if it
1669 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001670 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001671 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001672}
1673
Steven Morelandf2e0a952021-11-01 18:17:23 -07001674TEST_F(BinderLibTest, WeakRejected) {
1675 Parcel data, reply;
1676 sp<IBinder> server = addServer();
1677 ASSERT_TRUE(server != nullptr);
1678
1679 auto binder = sp<BBinder>::make();
1680 wp<BBinder> wpBinder(binder);
1681 flat_binder_object obj{
1682 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1683 .flags = 0,
1684 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1685 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1686 };
1687 data.setDataCapacity(1024);
1688 // Write a bogus object at offset 0 to get an entry in the offset table
1689 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001690 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001691 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1692 // And now, overwrite it with the weak binder
1693 memcpy(parcelData, &obj, sizeof(obj));
1694 data.setDataSize(sizeof(obj));
1695
1696 // a previous bug caused other objects to be released an extra time, so we
1697 // test with an object that libbinder will actually try to release
1698 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1699
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001700 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001701
1702 // send it many times, since previous error was memory corruption, make it
1703 // more likely that the server crashes
1704 for (size_t i = 0; i < 100; i++) {
1705 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1706 StatusEq(BAD_VALUE));
1707 }
1708
1709 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1710}
1711
Steven Moreland254e8ef2021-04-19 22:28:50 +00001712TEST_F(BinderLibTest, GotSid) {
1713 sp<IBinder> server = addServer();
1714
1715 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001716 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001717}
1718
Andrei Homescu1519b982022-06-09 02:04:44 +00001719struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1720 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1721
1722 // Flattenable protocol
1723 size_t getFlattenedSize() const {
1724 // Return a valid non-zero size here so we don't get an unintended
1725 // BAD_VALUE from Parcel::write
1726 return 16;
1727 }
1728 size_t getFdCount() const { return mFdCount; }
1729 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1730 for (size_t i = 0; i < count; i++) {
1731 fds[i] = STDIN_FILENO;
1732 }
1733 return NO_ERROR;
1734 }
1735 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1736 size_t & /*count*/) {
1737 /* This doesn't get called */
1738 return NO_ERROR;
1739 }
1740
1741 size_t mFdCount;
1742};
1743
1744TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1745 rlimit origNofile;
1746 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1747 ASSERT_EQ(0, ret);
1748
1749 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001750 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001751
1752 rlimit testNofile = {1024, 1024};
1753 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1754 ASSERT_EQ(0, ret);
1755
1756 Parcel parcel;
1757 // Try to write more file descriptors than supported by the OS
1758 TooManyFdsFlattenable tooManyFds1(1024);
1759 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1760
1761 // Try to write more file descriptors than the internal limit
1762 TooManyFdsFlattenable tooManyFds2(1025);
1763 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1764}
1765
Jayant Chowdhary30700942022-01-31 14:12:40 -08001766TEST(ServiceNotifications, Unregister) {
1767 auto sm = defaultServiceManager();
1768 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1769 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1770 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1771 virtual ~LocalRegistrationCallbackImpl() {}
1772 };
1773 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1774
1775 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1776 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1777}
1778
Elie Kheirallah47431c12022-04-21 23:46:17 +00001779TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1780 Parcel data, reply;
1781 sp<IBinder> server = addServer();
1782 ASSERT_TRUE(server != nullptr);
1783 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1784 StatusEq(NO_ERROR));
1785 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001786 // see getThreadPoolMaxTotalThreadCount for why there is a race
1787 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1788
Elie Kheirallah47431c12022-04-21 23:46:17 +00001789 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1790
1791 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001792 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1793 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1794 * started threads from setThreadPoolMaxThreadCount
1795 *
1796 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001797 */
1798 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001799 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001800 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001801 Parcel local_reply;
1802 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1803 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001804 }));
1805 }
1806
Steven Moreland3e9debc2023-06-15 00:35:29 +00001807 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1808 // the time, the below call will pre-empt them (presumably because we have the
1809 // scheduler timeslice already + scheduler hint).
1810 sleep(1);
1811
1812 data.writeInt32(1000);
1813 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001814 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1815
1816 for (auto &t : ts) {
1817 t.join();
1818 }
1819
1820 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1821 StatusEq(NO_ERROR));
1822 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001823 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001824}
1825
Devin Moore4354f712022-12-08 01:44:46 +00001826TEST_F(BinderLibTest, ThreadPoolStarted) {
1827 Parcel data, reply;
1828 sp<IBinder> server = addServer();
1829 ASSERT_TRUE(server != nullptr);
1830 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1831 EXPECT_TRUE(reply.readBool());
1832}
1833
Elie Kheirallah47431c12022-04-21 23:46:17 +00001834size_t epochMillis() {
1835 using std::chrono::duration_cast;
1836 using std::chrono::milliseconds;
1837 using std::chrono::seconds;
1838 using std::chrono::system_clock;
1839 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1840}
1841
1842TEST_F(BinderLibTest, HangingServices) {
1843 Parcel data, reply;
1844 sp<IBinder> server = addServer();
1845 ASSERT_TRUE(server != nullptr);
1846 int32_t delay = 1000; // ms
1847 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001848 // b/266537959 - must take before taking lock, since countdown is started in the remote
1849 // process there.
1850 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001851 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1852 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001853 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1854 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001855 Parcel local_reply;
1856 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1857 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001858 }));
1859 }
1860
1861 for (auto &t : ts) {
1862 t.join();
1863 }
1864 size_t epochMsAfter = epochMillis();
1865
1866 // deadlock occurred and threads only finished after 1s passed.
1867 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1868}
1869
Jing Jibbe9ae62023-10-07 15:26:02 -07001870TEST_F(BinderLibTest, BinderProxyCount) {
1871 Parcel data, reply;
1872 sp<IBinder> server = addServer();
1873 ASSERT_NE(server, nullptr);
1874
1875 uint32_t initialCount = BpBinder::getBinderProxyCount();
1876 size_t iterations = 100;
1877 {
1878 uint32_t count = initialCount;
1879 std::vector<sp<IBinder> > proxies;
1880 sp<IBinder> proxy;
1881 // Create binder proxies and verify the count.
1882 for (size_t i = 0; i < iterations; i++) {
1883 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1884 StatusEq(NO_ERROR));
1885 proxies.push_back(reply.readStrongBinder());
1886 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1887 }
1888 // Remove every other one and verify the count.
1889 auto it = proxies.begin();
1890 for (size_t i = 0; it != proxies.end(); i++) {
1891 if (i % 2 == 0) {
1892 it = proxies.erase(it);
1893 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1894 }
1895 }
1896 }
1897 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1898}
1899
Jing Jibdbe29a2023-10-03 00:03:28 -07001900static constexpr int kBpCountHighWatermark = 20;
1901static constexpr int kBpCountLowWatermark = 10;
1902static constexpr int kBpCountWarningWatermark = 15;
1903static constexpr int kInvalidUid = -1;
1904
1905TEST_F(BinderLibTest, BinderProxyCountCallback) {
1906 Parcel data, reply;
1907 sp<IBinder> server = addServer();
1908 ASSERT_NE(server, nullptr);
1909
1910 BpBinder::enableCountByUid();
1911 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1912 int32_t uid = reply.readInt32();
1913 ASSERT_NE(uid, kInvalidUid);
1914
1915 uint32_t initialCount = BpBinder::getBinderProxyCount();
1916 {
1917 uint32_t count = initialCount;
1918 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1919 kBpCountLowWatermark,
1920 kBpCountWarningWatermark);
1921 int limitCallbackUid = kInvalidUid;
1922 int warningCallbackUid = kInvalidUid;
1923 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1924 [&](int uid) { warningCallbackUid = uid; });
1925
1926 std::vector<sp<IBinder> > proxies;
1927 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1928 warningCallbackUid = limitCallbackUid = kInvalidUid;
1929 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1930 StatusEq(NO_ERROR));
1931 proxies.push_back(reply.readStrongBinder());
1932 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1933 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1934 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1935 };
1936 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1937 warningCallbackUid = limitCallbackUid = kInvalidUid;
1938 proxies.pop_back();
1939 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1940 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1941 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1942 };
1943
1944 // Test the increment/decrement of the binder proxies.
1945 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1946 createProxyOnce(kInvalidUid, kInvalidUid);
1947 }
1948 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1949 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1950 createProxyOnce(kInvalidUid, kInvalidUid);
1951 }
1952 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1953 createProxyOnce(kInvalidUid, kInvalidUid);
1954 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1955 removeProxyOnce(kInvalidUid, kInvalidUid);
1956 }
1957 createProxyOnce(kInvalidUid, kInvalidUid);
1958
1959 // Go down below the low watermark.
1960 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1961 removeProxyOnce(kInvalidUid, kInvalidUid);
1962 }
1963 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1964 createProxyOnce(kInvalidUid, kInvalidUid);
1965 }
1966 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1967 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1968 createProxyOnce(kInvalidUid, kInvalidUid);
1969 }
1970 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1971 createProxyOnce(kInvalidUid, kInvalidUid);
1972 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1973 removeProxyOnce(kInvalidUid, kInvalidUid);
1974 }
1975 createProxyOnce(kInvalidUid, kInvalidUid);
1976 }
1977 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1978}
1979
Yifan Hong84bedeb2021-04-21 21:37:17 -07001980class BinderLibRpcTestBase : public BinderLibTest {
1981public:
1982 void SetUp() override {
1983 if (!base::GetBoolProperty("ro.debuggable", false)) {
1984 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1985 "non-debuggable builds.";
1986 }
1987 BinderLibTest::SetUp();
1988 }
1989
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001990 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001991 auto rpcServer = RpcServer::make();
1992 EXPECT_NE(nullptr, rpcServer);
1993 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001994 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001995 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1996 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001997 return {};
1998 }
1999 return {rpcServer->releaseServer(), port};
2000 }
2001};
2002
Yifan Hong8b890852021-06-10 13:44:09 -07002003class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07002004
Yifan Hongbd276552022-02-28 15:28:51 -08002005// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
2006// If device is debuggable AND not on user builds, expects matcher.
2007// Otherwise expects INVALID_OPERATION.
2008// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
2009static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
2010 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
2011 android::base::GetProperty("ro.build.type", "") != "user";
2012 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
2013}
2014
Yifan Hong8b890852021-06-10 13:44:09 -07002015TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
2016 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07002017 ASSERT_TRUE(binder != nullptr);
2018 auto [socket, port] = CreateSocket();
2019 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08002020 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
2021 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002022}
2023
Yifan Hong8b890852021-06-10 13:44:09 -07002024// Tests for multiple RpcServer's on the same binder object.
2025TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
2026 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07002027 ASSERT_TRUE(binder != nullptr);
2028
2029 auto [socket1, port1] = CreateSocket();
2030 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07002031 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08002032 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
2033 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002034
2035 auto [socket2, port2] = CreateSocket();
2036 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07002037 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08002038 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
2039 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002040}
2041
Yifan Hong8b890852021-06-10 13:44:09 -07002042// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
2043// local binders.
2044class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07002045public:
2046 sp<IBinder> GetService() {
2047 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
2048 }
2049 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
2050 return info.param ? "remote" : "local";
2051 }
2052};
2053
Yifan Hong8b890852021-06-10 13:44:09 -07002054TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
2055 auto binder = GetService();
2056 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002057 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08002058 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07002059}
2060
2061TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07002062 auto binder = GetService();
2063 ASSERT_TRUE(binder != nullptr);
2064 auto [socket, port] = CreateSocket();
2065 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08002066 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
2067 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07002068}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07002069INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
2070 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07002071
Yifan Hong543edcd2021-05-18 19:47:30 -07002072class BinderLibTestService : public BBinder {
2073public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07002074 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
2075 : m_id(id),
2076 m_nextServerId(id + 1),
2077 m_serverStartRequested(false),
2078 m_callback(nullptr),
2079 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07002080 pthread_mutex_init(&m_serverWaitMutex, nullptr);
2081 pthread_cond_init(&m_serverWaitCond, nullptr);
2082 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07002083 ~BinderLibTestService() {
2084 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
2085 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002086
Yifan Hong543edcd2021-05-18 19:47:30 -07002087 void processPendingCall() {
2088 if (m_callback != nullptr) {
2089 Parcel data;
2090 data.writeInt32(NO_ERROR);
2091 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
2092 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002093 }
Yifan Hong543edcd2021-05-18 19:47:30 -07002094 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002095
Yifan Hong543edcd2021-05-18 19:47:30 -07002096 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
2097 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07002098 // TODO(b/182914638): also checks getCallingUid() for RPC
2099 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07002100 return PERMISSION_DENIED;
2101 }
2102 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002103 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002104 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00002105 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08002106 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002107 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002108 return BAD_VALUE;
2109 }
2110
Yifan Hong543edcd2021-05-18 19:47:30 -07002111 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002112
2113 pthread_mutex_lock(&m_serverWaitMutex);
2114 if (m_serverStartRequested) {
2115 m_serverStartRequested = false;
2116 m_serverStarted = binder;
2117 pthread_cond_signal(&m_serverWaitCond);
2118 }
2119 pthread_mutex_unlock(&m_serverWaitMutex);
2120 return NO_ERROR;
2121 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002122 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08002123 case BINDER_LIB_TEST_ADD_SERVER: {
2124 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002125 int serverid;
2126
2127 if (m_id != 0) {
2128 return INVALID_OPERATION;
2129 }
2130 pthread_mutex_lock(&m_serverWaitMutex);
2131 if (m_serverStartRequested) {
2132 ret = -EBUSY;
2133 } else {
2134 serverid = m_nextServerId++;
2135 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002136 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002137
2138 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002139 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002140 pthread_mutex_lock(&m_serverWaitMutex);
2141 }
2142 if (ret > 0) {
2143 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002144 struct timespec ts;
2145 clock_gettime(CLOCK_REALTIME, &ts);
2146 ts.tv_sec += 5;
2147 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002148 }
2149 if (m_serverStartRequested) {
2150 m_serverStartRequested = false;
2151 ret = -ETIMEDOUT;
2152 } else {
2153 reply->writeStrongBinder(m_serverStarted);
2154 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07002155 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002156 ret = NO_ERROR;
2157 }
2158 } else if (ret >= 0) {
2159 m_serverStartRequested = false;
2160 ret = UNKNOWN_ERROR;
2161 }
2162 pthread_mutex_unlock(&m_serverWaitMutex);
2163 return ret;
2164 }
Steven Moreland35626652021-05-15 01:32:04 +00002165 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
2166 IPCThreadState::SpGuard spGuard{
2167 .address = __builtin_frame_address(0),
2168 .context = "GuardInBinderTransaction",
2169 };
2170 const IPCThreadState::SpGuard *origGuard =
2171 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2172
2173 // if the guard works, this should abort
2174 (void)IPCThreadState::self()->getCallingPid();
2175
2176 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
2177 return NO_ERROR;
2178 }
2179
Marco Ballesio7ee17572020-09-08 10:30:03 -07002180 case BINDER_LIB_TEST_GETPID:
2181 reply->writeInt32(getpid());
2182 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07002183 case BINDER_LIB_TEST_GETUID:
2184 reply->writeInt32(getuid());
2185 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07002186 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
2187 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00002188 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08002189 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00002190 // oneway error codes should be ignored
2191 if (flags & TF_ONE_WAY) {
2192 return UNKNOWN_ERROR;
2193 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002194 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002195 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
2196 // Note: this transaction is only designed for use with a
2197 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07002198 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02002199 // A callback was already pending; this means that
2200 // we received a second call while still processing
2201 // the first one. Fail the test.
2202 sp<IBinder> callback = data.readStrongBinder();
2203 Parcel data2;
2204 data2.writeInt32(UNKNOWN_ERROR);
2205
Yi Kong91635562018-06-07 14:38:36 -07002206 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002207 } else {
2208 m_callback = data.readStrongBinder();
2209 int32_t delayUs = data.readInt32();
2210 /*
2211 * It's necessary that we sleep here, so the next
2212 * transaction the caller makes will be queued to
2213 * the async queue.
2214 */
2215 usleep(delayUs);
2216
2217 /*
2218 * Now when we return, libbinder will tell the kernel
2219 * we are done with this transaction, and the kernel
2220 * can move the queued transaction to either the
2221 * thread todo worklist (for kernels without the fix),
2222 * or the proc todo worklist. In case of the former,
2223 * the next outbound call will pick up the pending
2224 * transaction, which leads to undesired reentrant
2225 * behavior. This is caught in the if() branch above.
2226 */
2227 }
2228
2229 return NO_ERROR;
2230 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002231 case BINDER_LIB_TEST_NOP_CALL_BACK: {
2232 Parcel data2, reply2;
2233 sp<IBinder> binder;
2234 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002235 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002236 return BAD_VALUE;
2237 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02002238 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002239 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2240 return NO_ERROR;
2241 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07002242 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
2243 reply->writeStrongBinder(this);
2244 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002245 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
2246 reply->writeInt32(m_id);
2247 return NO_ERROR;
2248 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
2249 int32_t count;
2250 uint32_t indirect_code;
2251 sp<IBinder> binder;
2252
2253 count = data.readInt32();
2254 reply->writeInt32(m_id);
2255 reply->writeInt32(count);
2256 for (int i = 0; i < count; i++) {
2257 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002258 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002259 return BAD_VALUE;
2260 }
2261 indirect_code = data.readInt32();
2262 BinderLibTestBundle data2(&data);
2263 if (!data2.isValid()) {
2264 return BAD_VALUE;
2265 }
2266 BinderLibTestBundle reply2;
2267 binder->transact(indirect_code, data2, &reply2);
2268 reply2.appendTo(reply);
2269 }
2270 return NO_ERROR;
2271 }
2272 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
2273 reply->setError(data.readInt32());
2274 return NO_ERROR;
2275 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
2276 reply->writeInt32(sizeof(void *));
2277 return NO_ERROR;
2278 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
2279 return NO_ERROR;
2280 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
2281 m_strongRef = data.readStrongBinder();
2282 return NO_ERROR;
2283 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
2284 int ret;
2285 Parcel data2, reply2;
2286 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
2287 sp<IBinder> target;
2288 sp<IBinder> callback;
2289
2290 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002291 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002292 return BAD_VALUE;
2293 }
2294 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002295 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002296 return BAD_VALUE;
2297 }
2298 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07002299 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002300 data2.writeInt32(ret);
2301 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2302 return NO_ERROR;
2303 }
2304 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
2305 int ret;
2306 int32_t size;
2307 const void *buf;
2308 int fd;
2309
2310 fd = data.readFileDescriptor();
2311 if (fd < 0) {
2312 return BAD_VALUE;
2313 }
2314 ret = data.readInt32(&size);
2315 if (ret != NO_ERROR) {
2316 return ret;
2317 }
2318 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07002319 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002320 return BAD_VALUE;
2321 }
2322 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07002323 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002324 return NO_ERROR;
2325 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09002326 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
2327 int ret;
2328 int32_t size;
2329 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002330 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09002331
2332 ret = data.readUniqueParcelFileDescriptor(&fd);
2333 if (ret != NO_ERROR) {
2334 return ret;
2335 }
2336 ret = data.readInt32(&size);
2337 if (ret != NO_ERROR) {
2338 return ret;
2339 }
2340 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07002341 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09002342 return BAD_VALUE;
2343 }
2344 ret = write(fd.get(), buf, size);
2345 if (ret != size) return UNKNOWN_ERROR;
2346 return NO_ERROR;
2347 }
Frederick Mayle884d1a52024-09-30 17:42:45 -07002348 case BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_OWNED_TRANSACTION: {
2349 unique_fd fd1(memfd_create("memfd1", MFD_CLOEXEC));
2350 if (!fd1.ok()) {
2351 PLOGE("memfd_create failed");
2352 return UNKNOWN_ERROR;
2353 }
2354 unique_fd fd2(memfd_create("memfd2", MFD_CLOEXEC));
2355 if (!fd2.ok()) {
2356 PLOGE("memfd_create failed");
2357 return UNKNOWN_ERROR;
2358 }
2359 status_t ret;
2360 ret = reply->writeFileDescriptor(fd1.release(), true);
2361 if (ret != NO_ERROR) {
2362 return ret;
2363 }
2364 ret = reply->writeFileDescriptor(fd2.release(), true);
2365 if (ret != NO_ERROR) {
2366 return ret;
2367 }
2368 return NO_ERROR;
2369 }
2370 case BINDER_LIB_TEST_GET_FILE_DESCRIPTORS_UNOWNED_TRANSACTION: {
2371 status_t ret;
2372 ret = reply->writeFileDescriptor(STDOUT_FILENO, false);
2373 if (ret != NO_ERROR) {
2374 return ret;
2375 }
2376 ret = reply->writeFileDescriptor(STDERR_FILENO, false);
2377 if (ret != NO_ERROR) {
2378 return ret;
2379 }
2380 return NO_ERROR;
2381 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002382 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
2383 alarm(10);
2384 return NO_ERROR;
2385 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07002386 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002387 ;
2388 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002389 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07002390 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07002391 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002392 return NO_ERROR;
2393 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002394 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
2395 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00002396 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002397 return NO_ERROR;
2398 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00002399 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
2400 int policy = 0;
2401 sched_param param;
2402 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
2403 return UNKNOWN_ERROR;
2404 }
2405 reply->writeInt32(policy);
2406 reply->writeInt32(param.sched_priority);
2407 return NO_ERROR;
2408 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002409 case BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE: {
2410 sp<IBinder> binder = data.readStrongBinder();
2411 frozenStateChangeCallback = sp<TestFrozenStateChangeCallback>::make();
2412 // Hold an strong pointer to the binder object so it doesn't go
2413 // away.
2414 frozenStateChangeCallback->binder = binder;
2415 int ret = binder->addFrozenStateChangeCallback(frozenStateChangeCallback);
2416 if (ret != NO_ERROR) {
2417 return ret;
2418 }
2419 auto event = frozenStateChangeCallback->events.popWithTimeout(10ms);
2420 if (!event.has_value()) {
2421 return NOT_ENOUGH_DATA;
2422 }
2423 return NO_ERROR;
2424 }
2425 case BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS: {
2426 reply->writeBoolVector(frozenStateChangeCallback->getAllAndClear());
2427 return NO_ERROR;
2428 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002429 case BINDER_LIB_TEST_ECHO_VECTOR: {
2430 std::vector<uint64_t> vector;
2431 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07002432 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002433 reply->writeUint64Vector(vector);
2434 return NO_ERROR;
2435 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002436 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
2437 std::array<int, 2> sockets;
2438 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
2439 if (!created) {
2440 ALOGE("Could not create socket pair");
2441 return UNKNOWN_ERROR;
2442 }
2443
2444 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2445 if (result != 0) {
2446 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2447 return UNKNOWN_ERROR;
2448 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002449 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002450 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2451 if (writeResult != NO_ERROR) {
2452 ALOGE("Could not write unique_fd");
2453 return writeResult;
2454 }
2455 close(sockets[1]); // we don't need the other side of the fd
2456 return NO_ERROR;
2457 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07002458 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02002459 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2460 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00002461 case BINDER_LIB_TEST_CAN_GET_SID: {
2462 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2463 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002464 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2465 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2466 return NO_ERROR;
2467 }
Devin Moore4354f712022-12-08 01:44:46 +00002468 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2469 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2470 return NO_ERROR;
2471 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002472 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002473 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002474 return NO_ERROR;
2475 }
2476 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002477 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002478 return NO_ERROR;
2479 }
2480 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2481 int32_t ms = data.readInt32();
2482 return unlockInMs(ms);
2483 }
2484 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002485 m_blockMutex.lock();
2486 sp<BinderLibTestService> thisService = this;
2487 int32_t value = data.readInt32();
2488 // start local thread to unlock in 1s
2489 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002490 t.detach();
2491 return NO_ERROR;
2492 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002493 default:
2494 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002495 };
2496 }
2497
Elie Kheirallah47431c12022-04-21 23:46:17 +00002498 status_t unlockInMs(int32_t ms) {
2499 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002500 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002501 return NO_ERROR;
2502 }
2503
Yifan Hong543edcd2021-05-18 19:47:30 -07002504private:
2505 int32_t m_id;
2506 int32_t m_nextServerId;
2507 pthread_mutex_t m_serverWaitMutex;
2508 pthread_cond_t m_serverWaitCond;
2509 bool m_serverStartRequested;
2510 sp<IBinder> m_serverStarted;
2511 sp<IBinder> m_strongRef;
2512 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002513 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002514 std::mutex m_blockMutex;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002515 sp<TestFrozenStateChangeCallback> frozenStateChangeCallback;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002516};
2517
Martijn Coenen45b07b42017-08-09 12:07:45 +02002518int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002519{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002520 binderLibTestServiceName += String16(binderserversuffix);
2521
Steven Moreland35626652021-05-15 01:32:04 +00002522 // Testing to make sure that calls that we are serving can use getCallin*
2523 // even though we don't here.
2524 IPCThreadState::SpGuard spGuard{
2525 .address = __builtin_frame_address(0),
2526 .context = "main server thread",
2527 };
2528 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2529
Riley Andrews06b01ad2014-12-18 12:10:08 -08002530 status_t ret;
2531 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02002532 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002533 {
2534 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002535
Steven Morelandbf1915b2020-07-16 22:43:02 +00002536 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2537
Steven Morelandcf03cf12020-12-04 02:58:40 +00002538 testService->setInheritRt(true);
2539
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002540 /*
2541 * Normally would also contain functionality as well, but we are only
2542 * testing the extension mechanism.
2543 */
2544 testService->setExtension(new BBinder());
2545
Martijn Coenen82c75312019-07-24 15:18:30 +02002546 // Required for test "BufRejected'
2547 testService->setRequestingSid(true);
2548
Martijn Coenen45b07b42017-08-09 12:07:45 +02002549 /*
2550 * We need this below, but can't hold a sp<> because it prevents the
2551 * node from being cleaned up automatically. It's safe in this case
2552 * because of how the tests are written.
2553 */
2554 testServicePtr = testService.get();
2555
Riley Andrews06b01ad2014-12-18 12:10:08 -08002556 if (index == 0) {
2557 ret = sm->addService(binderLibTestServiceName, testService);
2558 } else {
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002559 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -08002560 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002561 LIBBINDER_IGNORE_END()
Riley Andrews06b01ad2014-12-18 12:10:08 -08002562 Parcel data, reply;
2563 data.writeInt32(index);
2564 data.writeStrongBinder(testService);
2565
2566 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2567 }
2568 }
2569 write(readypipefd, &ret, sizeof(ret));
2570 close(readypipefd);
2571 //printf("%s: ret %d\n", __func__, ret);
2572 if (ret)
2573 return 1;
2574 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002575 if (usePoll) {
2576 int fd;
2577 struct epoll_event ev;
2578 int epoll_fd;
2579 IPCThreadState::self()->setupPolling(&fd);
2580 if (fd < 0) {
2581 return 1;
2582 }
2583 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2584
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002585 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002586 if (epoll_fd == -1) {
2587 return 1;
2588 }
2589
2590 ev.events = EPOLLIN;
2591 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2592 return 1;
2593 }
2594
2595 while (1) {
2596 /*
2597 * We simulate a single-threaded process using the binder poll
2598 * interface; besides handling binder commands, it can also
2599 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002600 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002601 *
2602 * processPendingCall() will then issue that transaction.
2603 */
2604 struct epoll_event events[1];
2605 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2606 if (numEvents < 0) {
2607 if (errno == EINTR) {
2608 continue;
2609 }
2610 return 1;
2611 }
2612 if (numEvents > 0) {
2613 IPCThreadState::self()->handlePolledCommands();
2614 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2615 testServicePtr->processPendingCall();
2616 }
2617 }
2618 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002619 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002620 ProcessState::self()->startThreadPool();
2621 IPCThreadState::self()->joinThreadPool();
2622 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002623 //printf("%s: joinThreadPool returned\n", __func__);
2624 return 1; /* joinThreadPool should not return */
2625}
2626
Steven Moreland68275d72023-04-21 22:12:45 +00002627int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002628 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002629 binderservername = argv[2];
2630 } else {
2631 binderservername = argv[0];
2632 }
2633
Martijn Coenen45b07b42017-08-09 12:07:45 +02002634 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2635 binderserversuffix = argv[5];
2636 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002637 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002638 binderserversuffix = new char[16];
2639 snprintf(binderserversuffix, 16, "%d", getpid());
2640 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002641
2642 ::testing::InitGoogleTest(&argc, argv);
2643 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2644 ProcessState::self()->startThreadPool();
2645 return RUN_ALL_TESTS();
2646}