blob: 55a3916112faa5320e8cd4f81c72a710e140b563 [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
175TEST(BinderAllocation, SmallTransaction) {
176 String16 empty_descriptor = String16("");
177 sp<IServiceManager> manager = defaultServiceManager();
178
179 size_t mallocs = 0;
180 const auto on_malloc = OnMalloc([&](size_t bytes) {
181 mallocs++;
182 // Parcel should allocate a small amount by default
183 EXPECT_EQ(bytes, 128);
184 });
185 manager->checkService(empty_descriptor);
186
187 EXPECT_EQ(mallocs, 1);
188}
189
Devin Moore2a49be62022-05-26 22:04:21 +0000190TEST(RpcBinderAllocation, SetupRpcServer) {
191 std::string tmp = getenv("TMPDIR") ?: "/tmp";
192 std::string addr = tmp + "/binderRpcBenchmark";
193 (void)unlink(addr.c_str());
194 auto server = RpcServer::make();
195 server->setRootObject(sp<BBinder>::make());
196
197 CHECK_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
198
199 std::thread([server]() { server->join(); }).detach();
200
201 status_t status;
202 auto session = RpcSession::make();
203 status = session->setupUnixDomainClient(addr.c_str());
204 CHECK_EQ(status, OK) << "Could not connect: " << addr << ": " << statusToString(status).c_str();
205
206 auto remoteBinder = session->getRootObject();
207
208 size_t mallocs = 0, totalBytes = 0;
Frederick Mayle68aa3bc2022-06-07 15:51:31 +0000209 {
210 const auto on_malloc = OnMalloc([&](size_t bytes) {
211 mallocs++;
212 totalBytes += bytes;
213 });
214 CHECK_EQ(OK, remoteBinder->pingBinder());
215 }
Frederick Mayleb86cda42022-06-09 23:17:45 +0000216 EXPECT_EQ(mallocs, 1);
217 EXPECT_EQ(totalBytes, 40);
Devin Moore2a49be62022-05-26 22:04:21 +0000218}
219
Steven Moreland042ae822020-05-27 17:45:17 +0000220int main(int argc, char** argv) {
221 if (getenv("LIBC_HOOKS_ENABLE") == nullptr) {
222 CHECK(0 == setenv("LIBC_HOOKS_ENABLE", "1", true /*overwrite*/));
223 execv(argv[0], argv);
224 return 1;
225 }
226 ::testing::InitGoogleTest(&argc, argv);
Steven Moreland66acefe2022-09-09 00:34:40 +0000227
228 // if tracing is enabled, take in one-time cost
229 (void)ATRACE_INIT();
230 (void)ATRACE_GET_ENABLED_TAGS();
231
Steven Moreland042ae822020-05-27 17:45:17 +0000232 return RUN_ALL_TESTS();
233}