summaryrefslogtreecommitdiff
path: root/libs/binder/tests/binderCacheUnitTest.cpp
blob: 121e5ae5e9d244562d4d56bc7665105420a646d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
/*
 * Copyright (C) 2024 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <gtest/gtest.h>

#include <android-base/logging.h>
#include <android/os/IServiceManager.h>
#include <binder/IBinder.h>
#include <binder/IPCThreadState.h>
#include <binder/IServiceManager.h>
#include <binder/IServiceManagerUnitTestHelper.h>
#include "fakeservicemanager/FakeServiceManager.h"

#include <sys/prctl.h>
#include <thread>

using namespace android;

#ifdef LIBBINDER_CLIENT_CACHE
constexpr bool kUseLibbinderCache = true;
#else
constexpr bool kUseLibbinderCache = false;
#endif

#ifdef LIBBINDER_ADDSERVICE_CACHE
constexpr bool kUseCacheInAddService = true;
#else
constexpr bool kUseCacheInAddService = false;
#endif

#ifdef LIBBINDER_REMOVE_CACHE_STATIC_LIST
constexpr bool kRemoveStaticList = true;
#else
constexpr bool kRemoveStaticList = false;
#endif

// A service name which is in the static list of cachable services
const String16 kCachedServiceName = String16("isub");

#define EXPECT_OK(status)                 \
    do {                                  \
        binder::Status stat = (status);   \
        EXPECT_TRUE(stat.isOk()) << stat; \
    } while (false)

const String16 kServerName = String16("binderCacheUnitTest");

class FooBar : public BBinder {
public:
    status_t onTransact(uint32_t, const Parcel&, Parcel*, uint32_t) {
        // exit the server
        std::thread([] { exit(EXIT_FAILURE); }).detach();
        return OK;
    }
    void killServer(sp<IBinder> binder) {
        Parcel data, reply;
        binder->transact(0, data, &reply, 0);
    }
};

class MockAidlServiceManager : public os::IServiceManagerDefault {
public:
    MockAidlServiceManager() : innerSm() {}

    binder::Status checkService2(const ::std::string& name, os::Service* _out) override {
        os::ServiceWithMetadata serviceWithMetadata = os::ServiceWithMetadata();
        serviceWithMetadata.service = innerSm.getService(String16(name.c_str()));
        serviceWithMetadata.isLazyService = false;
        *_out = os::Service::make<os::Service::Tag::serviceWithMetadata>(serviceWithMetadata);
        return binder::Status::ok();
    }

    binder::Status addService(const std::string& name, const sp<IBinder>& service,
                              bool allowIsolated, int32_t dumpPriority) override {
        return binder::Status::fromStatusT(
                innerSm.addService(String16(name.c_str()), service, allowIsolated, dumpPriority));
    }

    void clearServices() { innerSm.clear(); }

    FakeServiceManager innerSm;
};

// Returns services with isLazyService flag as true.
class MockAidlServiceManager2 : public os::IServiceManagerDefault {
public:
    MockAidlServiceManager2() : innerSm() {}

    binder::Status checkService2(const ::std::string& name, os::Service* _out) override {
        os::ServiceWithMetadata serviceWithMetadata = os::ServiceWithMetadata();
        serviceWithMetadata.service = innerSm.getService(String16(name.c_str()));
        serviceWithMetadata.isLazyService = true;
        *_out = os::Service::make<os::Service::Tag::serviceWithMetadata>(serviceWithMetadata);
        return binder::Status::ok();
    }

    binder::Status addService(const std::string& name, const sp<IBinder>& service,
                              bool allowIsolated, int32_t dumpPriority) override {
        return binder::Status::fromStatusT(
                innerSm.addService(String16(name.c_str()), service, allowIsolated, dumpPriority));
    }

    void clearServices() { innerSm.clear(); }

    FakeServiceManager innerSm;
};

class LibbinderCacheRemoveStaticList : public ::testing::Test {
protected:
    void SetUp() override {
        fakeServiceManager = sp<MockAidlServiceManager2>::make();
        mServiceManager = getServiceManagerShimFromAidlServiceManagerForTests(fakeServiceManager);
        mServiceManager->enableAddServiceCache(true);
    }
    void TearDown() override {}

public:
    void cacheAddServiceAndConfirmCacheMiss(const sp<IBinder>& binder1) {
        // Add a service. This shouldn't cache it.
        EXPECT_EQ(OK,
                  mServiceManager->addService(kCachedServiceName, binder1,
                                              /*allowIsolated = */ false,
                                              android::os::IServiceManager::FLAG_IS_LAZY_SERVICE));
        // Try to populate cache. Cache shouldn't be updated.
        EXPECT_EQ(binder1, mServiceManager->checkService(kCachedServiceName));
        fakeServiceManager->clearServices();
        EXPECT_EQ(nullptr, mServiceManager->checkService(kCachedServiceName));
    }

    sp<MockAidlServiceManager2> fakeServiceManager;
    sp<android::IServiceManager> mServiceManager;
};

TEST_F(LibbinderCacheRemoveStaticList, AddLocalServiceAndConfirmCacheMiss) {
    if (!kRemoveStaticList) {
        GTEST_SKIP() << "Skipping as feature is not enabled";
        return;
    }
    sp<IBinder> binder1 = sp<BBinder>::make();
    cacheAddServiceAndConfirmCacheMiss(binder1);
}

TEST_F(LibbinderCacheRemoveStaticList, AddRemoteServiceAndConfirmCacheMiss) {
    if (!kRemoveStaticList) {
        GTEST_SKIP() << "Skipping as feature is not enabled";
        return;
    }
    sp<IBinder> binder1 = defaultServiceManager()->checkService(kServerName);
    ASSERT_NE(binder1, nullptr);
    cacheAddServiceAndConfirmCacheMiss(binder1);
}

class LibbinderCacheAddServiceTest : public ::testing::Test {
protected:
    void SetUp() override {
        fakeServiceManager = sp<MockAidlServiceManager>::make();
        mServiceManager = getServiceManagerShimFromAidlServiceManagerForTests(fakeServiceManager);
        mServiceManager->enableAddServiceCache(true);
    }

    void TearDown() override {}

public:
    void cacheAddServiceAndConfirmCacheHit(const sp<IBinder>& binder1) {
        // Add a service. This also caches it.
        EXPECT_EQ(OK, mServiceManager->addService(kCachedServiceName, binder1));
        // remove services from fakeservicemanager
        fakeServiceManager->clearServices();

        sp<IBinder> result = mServiceManager->checkService(kCachedServiceName);
        if (kUseCacheInAddService && kUseLibbinderCache) {
            // If cache is enabled, we should get the binder.
            EXPECT_EQ(binder1, result);
        } else {
            // If cache is disabled, then we should get the null binder
            EXPECT_EQ(nullptr, result);
        }
    }
    sp<MockAidlServiceManager> fakeServiceManager;
    sp<android::IServiceManager> mServiceManager;
};

TEST_F(LibbinderCacheAddServiceTest, AddLocalServiceAndConfirmCacheHit) {
    sp<IBinder> binder1 = sp<BBinder>::make();
    cacheAddServiceAndConfirmCacheHit(binder1);
}

TEST_F(LibbinderCacheAddServiceTest, AddRemoteServiceAndConfirmCacheHit) {
    sp<IBinder> binder1 = defaultServiceManager()->checkService(kServerName);
    ASSERT_NE(binder1, nullptr);
    cacheAddServiceAndConfirmCacheHit(binder1);
}

class LibbinderCacheTest : public ::testing::Test {
protected:
    void SetUp() override {
        fakeServiceManager = sp<MockAidlServiceManager>::make();
        mServiceManager = getServiceManagerShimFromAidlServiceManagerForTests(fakeServiceManager);
        mServiceManager->enableAddServiceCache(false);
    }

    void TearDown() override {}

public:
    void cacheAndConfirmCacheHit(const sp<IBinder>& binder1, const sp<IBinder>& binder2) {
        // Add a service
        EXPECT_EQ(OK, mServiceManager->addService(kCachedServiceName, binder1));
        // Get the service. This caches it.
        sp<IBinder> result = mServiceManager->checkService(kCachedServiceName);
        ASSERT_EQ(binder1, result);

        // Add the different binder and replace the service.
        // The cache should still hold the original binder.
        EXPECT_EQ(OK, mServiceManager->addService(kCachedServiceName, binder2));

        result = mServiceManager->checkService(kCachedServiceName);
        if (kUseLibbinderCache) {
            // If cache is enabled, we should get the binder to Service Manager.
            EXPECT_EQ(binder1, result);
        } else {
            // If cache is disabled, then we should get the newer binder
            EXPECT_EQ(binder2, result);
        }
    }

    sp<MockAidlServiceManager> fakeServiceManager;
    sp<android::IServiceManager> mServiceManager;
};

TEST_F(LibbinderCacheTest, AddLocalServiceAndConfirmCacheHit) {
    sp<IBinder> binder1 = sp<BBinder>::make();
    sp<IBinder> binder2 = sp<BBinder>::make();

    cacheAndConfirmCacheHit(binder1, binder2);
}

TEST_F(LibbinderCacheTest, AddRemoteServiceAndConfirmCacheHit) {
    sp<IBinder> binder1 = defaultServiceManager()->checkService(kServerName);
    ASSERT_NE(binder1, nullptr);
    sp<IBinder> binder2 = IInterface::asBinder(mServiceManager);

    cacheAndConfirmCacheHit(binder1, binder2);
}

TEST_F(LibbinderCacheTest, RemoveFromCacheOnServerDeath) {
    sp<IBinder> binder1 = defaultServiceManager()->checkService(kServerName);
    FooBar foo = FooBar();

    EXPECT_EQ(OK, mServiceManager->addService(kCachedServiceName, binder1));

    // Check Service, this caches the binder
    sp<IBinder> result = mServiceManager->checkService(kCachedServiceName);
    ASSERT_EQ(binder1, result);

    // Kill the server, this should remove from cache.
    pid_t pid;
    ASSERT_EQ(OK, binder1->getDebugPid(&pid));
    foo.killServer(binder1);
    system(("kill -9 " + std::to_string(pid)).c_str());

    sp<IBinder> binder2 = sp<BBinder>::make();

    // Add new service with the same name.
    // This will replace the service in FakeServiceManager.
    EXPECT_EQ(OK, mServiceManager->addService(kCachedServiceName, binder2));

    // Confirm that new service is returned instead of old.
    int retry_count = 20;
    sp<IBinder> result2;
    do {
        std::this_thread::sleep_for(std::chrono::milliseconds(50));
        if (retry_count-- == 0) {
            break;
        }
        result2 = mServiceManager->checkService(kCachedServiceName);
    } while (result2 != binder2);

    ASSERT_EQ(binder2, result2);
}

TEST_F(LibbinderCacheTest, NullBinderNotCached) {
    sp<IBinder> binder1 = nullptr;
    sp<IBinder> binder2 = sp<BBinder>::make();

    // Check for a cacheble service which isn't registered.
    // FakeServiceManager should return nullptr.
    // This shouldn't be cached.
    sp<IBinder> result = mServiceManager->checkService(kCachedServiceName);
    ASSERT_EQ(binder1, result);

    // Add the same service
    EXPECT_EQ(OK, mServiceManager->addService(kCachedServiceName, binder2));

    // This should return the newly added service.
    result = mServiceManager->checkService(kCachedServiceName);
    EXPECT_EQ(binder2, result);
}

// TODO(b/333854840): Remove this test removing the static list
TEST_F(LibbinderCacheTest, DoNotCacheServiceNotInList) {
    if (kRemoveStaticList) {
        GTEST_SKIP() << "Skipping test as static list is disabled";
        return;
    }

    sp<IBinder> binder1 = sp<BBinder>::make();
    sp<IBinder> binder2 = sp<BBinder>::make();
    String16 serviceName = String16("NewLibbinderCacheTest");
    // Add a service
    EXPECT_EQ(OK, mServiceManager->addService(serviceName, binder1));
    // Get the service. This shouldn't caches it.
    sp<IBinder> result = mServiceManager->checkService(serviceName);
    ASSERT_EQ(binder1, result);

    // Add the different binder and replace the service.
    EXPECT_EQ(OK, mServiceManager->addService(serviceName, binder2));

    // Confirm that we get the new service
    result = mServiceManager->checkService(serviceName);
    EXPECT_EQ(binder2, result);
}

int main(int argc, char** argv) {
    ::testing::InitGoogleTest(&argc, argv);

    if (fork() == 0) {
        prctl(PR_SET_PDEATHSIG, SIGHUP);

        // Start a FooBar service and add it to the servicemanager.
        sp<IBinder> server = new FooBar();
        defaultServiceManager()->addService(kServerName, server);

        IPCThreadState::self()->joinThreadPool(true);
        exit(1); // should not reach
    }

    status_t err = ProcessState::self()->setThreadPoolMaxThreadCount(3);
    ProcessState::self()->startThreadPool();
    CHECK_EQ(ProcessState::self()->isThreadPoolStarted(), true);
    CHECK_GT(ProcessState::self()->getThreadPoolMaxTotalThreadCount(), 0);

    auto binder = defaultServiceManager()->waitForService(kServerName);
    CHECK_NE(nullptr, binder.get());
    return RUN_ALL_TESTS();
}