blob: 6712c9cecee7f87f4eb417d2c269ab6ea4a18765 [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>
Steven Moreland042ae822020-05-27 17:45:17 +000019#include <binder/IServiceManager.h>
Devin Moore2a49be62022-05-26 22:04:21 +000020#include <binder/Parcel.h>
21#include <binder/RpcServer.h>
22#include <binder/RpcSession.h>
Steven Moreland66acefe2022-09-09 00:34:40 +000023#include <cutils/trace.h>
Steven Moreland042ae822020-05-27 17:45:17 +000024#include <gtest/gtest.h>
25#include <utils/CallStack.h>
26
27#include <malloc.h>
28#include <functional>
29#include <vector>
30
Devin Moorea39f3db2022-08-15 23:28:55 +000031static android::String8 gEmpty(""); // make sure first allocation from optimization runs
32
Steven Moreland042ae822020-05-27 17:45:17 +000033struct DestructionAction {
34 DestructionAction(std::function<void()> f) : mF(std::move(f)) {}
35 ~DestructionAction() { mF(); };
36private:
37 std::function<void()> mF;
38};
39
40// Group of hooks
41struct MallocHooks {
42 decltype(__malloc_hook) malloc_hook;
43 decltype(__realloc_hook) realloc_hook;
44
45 static MallocHooks save() {
46 return {
47 .malloc_hook = __malloc_hook,
48 .realloc_hook = __realloc_hook,
49 };
50 }
51
52 void overwrite() const {
53 __malloc_hook = malloc_hook;
54 __realloc_hook = realloc_hook;
55 }
56};
57
58static const MallocHooks orig_malloc_hooks = MallocHooks::save();
59
60// When malloc is hit, executes lambda.
61namespace LambdaHooks {
62 using AllocationHook = std::function<void(size_t)>;
63 static std::vector<AllocationHook> lambdas = {};
64
65 static void* lambda_realloc_hook(void* ptr, size_t bytes, const void* arg);
66 static void* lambda_malloc_hook(size_t bytes, const void* arg);
67
68 static const MallocHooks lambda_malloc_hooks = {
69 .malloc_hook = lambda_malloc_hook,
70 .realloc_hook = lambda_realloc_hook,
71 };
72
73 static void* lambda_malloc_hook(size_t bytes, const void* arg) {
74 {
75 orig_malloc_hooks.overwrite();
76 lambdas.at(lambdas.size() - 1)(bytes);
77 lambda_malloc_hooks.overwrite();
78 }
79 return orig_malloc_hooks.malloc_hook(bytes, arg);
80 }
81
82 static void* lambda_realloc_hook(void* ptr, size_t bytes, const void* arg) {
83 {
84 orig_malloc_hooks.overwrite();
85 lambdas.at(lambdas.size() - 1)(bytes);
86 lambda_malloc_hooks.overwrite();
87 }
88 return orig_malloc_hooks.realloc_hook(ptr, bytes, arg);
89 }
90
91}
92
93// Action to execute when malloc is hit. Supports nesting. Malloc is not
94// restricted when the allocation hook is being processed.
95__attribute__((warn_unused_result))
96DestructionAction OnMalloc(LambdaHooks::AllocationHook f) {
97 MallocHooks before = MallocHooks::save();
98 LambdaHooks::lambdas.emplace_back(std::move(f));
99 LambdaHooks::lambda_malloc_hooks.overwrite();
100 return DestructionAction([before]() {
101 before.overwrite();
102 LambdaHooks::lambdas.pop_back();
103 });
104}
105
106// exported symbol, to force compiler not to optimize away pointers we set here
107const void* imaginary_use;
108
109TEST(TestTheTest, OnMalloc) {
110 size_t mallocs = 0;
111 {
112 const auto on_malloc = OnMalloc([&](size_t bytes) {
113 mallocs++;
114 EXPECT_EQ(bytes, 40);
115 });
116
117 imaginary_use = new int[10];
118 }
119 EXPECT_EQ(mallocs, 1);
120}
121
122
123__attribute__((warn_unused_result))
124DestructionAction ScopeDisallowMalloc() {
125 return OnMalloc([&](size_t bytes) {
126 ADD_FAILURE() << "Unexpected allocation: " << bytes;
127 using android::CallStack;
128 std::cout << CallStack::stackToString("UNEXPECTED ALLOCATION", CallStack::getCurrent(4 /*ignoreDepth*/).get())
129 << std::endl;
130 });
131}
132
Devin Moore2a49be62022-05-26 22:04:21 +0000133using android::BBinder;
Steven Moreland042ae822020-05-27 17:45:17 +0000134using android::defaultServiceManager;
Devin Moore2a49be62022-05-26 22:04:21 +0000135using android::IBinder;
Steven Moreland042ae822020-05-27 17:45:17 +0000136using android::IServiceManager;
Devin Moore2a49be62022-05-26 22:04:21 +0000137using android::OK;
138using android::Parcel;
139using android::RpcServer;
140using android::RpcSession;
141using android::sp;
142using android::status_t;
143using android::statusToString;
144using android::String16;
Steven Moreland042ae822020-05-27 17:45:17 +0000145
146static sp<IBinder> GetRemoteBinder() {
147 // This gets binder representing the service manager
148 // the current IServiceManager API doesn't expose the binder, and
149 // I want to avoid adding usages of the AIDL generated interface it
150 // is using underneath, so to avoid people copying it.
151 sp<IBinder> binder = defaultServiceManager()->checkService(String16("manager"));
152 EXPECT_NE(nullptr, binder);
153 return binder;
154}
155
156TEST(BinderAllocation, ParcelOnStack) {
157 const auto m = ScopeDisallowMalloc();
158 Parcel p;
159 imaginary_use = p.data();
160}
161
162TEST(BinderAllocation, GetServiceManager) {
163 defaultServiceManager(); // first call may alloc
164 const auto m = ScopeDisallowMalloc();
165 defaultServiceManager();
166}
167
168// note, ping does not include interface descriptor
169TEST(BinderAllocation, PingTransaction) {
170 sp<IBinder> a_binder = GetRemoteBinder();
171 const auto m = ScopeDisallowMalloc();
172 a_binder->pingBinder();
173}
174
Steven Morelandf2830fe2022-12-21 00:45:34 +0000175TEST(BinderAllocation, InterfaceDescriptorTransaction) {
176 sp<IBinder> a_binder = GetRemoteBinder();
177
178 size_t mallocs = 0;
179 const auto on_malloc = OnMalloc([&](size_t bytes) {
180 mallocs++;
181 // Happens to be SM package length. We could switch to forking
182 // and registering our own service if it became an issue.
Steven Moreland33813942023-01-05 17:43:01 +0000183#if defined(__LP64__)
Steven Morelandf2830fe2022-12-21 00:45:34 +0000184 EXPECT_EQ(bytes, 78);
Steven Moreland33813942023-01-05 17:43:01 +0000185#else
186 EXPECT_EQ(bytes, 70);
187#endif
Steven Morelandf2830fe2022-12-21 00:45:34 +0000188 });
189
190 a_binder->getInterfaceDescriptor();
191 a_binder->getInterfaceDescriptor();
192 a_binder->getInterfaceDescriptor();
193
194 EXPECT_EQ(mallocs, 1);
195}
196
Steven Moreland042ae822020-05-27 17:45:17 +0000197TEST(BinderAllocation, SmallTransaction) {
198 String16 empty_descriptor = String16("");
199 sp<IServiceManager> manager = defaultServiceManager();
200
201 size_t mallocs = 0;
202 const auto on_malloc = OnMalloc([&](size_t bytes) {
203 mallocs++;
204 // Parcel should allocate a small amount by default
205 EXPECT_EQ(bytes, 128);
206 });
207 manager->checkService(empty_descriptor);
208
209 EXPECT_EQ(mallocs, 1);
210}
211
Devin Moore2a49be62022-05-26 22:04:21 +0000212TEST(RpcBinderAllocation, SetupRpcServer) {
213 std::string tmp = getenv("TMPDIR") ?: "/tmp";
214 std::string addr = tmp + "/binderRpcBenchmark";
215 (void)unlink(addr.c_str());
216 auto server = RpcServer::make();
217 server->setRootObject(sp<BBinder>::make());
218
Steven Moreland3652ba02023-07-21 00:37:18 +0000219 ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
Devin Moore2a49be62022-05-26 22:04:21 +0000220
221 std::thread([server]() { server->join(); }).detach();
222
Devin Moore2a49be62022-05-26 22:04:21 +0000223 auto session = RpcSession::make();
Steven Moreland3652ba02023-07-21 00:37:18 +0000224 status_t status = session->setupUnixDomainClient(addr.c_str());
225 ASSERT_EQ(status, OK) << "Could not connect: " << addr << ": " << statusToString(status).c_str();
Devin Moore2a49be62022-05-26 22:04:21 +0000226
227 auto remoteBinder = session->getRootObject();
Steven Moreland3652ba02023-07-21 00:37:18 +0000228 ASSERT_NE(remoteBinder, nullptr);
Devin Moore2a49be62022-05-26 22:04:21 +0000229
230 size_t mallocs = 0, totalBytes = 0;
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000231 {
232 const auto on_malloc = OnMalloc([&](size_t bytes) {
233 mallocs++;
234 totalBytes += bytes;
235 });
Steven Moreland3652ba02023-07-21 00:37:18 +0000236 ASSERT_EQ(OK, remoteBinder->pingBinder());
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000237 }
Frederick Mayleb86cda42022-06-09 23:17:45 +0000238 EXPECT_EQ(mallocs, 1);
239 EXPECT_EQ(totalBytes, 40);
Devin Moore2a49be62022-05-26 22:04:21 +0000240}
241
Steven Moreland042ae822020-05-27 17:45:17 +0000242int main(int argc, char** argv) {
243 if (getenv("LIBC_HOOKS_ENABLE") == nullptr) {
244 CHECK(0 == setenv("LIBC_HOOKS_ENABLE", "1", true /*overwrite*/));
245 execv(argv[0], argv);
246 return 1;
247 }
248 ::testing::InitGoogleTest(&argc, argv);
Steven Moreland66acefe2022-09-09 00:34:40 +0000249
250 // if tracing is enabled, take in one-time cost
251 (void)ATRACE_INIT();
252 (void)ATRACE_GET_ENABLED_TAGS();
253
Steven Moreland042ae822020-05-27 17:45:17 +0000254 return RUN_ALL_TESTS();
255}