1 /*
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>
18 #include <binder/Binder.h>
19 #include <binder/Functional.h>
20 #include <binder/IServiceManager.h>
21 #include <binder/Parcel.h>
22 #include <binder/RpcServer.h>
23 #include <binder/RpcSession.h>
24 #include <cutils/trace.h>
25 #include <gtest/gtest-spi.h>
26 #include <gtest/gtest.h>
27 #include <utils/CallStack.h>
28
29 #include <malloc.h>
30 #include <atomic>
31 #include <functional>
32 #include <numeric>
33 #include <vector>
34
35 using namespace android::binder::impl;
36
37 static android::String8 gEmpty(""); // make sure first allocation from optimization runs
38
39 struct State {
StateState40 State(std::vector<size_t>&& expectedMallocs) : expectedMallocs(std::move(expectedMallocs)) {}
~StateState41 ~State() {
42 size_t num = numMallocs.load();
43 if (expectedMallocs.size() != num) {
44 ADD_FAILURE() << "Expected " << expectedMallocs.size() << " allocations, but got "
45 << num;
46 }
47 }
48 const std::vector<size_t> expectedMallocs;
49 std::atomic<size_t> numMallocs;
50 };
51
52 struct DestructionAction {
DestructionActionDestructionAction53 DestructionAction(std::function<void()> f) : mF(std::move(f)) {}
~DestructionActionDestructionAction54 ~DestructionAction() { mF(); };
55 private:
56 std::function<void()> mF;
57 };
58
59 // Group of hooks
60 struct MallocHooks {
61 decltype(__malloc_hook) malloc_hook;
62 decltype(__realloc_hook) realloc_hook;
63
saveMallocHooks64 static MallocHooks save() {
65 return {
66 .malloc_hook = __malloc_hook,
67 .realloc_hook = __realloc_hook,
68 };
69 }
70
overwriteMallocHooks71 void overwrite() const {
72 __malloc_hook = malloc_hook;
73 __realloc_hook = realloc_hook;
74 }
75 };
76
77 static const MallocHooks orig_malloc_hooks = MallocHooks::save();
78
79 // When malloc is hit, executes lambda.
80 namespace LambdaHooks {
81 using AllocationHook = std::function<void(size_t)>;
82 static std::vector<AllocationHook> lambdas = {};
83
84 static void* lambda_realloc_hook(void* ptr, size_t bytes, const void* arg);
85 static void* lambda_malloc_hook(size_t bytes, const void* arg);
86
87 static const MallocHooks lambda_malloc_hooks = {
88 .malloc_hook = lambda_malloc_hook,
89 .realloc_hook = lambda_realloc_hook,
90 };
91
lambda_malloc_hook(size_t bytes,const void * arg)92 static void* lambda_malloc_hook(size_t bytes, const void* arg) {
93 {
94 orig_malloc_hooks.overwrite();
95 lambdas.at(lambdas.size() - 1)(bytes);
96 lambda_malloc_hooks.overwrite();
97 }
98 return orig_malloc_hooks.malloc_hook(bytes, arg);
99 }
100
lambda_realloc_hook(void * ptr,size_t bytes,const void * arg)101 static void* lambda_realloc_hook(void* ptr, size_t bytes, const void* arg) {
102 {
103 orig_malloc_hooks.overwrite();
104 lambdas.at(lambdas.size() - 1)(bytes);
105 lambda_malloc_hooks.overwrite();
106 }
107 return orig_malloc_hooks.realloc_hook(ptr, bytes, arg);
108 }
109
110 }
111
112 // Action to execute when malloc is hit. Supports nesting. Malloc is not
113 // restricted when the allocation hook is being processed.
OnMalloc(LambdaHooks::AllocationHook f)114 __attribute__((warn_unused_result)) DestructionAction OnMalloc(LambdaHooks::AllocationHook f) {
115 MallocHooks before = MallocHooks::save();
116 LambdaHooks::lambdas.emplace_back(std::move(f));
117 LambdaHooks::lambda_malloc_hooks.overwrite();
118 return DestructionAction([before]() {
119 before.overwrite();
120 LambdaHooks::lambdas.pop_back();
121 });
122 }
123
setExpectedMallocs(std::vector<size_t> && expected)124 DestructionAction setExpectedMallocs(std::vector<size_t>&& expected) {
125 auto state = std::make_shared<State>(std::move(expected));
126 return OnMalloc([state = state](size_t bytes) {
127 size_t num = state->numMallocs.fetch_add(1);
128 if (num >= state->expectedMallocs.size() || state->expectedMallocs[num] != bytes) {
129 ADD_FAILURE() << "Unexpected allocation number " << num << " of size " << bytes
130 << " bytes" << std::endl
131 << android::CallStack::stackToString("UNEXPECTED ALLOCATION",
132 android::CallStack::getCurrent(
133 4 /*ignoreDepth*/)
134 .get())
135 << std::endl;
136 }
137 });
138 }
139
140 // exported symbol, to force compiler not to optimize away pointers we set here
141 const void* imaginary_use;
142
TEST(TestTheTest,OnMalloc)143 TEST(TestTheTest, OnMalloc) {
144 size_t mallocs = 0;
145 {
146 const auto on_malloc = OnMalloc([&](size_t bytes) {
147 mallocs++;
148 EXPECT_EQ(bytes, 40u);
149 });
150
151 imaginary_use = new int[10];
152 }
153 delete[] reinterpret_cast<const int*>(imaginary_use);
154 EXPECT_EQ(mallocs, 1u);
155 }
156
TEST(TestTheTest,OnMallocWithExpectedMallocs)157 TEST(TestTheTest, OnMallocWithExpectedMallocs) {
158 std::vector<size_t> expectedMallocs = {
159 4,
160 16,
161 8,
162 };
163 {
164 const auto on_malloc = setExpectedMallocs(std::move(expectedMallocs));
165 imaginary_use = new int32_t[1];
166 delete[] reinterpret_cast<const int*>(imaginary_use);
167 imaginary_use = new int32_t[4];
168 delete[] reinterpret_cast<const int*>(imaginary_use);
169 imaginary_use = new int32_t[2];
170 delete[] reinterpret_cast<const int*>(imaginary_use);
171 }
172 }
173
TEST(TestTheTest,OnMallocWithExpectedMallocsWrongSize)174 TEST(TestTheTest, OnMallocWithExpectedMallocsWrongSize) {
175 std::vector<size_t> expectedMallocs = {
176 4,
177 16,
178 100000,
179 };
180 EXPECT_NONFATAL_FAILURE(
181 {
182 const auto on_malloc = setExpectedMallocs(std::move(expectedMallocs));
183 imaginary_use = new int32_t[1];
184 delete[] reinterpret_cast<const int*>(imaginary_use);
185 imaginary_use = new int32_t[4];
186 delete[] reinterpret_cast<const int*>(imaginary_use);
187 imaginary_use = new int32_t[2];
188 delete[] reinterpret_cast<const int*>(imaginary_use);
189 },
190 "Unexpected allocation number 2 of size 8 bytes");
191 }
192
193 __attribute__((warn_unused_result))
ScopeDisallowMalloc()194 DestructionAction ScopeDisallowMalloc() {
195 return OnMalloc([&](size_t bytes) {
196 FAIL() << "Unexpected allocation: " << bytes;
197 using android::CallStack;
198 std::cout << CallStack::stackToString("UNEXPECTED ALLOCATION",
199 CallStack::getCurrent(4 /*ignoreDepth*/).get())
200 << std::endl;
201 });
202 }
203
204 using android::BBinder;
205 using android::defaultServiceManager;
206 using android::IBinder;
207 using android::IServiceManager;
208 using android::OK;
209 using android::Parcel;
210 using android::RpcServer;
211 using android::RpcSession;
212 using android::sp;
213 using android::status_t;
214 using android::statusToString;
215 using android::String16;
216
GetRemoteBinder()217 static sp<IBinder> GetRemoteBinder() {
218 // This gets binder representing the service manager
219 // the current IServiceManager API doesn't expose the binder, and
220 // I want to avoid adding usages of the AIDL generated interface it
221 // is using underneath, so to avoid people copying it.
222 sp<IBinder> binder = defaultServiceManager()->checkService(String16("manager"));
223 EXPECT_NE(nullptr, binder);
224 return binder;
225 }
226
TEST(BinderAllocation,ParcelOnStack)227 TEST(BinderAllocation, ParcelOnStack) {
228 const auto m = ScopeDisallowMalloc();
229 Parcel p;
230 imaginary_use = p.data();
231 }
232
TEST(BinderAllocation,GetServiceManager)233 TEST(BinderAllocation, GetServiceManager) {
234 defaultServiceManager(); // first call may alloc
235 const auto m = ScopeDisallowMalloc();
236 defaultServiceManager();
237 }
238
239 // note, ping does not include interface descriptor
TEST(BinderAllocation,PingTransaction)240 TEST(BinderAllocation, PingTransaction) {
241 sp<IBinder> a_binder = GetRemoteBinder();
242 const auto m = ScopeDisallowMalloc();
243 a_binder->pingBinder();
244 }
245
TEST(BinderAllocation,MakeScopeGuard)246 TEST(BinderAllocation, MakeScopeGuard) {
247 const auto m = ScopeDisallowMalloc();
248 {
249 auto guard1 = make_scope_guard([] {});
250 guard1.release();
251
252 auto guard2 = make_scope_guard([&guard1, ptr = imaginary_use] {
253 if (ptr == nullptr) guard1.release();
254 });
255 }
256 }
257
TEST(BinderAllocation,InterfaceDescriptorTransaction)258 TEST(BinderAllocation, InterfaceDescriptorTransaction) {
259 sp<IBinder> a_binder = GetRemoteBinder();
260
261 size_t mallocs = 0;
262 const auto on_malloc = OnMalloc([&](size_t bytes) {
263 mallocs++;
264 // Happens to be SM package length. We could switch to forking
265 // and registering our own service if it became an issue.
266 #if defined(__LP64__)
267 EXPECT_EQ(bytes, 78u);
268 #else
269 EXPECT_EQ(bytes, 70u);
270 #endif
271 });
272
273 a_binder->getInterfaceDescriptor();
274 a_binder->getInterfaceDescriptor();
275 a_binder->getInterfaceDescriptor();
276
277 EXPECT_EQ(mallocs, 1u);
278 }
279
TEST(BinderAllocation,SmallTransaction)280 TEST(BinderAllocation, SmallTransaction) {
281 String16 empty_descriptor = String16("");
282 sp<IServiceManager> manager = defaultServiceManager();
283
284 size_t mallocs = 0;
285 const auto on_malloc = OnMalloc([&](size_t bytes) {
286 mallocs++;
287 // Parcel should allocate a small amount by default
288 EXPECT_EQ(bytes, 128u);
289 });
290 manager->checkService(empty_descriptor);
291
292 EXPECT_EQ(mallocs, 1u);
293 }
294
TEST(BinderAccessorAllocation,AddAccessorCheckService)295 TEST(BinderAccessorAllocation, AddAccessorCheckService) {
296 // Need to call defaultServiceManager() before checking malloc because it
297 // will allocate an instance in the call_once
298 const auto sm = defaultServiceManager();
299 const std::string kInstanceName1 = "foo.bar.IFoo/default";
300 const std::string kInstanceName2 = "foo.bar.IFoo2/default";
301 const String16 kInstanceName16(kInstanceName1.c_str());
302 std::vector<size_t> expectedMallocs = {
303 // addAccessorProvider
304 112, // new AccessorProvider
305 16, // new AccessorProviderEntry
306 // checkService
307 45, // String8 from String16 in CppShim::checkService
308 128, // writeInterfaceToken
309 16, // getInjectedAccessor, new AccessorProviderEntry
310 66, // getInjectedAccessor, String16
311 45, // String8 from String16 in AccessorProvider::provide
312 };
313 std::set<std::string> supportedInstances = {kInstanceName1, kInstanceName2};
314 auto onMalloc = setExpectedMallocs(std::move(expectedMallocs));
315
316 auto receipt =
317 android::addAccessorProvider(std::move(supportedInstances),
318 [&](const String16&) -> sp<IBinder> { return nullptr; });
319 EXPECT_FALSE(receipt.expired());
320
321 sp<IBinder> binder = sm->checkService(kInstanceName16);
322
323 status_t status = android::removeAccessorProvider(receipt);
324 }
325
TEST(BinderAccessorAllocation,AddAccessorEmpty)326 TEST(BinderAccessorAllocation, AddAccessorEmpty) {
327 std::vector<size_t> expectedMallocs = {
328 48, // From ALOGE with empty set of instances
329 };
330 std::set<std::string> supportedInstances = {};
331 auto onMalloc = setExpectedMallocs(std::move(expectedMallocs));
332
333 auto receipt =
334 android::addAccessorProvider(std::move(supportedInstances),
335 [&](const String16&) -> sp<IBinder> { return nullptr; });
336
337 EXPECT_TRUE(receipt.expired());
338 }
339
TEST(RpcBinderAllocation,SetupRpcServer)340 TEST(RpcBinderAllocation, SetupRpcServer) {
341 std::string tmp = getenv("TMPDIR") ?: "/tmp";
342 std::string addr = tmp + "/binderRpcBenchmark";
343 (void)unlink(addr.c_str());
344 auto server = RpcServer::make();
345 server->setRootObject(sp<BBinder>::make());
346
347 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
348
349 std::thread([server]() { server->join(); }).detach();
350
351 auto session = RpcSession::make();
352 status_t status = session->setupUnixDomainClient(addr.c_str());
353 ASSERT_EQ(status, OK) << "Could not connect: " << addr << ": " << statusToString(status).c_str();
354
355 auto remoteBinder = session->getRootObject();
356 ASSERT_NE(remoteBinder, nullptr);
357
358 size_t mallocs = 0, totalBytes = 0;
359 {
360 const auto on_malloc = OnMalloc([&](size_t bytes) {
361 mallocs++;
362 totalBytes += bytes;
363 });
364 ASSERT_EQ(OK, remoteBinder->pingBinder());
365 }
366 EXPECT_EQ(mallocs, 1u);
367 EXPECT_EQ(totalBytes, 40u);
368 }
369
main(int argc,char ** argv)370 int main(int argc, char** argv) {
371 LOG(INFO) << "Priming static log variables for binderAllocationLimits.";
372 if (getenv("LIBC_HOOKS_ENABLE") == nullptr) {
373 CHECK(0 == setenv("LIBC_HOOKS_ENABLE", "1", true /*overwrite*/));
374 execv(argv[0], argv);
375 return 1;
376 }
377 ::testing::InitGoogleTest(&argc, argv);
378
379 // if tracing is enabled, take in one-time cost
380 (void)ATRACE_INIT();
381 (void)ATRACE_GET_ENABLED_TAGS();
382
383 return RUN_ALL_TESTS();
384 }
385