1 /*
2  * Copyright (C) 2017 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 <hidladapter/HidlBinderAdapter.h>
18 
19 #include <android-base/logging.h>
20 #include <android-base/properties.h>
21 #include <android/hidl/base/1.0/IBase.h>
22 #include <android/hidl/manager/1.0/IServiceManager.h>
23 #include <hidl/HidlTransportSupport.h>
24 
25 #include <unistd.h>
26 #include <iostream>
27 #include <map>
28 #include <string>
29 
30 namespace android {
31 namespace hardware {
32 namespace details {
33 
34 using android::base::SetProperty;
35 using android::base::WaitForProperty;
36 
37 const static std::string kDeactivateProp = "test.hidl.adapters.deactivated";
38 
39 int usage(const std::string& me) {
40     std::cerr << "usage: " << me
41               << " [-p|P] [-n instance-name] interface-name instance-name number-of-threads."
42               << std::endl;
43     std::cerr << "    -p: stop based on property " << kDeactivateProp << "and reset it."
44               << std::endl;
45     std::cerr << "    -P: stop based on interface specific property " << kDeactivateProp
46               << ".<fq-name>.<instance-name>" << std::endl;
47     std::cerr
48         << "    -n instance-name: register as a different instance name (does not de-register)"
49         << std::endl;
50     return EINVAL;
51 }
52 
53 enum class StopMethod {
54     NONE,
55     ALL,
56     SPECIFIC,
57 };
58 
59 struct Args {
60     StopMethod stopMethod = StopMethod::NONE;
61     std::string interface;     // e.x. IFoo
62     std::string instanceName;  // e.x. default
63     int threadNumber;
64     std::string registerInstanceName;  // e.x. default
65 };
66 
67 bool processArguments(int argc, char** argv, Args* args) {
68     int c;
69     while ((c = getopt(argc, argv, "pPn:")) != -1) {
70         switch (c) {
71             case 'p': {
72                 args->stopMethod = StopMethod::ALL;
73                 break;
74             }
75             case 'P': {
76                 args->stopMethod = StopMethod::SPECIFIC;
77                 break;
78             }
79             case 'n': {
80                 args->registerInstanceName = optarg;
81                 break;
82             }
83             default: { return false; }
84         }
85     }
86 
87     argc -= optind;
88     argv += optind;
89 
90     if (argc != 3) {
91         std::cerr << "ERROR: requires exactly three positional arguments for "
92                      "interface, instance name, and number of threads, but "
93                   << argc << " provided." << std::endl;
94         return false;
95     }
96 
97     args->interface = argv[0];
98     args->instanceName = argv[1];
99     args->threadNumber = std::stoi(argv[2]);
100 
101     if (args->threadNumber <= 0) {
102         std::cerr << "ERROR: invalid thread number " << args->threadNumber
103                   << " must be a positive integer." << std::endl;
104         return false;
105     }
106 
107     if (args->registerInstanceName.empty()) {
108         args->registerInstanceName = args->instanceName;
109     }
110 
111     return true;
112 }
113 
114 // only applies for -p argument
115 void waitForAdaptersDeactivated(const std::string& property) {
116     using std::literals::chrono_literals::operator""s;
117 
118     while (!WaitForProperty(property, "true", 30s)) {
119         // Log this so that when using this option on testing devices, there is
120         // a clear indication if adapters are not properly stopped
121         LOG(WARNING) << "Adapter use in progress. Waiting for stop based on 'true' " << property;
122     }
123 
124     SetProperty(property, "false");
125 }
126 
127 int adapterMain(const std::string& package, int argc, char** argv,
128                 const AdaptersFactory& adapters) {
129     using android::hardware::configureRpcThreadpool;
130     using android::hidl::base::V1_0::IBase;
131     using android::hidl::manager::V1_0::IServiceManager;
132 
133     const std::string& me = argc > 0 ? argv[0] : "(error)";
134 
135     Args args;
136     if (!processArguments(argc, argv, &args)) {
137         return usage(me);
138     }
139 
140     std::string interfaceName = package + "::" + args.interface;
141 
142     auto it = adapters.find(interfaceName);
143     if (it == adapters.end()) {
144         std::cerr << "ERROR: could not resolve " << interfaceName << "." << std::endl;
145         return 1;
146     }
147 
148     std::cout << "Trying to adapt down " << interfaceName << "/" << args.instanceName << " to "
149               << args.registerInstanceName << std::endl;
150 
151     configureRpcThreadpool(args.threadNumber, false /* callerWillJoin */);
152 
153     sp<IServiceManager> manager = IServiceManager::getService();
154     if (manager == nullptr) {
155         std::cerr << "ERROR: could not retrieve service manager." << std::endl;
156         return 1;
157     }
158 
159     sp<IBase> implementation = manager->get(interfaceName, args.instanceName).withDefault(nullptr);
160     if (implementation == nullptr) {
161         std::cerr << "ERROR: could not retrieve desired implementation" << std::endl;
162         return 1;
163     }
164 
165     sp<IBase> adapter = it->second(implementation);
166     if (adapter == nullptr) {
167         std::cerr << "ERROR: could not create adapter." << std::endl;
168         return 1;
169     }
170 
171     bool replaced = manager->add(args.registerInstanceName, adapter).withDefault(false);
172     if (!replaced) {
173         std::cerr << "ERROR: could not register the service with the service manager." << std::endl;
174         return 1;
175     }
176 
177     switch (args.stopMethod) {
178         case StopMethod::NONE: {
179             std::cout << "Press any key to disassociate adapter." << std::endl;
180             getchar();
181             break;
182         };
183         case StopMethod::SPECIFIC: {
184             const std::string property =
185                 kDeactivateProp + "." + interfaceName + "." + args.registerInstanceName;
186             std::cout << "Set " << property << " to true to deactivate." << std::endl;
187             waitForAdaptersDeactivated(property);
188             break;
189         };
190         case StopMethod::ALL: {
191             std::cout << "Set " << kDeactivateProp << " to true to deactivate." << std::endl;
192             waitForAdaptersDeactivated(kDeactivateProp);
193             break;
194         };
195     }
196 
197     // automatically unregistered on process exit if it is a new instance name
198     if (args.registerInstanceName == args.instanceName) {
199         bool restored = manager->add(args.instanceName, implementation).withDefault(false);
200         if (!restored) {
201             std::cerr << "ERROR: could not re-register interface with the service manager."
202                       << std::endl;
203             return 1;
204         }
205     }
206 
207     std::cout << "Success." << std::endl;
208 
209     return 0;
210 }
211 
212 // If an interface is adapted to 1.0, it can then not be adapted to 1.1 in the same process.
213 // This poses a problem in the following scenario:
214 // auto interface = new V1_1::implementation::IFoo;
215 // hidlObject1_0->foo(interface) // adaptation set at 1.0
216 // hidlObject1_1->bar(interface) // adaptation still is 1.0
217 // This could be solved by keeping a map of IBase,fqName -> IBase, but then you end up
218 // with multiple names for the same interface.
219 sp<IBase> adaptWithDefault(const sp<IBase>& something,
220                            const std::function<sp<IBase>()>& makeDefault) {
221     static std::map<sp<IBase>, sp<IBase>> sAdapterMap;
222 
223     if (something == nullptr) {
224         return something;
225     }
226 
227     auto it = sAdapterMap.find(something);
228     if (it == sAdapterMap.end()) {
229         it = sAdapterMap.insert(it, {something, makeDefault()});
230     }
231 
232     return it->second;
233 }
234 
235 }  // namespace details
236 }  // namespace hardware
237 }  // namespace android
238