blob: c0c0aae80b45a016401b054f7410c7554787d7c3 [file] [log] [blame]
Steven Moreland042ae822020-05-27 17:45:17 +00001/*
2 * Copyright (C) 2020 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 <android-base/logging.h>
Devin Moore2a49be62022-05-26 22:04:21 +000018#include <binder/Binder.h>
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000019#include <binder/Functional.h>
Steven Moreland042ae822020-05-27 17:45:17 +000020#include <binder/IServiceManager.h>
Devin Moore2a49be62022-05-26 22:04:21 +000021#include <binder/Parcel.h>
22#include <binder/RpcServer.h>
23#include <binder/RpcSession.h>
Steven Moreland66acefe2022-09-09 00:34:40 +000024#include <cutils/trace.h>
Steven Moreland042ae822020-05-27 17:45:17 +000025#include <gtest/gtest.h>
26#include <utils/CallStack.h>
27
28#include <malloc.h>
29#include <functional>
30#include <vector>
31
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +000032using namespace android::binder::impl;
33
Devin Moorea39f3db2022-08-15 23:28:55 +000034static android::String8 gEmpty(""); // make sure first allocation from optimization runs
35
Steven Moreland042ae822020-05-27 17:45:17 +000036struct DestructionAction {
37 DestructionAction(std::function<void()> f) : mF(std::move(f)) {}
38 ~DestructionAction() { mF(); };
39private:
40 std::function<void()> mF;
41};
42
43// Group of hooks
44struct MallocHooks {
45 decltype(__malloc_hook) malloc_hook;
46 decltype(__realloc_hook) realloc_hook;
47
48 static MallocHooks save() {
49 return {
50 .malloc_hook = __malloc_hook,
51 .realloc_hook = __realloc_hook,
52 };
53 }
54
55 void overwrite() const {
56 __malloc_hook = malloc_hook;
57 __realloc_hook = realloc_hook;
58 }
59};
60
61static const MallocHooks orig_malloc_hooks = MallocHooks::save();
62
63// When malloc is hit, executes lambda.
64namespace LambdaHooks {
65 using AllocationHook = std::function<void(size_t)>;
66 static std::vector<AllocationHook> lambdas = {};
67
68 static void* lambda_realloc_hook(void* ptr, size_t bytes, const void* arg);
69 static void* lambda_malloc_hook(size_t bytes, const void* arg);
70
71 static const MallocHooks lambda_malloc_hooks = {
72 .malloc_hook = lambda_malloc_hook,
73 .realloc_hook = lambda_realloc_hook,
74 };
75
76 static void* lambda_malloc_hook(size_t bytes, const void* arg) {
77 {
78 orig_malloc_hooks.overwrite();
79 lambdas.at(lambdas.size() - 1)(bytes);
80 lambda_malloc_hooks.overwrite();
81 }
82 return orig_malloc_hooks.malloc_hook(bytes, arg);
83 }
84
85 static void* lambda_realloc_hook(void* ptr, size_t bytes, const void* arg) {
86 {
87 orig_malloc_hooks.overwrite();
88 lambdas.at(lambdas.size() - 1)(bytes);
89 lambda_malloc_hooks.overwrite();
90 }
91 return orig_malloc_hooks.realloc_hook(ptr, bytes, arg);
92 }
93
94}
95
96// Action to execute when malloc is hit. Supports nesting. Malloc is not
97// restricted when the allocation hook is being processed.
98__attribute__((warn_unused_result))
99DestructionAction OnMalloc(LambdaHooks::AllocationHook f) {
100 MallocHooks before = MallocHooks::save();
101 LambdaHooks::lambdas.emplace_back(std::move(f));
102 LambdaHooks::lambda_malloc_hooks.overwrite();
103 return DestructionAction([before]() {
104 before.overwrite();
105 LambdaHooks::lambdas.pop_back();
106 });
107}
108
109// exported symbol, to force compiler not to optimize away pointers we set here
110const void* imaginary_use;
111
112TEST(TestTheTest, OnMalloc) {
113 size_t mallocs = 0;
114 {
115 const auto on_malloc = OnMalloc([&](size_t bytes) {
116 mallocs++;
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700117 EXPECT_EQ(bytes, 40u);
Steven Moreland042ae822020-05-27 17:45:17 +0000118 });
119
120 imaginary_use = new int[10];
121 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700122 EXPECT_EQ(mallocs, 1u);
Steven Moreland042ae822020-05-27 17:45:17 +0000123}
124
125
126__attribute__((warn_unused_result))
127DestructionAction ScopeDisallowMalloc() {
128 return OnMalloc([&](size_t bytes) {
129 ADD_FAILURE() << "Unexpected allocation: " << bytes;
130 using android::CallStack;
131 std::cout << CallStack::stackToString("UNEXPECTED ALLOCATION", CallStack::getCurrent(4 /*ignoreDepth*/).get())
132 << std::endl;
133 });
134}
135
Devin Moore2a49be62022-05-26 22:04:21 +0000136using android::BBinder;
Steven Moreland042ae822020-05-27 17:45:17 +0000137using android::defaultServiceManager;
Devin Moore2a49be62022-05-26 22:04:21 +0000138using android::IBinder;
Steven Moreland042ae822020-05-27 17:45:17 +0000139using android::IServiceManager;
Devin Moore2a49be62022-05-26 22:04:21 +0000140using android::OK;
141using android::Parcel;
142using android::RpcServer;
143using android::RpcSession;
144using android::sp;
145using android::status_t;
146using android::statusToString;
147using android::String16;
Steven Moreland042ae822020-05-27 17:45:17 +0000148
149static sp<IBinder> GetRemoteBinder() {
150 // This gets binder representing the service manager
151 // the current IServiceManager API doesn't expose the binder, and
152 // I want to avoid adding usages of the AIDL generated interface it
153 // is using underneath, so to avoid people copying it.
154 sp<IBinder> binder = defaultServiceManager()->checkService(String16("manager"));
155 EXPECT_NE(nullptr, binder);
156 return binder;
157}
158
159TEST(BinderAllocation, ParcelOnStack) {
160 const auto m = ScopeDisallowMalloc();
161 Parcel p;
162 imaginary_use = p.data();
163}
164
165TEST(BinderAllocation, GetServiceManager) {
166 defaultServiceManager(); // first call may alloc
167 const auto m = ScopeDisallowMalloc();
168 defaultServiceManager();
169}
170
171// note, ping does not include interface descriptor
172TEST(BinderAllocation, PingTransaction) {
173 sp<IBinder> a_binder = GetRemoteBinder();
174 const auto m = ScopeDisallowMalloc();
175 a_binder->pingBinder();
176}
177
Tomasz Wasilczyk1de48a22023-10-30 14:19:19 +0000178TEST(BinderAllocation, MakeScopeGuard) {
179 const auto m = ScopeDisallowMalloc();
180 {
181 auto guard1 = make_scope_guard([] {});
182 guard1.release();
183
184 auto guard2 = make_scope_guard([&guard1, ptr = imaginary_use] {
185 if (ptr == nullptr) guard1.release();
186 });
187 }
188}
189
Steven Morelandf2830fe2022-12-21 00:45:34 +0000190TEST(BinderAllocation, InterfaceDescriptorTransaction) {
191 sp<IBinder> a_binder = GetRemoteBinder();
192
193 size_t mallocs = 0;
194 const auto on_malloc = OnMalloc([&](size_t bytes) {
195 mallocs++;
196 // Happens to be SM package length. We could switch to forking
197 // and registering our own service if it became an issue.
Steven Moreland33813942023-01-05 17:43:01 +0000198#if defined(__LP64__)
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700199 EXPECT_EQ(bytes, 78u);
Steven Moreland33813942023-01-05 17:43:01 +0000200#else
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700201 EXPECT_EQ(bytes, 70u);
Steven Moreland33813942023-01-05 17:43:01 +0000202#endif
Steven Morelandf2830fe2022-12-21 00:45:34 +0000203 });
204
205 a_binder->getInterfaceDescriptor();
206 a_binder->getInterfaceDescriptor();
207 a_binder->getInterfaceDescriptor();
208
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700209 EXPECT_EQ(mallocs, 1u);
Steven Morelandf2830fe2022-12-21 00:45:34 +0000210}
211
Steven Moreland042ae822020-05-27 17:45:17 +0000212TEST(BinderAllocation, SmallTransaction) {
213 String16 empty_descriptor = String16("");
214 sp<IServiceManager> manager = defaultServiceManager();
215
216 size_t mallocs = 0;
217 const auto on_malloc = OnMalloc([&](size_t bytes) {
218 mallocs++;
219 // Parcel should allocate a small amount by default
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700220 EXPECT_EQ(bytes, 128u);
Steven Moreland042ae822020-05-27 17:45:17 +0000221 });
222 manager->checkService(empty_descriptor);
223
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700224 EXPECT_EQ(mallocs, 1u);
Steven Moreland042ae822020-05-27 17:45:17 +0000225}
226
Devin Moore2a49be62022-05-26 22:04:21 +0000227TEST(RpcBinderAllocation, SetupRpcServer) {
228 std::string tmp = getenv("TMPDIR") ?: "/tmp";
229 std::string addr = tmp + "/binderRpcBenchmark";
230 (void)unlink(addr.c_str());
231 auto server = RpcServer::make();
232 server->setRootObject(sp<BBinder>::make());
233
Steven Moreland3652ba02023-07-21 00:37:18 +0000234 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Devin Moore2a49be62022-05-26 22:04:21 +0000235
236 std::thread([server]() { server->join(); }).detach();
237
Devin Moore2a49be62022-05-26 22:04:21 +0000238 auto session = RpcSession::make();
Steven Moreland3652ba02023-07-21 00:37:18 +0000239 status_t status = session->setupUnixDomainClient(addr.c_str());
240 ASSERT_EQ(status, OK) << "Could not connect: " << addr << ": " << statusToString(status).c_str();
Devin Moore2a49be62022-05-26 22:04:21 +0000241
242 auto remoteBinder = session->getRootObject();
Steven Moreland3652ba02023-07-21 00:37:18 +0000243 ASSERT_NE(remoteBinder, nullptr);
Devin Moore2a49be62022-05-26 22:04:21 +0000244
245 size_t mallocs = 0, totalBytes = 0;
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000246 {
247 const auto on_malloc = OnMalloc([&](size_t bytes) {
248 mallocs++;
249 totalBytes += bytes;
250 });
Steven Moreland3652ba02023-07-21 00:37:18 +0000251 ASSERT_EQ(OK, remoteBinder->pingBinder());
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000252 }
Tomasz Wasilczyke97f3a82024-04-30 10:37:32 -0700253 EXPECT_EQ(mallocs, 1u);
254 EXPECT_EQ(totalBytes, 40u);
Devin Moore2a49be62022-05-26 22:04:21 +0000255}
256
Steven Moreland042ae822020-05-27 17:45:17 +0000257int main(int argc, char** argv) {
258 if (getenv("LIBC_HOOKS_ENABLE") == nullptr) {
259 CHECK(0 == setenv("LIBC_HOOKS_ENABLE", "1", true /*overwrite*/));
260 execv(argv[0], argv);
261 return 1;
262 }
263 ::testing::InitGoogleTest(&argc, argv);
Steven Moreland66acefe2022-09-09 00:34:40 +0000264
265 // if tracing is enabled, take in one-time cost
266 (void)ATRACE_INIT();
267 (void)ATRACE_GET_ENABLED_TAGS();
268
Steven Moreland042ae822020-05-27 17:45:17 +0000269 return RUN_ALL_TESTS();
270}