• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.h>
26 #include <utils/CallStack.h>
27 
28 #include <malloc.h>
29 #include <functional>
30 #include <vector>
31 
32 using namespace android::binder::impl;
33 
34 static android::String8 gEmpty(""); // make sure first allocation from optimization runs
35 
36 struct DestructionAction {
DestructionActionDestructionAction37     DestructionAction(std::function<void()> f) : mF(std::move(f)) {}
~DestructionActionDestructionAction38     ~DestructionAction() { mF(); };
39 private:
40     std::function<void()> mF;
41 };
42 
43 // Group of hooks
44 struct MallocHooks {
45     decltype(__malloc_hook) malloc_hook;
46     decltype(__realloc_hook) realloc_hook;
47 
saveMallocHooks48     static MallocHooks save() {
49         return {
50             .malloc_hook = __malloc_hook,
51             .realloc_hook = __realloc_hook,
52         };
53     }
54 
overwriteMallocHooks55     void overwrite() const {
56         __malloc_hook = malloc_hook;
57         __realloc_hook = realloc_hook;
58     }
59 };
60 
61 static const MallocHooks orig_malloc_hooks = MallocHooks::save();
62 
63 // When malloc is hit, executes lambda.
64 namespace 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 
lambda_malloc_hook(size_t bytes,const void * arg)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 
lambda_realloc_hook(void * ptr,size_t bytes,const void * arg)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))
OnMalloc(LambdaHooks::AllocationHook f)99 DestructionAction 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
110 const void* imaginary_use;
111 
TEST(TestTheTest,OnMalloc)112 TEST(TestTheTest, OnMalloc) {
113     size_t mallocs = 0;
114     {
115         const auto on_malloc = OnMalloc([&](size_t bytes) {
116             mallocs++;
117             EXPECT_EQ(bytes, 40u);
118         });
119 
120         imaginary_use = new int[10];
121     }
122     EXPECT_EQ(mallocs, 1u);
123 }
124 
125 
126 __attribute__((warn_unused_result))
ScopeDisallowMalloc()127 DestructionAction 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 
136 using android::BBinder;
137 using android::defaultServiceManager;
138 using android::IBinder;
139 using android::IServiceManager;
140 using android::OK;
141 using android::Parcel;
142 using android::RpcServer;
143 using android::RpcSession;
144 using android::sp;
145 using android::status_t;
146 using android::statusToString;
147 using android::String16;
148 
GetRemoteBinder()149 static 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 
TEST(BinderAllocation,ParcelOnStack)159 TEST(BinderAllocation, ParcelOnStack) {
160     const auto m = ScopeDisallowMalloc();
161     Parcel p;
162     imaginary_use = p.data();
163 }
164 
TEST(BinderAllocation,GetServiceManager)165 TEST(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
TEST(BinderAllocation,PingTransaction)172 TEST(BinderAllocation, PingTransaction) {
173     sp<IBinder> a_binder = GetRemoteBinder();
174     const auto m = ScopeDisallowMalloc();
175     a_binder->pingBinder();
176 }
177 
TEST(BinderAllocation,MakeScopeGuard)178 TEST(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 
TEST(BinderAllocation,InterfaceDescriptorTransaction)190 TEST(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.
198 #if defined(__LP64__)
199         EXPECT_EQ(bytes, 78u);
200 #else
201         EXPECT_EQ(bytes, 70u);
202 #endif
203     });
204 
205     a_binder->getInterfaceDescriptor();
206     a_binder->getInterfaceDescriptor();
207     a_binder->getInterfaceDescriptor();
208 
209     EXPECT_EQ(mallocs, 1u);
210 }
211 
TEST(BinderAllocation,SmallTransaction)212 TEST(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
220         EXPECT_EQ(bytes, 128u);
221     });
222     manager->checkService(empty_descriptor);
223 
224     EXPECT_EQ(mallocs, 1u);
225 }
226 
TEST(RpcBinderAllocation,SetupRpcServer)227 TEST(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 
234     ASSERT_EQ(OK, server->setupUnixDomainServer(addr.c_str()));
235 
236     std::thread([server]() { server->join(); }).detach();
237 
238     auto session = RpcSession::make();
239     status_t status = session->setupUnixDomainClient(addr.c_str());
240     ASSERT_EQ(status, OK) << "Could not connect: " << addr << ": " << statusToString(status).c_str();
241 
242     auto remoteBinder = session->getRootObject();
243     ASSERT_NE(remoteBinder, nullptr);
244 
245     size_t mallocs = 0, totalBytes = 0;
246     {
247         const auto on_malloc = OnMalloc([&](size_t bytes) {
248             mallocs++;
249             totalBytes += bytes;
250         });
251         ASSERT_EQ(OK, remoteBinder->pingBinder());
252     }
253     EXPECT_EQ(mallocs, 1u);
254     EXPECT_EQ(totalBytes, 40u);
255 }
256 
main(int argc,char ** argv)257 int 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);
264 
265     // if tracing is enabled, take in one-time cost
266     (void)ATRACE_INIT();
267     (void)ATRACE_GET_ENABLED_TAGS();
268 
269     return RUN_ALL_TESTS();
270 }
271