blob: bcab6decca28553801785f6025a00172b8517017 [file] [log] [blame]
Riley Andrews06b01ad2014-12-18 12:10:08 -08001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080018#include <poll.h>
19#include <pthread.h>
20#include <stdio.h>
21#include <stdlib.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070022
23#include <chrono>
Yifan Hong8b890852021-06-10 13:44:09 -070024#include <fstream>
Steven Morelandd7088702021-01-13 00:27:00 +000025#include <thread>
Riley Andrews06b01ad2014-12-18 12:10:08 -080026
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070027#include <gmock/gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080028#include <gtest/gtest.h>
29
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070030#include <android-base/logging.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070031#include <android-base/properties.h>
Yifan Hong28d6c352021-06-04 17:27:35 -070032#include <android-base/result-gmock.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080033#include <binder/Binder.h>
Yifan Hong34823232021-06-07 17:23:00 -070034#include <binder/BpBinder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000035#include <binder/Functional.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080036#include <binder/IBinder.h>
37#include <binder/IPCThreadState.h>
38#include <binder/IServiceManager.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070039#include <binder/RpcServer.h>
40#include <binder/RpcSession.h>
Parth Sane81b4d5a2024-05-23 14:11:13 +000041#include <binder/Status.h>
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070042#include <binder/unique_fd.h>
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070043#include <input/BlockingQueue.h>
44#include <processgroup/processgroup.h>
Tomasz Wasilczyk300aa132023-10-26 15:00:04 -070045#include <utils/Flattenable.h>
Riley Andrews06b01ad2014-12-18 12:10:08 -080046
Steven Morelandcf03cf12020-12-04 02:58:40 +000047#include <linux/sched.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020048#include <sys/epoll.h>
Steven Morelandda048352020-02-19 13:25:53 -080049#include <sys/prctl.h>
Yifan Hong84bedeb2021-04-21 21:37:17 -070050#include <sys/socket.h>
51#include <sys/un.h>
Martijn Coenen45b07b42017-08-09 12:07:45 +020052
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -070053#include "../Utils.h"
Steven Moreland6ba5a252021-05-04 22:49:00 +000054#include "../binder_module.h"
Steven Morelandf9f3de22020-05-06 17:14:39 -070055
Riley Andrews06b01ad2014-12-18 12:10:08 -080056using namespace android;
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000057using namespace android::binder::impl;
Yifan Hong84bedeb2021-04-21 21:37:17 -070058using namespace std::string_literals;
59using namespace std::chrono_literals;
Yifan Hong28d6c352021-06-04 17:27:35 -070060using android::base::testing::HasValue;
Parth Sane81b4d5a2024-05-23 14:11:13 +000061using android::binder::Status;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -070062using android::binder::unique_fd;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -070063using std::chrono_literals::operator""ms;
Yifan Hong84bedeb2021-04-21 21:37:17 -070064using testing::ExplainMatchResult;
Yifan Hongbd276552022-02-28 15:28:51 -080065using testing::Matcher;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070066using testing::Not;
Yifan Hong84bedeb2021-04-21 21:37:17 -070067using testing::WithParamInterface;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -070068
69// e.g. EXPECT_THAT(expr, StatusEq(OK)) << "additional message";
70MATCHER_P(StatusEq, expected, (negation ? "not " : "") + statusToString(expected)) {
71 *result_listener << statusToString(arg);
72 return expected == arg;
73}
Riley Andrews06b01ad2014-12-18 12:10:08 -080074
Sherry Yang336cdd32017-07-24 14:12:27 -070075static ::testing::AssertionResult IsPageAligned(void *buf) {
Vilas Bhat04e28c72024-02-12 21:47:15 +000076 if (((unsigned long)buf & ((unsigned long)getpagesize() - 1)) == 0)
Sherry Yang336cdd32017-07-24 14:12:27 -070077 return ::testing::AssertionSuccess();
78 else
79 return ::testing::AssertionFailure() << buf << " is not page aligned";
80}
81
Riley Andrews06b01ad2014-12-18 12:10:08 -080082static testing::Environment* binder_env;
83static char *binderservername;
Connor O'Brien87c03cf2016-10-26 17:58:51 -070084static char *binderserversuffix;
Riley Andrews06b01ad2014-12-18 12:10:08 -080085static char binderserverarg[] = "--binderserver";
86
Steven Morelandbf1915b2020-07-16 22:43:02 +000087static constexpr int kSchedPolicy = SCHED_RR;
88static constexpr int kSchedPriority = 7;
Steven Morelandcf03cf12020-12-04 02:58:40 +000089static constexpr int kSchedPriorityMore = 8;
Steven Moreland3e9debc2023-06-15 00:35:29 +000090static constexpr int kKernelThreads = 17; // anything different than the default
Steven Morelandbf1915b2020-07-16 22:43:02 +000091
Riley Andrews06b01ad2014-12-18 12:10:08 -080092static String16 binderLibTestServiceName = String16("test.binderLib");
93
94enum BinderLibTestTranscationCode {
95 BINDER_LIB_TEST_NOP_TRANSACTION = IBinder::FIRST_CALL_TRANSACTION,
96 BINDER_LIB_TEST_REGISTER_SERVER,
97 BINDER_LIB_TEST_ADD_SERVER,
Martijn Coenen45b07b42017-08-09 12:07:45 +020098 BINDER_LIB_TEST_ADD_POLL_SERVER,
Steven Moreland35626652021-05-15 01:32:04 +000099 BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800100 BINDER_LIB_TEST_CALL_BACK,
Sherry Yang336cdd32017-07-24 14:12:27 -0700101 BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200102 BINDER_LIB_TEST_DELAYED_CALL_BACK,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800103 BINDER_LIB_TEST_NOP_CALL_BACK,
Arve Hjønnevåg70604312016-08-12 15:34:51 -0700104 BINDER_LIB_TEST_GET_SELF_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800105 BINDER_LIB_TEST_GET_ID_TRANSACTION,
106 BINDER_LIB_TEST_INDIRECT_TRANSACTION,
107 BINDER_LIB_TEST_SET_ERROR_TRANSACTION,
108 BINDER_LIB_TEST_GET_STATUS_TRANSACTION,
109 BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION,
110 BINDER_LIB_TEST_LINK_DEATH_TRANSACTION,
111 BINDER_LIB_TEST_WRITE_FILE_TRANSACTION,
Ryo Hashimotobf551892018-05-31 16:58:35 +0900112 BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION,
Riley Andrews06b01ad2014-12-18 12:10:08 -0800113 BINDER_LIB_TEST_EXIT_TRANSACTION,
114 BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION,
115 BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION,
Connor O'Brien52be2c92016-09-20 14:18:08 -0700116 BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION,
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +0100117 BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION,
Steven Morelandbf1915b2020-07-16 22:43:02 +0000118 BINDER_LIB_TEST_GET_SCHEDULING_POLICY,
Marco Ballesio7ee17572020-09-08 10:30:03 -0700119 BINDER_LIB_TEST_NOP_TRANSACTION_WAIT,
120 BINDER_LIB_TEST_GETPID,
Jing Jibdbe29a2023-10-03 00:03:28 -0700121 BINDER_LIB_TEST_GETUID,
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700122 BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE,
123 BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS,
Kevin DuBois2f82d5b2018-12-05 12:56:10 -0800124 BINDER_LIB_TEST_ECHO_VECTOR,
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -0700125 BINDER_LIB_TEST_GET_NON_BLOCKING_FD,
Steven Morelandf2e0a952021-11-01 18:17:23 -0700126 BINDER_LIB_TEST_REJECT_OBJECTS,
Steven Moreland254e8ef2021-04-19 22:28:50 +0000127 BINDER_LIB_TEST_CAN_GET_SID,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000128 BINDER_LIB_TEST_GET_MAX_THREAD_COUNT,
129 BINDER_LIB_TEST_SET_MAX_THREAD_COUNT,
Devin Moore4354f712022-12-08 01:44:46 +0000130 BINDER_LIB_TEST_IS_THREADPOOL_STARTED,
Elie Kheirallah47431c12022-04-21 23:46:17 +0000131 BINDER_LIB_TEST_LOCK_UNLOCK,
132 BINDER_LIB_TEST_PROCESS_LOCK,
133 BINDER_LIB_TEST_UNLOCK_AFTER_MS,
134 BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK
Riley Andrews06b01ad2014-12-18 12:10:08 -0800135};
136
Martijn Coenen45b07b42017-08-09 12:07:45 +0200137pid_t start_server_process(int arg2, bool usePoll = false)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800138{
139 int ret;
140 pid_t pid;
141 status_t status;
142 int pipefd[2];
143 char stri[16];
144 char strpipefd1[16];
Martijn Coenen45b07b42017-08-09 12:07:45 +0200145 char usepoll[2];
Riley Andrews06b01ad2014-12-18 12:10:08 -0800146 char *childargv[] = {
147 binderservername,
148 binderserverarg,
149 stri,
150 strpipefd1,
Martijn Coenen45b07b42017-08-09 12:07:45 +0200151 usepoll,
Connor O'Brien87c03cf2016-10-26 17:58:51 -0700152 binderserversuffix,
Yi Kong91635562018-06-07 14:38:36 -0700153 nullptr
Riley Andrews06b01ad2014-12-18 12:10:08 -0800154 };
155
156 ret = pipe(pipefd);
157 if (ret < 0)
158 return ret;
159
160 snprintf(stri, sizeof(stri), "%d", arg2);
161 snprintf(strpipefd1, sizeof(strpipefd1), "%d", pipefd[1]);
Martijn Coenen45b07b42017-08-09 12:07:45 +0200162 snprintf(usepoll, sizeof(usepoll), "%d", usePoll ? 1 : 0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800163
164 pid = fork();
165 if (pid == -1)
166 return pid;
167 if (pid == 0) {
Steven Morelandda048352020-02-19 13:25:53 -0800168 prctl(PR_SET_PDEATHSIG, SIGHUP);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800169 close(pipefd[0]);
170 execv(binderservername, childargv);
171 status = -errno;
172 write(pipefd[1], &status, sizeof(status));
173 fprintf(stderr, "execv failed, %s\n", strerror(errno));
174 _exit(EXIT_FAILURE);
175 }
176 close(pipefd[1]);
177 ret = read(pipefd[0], &status, sizeof(status));
178 //printf("pipe read returned %d, status %d\n", ret, status);
179 close(pipefd[0]);
180 if (ret == sizeof(status)) {
181 ret = status;
182 } else {
183 kill(pid, SIGKILL);
184 if (ret >= 0) {
185 ret = NO_INIT;
186 }
187 }
188 if (ret < 0) {
Yi Kong91635562018-06-07 14:38:36 -0700189 wait(nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800190 return ret;
191 }
192 return pid;
193}
194
Yifan Hong84bedeb2021-04-21 21:37:17 -0700195android::base::Result<int32_t> GetId(sp<IBinder> service) {
196 using android::base::Error;
197 Parcel data, reply;
198 data.markForBinder(service);
199 const char *prefix = data.isForRpc() ? "On RPC server, " : "On binder server, ";
200 status_t status = service->transact(BINDER_LIB_TEST_GET_ID_TRANSACTION, data, &reply);
201 if (status != OK)
202 return Error(status) << prefix << "transact(GET_ID): " << statusToString(status);
203 int32_t result = 0;
204 status = reply.readInt32(&result);
205 if (status != OK) return Error(status) << prefix << "readInt32: " << statusToString(status);
206 return result;
207}
208
Riley Andrews06b01ad2014-12-18 12:10:08 -0800209class BinderLibTestEnv : public ::testing::Environment {
210 public:
211 BinderLibTestEnv() {}
212 sp<IBinder> getServer(void) {
213 return m_server;
214 }
215
216 private:
217 virtual void SetUp() {
218 m_serverpid = start_server_process(0);
219 //printf("m_serverpid %d\n", m_serverpid);
220 ASSERT_GT(m_serverpid, 0);
221
222 sp<IServiceManager> sm = defaultServiceManager();
223 //printf("%s: pid %d, get service\n", __func__, m_pid);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700224 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -0800225 m_server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700226 LIBBINDER_IGNORE_END()
Yi Kong91635562018-06-07 14:38:36 -0700227 ASSERT_TRUE(m_server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800228 //printf("%s: pid %d, get service done\n", __func__, m_pid);
229 }
230 virtual void TearDown() {
231 status_t ret;
232 Parcel data, reply;
233 int exitStatus;
234 pid_t pid;
235
236 //printf("%s: pid %d\n", __func__, m_pid);
Yi Kong91635562018-06-07 14:38:36 -0700237 if (m_server != nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800238 ret = m_server->transact(BINDER_LIB_TEST_GET_STATUS_TRANSACTION, data, &reply);
239 EXPECT_EQ(0, ret);
240 ret = m_server->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
241 EXPECT_EQ(0, ret);
242 }
243 if (m_serverpid > 0) {
244 //printf("wait for %d\n", m_pids[i]);
245 pid = wait(&exitStatus);
246 EXPECT_EQ(m_serverpid, pid);
247 EXPECT_TRUE(WIFEXITED(exitStatus));
248 EXPECT_EQ(0, WEXITSTATUS(exitStatus));
249 }
250 }
251
252 pid_t m_serverpid;
253 sp<IBinder> m_server;
254};
255
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700256class TestFrozenStateChangeCallback : public IBinder::FrozenStateChangeCallback {
257public:
258 BlockingQueue<std::pair<const wp<IBinder>, State>> events;
259
260 virtual void onStateChanged(const wp<IBinder>& who, State state) {
261 events.push(std::make_pair(who, state));
262 }
263
264 void ensureFrozenEventReceived() {
265 auto event = events.popWithTimeout(500ms);
266 ASSERT_TRUE(event.has_value());
267 EXPECT_EQ(State::FROZEN, event->second); // isFrozen should be true
268 EXPECT_EQ(0u, events.size());
269 }
270
271 void ensureUnfrozenEventReceived() {
272 auto event = events.popWithTimeout(500ms);
273 ASSERT_TRUE(event.has_value());
274 EXPECT_EQ(State::UNFROZEN, event->second); // isFrozen should be false
275 EXPECT_EQ(0u, events.size());
276 }
277
278 std::vector<bool> getAllAndClear() {
279 std::vector<bool> results;
280 while (true) {
281 auto event = events.popWithTimeout(0ms);
282 if (!event.has_value()) {
283 break;
284 }
285 results.push_back(event->second == State::FROZEN);
286 }
287 return results;
288 }
289
290 sp<IBinder> binder;
291};
292
Riley Andrews06b01ad2014-12-18 12:10:08 -0800293class BinderLibTest : public ::testing::Test {
294 public:
295 virtual void SetUp() {
296 m_server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
Parth Sane81b4d5a2024-05-23 14:11:13 +0000297 IPCThreadState::self()->restoreCallingWorkSource(0);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800298 }
299 virtual void TearDown() {
300 }
301 protected:
Martijn Coenen45b07b42017-08-09 12:07:45 +0200302 sp<IBinder> addServerEtc(int32_t *idPtr, int code)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800303 {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800304 int32_t id;
305 Parcel data, reply;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800306
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700307 EXPECT_THAT(m_server->transact(code, data, &reply), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800308
Elie Kheirallahb7246642022-05-03 18:01:43 +0000309 sp<IBinder> binder = reply.readStrongBinder();
310 EXPECT_NE(nullptr, binder);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700311 EXPECT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800312 if (idPtr)
313 *idPtr = id;
314 return binder;
315 }
Martijn Coenen45b07b42017-08-09 12:07:45 +0200316
Yi Kong91635562018-06-07 14:38:36 -0700317 sp<IBinder> addServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200318 {
319 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_SERVER);
320 }
321
Yi Kong91635562018-06-07 14:38:36 -0700322 sp<IBinder> addPollServer(int32_t *idPtr = nullptr)
Martijn Coenen45b07b42017-08-09 12:07:45 +0200323 {
324 return addServerEtc(idPtr, BINDER_LIB_TEST_ADD_POLL_SERVER);
325 }
326
Riley Andrews06b01ad2014-12-18 12:10:08 -0800327 void waitForReadData(int fd, int timeout_ms) {
328 int ret;
329 pollfd pfd = pollfd();
330
331 pfd.fd = fd;
332 pfd.events = POLLIN;
333 ret = poll(&pfd, 1, timeout_ms);
334 EXPECT_EQ(1, ret);
335 }
336
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700337 bool checkFreezeSupport() {
338 std::ifstream freezer_file("/sys/fs/cgroup/uid_0/cgroup.freeze");
339 // Pass test on devices where the cgroup v2 freezer is not supported
340 if (freezer_file.fail()) {
341 return false;
342 }
343 return IPCThreadState::self()->freeze(getpid(), false, 0) == NO_ERROR;
344 }
345
346 bool checkFreezeAndNotificationSupport() {
347 if (!checkFreezeSupport()) {
348 return false;
349 }
350 return ProcessState::isDriverFeatureEnabled(
351 ProcessState::DriverFeature::FREEZE_NOTIFICATION);
352 }
353
354 bool getBinderPid(int32_t* pid, sp<IBinder> server) {
355 Parcel data, replypid;
356 if (server->transact(BINDER_LIB_TEST_GETPID, data, &replypid) != NO_ERROR) {
357 ALOGE("BINDER_LIB_TEST_GETPID failed");
358 return false;
359 }
360 *pid = replypid.readInt32();
361 if (*pid <= 0) {
362 ALOGE("pid should be greater than zero");
363 return false;
364 }
365 return true;
366 }
367
368 void freezeProcess(int32_t pid) {
369 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
370 }
371
372 void unfreezeProcess(int32_t pid) {
373 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
374 }
375
376 void removeCallbackAndValidateNoEvent(sp<IBinder> binder,
377 sp<TestFrozenStateChangeCallback> callback) {
378 EXPECT_THAT(binder->removeFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
379 EXPECT_EQ(0u, callback->events.size());
380 }
381
Riley Andrews06b01ad2014-12-18 12:10:08 -0800382 sp<IBinder> m_server;
383};
384
385class BinderLibTestBundle : public Parcel
386{
387 public:
388 BinderLibTestBundle(void) {}
Chih-Hung Hsieh5ca1ea42018-12-20 15:42:22 -0800389 explicit BinderLibTestBundle(const Parcel *source) : m_isValid(false) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800390 int32_t mark;
391 int32_t bundleLen;
392 size_t pos;
393
394 if (source->readInt32(&mark))
395 return;
396 if (mark != MARK_START)
397 return;
398 if (source->readInt32(&bundleLen))
399 return;
400 pos = source->dataPosition();
401 if (Parcel::appendFrom(source, pos, bundleLen))
402 return;
403 source->setDataPosition(pos + bundleLen);
404 if (source->readInt32(&mark))
405 return;
406 if (mark != MARK_END)
407 return;
408 m_isValid = true;
409 setDataPosition(0);
410 }
411 void appendTo(Parcel *dest) {
412 dest->writeInt32(MARK_START);
413 dest->writeInt32(dataSize());
414 dest->appendFrom(this, 0, dataSize());
415 dest->writeInt32(MARK_END);
416 };
417 bool isValid(void) {
418 return m_isValid;
419 }
420 private:
421 enum {
422 MARK_START = B_PACK_CHARS('B','T','B','S'),
423 MARK_END = B_PACK_CHARS('B','T','B','E'),
424 };
425 bool m_isValid;
426};
427
428class BinderLibTestEvent
429{
430 public:
431 BinderLibTestEvent(void)
432 : m_eventTriggered(false)
433 {
Yi Kong91635562018-06-07 14:38:36 -0700434 pthread_mutex_init(&m_waitMutex, nullptr);
435 pthread_cond_init(&m_waitCond, nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800436 }
437 int waitEvent(int timeout_s)
438 {
439 int ret;
440 pthread_mutex_lock(&m_waitMutex);
441 if (!m_eventTriggered) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800442 struct timespec ts;
443 clock_gettime(CLOCK_REALTIME, &ts);
444 ts.tv_sec += timeout_s;
445 pthread_cond_timedwait(&m_waitCond, &m_waitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800446 }
447 ret = m_eventTriggered ? NO_ERROR : TIMED_OUT;
448 pthread_mutex_unlock(&m_waitMutex);
449 return ret;
450 }
Martijn Coenenf7100e42017-07-31 12:14:09 +0200451 pthread_t getTriggeringThread()
452 {
453 return m_triggeringThread;
454 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800455 protected:
456 void triggerEvent(void) {
457 pthread_mutex_lock(&m_waitMutex);
458 pthread_cond_signal(&m_waitCond);
459 m_eventTriggered = true;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200460 m_triggeringThread = pthread_self();
Riley Andrews06b01ad2014-12-18 12:10:08 -0800461 pthread_mutex_unlock(&m_waitMutex);
462 };
463 private:
464 pthread_mutex_t m_waitMutex;
465 pthread_cond_t m_waitCond;
466 bool m_eventTriggered;
Martijn Coenenf7100e42017-07-31 12:14:09 +0200467 pthread_t m_triggeringThread;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800468};
469
470class BinderLibTestCallBack : public BBinder, public BinderLibTestEvent
471{
472 public:
473 BinderLibTestCallBack()
474 : m_result(NOT_ENOUGH_DATA)
Yi Kong91635562018-06-07 14:38:36 -0700475 , m_prev_end(nullptr)
Riley Andrews06b01ad2014-12-18 12:10:08 -0800476 {
477 }
478 status_t getResult(void)
479 {
480 return m_result;
481 }
482
483 private:
484 virtual status_t onTransact(uint32_t code,
485 const Parcel& data, Parcel* reply,
486 uint32_t flags = 0)
487 {
488 (void)reply;
489 (void)flags;
490 switch(code) {
Martijn Coenenfb368f72017-08-10 15:03:18 +0200491 case BINDER_LIB_TEST_CALL_BACK: {
492 status_t status = data.readInt32(&m_result);
493 if (status != NO_ERROR) {
494 m_result = status;
495 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800496 triggerEvent();
497 return NO_ERROR;
Martijn Coenenfb368f72017-08-10 15:03:18 +0200498 }
Sherry Yang336cdd32017-07-24 14:12:27 -0700499 case BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF: {
500 sp<IBinder> server;
501 int ret;
502 const uint8_t *buf = data.data();
503 size_t size = data.dataSize();
504 if (m_prev_end) {
505 /* 64-bit kernel needs at most 8 bytes to align buffer end */
506 EXPECT_LE((size_t)(buf - m_prev_end), (size_t)8);
507 } else {
508 EXPECT_TRUE(IsPageAligned((void *)buf));
509 }
510
511 m_prev_end = buf + size + data.objectsCount() * sizeof(binder_size_t);
512
513 if (size > 0) {
514 server = static_cast<BinderLibTestEnv *>(binder_env)->getServer();
515 ret = server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION,
516 data, reply);
517 EXPECT_EQ(NO_ERROR, ret);
518 }
519 return NO_ERROR;
520 }
Riley Andrews06b01ad2014-12-18 12:10:08 -0800521 default:
522 return UNKNOWN_TRANSACTION;
523 }
524 }
525
526 status_t m_result;
Sherry Yang336cdd32017-07-24 14:12:27 -0700527 const uint8_t *m_prev_end;
Riley Andrews06b01ad2014-12-18 12:10:08 -0800528};
529
530class TestDeathRecipient : public IBinder::DeathRecipient, public BinderLibTestEvent
531{
532 private:
533 virtual void binderDied(const wp<IBinder>& who) {
534 (void)who;
535 triggerEvent();
536 };
537};
538
Steven Morelandbd98e0f2021-10-14 14:24:15 -0700539TEST_F(BinderLibTest, CannotUseBinderAfterFork) {
540 // EXPECT_DEATH works by forking the process
541 EXPECT_DEATH({ ProcessState::self(); }, "libbinder ProcessState can not be used after fork");
542}
543
Steven Moreland5c75a5a2022-05-11 22:15:10 +0000544TEST_F(BinderLibTest, AddManagerToManager) {
545 sp<IServiceManager> sm = defaultServiceManager();
546 sp<IBinder> binder = IInterface::asBinder(sm);
547 EXPECT_EQ(NO_ERROR, sm->addService(String16("binderLibTest-manager"), binder));
548}
549
Parth Sane81b4d5a2024-05-23 14:11:13 +0000550TEST_F(BinderLibTest, RegisterForNotificationsFailure) {
551 auto sm = defaultServiceManager();
552 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
553 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
554 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
555 virtual ~LocalRegistrationCallbackImpl() {}
556 };
557 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
558
559 EXPECT_EQ(BAD_VALUE, sm->registerForNotifications(String16("ValidName"), nullptr));
560 EXPECT_EQ(UNKNOWN_ERROR, sm->registerForNotifications(String16("InvalidName!$"), cb));
561}
562
563TEST_F(BinderLibTest, UnregisterForNotificationsFailure) {
564 auto sm = defaultServiceManager();
565 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
566 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
567 void onServiceRegistration(const String16&, const sp<IBinder>&) override {}
568 virtual ~LocalRegistrationCallbackImpl() {}
569 };
570 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
571
572 EXPECT_EQ(OK, sm->registerForNotifications(String16("ValidName"), cb));
573
574 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("ValidName"), nullptr));
575 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("AnotherValidName"), cb));
576 EXPECT_EQ(BAD_VALUE, sm->unregisterForNotifications(String16("InvalidName!!!"), cb));
577}
578
Kalesh Singhd67c8e82020-12-29 15:46:25 -0500579TEST_F(BinderLibTest, WasParceled) {
580 auto binder = sp<BBinder>::make();
581 EXPECT_FALSE(binder->wasParceled());
582 Parcel data;
583 data.writeStrongBinder(binder);
584 EXPECT_TRUE(binder->wasParceled());
585}
586
Riley Andrews06b01ad2014-12-18 12:10:08 -0800587TEST_F(BinderLibTest, NopTransaction) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800588 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700589 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply),
590 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800591}
592
Steven Moreland80844f72020-12-12 02:06:08 +0000593TEST_F(BinderLibTest, NopTransactionOneway) {
Steven Moreland80844f72020-12-12 02:06:08 +0000594 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700595 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_ONE_WAY),
596 StatusEq(NO_ERROR));
Steven Moreland80844f72020-12-12 02:06:08 +0000597}
598
Steven Morelandf183fdd2020-10-27 00:12:12 +0000599TEST_F(BinderLibTest, NopTransactionClear) {
Steven Morelandf183fdd2020-10-27 00:12:12 +0000600 Parcel data, reply;
601 // make sure it accepts the transaction flag
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700602 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply, TF_CLEAR_BUF),
603 StatusEq(NO_ERROR));
Steven Morelandf183fdd2020-10-27 00:12:12 +0000604}
605
Marco Ballesio7ee17572020-09-08 10:30:03 -0700606TEST_F(BinderLibTest, Freeze) {
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700607 if (!checkFreezeSupport()) {
608 GTEST_SKIP() << "Skipping test for kernels that do not support proceess freezing";
Marco Ballesio7ee17572020-09-08 10:30:03 -0700609 return;
610 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700611 Parcel data, reply, replypid;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700612 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETPID, data, &replypid), StatusEq(NO_ERROR));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700613 int32_t pid = replypid.readInt32();
Marco Ballesio7ee17572020-09-08 10:30:03 -0700614 for (int i = 0; i < 10; i++) {
615 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION_WAIT, data, &reply, TF_ONE_WAY));
616 }
Li Li6f059292021-09-10 09:59:30 -0700617
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700618 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Li Li6f059292021-09-10 09:59:30 -0700619 EXPECT_EQ(-EAGAIN, IPCThreadState::self()->freeze(pid, true, 0));
Steven Morelandee739eb2023-02-13 21:03:49 +0000620
621 // b/268232063 - succeeds ~0.08% of the time
622 {
623 auto ret = IPCThreadState::self()->freeze(pid, true, 0);
624 EXPECT_TRUE(ret == -EAGAIN || ret == OK);
625 }
626
Li Li6f059292021-09-10 09:59:30 -0700627 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, true, 1000));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700628 EXPECT_EQ(FAILED_TRANSACTION, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700629
Li Li4e678b92021-09-14 12:14:42 -0700630 uint32_t sync_received, async_received;
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700631
632 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->getProcessFreezeInfo(pid, &sync_received,
633 &async_received));
634
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700635 EXPECT_EQ(sync_received, 1u);
636 EXPECT_EQ(async_received, 0u);
Marco Ballesiob09fc4a2020-09-11 16:17:21 -0700637
Li Li4e678b92021-09-14 12:14:42 -0700638 EXPECT_EQ(NO_ERROR, IPCThreadState::self()->freeze(pid, false, 0));
Marco Ballesio7ee17572020-09-08 10:30:03 -0700639 EXPECT_EQ(NO_ERROR, m_server->transact(BINDER_LIB_TEST_NOP_TRANSACTION, data, &reply));
640}
641
Riley Andrews06b01ad2014-12-18 12:10:08 -0800642TEST_F(BinderLibTest, SetError) {
643 int32_t testValue[] = { 0, -123, 123 };
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700644 for (size_t i = 0; i < countof(testValue); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800645 Parcel data, reply;
646 data.writeInt32(testValue[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700647 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_SET_ERROR_TRANSACTION, data, &reply),
648 StatusEq(testValue[i]));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800649 }
650}
651
652TEST_F(BinderLibTest, GetId) {
Yifan Hong28d6c352021-06-04 17:27:35 -0700653 EXPECT_THAT(GetId(m_server), HasValue(0));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800654}
655
656TEST_F(BinderLibTest, PtrSize) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800657 int32_t ptrsize;
658 Parcel data, reply;
659 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700660 ASSERT_TRUE(server != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700661 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION, data, &reply),
662 StatusEq(NO_ERROR));
663 EXPECT_THAT(reply.readInt32(&ptrsize), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800664 RecordProperty("TestPtrSize", sizeof(void *));
665 RecordProperty("ServerPtrSize", sizeof(void *));
666}
667
668TEST_F(BinderLibTest, IndirectGetId2)
669{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800670 int32_t id;
671 int32_t count;
672 Parcel data, reply;
673 int32_t serverId[3];
674
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700675 data.writeInt32(countof(serverId));
676 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800677 sp<IBinder> server;
678 BinderLibTestBundle datai;
679
680 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700681 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800682 data.writeStrongBinder(server);
683 data.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
684 datai.appendTo(&data);
685 }
686
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700687 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
688 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800689
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700690 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800691 EXPECT_EQ(0, id);
692
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700693 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700694 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800695
696 for (size_t i = 0; i < (size_t)count; i++) {
697 BinderLibTestBundle replyi(&reply);
698 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700699 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800700 EXPECT_EQ(serverId[i], id);
701 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
702 }
703
704 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
705}
706
707TEST_F(BinderLibTest, IndirectGetId3)
708{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800709 int32_t id;
710 int32_t count;
711 Parcel data, reply;
712 int32_t serverId[3];
713
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700714 data.writeInt32(countof(serverId));
715 for (size_t i = 0; i < countof(serverId); i++) {
Riley Andrews06b01ad2014-12-18 12:10:08 -0800716 sp<IBinder> server;
717 BinderLibTestBundle datai;
718 BinderLibTestBundle datai2;
719
720 server = addServer(&serverId[i]);
Yi Kong91635562018-06-07 14:38:36 -0700721 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800722 data.writeStrongBinder(server);
723 data.writeInt32(BINDER_LIB_TEST_INDIRECT_TRANSACTION);
724
725 datai.writeInt32(1);
726 datai.writeStrongBinder(m_server);
727 datai.writeInt32(BINDER_LIB_TEST_GET_ID_TRANSACTION);
728 datai2.appendTo(&datai);
729
730 datai.appendTo(&data);
731 }
732
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700733 ASSERT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
734 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800735
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700736 ASSERT_THAT(reply.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800737 EXPECT_EQ(0, id);
738
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700739 ASSERT_THAT(reply.readInt32(&count), StatusEq(NO_ERROR));
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -0700740 EXPECT_EQ(countof(serverId), (size_t)count);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800741
742 for (size_t i = 0; i < (size_t)count; i++) {
743 int32_t counti;
744
745 BinderLibTestBundle replyi(&reply);
746 EXPECT_TRUE(replyi.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700747 EXPECT_THAT(replyi.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800748 EXPECT_EQ(serverId[i], id);
749
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700750 ASSERT_THAT(replyi.readInt32(&counti), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800751 EXPECT_EQ(1, counti);
752
753 BinderLibTestBundle replyi2(&replyi);
754 EXPECT_TRUE(replyi2.isValid());
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700755 EXPECT_THAT(replyi2.readInt32(&id), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800756 EXPECT_EQ(0, id);
757 EXPECT_EQ(replyi2.dataSize(), replyi2.dataPosition());
758
759 EXPECT_EQ(replyi.dataSize(), replyi.dataPosition());
760 }
761
762 EXPECT_EQ(reply.dataSize(), reply.dataPosition());
763}
764
765TEST_F(BinderLibTest, CallBack)
766{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800767 Parcel data, reply;
768 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
769 data.writeStrongBinder(callBack);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700770 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_NOP_CALL_BACK, data, &reply, TF_ONE_WAY),
771 StatusEq(NO_ERROR));
772 EXPECT_THAT(callBack->waitEvent(5), StatusEq(NO_ERROR));
773 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800774}
775
Steven Moreland35626652021-05-15 01:32:04 +0000776TEST_F(BinderLibTest, BinderCallContextGuard) {
777 sp<IBinder> binder = addServer();
778 Parcel data, reply;
779 EXPECT_THAT(binder->transact(BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION, data, &reply),
780 StatusEq(DEAD_OBJECT));
781}
782
Riley Andrews06b01ad2014-12-18 12:10:08 -0800783TEST_F(BinderLibTest, AddServer)
784{
785 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700786 ASSERT_TRUE(server != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800787}
788
Riley Andrews06b01ad2014-12-18 12:10:08 -0800789TEST_F(BinderLibTest, DeathNotificationStrongRef)
790{
Riley Andrews06b01ad2014-12-18 12:10:08 -0800791 sp<IBinder> sbinder;
792
793 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
794
795 {
796 sp<IBinder> binder = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700797 ASSERT_TRUE(binder != nullptr);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700798 EXPECT_THAT(binder->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800799 sbinder = binder;
800 }
801 {
802 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700803 EXPECT_THAT(sbinder->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY),
804 StatusEq(OK));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800805 }
806 IPCThreadState::self()->flushCommands();
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700807 EXPECT_THAT(testDeathRecipient->waitEvent(5), StatusEq(NO_ERROR));
808 EXPECT_THAT(sbinder->unlinkToDeath(testDeathRecipient), StatusEq(DEAD_OBJECT));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800809}
810
811TEST_F(BinderLibTest, DeathNotificationMultiple)
812{
813 status_t ret;
814 const int clientcount = 2;
815 sp<IBinder> target;
816 sp<IBinder> linkedclient[clientcount];
817 sp<BinderLibTestCallBack> callBack[clientcount];
818 sp<IBinder> passiveclient[clientcount];
819
820 target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700821 ASSERT_TRUE(target != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800822 for (int i = 0; i < clientcount; i++) {
823 {
824 Parcel data, reply;
825
826 linkedclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700827 ASSERT_TRUE(linkedclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800828 callBack[i] = new BinderLibTestCallBack();
829 data.writeStrongBinder(target);
830 data.writeStrongBinder(callBack[i]);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700831 EXPECT_THAT(linkedclient[i]->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data,
832 &reply, TF_ONE_WAY),
833 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800834 }
835 {
836 Parcel data, reply;
837
838 passiveclient[i] = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700839 ASSERT_TRUE(passiveclient[i] != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -0800840 data.writeStrongBinder(target);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700841 EXPECT_THAT(passiveclient[i]->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data,
842 &reply, TF_ONE_WAY),
843 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800844 }
845 }
846 {
847 Parcel data, reply;
848 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
849 EXPECT_EQ(0, ret);
850 }
851
852 for (int i = 0; i < clientcount; i++) {
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700853 EXPECT_THAT(callBack[i]->waitEvent(5), StatusEq(NO_ERROR));
854 EXPECT_THAT(callBack[i]->getResult(), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -0800855 }
856}
857
Martijn Coenenf7100e42017-07-31 12:14:09 +0200858TEST_F(BinderLibTest, DeathNotificationThread)
859{
860 status_t ret;
861 sp<BinderLibTestCallBack> callback;
862 sp<IBinder> target = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700863 ASSERT_TRUE(target != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200864 sp<IBinder> client = addServer();
Yi Kong91635562018-06-07 14:38:36 -0700865 ASSERT_TRUE(client != nullptr);
Martijn Coenenf7100e42017-07-31 12:14:09 +0200866
867 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
868
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700869 EXPECT_THAT(target->linkToDeath(testDeathRecipient), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200870
871 {
872 Parcel data, reply;
873 ret = target->transact(BINDER_LIB_TEST_EXIT_TRANSACTION, data, &reply, TF_ONE_WAY);
874 EXPECT_EQ(0, ret);
875 }
876
877 /* Make sure it's dead */
878 testDeathRecipient->waitEvent(5);
879
880 /* Now, pass the ref to another process and ask that process to
881 * call linkToDeath() on it, and wait for a response. This tests
882 * two things:
883 * 1) You still get death notifications when calling linkToDeath()
884 * on a ref that is already dead when it was passed to you.
885 * 2) That death notifications are not directly pushed to the thread
886 * registering them, but to the threadpool (proc workqueue) instead.
887 *
888 * 2) is tested because the thread handling BINDER_LIB_TEST_DEATH_TRANSACTION
889 * is blocked on a condition variable waiting for the death notification to be
890 * called; therefore, that thread is not available for handling proc work.
891 * So, if the death notification was pushed to the thread workqueue, the callback
892 * would never be called, and the test would timeout and fail.
893 *
894 * Note that we can't do this part of the test from this thread itself, because
895 * the binder driver would only push death notifications to the thread if
896 * it is a looper thread, which this thread is not.
897 *
898 * See b/23525545 for details.
899 */
900 {
901 Parcel data, reply;
902
903 callback = new BinderLibTestCallBack();
904 data.writeStrongBinder(target);
905 data.writeStrongBinder(callback);
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700906 EXPECT_THAT(client->transact(BINDER_LIB_TEST_LINK_DEATH_TRANSACTION, data, &reply,
907 TF_ONE_WAY),
908 StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200909 }
910
Yifan Hongbbd2a0d2021-05-07 22:12:23 -0700911 EXPECT_THAT(callback->waitEvent(5), StatusEq(NO_ERROR));
912 EXPECT_THAT(callback->getResult(), StatusEq(NO_ERROR));
Martijn Coenenf7100e42017-07-31 12:14:09 +0200913}
914
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -0700915TEST_F(BinderLibTest, ReturnErrorIfKernelDoesNotSupportFreezeNotification) {
916 if (ProcessState::isDriverFeatureEnabled(ProcessState::DriverFeature::FREEZE_NOTIFICATION)) {
917 GTEST_SKIP() << "Skipping test for kernels that support FREEZE_NOTIFICATION";
918 return;
919 }
920 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
921 sp<IBinder> binder = addServer();
922 ASSERT_NE(nullptr, binder);
923 ASSERT_EQ(nullptr, binder->localBinder());
924 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(INVALID_OPERATION));
925}
926
927TEST_F(BinderLibTest, FrozenStateChangeNotificatiion) {
928 if (!checkFreezeAndNotificationSupport()) {
929 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
930 return;
931 }
932 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
933 sp<IBinder> binder = addServer();
934 ASSERT_NE(nullptr, binder);
935 int32_t pid;
936 ASSERT_TRUE(getBinderPid(&pid, binder));
937
938 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
939 // Expect current state (unfrozen) to be delivered immediately.
940 callback->ensureUnfrozenEventReceived();
941 // Check that the process hasn't died otherwise there's a risk of freezing
942 // the wrong process.
943 EXPECT_EQ(OK, binder->pingBinder());
944 freezeProcess(pid);
945 callback->ensureFrozenEventReceived();
946 unfreezeProcess(pid);
947 callback->ensureUnfrozenEventReceived();
948 removeCallbackAndValidateNoEvent(binder, callback);
949}
950
951TEST_F(BinderLibTest, AddFrozenCallbackWhenFrozen) {
952 if (!checkFreezeAndNotificationSupport()) {
953 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
954 return;
955 }
956 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
957 sp<IBinder> binder = addServer();
958 ASSERT_NE(nullptr, binder);
959 int32_t pid;
960 ASSERT_TRUE(getBinderPid(&pid, binder));
961
962 // Check that the process hasn't died otherwise there's a risk of freezing
963 // the wrong process.
964 EXPECT_EQ(OK, binder->pingBinder());
965 freezeProcess(pid);
966 // Add the callback while the target process is frozen.
967 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
968 callback->ensureFrozenEventReceived();
969 unfreezeProcess(pid);
970 callback->ensureUnfrozenEventReceived();
971 removeCallbackAndValidateNoEvent(binder, callback);
972
973 // Check that the process hasn't died otherwise there's a risk of freezing
974 // the wrong process.
975 EXPECT_EQ(OK, binder->pingBinder());
976 freezeProcess(pid);
977 unfreezeProcess(pid);
978 // Make sure no callback happens since the listener has been removed.
979 EXPECT_EQ(0u, callback->events.size());
980}
981
982TEST_F(BinderLibTest, NoFrozenNotificationAfterCallbackRemoval) {
983 if (!checkFreezeAndNotificationSupport()) {
984 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
985 return;
986 }
987 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
988 sp<IBinder> binder = addServer();
989 ASSERT_NE(nullptr, binder);
990 int32_t pid;
991 ASSERT_TRUE(getBinderPid(&pid, binder));
992
993 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
994 callback->ensureUnfrozenEventReceived();
995 removeCallbackAndValidateNoEvent(binder, callback);
996
997 // Make sure no callback happens after the listener is removed.
998 freezeProcess(pid);
999 unfreezeProcess(pid);
1000 EXPECT_EQ(0u, callback->events.size());
1001}
1002
1003TEST_F(BinderLibTest, MultipleFrozenStateChangeCallbacks) {
1004 if (!checkFreezeAndNotificationSupport()) {
1005 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1006 return;
1007 }
1008 sp<TestFrozenStateChangeCallback> callback1 = sp<TestFrozenStateChangeCallback>::make();
1009 sp<TestFrozenStateChangeCallback> callback2 = sp<TestFrozenStateChangeCallback>::make();
1010 sp<IBinder> binder = addServer();
1011 ASSERT_NE(nullptr, binder);
1012 int32_t pid;
1013 ASSERT_TRUE(getBinderPid(&pid, binder));
1014
1015 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback1), StatusEq(NO_ERROR));
1016 // Expect current state (unfrozen) to be delivered immediately.
1017 callback1->ensureUnfrozenEventReceived();
1018
1019 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback2), StatusEq(NO_ERROR));
1020 // Expect current state (unfrozen) to be delivered immediately.
1021 callback2->ensureUnfrozenEventReceived();
1022
1023 freezeProcess(pid);
1024 callback1->ensureFrozenEventReceived();
1025 callback2->ensureFrozenEventReceived();
1026
1027 removeCallbackAndValidateNoEvent(binder, callback1);
1028 unfreezeProcess(pid);
1029 EXPECT_EQ(0u, callback1->events.size());
1030 callback2->ensureUnfrozenEventReceived();
1031 removeCallbackAndValidateNoEvent(binder, callback2);
1032
1033 freezeProcess(pid);
1034 EXPECT_EQ(0u, callback2->events.size());
1035}
1036
1037TEST_F(BinderLibTest, RemoveThenAddFrozenStateChangeCallbacks) {
1038 if (!checkFreezeAndNotificationSupport()) {
1039 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1040 return;
1041 }
1042 sp<TestFrozenStateChangeCallback> callback = sp<TestFrozenStateChangeCallback>::make();
1043 sp<IBinder> binder = addServer();
1044 ASSERT_NE(nullptr, binder);
1045 int32_t pid;
1046 ASSERT_TRUE(getBinderPid(&pid, binder));
1047
1048 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1049 // Expect current state (unfrozen) to be delivered immediately.
1050 callback->ensureUnfrozenEventReceived();
1051 removeCallbackAndValidateNoEvent(binder, callback);
1052
1053 EXPECT_THAT(binder->addFrozenStateChangeCallback(callback), StatusEq(NO_ERROR));
1054 callback->ensureUnfrozenEventReceived();
1055}
1056
1057TEST_F(BinderLibTest, CoalesceFreezeCallbacksWhenListenerIsFrozen) {
1058 if (!checkFreezeAndNotificationSupport()) {
1059 GTEST_SKIP() << "Skipping test for kernels that do not support FREEZE_NOTIFICATION";
1060 return;
1061 }
1062 sp<IBinder> binder = addServer();
1063 sp<IBinder> listener = addServer();
1064 ASSERT_NE(nullptr, binder);
1065 ASSERT_NE(nullptr, listener);
1066 int32_t pid, listenerPid;
1067 ASSERT_TRUE(getBinderPid(&pid, binder));
1068 ASSERT_TRUE(getBinderPid(&listenerPid, listener));
1069
1070 // Ask the listener process to register for state change callbacks.
1071 {
1072 Parcel data, reply;
1073 data.writeStrongBinder(binder);
1074 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE, data,
1075 &reply),
1076 StatusEq(NO_ERROR));
1077 }
1078 // Freeze the listener process.
1079 freezeProcess(listenerPid);
1080 createProcessGroup(getuid(), listenerPid);
1081 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Frozen"}));
1082 // Repeatedly flip the target process between frozen and unfrozen states.
1083 for (int i = 0; i < 1000; i++) {
1084 usleep(50);
1085 unfreezeProcess(pid);
1086 usleep(50);
1087 freezeProcess(pid);
1088 }
1089 // Unfreeze the listener process. Now it should receive the frozen state
1090 // change notifications.
1091 ASSERT_TRUE(SetProcessProfiles(getuid(), listenerPid, {"Unfrozen"}));
1092 unfreezeProcess(listenerPid);
1093 // Wait for 500ms to give the process enough time to wake up and handle
1094 // notifications.
1095 usleep(500 * 1000);
1096 {
1097 std::vector<bool> events;
1098 Parcel data, reply;
1099 ASSERT_THAT(listener->transact(BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS, data, &reply),
1100 StatusEq(NO_ERROR));
1101 reply.readBoolVector(&events);
1102 // There should only be one single state change notifications delievered.
1103 ASSERT_EQ(1u, events.size());
1104 EXPECT_TRUE(events[0]);
1105 }
1106}
1107
Riley Andrews06b01ad2014-12-18 12:10:08 -08001108TEST_F(BinderLibTest, PassFile) {
1109 int ret;
1110 int pipefd[2];
1111 uint8_t buf[1] = { 0 };
1112 uint8_t write_value = 123;
1113
1114 ret = pipe2(pipefd, O_NONBLOCK);
1115 ASSERT_EQ(0, ret);
1116
1117 {
1118 Parcel data, reply;
1119 uint8_t writebuf[1] = { write_value };
1120
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001121 EXPECT_THAT(data.writeFileDescriptor(pipefd[1], true), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001122
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001123 EXPECT_THAT(data.writeInt32(sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001124
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001125 EXPECT_THAT(data.write(writebuf, sizeof(writebuf)), StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001126
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001127 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_WRITE_FILE_TRANSACTION, data, &reply),
1128 StatusEq(NO_ERROR));
Riley Andrews06b01ad2014-12-18 12:10:08 -08001129 }
1130
1131 ret = read(pipefd[0], buf, sizeof(buf));
Arve Hjønnevåg6d5fa942016-08-12 15:32:48 -07001132 EXPECT_EQ(sizeof(buf), (size_t)ret);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001133 EXPECT_EQ(write_value, buf[0]);
1134
1135 waitForReadData(pipefd[0], 5000); /* wait for other proccess to close pipe */
1136
1137 ret = read(pipefd[0], buf, sizeof(buf));
1138 EXPECT_EQ(0, ret);
1139
1140 close(pipefd[0]);
1141}
1142
Ryo Hashimotobf551892018-05-31 16:58:35 +09001143TEST_F(BinderLibTest, PassParcelFileDescriptor) {
1144 const int datasize = 123;
1145 std::vector<uint8_t> writebuf(datasize);
1146 for (size_t i = 0; i < writebuf.size(); ++i) {
1147 writebuf[i] = i;
1148 }
1149
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001150 unique_fd read_end, write_end;
Ryo Hashimotobf551892018-05-31 16:58:35 +09001151 {
1152 int pipefd[2];
1153 ASSERT_EQ(0, pipe2(pipefd, O_NONBLOCK));
1154 read_end.reset(pipefd[0]);
1155 write_end.reset(pipefd[1]);
1156 }
1157 {
1158 Parcel data;
1159 EXPECT_EQ(NO_ERROR, data.writeDupParcelFileDescriptor(write_end.get()));
1160 write_end.reset();
1161 EXPECT_EQ(NO_ERROR, data.writeInt32(datasize));
1162 EXPECT_EQ(NO_ERROR, data.write(writebuf.data(), datasize));
1163
1164 Parcel reply;
1165 EXPECT_EQ(NO_ERROR,
1166 m_server->transact(BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION, data,
1167 &reply));
1168 }
1169 std::vector<uint8_t> readbuf(datasize);
1170 EXPECT_EQ(datasize, read(read_end.get(), readbuf.data(), datasize));
1171 EXPECT_EQ(writebuf, readbuf);
1172
1173 waitForReadData(read_end.get(), 5000); /* wait for other proccess to close pipe */
1174
1175 EXPECT_EQ(0, read(read_end.get(), readbuf.data(), datasize));
1176}
1177
Riley Andrews06b01ad2014-12-18 12:10:08 -08001178TEST_F(BinderLibTest, PromoteLocal) {
1179 sp<IBinder> strong = new BBinder();
1180 wp<IBinder> weak = strong;
1181 sp<IBinder> strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001182 EXPECT_TRUE(strong != nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001183 EXPECT_EQ(strong, strong_from_weak);
Yi Kong91635562018-06-07 14:38:36 -07001184 strong = nullptr;
1185 strong_from_weak = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001186 strong_from_weak = weak.promote();
Yi Kong91635562018-06-07 14:38:36 -07001187 EXPECT_TRUE(strong_from_weak == nullptr);
Riley Andrews06b01ad2014-12-18 12:10:08 -08001188}
1189
Steven Morelandb8ad08d2019-08-09 14:42:56 -07001190TEST_F(BinderLibTest, LocalGetExtension) {
1191 sp<BBinder> binder = new BBinder();
1192 sp<IBinder> ext = new BBinder();
1193 binder->setExtension(ext);
1194 EXPECT_EQ(ext, binder->getExtension());
1195}
1196
1197TEST_F(BinderLibTest, RemoteGetExtension) {
1198 sp<IBinder> server = addServer();
1199 ASSERT_TRUE(server != nullptr);
1200
1201 sp<IBinder> extension;
1202 EXPECT_EQ(NO_ERROR, server->getExtension(&extension));
1203 ASSERT_NE(nullptr, extension.get());
1204
1205 EXPECT_EQ(NO_ERROR, extension->pingBinder());
1206}
1207
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001208TEST_F(BinderLibTest, CheckHandleZeroBinderHighBitsZeroCookie) {
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001209 Parcel data, reply;
1210
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001211 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GET_SELF_TRANSACTION, data, &reply),
1212 StatusEq(NO_ERROR));
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001213
1214 const flat_binder_object *fb = reply.readObject(false);
Yi Kong91635562018-06-07 14:38:36 -07001215 ASSERT_TRUE(fb != nullptr);
Hsin-Yi Chenad6503c2017-07-28 11:28:52 +08001216 EXPECT_EQ(BINDER_TYPE_HANDLE, fb->hdr.type);
1217 EXPECT_EQ(m_server, ProcessState::self()->getStrongProxyForHandle(fb->handle));
1218 EXPECT_EQ((binder_uintptr_t)0, fb->cookie);
1219 EXPECT_EQ((uint64_t)0, (uint64_t)fb->binder >> 32);
Arve Hjønnevåg70604312016-08-12 15:34:51 -07001220}
1221
Connor O'Brien52be2c92016-09-20 14:18:08 -07001222TEST_F(BinderLibTest, FreedBinder) {
1223 status_t ret;
1224
1225 sp<IBinder> server = addServer();
Yi Kong91635562018-06-07 14:38:36 -07001226 ASSERT_TRUE(server != nullptr);
Connor O'Brien52be2c92016-09-20 14:18:08 -07001227
1228 __u32 freedHandle;
1229 wp<IBinder> keepFreedBinder;
1230 {
1231 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001232 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1233 StatusEq(NO_ERROR));
Connor O'Brien52be2c92016-09-20 14:18:08 -07001234 struct flat_binder_object *freed = (struct flat_binder_object *)(reply.data());
1235 freedHandle = freed->handle;
1236 /* Add a weak ref to the freed binder so the driver does not
1237 * delete its reference to it - otherwise the transaction
1238 * fails regardless of whether the driver is fixed.
1239 */
Steven Morelande171d622019-07-17 16:06:01 -07001240 keepFreedBinder = reply.readStrongBinder();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001241 }
Steven Morelande171d622019-07-17 16:06:01 -07001242 IPCThreadState::self()->flushCommands();
Connor O'Brien52be2c92016-09-20 14:18:08 -07001243 {
1244 Parcel data, reply;
1245 data.writeStrongBinder(server);
1246 /* Replace original handle with handle to the freed binder */
1247 struct flat_binder_object *strong = (struct flat_binder_object *)(data.data());
1248 __u32 oldHandle = strong->handle;
1249 strong->handle = freedHandle;
1250 ret = server->transact(BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION, data, &reply);
1251 /* Returns DEAD_OBJECT (-32) if target crashes and
1252 * FAILED_TRANSACTION if the driver rejects the invalid
1253 * object.
1254 */
1255 EXPECT_EQ((status_t)FAILED_TRANSACTION, ret);
1256 /* Restore original handle so parcel destructor does not use
1257 * the wrong handle.
1258 */
1259 strong->handle = oldHandle;
1260 }
1261}
1262
Sherry Yang336cdd32017-07-24 14:12:27 -07001263TEST_F(BinderLibTest, CheckNoHeaderMappedInUser) {
Sherry Yang336cdd32017-07-24 14:12:27 -07001264 Parcel data, reply;
1265 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1266 for (int i = 0; i < 2; i++) {
1267 BinderLibTestBundle datai;
1268 datai.appendFrom(&data, 0, data.dataSize());
1269
1270 data.freeData();
1271 data.writeInt32(1);
1272 data.writeStrongBinder(callBack);
1273 data.writeInt32(BINDER_LIB_TEST_CALL_BACK_VERIFY_BUF);
1274
1275 datai.appendTo(&data);
1276 }
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001277 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_INDIRECT_TRANSACTION, data, &reply),
1278 StatusEq(NO_ERROR));
Sherry Yang336cdd32017-07-24 14:12:27 -07001279}
1280
Martijn Coenen45b07b42017-08-09 12:07:45 +02001281TEST_F(BinderLibTest, OnewayQueueing)
1282{
Martijn Coenen45b07b42017-08-09 12:07:45 +02001283 Parcel data, data2;
1284
1285 sp<IBinder> pollServer = addPollServer();
1286
1287 sp<BinderLibTestCallBack> callBack = new BinderLibTestCallBack();
1288 data.writeStrongBinder(callBack);
1289 data.writeInt32(500000); // delay in us before calling back
1290
1291 sp<BinderLibTestCallBack> callBack2 = new BinderLibTestCallBack();
1292 data2.writeStrongBinder(callBack2);
1293 data2.writeInt32(0); // delay in us
1294
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001295 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data, nullptr, TF_ONE_WAY),
1296 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001297
1298 // The delay ensures that this second transaction will end up on the async_todo list
1299 // (for a single-threaded server)
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001300 EXPECT_THAT(pollServer->transact(BINDER_LIB_TEST_DELAYED_CALL_BACK, data2, nullptr, TF_ONE_WAY),
1301 StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001302
1303 // The server will ensure that the two transactions are handled in the expected order;
1304 // If the ordering is not as expected, an error will be returned through the callbacks.
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001305 EXPECT_THAT(callBack->waitEvent(2), StatusEq(NO_ERROR));
1306 EXPECT_THAT(callBack->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001307
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001308 EXPECT_THAT(callBack2->waitEvent(2), StatusEq(NO_ERROR));
1309 EXPECT_THAT(callBack2->getResult(), StatusEq(NO_ERROR));
Martijn Coenen45b07b42017-08-09 12:07:45 +02001310}
1311
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001312TEST_F(BinderLibTest, WorkSourceUnsetByDefault)
1313{
1314 status_t ret;
1315 Parcel data, reply;
1316 data.writeInterfaceToken(binderLibTestServiceName);
1317 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1318 EXPECT_EQ(-1, reply.readInt32());
1319 EXPECT_EQ(NO_ERROR, ret);
1320}
1321
1322TEST_F(BinderLibTest, WorkSourceSet)
1323{
1324 status_t ret;
1325 Parcel data, reply;
Olivier Gaillard91a04802018-11-14 17:32:41 +00001326 IPCThreadState::self()->clearCallingWorkSource();
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001327 int64_t previousWorkSource = IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001328 data.writeInterfaceToken(binderLibTestServiceName);
1329 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1330 EXPECT_EQ(100, reply.readInt32());
1331 EXPECT_EQ(-1, previousWorkSource);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001332 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1333 EXPECT_EQ(NO_ERROR, ret);
1334}
1335
1336TEST_F(BinderLibTest, WorkSourceSetWithoutPropagation)
1337{
1338 status_t ret;
1339 Parcel data, reply;
1340
1341 IPCThreadState::self()->setCallingWorkSourceUidWithoutPropagation(100);
1342 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1343
1344 data.writeInterfaceToken(binderLibTestServiceName);
1345 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1346 EXPECT_EQ(-1, reply.readInt32());
1347 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001348 EXPECT_EQ(NO_ERROR, ret);
1349}
1350
1351TEST_F(BinderLibTest, WorkSourceCleared)
1352{
1353 status_t ret;
1354 Parcel data, reply;
1355
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001356 IPCThreadState::self()->setCallingWorkSourceUid(100);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001357 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1358 int32_t previousWorkSource = (int32_t)token;
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01001359 data.writeInterfaceToken(binderLibTestServiceName);
1360 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1361
1362 EXPECT_EQ(-1, reply.readInt32());
1363 EXPECT_EQ(100, previousWorkSource);
1364 EXPECT_EQ(NO_ERROR, ret);
1365}
1366
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001367TEST_F(BinderLibTest, WorkSourceRestored)
1368{
1369 status_t ret;
1370 Parcel data, reply;
1371
1372 IPCThreadState::self()->setCallingWorkSourceUid(100);
1373 int64_t token = IPCThreadState::self()->clearCallingWorkSource();
1374 IPCThreadState::self()->restoreCallingWorkSource(token);
1375
1376 data.writeInterfaceToken(binderLibTestServiceName);
1377 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
1378
1379 EXPECT_EQ(100, reply.readInt32());
Olivier Gaillard91a04802018-11-14 17:32:41 +00001380 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00001381 EXPECT_EQ(NO_ERROR, ret);
1382}
1383
Olivier Gaillard91a04802018-11-14 17:32:41 +00001384TEST_F(BinderLibTest, PropagateFlagSet)
1385{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001386 IPCThreadState::self()->clearPropagateWorkSource();
1387 IPCThreadState::self()->setCallingWorkSourceUid(100);
1388 EXPECT_EQ(true, IPCThreadState::self()->shouldPropagateWorkSource());
1389}
1390
1391TEST_F(BinderLibTest, PropagateFlagCleared)
1392{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001393 IPCThreadState::self()->setCallingWorkSourceUid(100);
1394 IPCThreadState::self()->clearPropagateWorkSource();
1395 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1396}
1397
1398TEST_F(BinderLibTest, PropagateFlagRestored)
1399{
Olivier Gaillard91a04802018-11-14 17:32:41 +00001400 int token = IPCThreadState::self()->setCallingWorkSourceUid(100);
1401 IPCThreadState::self()->restoreCallingWorkSource(token);
1402
1403 EXPECT_EQ(false, IPCThreadState::self()->shouldPropagateWorkSource());
1404}
1405
1406TEST_F(BinderLibTest, WorkSourcePropagatedForAllFollowingBinderCalls)
1407{
1408 IPCThreadState::self()->setCallingWorkSourceUid(100);
1409
1410 Parcel data, reply;
1411 status_t ret;
1412 data.writeInterfaceToken(binderLibTestServiceName);
1413 ret = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data, &reply);
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001414 EXPECT_EQ(NO_ERROR, ret);
Olivier Gaillard91a04802018-11-14 17:32:41 +00001415
1416 Parcel data2, reply2;
1417 status_t ret2;
1418 data2.writeInterfaceToken(binderLibTestServiceName);
1419 ret2 = m_server->transact(BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION, data2, &reply2);
1420 EXPECT_EQ(100, reply2.readInt32());
1421 EXPECT_EQ(NO_ERROR, ret2);
1422}
1423
Steven Morelandbf1915b2020-07-16 22:43:02 +00001424TEST_F(BinderLibTest, SchedPolicySet) {
1425 sp<IBinder> server = addServer();
1426 ASSERT_TRUE(server != nullptr);
1427
1428 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001429 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1430 StatusEq(NO_ERROR));
Steven Morelandbf1915b2020-07-16 22:43:02 +00001431
1432 int policy = reply.readInt32();
1433 int priority = reply.readInt32();
1434
1435 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1436 EXPECT_EQ(kSchedPriority, priority);
1437}
1438
Steven Morelandcf03cf12020-12-04 02:58:40 +00001439TEST_F(BinderLibTest, InheritRt) {
1440 sp<IBinder> server = addServer();
1441 ASSERT_TRUE(server != nullptr);
1442
1443 const struct sched_param param {
1444 .sched_priority = kSchedPriorityMore,
1445 };
1446 EXPECT_EQ(0, sched_setscheduler(getpid(), SCHED_RR, &param));
1447
1448 Parcel data, reply;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001449 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_SCHEDULING_POLICY, data, &reply),
1450 StatusEq(NO_ERROR));
Steven Morelandcf03cf12020-12-04 02:58:40 +00001451
1452 int policy = reply.readInt32();
1453 int priority = reply.readInt32();
1454
1455 EXPECT_EQ(kSchedPolicy, policy & (~SCHED_RESET_ON_FORK));
1456 EXPECT_EQ(kSchedPriorityMore, priority);
1457}
Steven Morelandbf1915b2020-07-16 22:43:02 +00001458
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001459TEST_F(BinderLibTest, VectorSent) {
1460 Parcel data, reply;
1461 sp<IBinder> server = addServer();
1462 ASSERT_TRUE(server != nullptr);
1463
1464 std::vector<uint64_t> const testValue = { std::numeric_limits<uint64_t>::max(), 0, 200 };
1465 data.writeUint64Vector(testValue);
1466
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001467 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001468 std::vector<uint64_t> readValue;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001469 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08001470 EXPECT_EQ(readValue, testValue);
1471}
1472
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001473TEST_F(BinderLibTest, FileDescriptorRemainsNonBlocking) {
1474 sp<IBinder> server = addServer();
1475 ASSERT_TRUE(server != nullptr);
1476
1477 Parcel reply;
1478 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_NON_BLOCKING_FD, {} /*data*/, &reply),
1479 StatusEq(NO_ERROR));
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001480 unique_fd fd;
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07001481 EXPECT_THAT(reply.readUniqueFileDescriptor(&fd), StatusEq(OK));
1482
1483 const int result = fcntl(fd.get(), F_GETFL);
1484 ASSERT_NE(result, -1);
1485 EXPECT_EQ(result & O_NONBLOCK, O_NONBLOCK);
1486}
1487
Steven Moreland59b84442022-07-12 18:32:44 +00001488// see ProcessState.cpp BINDER_VM_SIZE = 1MB.
1489// This value is not exposed, but some code in the framework relies on being able to use
1490// buffers near the cap size.
Steven Morelandce15b9f2022-09-08 17:42:45 +00001491constexpr size_t kSizeBytesAlmostFull = 950'000;
Steven Moreland59b84442022-07-12 18:32:44 +00001492constexpr size_t kSizeBytesOverFull = 1'050'000;
1493
1494TEST_F(BinderLibTest, GargantuanVectorSent) {
1495 sp<IBinder> server = addServer();
1496 ASSERT_TRUE(server != nullptr);
1497
1498 for (size_t i = 0; i < 10; i++) {
1499 // a slight variation in size is used to consider certain possible caching implementations
1500 const std::vector<uint64_t> testValue((kSizeBytesAlmostFull + i) / sizeof(uint64_t), 42);
1501
1502 Parcel data, reply;
1503 data.writeUint64Vector(testValue);
1504 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply), StatusEq(NO_ERROR))
1505 << i;
1506 std::vector<uint64_t> readValue;
1507 EXPECT_THAT(reply.readUint64Vector(&readValue), StatusEq(OK));
1508 EXPECT_EQ(readValue, testValue);
1509 }
1510}
1511
1512TEST_F(BinderLibTest, LimitExceededVectorSent) {
1513 sp<IBinder> server = addServer();
1514 ASSERT_TRUE(server != nullptr);
1515 const std::vector<uint64_t> testValue(kSizeBytesOverFull / sizeof(uint64_t), 42);
1516
1517 Parcel data, reply;
1518 data.writeUint64Vector(testValue);
1519 EXPECT_THAT(server->transact(BINDER_LIB_TEST_ECHO_VECTOR, data, &reply),
1520 StatusEq(FAILED_TRANSACTION));
1521}
1522
Martijn Coenen82c75312019-07-24 15:18:30 +02001523TEST_F(BinderLibTest, BufRejected) {
1524 Parcel data, reply;
1525 uint32_t buf;
1526 sp<IBinder> server = addServer();
1527 ASSERT_TRUE(server != nullptr);
1528
1529 binder_buffer_object obj {
1530 .hdr = { .type = BINDER_TYPE_PTR },
Nick Desaulniers54891cd2019-11-19 09:31:05 -08001531 .flags = 0,
Martijn Coenen82c75312019-07-24 15:18:30 +02001532 .buffer = reinterpret_cast<binder_uintptr_t>((void*)&buf),
1533 .length = 4,
Martijn Coenen82c75312019-07-24 15:18:30 +02001534 };
1535 data.setDataCapacity(1024);
1536 // Write a bogus object at offset 0 to get an entry in the offset table
1537 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001538 EXPECT_EQ(data.objectsCount(), 1u);
Martijn Coenen82c75312019-07-24 15:18:30 +02001539 uint8_t *parcelData = const_cast<uint8_t*>(data.data());
1540 // And now, overwrite it with the buffer object
1541 memcpy(parcelData, &obj, sizeof(obj));
1542 data.setDataSize(sizeof(obj));
1543
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001544 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001545
Martijn Coenen82c75312019-07-24 15:18:30 +02001546 // Either the kernel should reject this transaction (if it's correct), but
1547 // if it's not, the server implementation should return an error if it
1548 // finds an object in the received Parcel.
Steven Morelandf2e0a952021-11-01 18:17:23 -07001549 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001550 Not(StatusEq(NO_ERROR)));
Martijn Coenen82c75312019-07-24 15:18:30 +02001551}
1552
Steven Morelandf2e0a952021-11-01 18:17:23 -07001553TEST_F(BinderLibTest, WeakRejected) {
1554 Parcel data, reply;
1555 sp<IBinder> server = addServer();
1556 ASSERT_TRUE(server != nullptr);
1557
1558 auto binder = sp<BBinder>::make();
1559 wp<BBinder> wpBinder(binder);
1560 flat_binder_object obj{
1561 .hdr = {.type = BINDER_TYPE_WEAK_BINDER},
1562 .flags = 0,
1563 .binder = reinterpret_cast<uintptr_t>(wpBinder.get_refs()),
1564 .cookie = reinterpret_cast<uintptr_t>(wpBinder.unsafe_get()),
1565 };
1566 data.setDataCapacity(1024);
1567 // Write a bogus object at offset 0 to get an entry in the offset table
1568 data.writeFileDescriptor(0);
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001569 EXPECT_EQ(data.objectsCount(), 1u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001570 uint8_t *parcelData = const_cast<uint8_t *>(data.data());
1571 // And now, overwrite it with the weak binder
1572 memcpy(parcelData, &obj, sizeof(obj));
1573 data.setDataSize(sizeof(obj));
1574
1575 // a previous bug caused other objects to be released an extra time, so we
1576 // test with an object that libbinder will actually try to release
1577 EXPECT_EQ(OK, data.writeStrongBinder(sp<BBinder>::make()));
1578
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001579 EXPECT_EQ(data.objectsCount(), 2u);
Steven Morelandf2e0a952021-11-01 18:17:23 -07001580
1581 // send it many times, since previous error was memory corruption, make it
1582 // more likely that the server crashes
1583 for (size_t i = 0; i < 100; i++) {
1584 EXPECT_THAT(server->transact(BINDER_LIB_TEST_REJECT_OBJECTS, data, &reply),
1585 StatusEq(BAD_VALUE));
1586 }
1587
1588 EXPECT_THAT(server->pingBinder(), StatusEq(NO_ERROR));
1589}
1590
Steven Moreland254e8ef2021-04-19 22:28:50 +00001591TEST_F(BinderLibTest, GotSid) {
1592 sp<IBinder> server = addServer();
1593
1594 Parcel data;
Yifan Hongbbd2a0d2021-05-07 22:12:23 -07001595 EXPECT_THAT(server->transact(BINDER_LIB_TEST_CAN_GET_SID, data, nullptr), StatusEq(OK));
Steven Moreland254e8ef2021-04-19 22:28:50 +00001596}
1597
Andrei Homescu1519b982022-06-09 02:04:44 +00001598struct TooManyFdsFlattenable : Flattenable<TooManyFdsFlattenable> {
1599 TooManyFdsFlattenable(size_t fdCount) : mFdCount(fdCount) {}
1600
1601 // Flattenable protocol
1602 size_t getFlattenedSize() const {
1603 // Return a valid non-zero size here so we don't get an unintended
1604 // BAD_VALUE from Parcel::write
1605 return 16;
1606 }
1607 size_t getFdCount() const { return mFdCount; }
1608 status_t flatten(void *& /*buffer*/, size_t & /*size*/, int *&fds, size_t &count) const {
1609 for (size_t i = 0; i < count; i++) {
1610 fds[i] = STDIN_FILENO;
1611 }
1612 return NO_ERROR;
1613 }
1614 status_t unflatten(void const *& /*buffer*/, size_t & /*size*/, int const *& /*fds*/,
1615 size_t & /*count*/) {
1616 /* This doesn't get called */
1617 return NO_ERROR;
1618 }
1619
1620 size_t mFdCount;
1621};
1622
1623TEST_F(BinderLibTest, TooManyFdsFlattenable) {
1624 rlimit origNofile;
1625 int ret = getrlimit(RLIMIT_NOFILE, &origNofile);
1626 ASSERT_EQ(0, ret);
1627
1628 // Restore the original file limits when the test finishes
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +00001629 auto guardUnguard = make_scope_guard([&]() { setrlimit(RLIMIT_NOFILE, &origNofile); });
Andrei Homescu1519b982022-06-09 02:04:44 +00001630
1631 rlimit testNofile = {1024, 1024};
1632 ret = setrlimit(RLIMIT_NOFILE, &testNofile);
1633 ASSERT_EQ(0, ret);
1634
1635 Parcel parcel;
1636 // Try to write more file descriptors than supported by the OS
1637 TooManyFdsFlattenable tooManyFds1(1024);
1638 EXPECT_THAT(parcel.write(tooManyFds1), StatusEq(-EMFILE));
1639
1640 // Try to write more file descriptors than the internal limit
1641 TooManyFdsFlattenable tooManyFds2(1025);
1642 EXPECT_THAT(parcel.write(tooManyFds2), StatusEq(BAD_VALUE));
1643}
1644
Jayant Chowdhary30700942022-01-31 14:12:40 -08001645TEST(ServiceNotifications, Unregister) {
1646 auto sm = defaultServiceManager();
1647 using LocalRegistrationCallback = IServiceManager::LocalRegistrationCallback;
1648 class LocalRegistrationCallbackImpl : public virtual LocalRegistrationCallback {
1649 void onServiceRegistration(const String16 &, const sp<IBinder> &) override {}
1650 virtual ~LocalRegistrationCallbackImpl() {}
1651 };
1652 sp<LocalRegistrationCallback> cb = sp<LocalRegistrationCallbackImpl>::make();
1653
1654 EXPECT_EQ(sm->registerForNotifications(String16("RogerRafa"), cb), OK);
1655 EXPECT_EQ(sm->unregisterForNotifications(String16("RogerRafa"), cb), OK);
1656}
1657
Elie Kheirallah47431c12022-04-21 23:46:17 +00001658TEST_F(BinderLibTest, ThreadPoolAvailableThreads) {
1659 Parcel data, reply;
1660 sp<IBinder> server = addServer();
1661 ASSERT_TRUE(server != nullptr);
1662 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1663 StatusEq(NO_ERROR));
1664 int32_t replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001665 // see getThreadPoolMaxTotalThreadCount for why there is a race
1666 EXPECT_TRUE(replyi == kKernelThreads + 1 || replyi == kKernelThreads + 2) << replyi;
1667
Elie Kheirallah47431c12022-04-21 23:46:17 +00001668 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_LOCK, data, &reply), NO_ERROR);
1669
1670 /*
Steven Moreland3e9debc2023-06-15 00:35:29 +00001671 * This will use all threads in the pool but one. There are actually kKernelThreads+2
1672 * available in the other process (startThreadPool, joinThreadPool, + the kernel-
1673 * started threads from setThreadPoolMaxThreadCount
1674 *
1675 * Adding one more will cause it to deadlock.
Elie Kheirallah47431c12022-04-21 23:46:17 +00001676 */
1677 std::vector<std::thread> ts;
Steven Moreland3e9debc2023-06-15 00:35:29 +00001678 for (size_t i = 0; i < kKernelThreads + 1; i++) {
Elie Kheirallah47431c12022-04-21 23:46:17 +00001679 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001680 Parcel local_reply;
1681 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1682 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001683 }));
1684 }
1685
Steven Moreland3e9debc2023-06-15 00:35:29 +00001686 // make sure all of the above calls will be queued in parallel. Otherwise, most of
1687 // the time, the below call will pre-empt them (presumably because we have the
1688 // scheduler timeslice already + scheduler hint).
1689 sleep(1);
1690
1691 data.writeInt32(1000);
1692 // Give a chance for all threads to be used (kKernelThreads + 1 thread in use)
Elie Kheirallah47431c12022-04-21 23:46:17 +00001693 EXPECT_THAT(server->transact(BINDER_LIB_TEST_UNLOCK_AFTER_MS, data, &reply), NO_ERROR);
1694
1695 for (auto &t : ts) {
1696 t.join();
1697 }
1698
1699 EXPECT_THAT(server->transact(BINDER_LIB_TEST_GET_MAX_THREAD_COUNT, data, &reply),
1700 StatusEq(NO_ERROR));
1701 replyi = reply.readInt32();
Steven Moreland3e9debc2023-06-15 00:35:29 +00001702 EXPECT_EQ(replyi, kKernelThreads + 2);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001703}
1704
Devin Moore4354f712022-12-08 01:44:46 +00001705TEST_F(BinderLibTest, ThreadPoolStarted) {
1706 Parcel data, reply;
1707 sp<IBinder> server = addServer();
1708 ASSERT_TRUE(server != nullptr);
1709 EXPECT_THAT(server->transact(BINDER_LIB_TEST_IS_THREADPOOL_STARTED, data, &reply), NO_ERROR);
1710 EXPECT_TRUE(reply.readBool());
1711}
1712
Elie Kheirallah47431c12022-04-21 23:46:17 +00001713size_t epochMillis() {
1714 using std::chrono::duration_cast;
1715 using std::chrono::milliseconds;
1716 using std::chrono::seconds;
1717 using std::chrono::system_clock;
1718 return duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();
1719}
1720
1721TEST_F(BinderLibTest, HangingServices) {
1722 Parcel data, reply;
1723 sp<IBinder> server = addServer();
1724 ASSERT_TRUE(server != nullptr);
1725 int32_t delay = 1000; // ms
1726 data.writeInt32(delay);
Steven Moreland436a1102023-01-24 21:48:11 +00001727 // b/266537959 - must take before taking lock, since countdown is started in the remote
1728 // process there.
1729 size_t epochMsBefore = epochMillis();
Elie Kheirallah47431c12022-04-21 23:46:17 +00001730 EXPECT_THAT(server->transact(BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK, data, &reply), NO_ERROR);
1731 std::vector<std::thread> ts;
Elie Kheirallah47431c12022-04-21 23:46:17 +00001732 for (size_t i = 0; i < kKernelThreads + 1; i++) {
1733 ts.push_back(std::thread([&] {
Elie Kheirallah59f60fd2022-06-09 23:59:04 +00001734 Parcel local_reply;
1735 EXPECT_THAT(server->transact(BINDER_LIB_TEST_LOCK_UNLOCK, data, &local_reply),
1736 NO_ERROR);
Elie Kheirallah47431c12022-04-21 23:46:17 +00001737 }));
1738 }
1739
1740 for (auto &t : ts) {
1741 t.join();
1742 }
1743 size_t epochMsAfter = epochMillis();
1744
1745 // deadlock occurred and threads only finished after 1s passed.
1746 EXPECT_GE(epochMsAfter, epochMsBefore + delay);
1747}
1748
Jing Jibbe9ae62023-10-07 15:26:02 -07001749TEST_F(BinderLibTest, BinderProxyCount) {
1750 Parcel data, reply;
1751 sp<IBinder> server = addServer();
1752 ASSERT_NE(server, nullptr);
1753
1754 uint32_t initialCount = BpBinder::getBinderProxyCount();
1755 size_t iterations = 100;
1756 {
1757 uint32_t count = initialCount;
1758 std::vector<sp<IBinder> > proxies;
1759 sp<IBinder> proxy;
1760 // Create binder proxies and verify the count.
1761 for (size_t i = 0; i < iterations; i++) {
1762 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1763 StatusEq(NO_ERROR));
1764 proxies.push_back(reply.readStrongBinder());
1765 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1766 }
1767 // Remove every other one and verify the count.
1768 auto it = proxies.begin();
1769 for (size_t i = 0; it != proxies.end(); i++) {
1770 if (i % 2 == 0) {
1771 it = proxies.erase(it);
1772 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1773 }
1774 }
1775 }
1776 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1777}
1778
Jing Jibdbe29a2023-10-03 00:03:28 -07001779static constexpr int kBpCountHighWatermark = 20;
1780static constexpr int kBpCountLowWatermark = 10;
1781static constexpr int kBpCountWarningWatermark = 15;
1782static constexpr int kInvalidUid = -1;
1783
1784TEST_F(BinderLibTest, BinderProxyCountCallback) {
1785 Parcel data, reply;
1786 sp<IBinder> server = addServer();
1787 ASSERT_NE(server, nullptr);
1788
1789 BpBinder::enableCountByUid();
1790 EXPECT_THAT(m_server->transact(BINDER_LIB_TEST_GETUID, data, &reply), StatusEq(NO_ERROR));
1791 int32_t uid = reply.readInt32();
1792 ASSERT_NE(uid, kInvalidUid);
1793
1794 uint32_t initialCount = BpBinder::getBinderProxyCount();
1795 {
1796 uint32_t count = initialCount;
1797 BpBinder::setBinderProxyCountWatermarks(kBpCountHighWatermark,
1798 kBpCountLowWatermark,
1799 kBpCountWarningWatermark);
1800 int limitCallbackUid = kInvalidUid;
1801 int warningCallbackUid = kInvalidUid;
1802 BpBinder::setBinderProxyCountEventCallback([&](int uid) { limitCallbackUid = uid; },
1803 [&](int uid) { warningCallbackUid = uid; });
1804
1805 std::vector<sp<IBinder> > proxies;
1806 auto createProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1807 warningCallbackUid = limitCallbackUid = kInvalidUid;
1808 ASSERT_THAT(server->transact(BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION, data, &reply),
1809 StatusEq(NO_ERROR));
1810 proxies.push_back(reply.readStrongBinder());
1811 EXPECT_EQ(BpBinder::getBinderProxyCount(), ++count);
1812 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1813 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1814 };
1815 auto removeProxyOnce = [&](int expectedWarningCallbackUid, int expectedLimitCallbackUid) {
1816 warningCallbackUid = limitCallbackUid = kInvalidUid;
1817 proxies.pop_back();
1818 EXPECT_EQ(BpBinder::getBinderProxyCount(), --count);
1819 EXPECT_EQ(warningCallbackUid, expectedWarningCallbackUid);
1820 EXPECT_EQ(limitCallbackUid, expectedLimitCallbackUid);
1821 };
1822
1823 // Test the increment/decrement of the binder proxies.
1824 for (int i = 1; i <= kBpCountWarningWatermark; i++) {
1825 createProxyOnce(kInvalidUid, kInvalidUid);
1826 }
1827 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1828 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1829 createProxyOnce(kInvalidUid, kInvalidUid);
1830 }
1831 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1832 createProxyOnce(kInvalidUid, kInvalidUid);
1833 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1834 removeProxyOnce(kInvalidUid, kInvalidUid);
1835 }
1836 createProxyOnce(kInvalidUid, kInvalidUid);
1837
1838 // Go down below the low watermark.
1839 for (int i = kBpCountHighWatermark; i >= kBpCountLowWatermark; i--) {
1840 removeProxyOnce(kInvalidUid, kInvalidUid);
1841 }
1842 for (int i = kBpCountLowWatermark; i <= kBpCountWarningWatermark; i++) {
1843 createProxyOnce(kInvalidUid, kInvalidUid);
1844 }
1845 createProxyOnce(uid, kInvalidUid); // Warning callback should have been triggered.
1846 for (int i = kBpCountWarningWatermark + 2; i <= kBpCountHighWatermark; i++) {
1847 createProxyOnce(kInvalidUid, kInvalidUid);
1848 }
1849 createProxyOnce(kInvalidUid, uid); // Limit callback should have been triggered.
1850 createProxyOnce(kInvalidUid, kInvalidUid);
1851 for (int i = kBpCountHighWatermark + 2; i >= kBpCountHighWatermark; i--) {
1852 removeProxyOnce(kInvalidUid, kInvalidUid);
1853 }
1854 createProxyOnce(kInvalidUid, kInvalidUid);
1855 }
1856 EXPECT_EQ(BpBinder::getBinderProxyCount(), initialCount);
1857}
1858
Yifan Hong84bedeb2021-04-21 21:37:17 -07001859class BinderLibRpcTestBase : public BinderLibTest {
1860public:
1861 void SetUp() override {
1862 if (!base::GetBoolProperty("ro.debuggable", false)) {
1863 GTEST_SKIP() << "Binder RPC is only enabled on debuggable builds, skipping test on "
1864 "non-debuggable builds.";
1865 }
1866 BinderLibTest::SetUp();
1867 }
1868
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001869 std::tuple<unique_fd, unsigned int> CreateSocket() {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001870 auto rpcServer = RpcServer::make();
1871 EXPECT_NE(nullptr, rpcServer);
1872 if (rpcServer == nullptr) return {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001873 unsigned int port;
Steven Moreland2372f9d2021-08-05 15:42:01 -07001874 if (status_t status = rpcServer->setupInetServer("127.0.0.1", 0, &port); status != OK) {
1875 ADD_FAILURE() << "setupInetServer failed" << statusToString(status);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001876 return {};
1877 }
1878 return {rpcServer->releaseServer(), port};
1879 }
1880};
1881
Yifan Hong8b890852021-06-10 13:44:09 -07001882class BinderLibRpcTest : public BinderLibRpcTestBase {};
Yifan Hong84bedeb2021-04-21 21:37:17 -07001883
Yifan Hongbd276552022-02-28 15:28:51 -08001884// e.g. EXPECT_THAT(expr, Debuggable(StatusEq(...))
1885// If device is debuggable AND not on user builds, expects matcher.
1886// Otherwise expects INVALID_OPERATION.
1887// Debuggable + non user builds is necessary but not sufficient for setRpcClientDebug to work.
1888static Matcher<status_t> Debuggable(const Matcher<status_t> &matcher) {
1889 bool isDebuggable = android::base::GetBoolProperty("ro.debuggable", false) &&
1890 android::base::GetProperty("ro.build.type", "") != "user";
1891 return isDebuggable ? matcher : StatusEq(INVALID_OPERATION);
1892}
1893
Yifan Hong8b890852021-06-10 13:44:09 -07001894TEST_F(BinderLibRpcTest, SetRpcClientDebug) {
1895 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001896 ASSERT_TRUE(binder != nullptr);
1897 auto [socket, port] = CreateSocket();
1898 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001899 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), sp<BBinder>::make()),
1900 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001901}
1902
Yifan Hong8b890852021-06-10 13:44:09 -07001903// Tests for multiple RpcServer's on the same binder object.
1904TEST_F(BinderLibRpcTest, SetRpcClientDebugTwice) {
1905 auto binder = addServer();
Yifan Hong84bedeb2021-04-21 21:37:17 -07001906 ASSERT_TRUE(binder != nullptr);
1907
1908 auto [socket1, port1] = CreateSocket();
1909 ASSERT_TRUE(socket1.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001910 auto keepAliveBinder1 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001911 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket1), keepAliveBinder1),
1912 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001913
1914 auto [socket2, port2] = CreateSocket();
1915 ASSERT_TRUE(socket2.ok());
Yifan Hong02530ec2021-06-10 13:38:38 -07001916 auto keepAliveBinder2 = sp<BBinder>::make();
Yifan Hongbd276552022-02-28 15:28:51 -08001917 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket2), keepAliveBinder2),
1918 Debuggable(StatusEq(OK)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001919}
1920
Yifan Hong8b890852021-06-10 13:44:09 -07001921// Negative tests for RPC APIs on IBinder. Call should fail in the same way on both remote and
1922// local binders.
1923class BinderLibRpcTestP : public BinderLibRpcTestBase, public WithParamInterface<bool> {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001924public:
1925 sp<IBinder> GetService() {
1926 return GetParam() ? sp<IBinder>(addServer()) : sp<IBinder>(sp<BBinder>::make());
1927 }
1928 static std::string ParamToString(const testing::TestParamInfo<ParamType> &info) {
1929 return info.param ? "remote" : "local";
1930 }
1931};
1932
Yifan Hong8b890852021-06-10 13:44:09 -07001933TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoFd) {
1934 auto binder = GetService();
1935 ASSERT_TRUE(binder != nullptr);
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07001936 EXPECT_THAT(binder->setRpcClientDebug(unique_fd(), sp<BBinder>::make()),
Yifan Hongbd276552022-02-28 15:28:51 -08001937 Debuggable(StatusEq(BAD_VALUE)));
Yifan Hong8b890852021-06-10 13:44:09 -07001938}
1939
1940TEST_P(BinderLibRpcTestP, SetRpcClientDebugNoKeepAliveBinder) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001941 auto binder = GetService();
1942 ASSERT_TRUE(binder != nullptr);
1943 auto [socket, port] = CreateSocket();
1944 ASSERT_TRUE(socket.ok());
Yifan Hongbd276552022-02-28 15:28:51 -08001945 EXPECT_THAT(binder->setRpcClientDebug(std::move(socket), nullptr),
1946 Debuggable(StatusEq(UNEXPECTED_NULL)));
Yifan Hong84bedeb2021-04-21 21:37:17 -07001947}
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -07001948INSTANTIATE_TEST_SUITE_P(BinderLibTest, BinderLibRpcTestP, testing::Bool(),
1949 BinderLibRpcTestP::ParamToString);
Yifan Hong84bedeb2021-04-21 21:37:17 -07001950
Yifan Hong543edcd2021-05-18 19:47:30 -07001951class BinderLibTestService : public BBinder {
1952public:
Yifan Hong84bedeb2021-04-21 21:37:17 -07001953 explicit BinderLibTestService(int32_t id, bool exitOnDestroy = true)
1954 : m_id(id),
1955 m_nextServerId(id + 1),
1956 m_serverStartRequested(false),
1957 m_callback(nullptr),
1958 m_exitOnDestroy(exitOnDestroy) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001959 pthread_mutex_init(&m_serverWaitMutex, nullptr);
1960 pthread_cond_init(&m_serverWaitCond, nullptr);
1961 }
Yifan Hong84bedeb2021-04-21 21:37:17 -07001962 ~BinderLibTestService() {
1963 if (m_exitOnDestroy) exit(EXIT_SUCCESS);
1964 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001965
Yifan Hong543edcd2021-05-18 19:47:30 -07001966 void processPendingCall() {
1967 if (m_callback != nullptr) {
1968 Parcel data;
1969 data.writeInt32(NO_ERROR);
1970 m_callback->transact(BINDER_LIB_TEST_CALL_BACK, data, nullptr, TF_ONE_WAY);
1971 m_callback = nullptr;
Martijn Coenen45b07b42017-08-09 12:07:45 +02001972 }
Yifan Hong543edcd2021-05-18 19:47:30 -07001973 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02001974
Yifan Hong543edcd2021-05-18 19:47:30 -07001975 virtual status_t onTransact(uint32_t code, const Parcel &data, Parcel *reply,
1976 uint32_t flags = 0) {
Yifan Hong84bedeb2021-04-21 21:37:17 -07001977 // TODO(b/182914638): also checks getCallingUid() for RPC
1978 if (!data.isForRpc() && getuid() != (uid_t)IPCThreadState::self()->getCallingUid()) {
Yifan Hong543edcd2021-05-18 19:47:30 -07001979 return PERMISSION_DENIED;
1980 }
1981 switch (code) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001982 case BINDER_LIB_TEST_REGISTER_SERVER: {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001983 sp<IBinder> binder;
Tomasz Wasilczykbb07b982023-10-11 21:25:36 +00001984 /*id =*/data.readInt32();
Riley Andrews06b01ad2014-12-18 12:10:08 -08001985 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07001986 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08001987 return BAD_VALUE;
1988 }
1989
Yifan Hong543edcd2021-05-18 19:47:30 -07001990 if (m_id != 0) return INVALID_OPERATION;
Riley Andrews06b01ad2014-12-18 12:10:08 -08001991
1992 pthread_mutex_lock(&m_serverWaitMutex);
1993 if (m_serverStartRequested) {
1994 m_serverStartRequested = false;
1995 m_serverStarted = binder;
1996 pthread_cond_signal(&m_serverWaitCond);
1997 }
1998 pthread_mutex_unlock(&m_serverWaitMutex);
1999 return NO_ERROR;
2000 }
Martijn Coenen45b07b42017-08-09 12:07:45 +02002001 case BINDER_LIB_TEST_ADD_POLL_SERVER:
Riley Andrews06b01ad2014-12-18 12:10:08 -08002002 case BINDER_LIB_TEST_ADD_SERVER: {
2003 int ret;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002004 int serverid;
2005
2006 if (m_id != 0) {
2007 return INVALID_OPERATION;
2008 }
2009 pthread_mutex_lock(&m_serverWaitMutex);
2010 if (m_serverStartRequested) {
2011 ret = -EBUSY;
2012 } else {
2013 serverid = m_nextServerId++;
2014 m_serverStartRequested = true;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002015 bool usePoll = code == BINDER_LIB_TEST_ADD_POLL_SERVER;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002016
2017 pthread_mutex_unlock(&m_serverWaitMutex);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002018 ret = start_server_process(serverid, usePoll);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002019 pthread_mutex_lock(&m_serverWaitMutex);
2020 }
2021 if (ret > 0) {
2022 if (m_serverStartRequested) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002023 struct timespec ts;
2024 clock_gettime(CLOCK_REALTIME, &ts);
2025 ts.tv_sec += 5;
2026 ret = pthread_cond_timedwait(&m_serverWaitCond, &m_serverWaitMutex, &ts);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002027 }
2028 if (m_serverStartRequested) {
2029 m_serverStartRequested = false;
2030 ret = -ETIMEDOUT;
2031 } else {
2032 reply->writeStrongBinder(m_serverStarted);
2033 reply->writeInt32(serverid);
Yi Kong91635562018-06-07 14:38:36 -07002034 m_serverStarted = nullptr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002035 ret = NO_ERROR;
2036 }
2037 } else if (ret >= 0) {
2038 m_serverStartRequested = false;
2039 ret = UNKNOWN_ERROR;
2040 }
2041 pthread_mutex_unlock(&m_serverWaitMutex);
2042 return ret;
2043 }
Steven Moreland35626652021-05-15 01:32:04 +00002044 case BINDER_LIB_TEST_USE_CALLING_GUARD_TRANSACTION: {
2045 IPCThreadState::SpGuard spGuard{
2046 .address = __builtin_frame_address(0),
2047 .context = "GuardInBinderTransaction",
2048 };
2049 const IPCThreadState::SpGuard *origGuard =
2050 IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2051
2052 // if the guard works, this should abort
2053 (void)IPCThreadState::self()->getCallingPid();
2054
2055 IPCThreadState::self()->restoreGetCallingSpGuard(origGuard);
2056 return NO_ERROR;
2057 }
2058
Marco Ballesio7ee17572020-09-08 10:30:03 -07002059 case BINDER_LIB_TEST_GETPID:
2060 reply->writeInt32(getpid());
2061 return NO_ERROR;
Jing Jibdbe29a2023-10-03 00:03:28 -07002062 case BINDER_LIB_TEST_GETUID:
2063 reply->writeInt32(getuid());
2064 return NO_ERROR;
Marco Ballesio7ee17572020-09-08 10:30:03 -07002065 case BINDER_LIB_TEST_NOP_TRANSACTION_WAIT:
2066 usleep(5000);
Steven Moreland80844f72020-12-12 02:06:08 +00002067 [[fallthrough]];
Riley Andrews06b01ad2014-12-18 12:10:08 -08002068 case BINDER_LIB_TEST_NOP_TRANSACTION:
Steven Moreland80844f72020-12-12 02:06:08 +00002069 // oneway error codes should be ignored
2070 if (flags & TF_ONE_WAY) {
2071 return UNKNOWN_ERROR;
2072 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002073 return NO_ERROR;
Martijn Coenen45b07b42017-08-09 12:07:45 +02002074 case BINDER_LIB_TEST_DELAYED_CALL_BACK: {
2075 // Note: this transaction is only designed for use with a
2076 // poll() server. See comments around epoll_wait().
Yi Kong91635562018-06-07 14:38:36 -07002077 if (m_callback != nullptr) {
Martijn Coenen45b07b42017-08-09 12:07:45 +02002078 // A callback was already pending; this means that
2079 // we received a second call while still processing
2080 // the first one. Fail the test.
2081 sp<IBinder> callback = data.readStrongBinder();
2082 Parcel data2;
2083 data2.writeInt32(UNKNOWN_ERROR);
2084
Yi Kong91635562018-06-07 14:38:36 -07002085 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, nullptr, TF_ONE_WAY);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002086 } else {
2087 m_callback = data.readStrongBinder();
2088 int32_t delayUs = data.readInt32();
2089 /*
2090 * It's necessary that we sleep here, so the next
2091 * transaction the caller makes will be queued to
2092 * the async queue.
2093 */
2094 usleep(delayUs);
2095
2096 /*
2097 * Now when we return, libbinder will tell the kernel
2098 * we are done with this transaction, and the kernel
2099 * can move the queued transaction to either the
2100 * thread todo worklist (for kernels without the fix),
2101 * or the proc todo worklist. In case of the former,
2102 * the next outbound call will pick up the pending
2103 * transaction, which leads to undesired reentrant
2104 * behavior. This is caught in the if() branch above.
2105 */
2106 }
2107
2108 return NO_ERROR;
2109 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002110 case BINDER_LIB_TEST_NOP_CALL_BACK: {
2111 Parcel data2, reply2;
2112 sp<IBinder> binder;
2113 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002114 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002115 return BAD_VALUE;
2116 }
Martijn Coenenfb368f72017-08-10 15:03:18 +02002117 data2.writeInt32(NO_ERROR);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002118 binder->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2119 return NO_ERROR;
2120 }
Arve Hjønnevåg70604312016-08-12 15:34:51 -07002121 case BINDER_LIB_TEST_GET_SELF_TRANSACTION:
2122 reply->writeStrongBinder(this);
2123 return NO_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002124 case BINDER_LIB_TEST_GET_ID_TRANSACTION:
2125 reply->writeInt32(m_id);
2126 return NO_ERROR;
2127 case BINDER_LIB_TEST_INDIRECT_TRANSACTION: {
2128 int32_t count;
2129 uint32_t indirect_code;
2130 sp<IBinder> binder;
2131
2132 count = data.readInt32();
2133 reply->writeInt32(m_id);
2134 reply->writeInt32(count);
2135 for (int i = 0; i < count; i++) {
2136 binder = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002137 if (binder == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002138 return BAD_VALUE;
2139 }
2140 indirect_code = data.readInt32();
2141 BinderLibTestBundle data2(&data);
2142 if (!data2.isValid()) {
2143 return BAD_VALUE;
2144 }
2145 BinderLibTestBundle reply2;
2146 binder->transact(indirect_code, data2, &reply2);
2147 reply2.appendTo(reply);
2148 }
2149 return NO_ERROR;
2150 }
2151 case BINDER_LIB_TEST_SET_ERROR_TRANSACTION:
2152 reply->setError(data.readInt32());
2153 return NO_ERROR;
2154 case BINDER_LIB_TEST_GET_PTR_SIZE_TRANSACTION:
2155 reply->writeInt32(sizeof(void *));
2156 return NO_ERROR;
2157 case BINDER_LIB_TEST_GET_STATUS_TRANSACTION:
2158 return NO_ERROR;
2159 case BINDER_LIB_TEST_ADD_STRONG_REF_TRANSACTION:
2160 m_strongRef = data.readStrongBinder();
2161 return NO_ERROR;
2162 case BINDER_LIB_TEST_LINK_DEATH_TRANSACTION: {
2163 int ret;
2164 Parcel data2, reply2;
2165 sp<TestDeathRecipient> testDeathRecipient = new TestDeathRecipient();
2166 sp<IBinder> target;
2167 sp<IBinder> callback;
2168
2169 target = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002170 if (target == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002171 return BAD_VALUE;
2172 }
2173 callback = data.readStrongBinder();
Yi Kong91635562018-06-07 14:38:36 -07002174 if (callback == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002175 return BAD_VALUE;
2176 }
2177 ret = target->linkToDeath(testDeathRecipient);
Yifan Hong543edcd2021-05-18 19:47:30 -07002178 if (ret == NO_ERROR) ret = testDeathRecipient->waitEvent(5);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002179 data2.writeInt32(ret);
2180 callback->transact(BINDER_LIB_TEST_CALL_BACK, data2, &reply2);
2181 return NO_ERROR;
2182 }
2183 case BINDER_LIB_TEST_WRITE_FILE_TRANSACTION: {
2184 int ret;
2185 int32_t size;
2186 const void *buf;
2187 int fd;
2188
2189 fd = data.readFileDescriptor();
2190 if (fd < 0) {
2191 return BAD_VALUE;
2192 }
2193 ret = data.readInt32(&size);
2194 if (ret != NO_ERROR) {
2195 return ret;
2196 }
2197 buf = data.readInplace(size);
Yi Kong91635562018-06-07 14:38:36 -07002198 if (buf == nullptr) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002199 return BAD_VALUE;
2200 }
2201 ret = write(fd, buf, size);
Yifan Hong543edcd2021-05-18 19:47:30 -07002202 if (ret != size) return UNKNOWN_ERROR;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002203 return NO_ERROR;
2204 }
Ryo Hashimotobf551892018-05-31 16:58:35 +09002205 case BINDER_LIB_TEST_WRITE_PARCEL_FILE_DESCRIPTOR_TRANSACTION: {
2206 int ret;
2207 int32_t size;
2208 const void *buf;
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002209 unique_fd fd;
Ryo Hashimotobf551892018-05-31 16:58:35 +09002210
2211 ret = data.readUniqueParcelFileDescriptor(&fd);
2212 if (ret != NO_ERROR) {
2213 return ret;
2214 }
2215 ret = data.readInt32(&size);
2216 if (ret != NO_ERROR) {
2217 return ret;
2218 }
2219 buf = data.readInplace(size);
Yi Kong0cf75842018-07-10 11:44:36 -07002220 if (buf == nullptr) {
Ryo Hashimotobf551892018-05-31 16:58:35 +09002221 return BAD_VALUE;
2222 }
2223 ret = write(fd.get(), buf, size);
2224 if (ret != size) return UNKNOWN_ERROR;
2225 return NO_ERROR;
2226 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002227 case BINDER_LIB_TEST_DELAYED_EXIT_TRANSACTION:
2228 alarm(10);
2229 return NO_ERROR;
2230 case BINDER_LIB_TEST_EXIT_TRANSACTION:
Yi Kong91635562018-06-07 14:38:36 -07002231 while (wait(nullptr) != -1 || errno != ECHILD)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002232 ;
2233 exit(EXIT_SUCCESS);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002234 case BINDER_LIB_TEST_CREATE_BINDER_TRANSACTION: {
Connor O'Brien52be2c92016-09-20 14:18:08 -07002235 sp<IBinder> binder = new BBinder();
Steven Morelande171d622019-07-17 16:06:01 -07002236 reply->writeStrongBinder(binder);
Connor O'Brien52be2c92016-09-20 14:18:08 -07002237 return NO_ERROR;
2238 }
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002239 case BINDER_LIB_TEST_GET_WORK_SOURCE_TRANSACTION: {
2240 data.enforceInterface(binderLibTestServiceName);
Olivier Gaillarda8e7bf22018-11-14 15:35:50 +00002241 reply->writeInt32(IPCThreadState::self()->getCallingWorkSourceUid());
Olivier Gaillard0e0f1de2018-08-16 14:04:09 +01002242 return NO_ERROR;
2243 }
Steven Morelandbf1915b2020-07-16 22:43:02 +00002244 case BINDER_LIB_TEST_GET_SCHEDULING_POLICY: {
2245 int policy = 0;
2246 sched_param param;
2247 if (0 != pthread_getschedparam(pthread_self(), &policy, &param)) {
2248 return UNKNOWN_ERROR;
2249 }
2250 reply->writeInt32(policy);
2251 reply->writeInt32(param.sched_priority);
2252 return NO_ERROR;
2253 }
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002254 case BINDER_LIB_TEST_LISTEN_FOR_FROZEN_STATE_CHANGE: {
2255 sp<IBinder> binder = data.readStrongBinder();
2256 frozenStateChangeCallback = sp<TestFrozenStateChangeCallback>::make();
2257 // Hold an strong pointer to the binder object so it doesn't go
2258 // away.
2259 frozenStateChangeCallback->binder = binder;
2260 int ret = binder->addFrozenStateChangeCallback(frozenStateChangeCallback);
2261 if (ret != NO_ERROR) {
2262 return ret;
2263 }
2264 auto event = frozenStateChangeCallback->events.popWithTimeout(10ms);
2265 if (!event.has_value()) {
2266 return NOT_ENOUGH_DATA;
2267 }
2268 return NO_ERROR;
2269 }
2270 case BINDER_LIB_TEST_CONSUME_STATE_CHANGE_EVENTS: {
2271 reply->writeBoolVector(frozenStateChangeCallback->getAllAndClear());
2272 return NO_ERROR;
2273 }
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002274 case BINDER_LIB_TEST_ECHO_VECTOR: {
2275 std::vector<uint64_t> vector;
2276 auto err = data.readUint64Vector(&vector);
Yifan Hong543edcd2021-05-18 19:47:30 -07002277 if (err != NO_ERROR) return err;
Kevin DuBois2f82d5b2018-12-05 12:56:10 -08002278 reply->writeUint64Vector(vector);
2279 return NO_ERROR;
2280 }
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002281 case BINDER_LIB_TEST_GET_NON_BLOCKING_FD: {
2282 std::array<int, 2> sockets;
2283 const bool created = socketpair(AF_UNIX, SOCK_SEQPACKET, 0, sockets.data()) == 0;
2284 if (!created) {
2285 ALOGE("Could not create socket pair");
2286 return UNKNOWN_ERROR;
2287 }
2288
2289 const int result = fcntl(sockets[0], F_SETFL, O_NONBLOCK);
2290 if (result != 0) {
2291 ALOGE("Could not make socket non-blocking: %s", strerror(errno));
2292 return UNKNOWN_ERROR;
2293 }
Tomasz Wasilczyk639490b2023-11-01 13:49:41 -07002294 unique_fd out(sockets[0]);
Siarhei Vishniakou116f6b82022-10-03 13:43:15 -07002295 status_t writeResult = reply->writeUniqueFileDescriptor(out);
2296 if (writeResult != NO_ERROR) {
2297 ALOGE("Could not write unique_fd");
2298 return writeResult;
2299 }
2300 close(sockets[1]); // we don't need the other side of the fd
2301 return NO_ERROR;
2302 }
Steven Morelandf2e0a952021-11-01 18:17:23 -07002303 case BINDER_LIB_TEST_REJECT_OBJECTS: {
Martijn Coenen82c75312019-07-24 15:18:30 +02002304 return data.objectsCount() == 0 ? BAD_VALUE : NO_ERROR;
2305 }
Steven Moreland254e8ef2021-04-19 22:28:50 +00002306 case BINDER_LIB_TEST_CAN_GET_SID: {
2307 return IPCThreadState::self()->getCallingSid() == nullptr ? BAD_VALUE : NO_ERROR;
2308 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002309 case BINDER_LIB_TEST_GET_MAX_THREAD_COUNT: {
2310 reply->writeInt32(ProcessState::self()->getThreadPoolMaxTotalThreadCount());
2311 return NO_ERROR;
2312 }
Devin Moore4354f712022-12-08 01:44:46 +00002313 case BINDER_LIB_TEST_IS_THREADPOOL_STARTED: {
2314 reply->writeBool(ProcessState::self()->isThreadPoolStarted());
2315 return NO_ERROR;
2316 }
Elie Kheirallah47431c12022-04-21 23:46:17 +00002317 case BINDER_LIB_TEST_PROCESS_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002318 m_blockMutex.lock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002319 return NO_ERROR;
2320 }
2321 case BINDER_LIB_TEST_LOCK_UNLOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002322 std::lock_guard<std::mutex> _l(m_blockMutex);
Elie Kheirallah47431c12022-04-21 23:46:17 +00002323 return NO_ERROR;
2324 }
2325 case BINDER_LIB_TEST_UNLOCK_AFTER_MS: {
2326 int32_t ms = data.readInt32();
2327 return unlockInMs(ms);
2328 }
2329 case BINDER_LIB_TEST_PROCESS_TEMPORARY_LOCK: {
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002330 m_blockMutex.lock();
2331 sp<BinderLibTestService> thisService = this;
2332 int32_t value = data.readInt32();
2333 // start local thread to unlock in 1s
2334 std::thread t([=] { thisService->unlockInMs(value); });
Elie Kheirallah47431c12022-04-21 23:46:17 +00002335 t.detach();
2336 return NO_ERROR;
2337 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002338 default:
2339 return UNKNOWN_TRANSACTION;
Yifan Hong543edcd2021-05-18 19:47:30 -07002340 };
2341 }
2342
Elie Kheirallah47431c12022-04-21 23:46:17 +00002343 status_t unlockInMs(int32_t ms) {
2344 usleep(ms * 1000);
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002345 m_blockMutex.unlock();
Elie Kheirallah47431c12022-04-21 23:46:17 +00002346 return NO_ERROR;
2347 }
2348
Yifan Hong543edcd2021-05-18 19:47:30 -07002349private:
2350 int32_t m_id;
2351 int32_t m_nextServerId;
2352 pthread_mutex_t m_serverWaitMutex;
2353 pthread_cond_t m_serverWaitCond;
2354 bool m_serverStartRequested;
2355 sp<IBinder> m_serverStarted;
2356 sp<IBinder> m_strongRef;
2357 sp<IBinder> m_callback;
Yifan Hong84bedeb2021-04-21 21:37:17 -07002358 bool m_exitOnDestroy;
Elie Kheirallahc2f5a7e2022-05-27 22:43:40 +00002359 std::mutex m_blockMutex;
Yu-Ting Tsengd5fc4462024-04-30 15:07:13 -07002360 sp<TestFrozenStateChangeCallback> frozenStateChangeCallback;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002361};
2362
Martijn Coenen45b07b42017-08-09 12:07:45 +02002363int run_server(int index, int readypipefd, bool usePoll)
Riley Andrews06b01ad2014-12-18 12:10:08 -08002364{
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002365 binderLibTestServiceName += String16(binderserversuffix);
2366
Steven Moreland35626652021-05-15 01:32:04 +00002367 // Testing to make sure that calls that we are serving can use getCallin*
2368 // even though we don't here.
2369 IPCThreadState::SpGuard spGuard{
2370 .address = __builtin_frame_address(0),
2371 .context = "main server thread",
2372 };
2373 (void)IPCThreadState::self()->pushGetCallingSpGuard(&spGuard);
2374
Riley Andrews06b01ad2014-12-18 12:10:08 -08002375 status_t ret;
2376 sp<IServiceManager> sm = defaultServiceManager();
Martijn Coenen45b07b42017-08-09 12:07:45 +02002377 BinderLibTestService* testServicePtr;
Riley Andrews06b01ad2014-12-18 12:10:08 -08002378 {
2379 sp<BinderLibTestService> testService = new BinderLibTestService(index);
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002380
Steven Morelandbf1915b2020-07-16 22:43:02 +00002381 testService->setMinSchedulerPolicy(kSchedPolicy, kSchedPriority);
2382
Steven Morelandcf03cf12020-12-04 02:58:40 +00002383 testService->setInheritRt(true);
2384
Steven Morelandb8ad08d2019-08-09 14:42:56 -07002385 /*
2386 * Normally would also contain functionality as well, but we are only
2387 * testing the extension mechanism.
2388 */
2389 testService->setExtension(new BBinder());
2390
Martijn Coenen82c75312019-07-24 15:18:30 +02002391 // Required for test "BufRejected'
2392 testService->setRequestingSid(true);
2393
Martijn Coenen45b07b42017-08-09 12:07:45 +02002394 /*
2395 * We need this below, but can't hold a sp<> because it prevents the
2396 * node from being cleaned up automatically. It's safe in this case
2397 * because of how the tests are written.
2398 */
2399 testServicePtr = testService.get();
2400
Riley Andrews06b01ad2014-12-18 12:10:08 -08002401 if (index == 0) {
2402 ret = sm->addService(binderLibTestServiceName, testService);
2403 } else {
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002404 LIBBINDER_IGNORE("-Wdeprecated-declarations")
Riley Andrews06b01ad2014-12-18 12:10:08 -08002405 sp<IBinder> server = sm->getService(binderLibTestServiceName);
Tomasz Wasilczyk370408e2024-06-21 15:45:26 -07002406 LIBBINDER_IGNORE_END()
Riley Andrews06b01ad2014-12-18 12:10:08 -08002407 Parcel data, reply;
2408 data.writeInt32(index);
2409 data.writeStrongBinder(testService);
2410
2411 ret = server->transact(BINDER_LIB_TEST_REGISTER_SERVER, data, &reply);
2412 }
2413 }
2414 write(readypipefd, &ret, sizeof(ret));
2415 close(readypipefd);
2416 //printf("%s: ret %d\n", __func__, ret);
2417 if (ret)
2418 return 1;
2419 //printf("%s: joinThreadPool\n", __func__);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002420 if (usePoll) {
2421 int fd;
2422 struct epoll_event ev;
2423 int epoll_fd;
2424 IPCThreadState::self()->setupPolling(&fd);
2425 if (fd < 0) {
2426 return 1;
2427 }
2428 IPCThreadState::self()->flushCommands(); // flush BC_ENTER_LOOPER
2429
Nick Kralevichfcf1b2b2018-12-15 11:59:30 -08002430 epoll_fd = epoll_create1(EPOLL_CLOEXEC);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002431 if (epoll_fd == -1) {
2432 return 1;
2433 }
2434
2435 ev.events = EPOLLIN;
2436 if (epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fd, &ev) == -1) {
2437 return 1;
2438 }
2439
2440 while (1) {
2441 /*
2442 * We simulate a single-threaded process using the binder poll
2443 * interface; besides handling binder commands, it can also
2444 * issue outgoing transactions, by storing a callback in
Steven Moreland573adc12019-07-17 13:29:06 -07002445 * m_callback.
Martijn Coenen45b07b42017-08-09 12:07:45 +02002446 *
2447 * processPendingCall() will then issue that transaction.
2448 */
2449 struct epoll_event events[1];
2450 int numEvents = epoll_wait(epoll_fd, events, 1, 1000);
2451 if (numEvents < 0) {
2452 if (errno == EINTR) {
2453 continue;
2454 }
2455 return 1;
2456 }
2457 if (numEvents > 0) {
2458 IPCThreadState::self()->handlePolledCommands();
2459 IPCThreadState::self()->flushCommands(); // flush BC_FREE_BUFFER
2460 testServicePtr->processPendingCall();
2461 }
2462 }
2463 } else {
Elie Kheirallah47431c12022-04-21 23:46:17 +00002464 ProcessState::self()->setThreadPoolMaxThreadCount(kKernelThreads);
Martijn Coenen45b07b42017-08-09 12:07:45 +02002465 ProcessState::self()->startThreadPool();
2466 IPCThreadState::self()->joinThreadPool();
2467 }
Riley Andrews06b01ad2014-12-18 12:10:08 -08002468 //printf("%s: joinThreadPool returned\n", __func__);
2469 return 1; /* joinThreadPool should not return */
2470}
2471
Steven Moreland68275d72023-04-21 22:12:45 +00002472int main(int argc, char** argv) {
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002473 if (argc == 4 && !strcmp(argv[1], "--servername")) {
Riley Andrews06b01ad2014-12-18 12:10:08 -08002474 binderservername = argv[2];
2475 } else {
2476 binderservername = argv[0];
2477 }
2478
Martijn Coenen45b07b42017-08-09 12:07:45 +02002479 if (argc == 6 && !strcmp(argv[1], binderserverarg)) {
2480 binderserversuffix = argv[5];
2481 return run_server(atoi(argv[2]), atoi(argv[3]), atoi(argv[4]) == 1);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002482 }
Connor O'Brien87c03cf2016-10-26 17:58:51 -07002483 binderserversuffix = new char[16];
2484 snprintf(binderserversuffix, 16, "%d", getpid());
2485 binderLibTestServiceName += String16(binderserversuffix);
Riley Andrews06b01ad2014-12-18 12:10:08 -08002486
2487 ::testing::InitGoogleTest(&argc, argv);
2488 binder_env = AddGlobalTestEnvironment(new BinderLibTestEnv());
2489 ProcessState::self()->startThreadPool();
2490 return RUN_ALL_TESTS();
2491}