1 /*
2  * Copyright (C) 2021 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 <sys/eventfd.h>
18 
19 #include <binder/LazyServiceRegistrar.h>
20 #include "LazyTestServiceCb.h"
21 
22 namespace android {
23 namespace binder {
24 
setCustomActiveServicesCallback()25 void LazyTestServiceCb::setCustomActiveServicesCallback() {
26   auto lazyRegistrar = LazyServiceRegistrar::getInstance();
27   lazyRegistrar.setActiveServicesCallback([lazyRegistrar, this](bool hasClients) mutable -> bool {
28     if (hasClients) {
29       return false;
30     }
31 
32     if (mFd < 0) {
33       // Prevent shutdown (test will fail)
34       return true;
35     }
36 
37     // Unregister all services
38     if (!lazyRegistrar.tryUnregister()) {
39       // Prevent shutdown (test will fail)
40       return true;
41     }
42 
43     // Re-register all services
44     lazyRegistrar.reRegister();
45 
46     // Unregister again before shutdown
47     if (!lazyRegistrar.tryUnregister()) {
48       // Prevent shutdown (test will fail)
49       return true;
50     }
51 
52     // Tell the test we're shutting down
53     if (TEMP_FAILURE_RETRY(eventfd_write(mFd, /* value */ 1)) < 0) {
54       // Prevent shutdown (test will fail)
55       return true;
56     }
57 
58     exit(EXIT_SUCCESS);
59     // Unreachable
60   });
61 }
62 
setEventFd(const::android::os::ParcelFileDescriptor & parcelFd)63 Status LazyTestServiceCb::setEventFd(const ::android::os::ParcelFileDescriptor& parcelFd) {
64   mFd = dup(parcelFd.get());
65 
66   return mFd < 0 ? Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT) : Status::ok();
67 }
68 
69 }  // namespace binder
70 }  // namespace android
71