blob: b21010d49a25edf2420b25b53d003e4e98980a49 [file] [log] [blame]
Steven Moreland80e1e6d2019-06-21 12:35:59 -07001/*
2 * Copyright (C) 2019 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 "ServiceManager.h"
18
19#include <android-base/logging.h>
Jon Spivack0d844302019-07-22 18:40:34 -070020#include <android-base/properties.h>
Jon Spivack9f503a42019-10-22 16:49:19 -070021#include <binder/BpBinder.h>
22#include <binder/IPCThreadState.h>
23#include <binder/ProcessState.h>
Steven Moreland86a17f82019-09-10 10:18:00 -070024#include <binder/Stability.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070025#include <cutils/android_filesystem_config.h>
26#include <cutils/multiuser.h>
Jon Spivack0d844302019-07-22 18:40:34 -070027#include <thread>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070028
Steven Moreland86a17f82019-09-10 10:18:00 -070029#ifndef VENDORSERVICEMANAGER
30#include <vintf/VintfObject.h>
31#include <vintf/constants.h>
32#endif // !VENDORSERVICEMANAGER
33
Steven Moreland80e1e6d2019-06-21 12:35:59 -070034using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070035using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070036
37namespace android {
38
Steven Moreland86a17f82019-09-10 10:18:00 -070039#ifndef VENDORSERVICEMANAGER
Steven Moreland2e293aa2020-09-23 00:25:16 +000040struct ManifestWithDescription {
41 std::shared_ptr<const vintf::HalManifest> manifest;
42 const char* description;
43};
44// func true -> stop search and forEachManifest will return true
45static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
46 for (const ManifestWithDescription& mwd : {
47 ManifestWithDescription{ vintf::VintfObject::GetDeviceHalManifest(), "device" },
48 ManifestWithDescription{ vintf::VintfObject::GetFrameworkHalManifest(), "framework" },
49 }) {
50 if (mwd.manifest == nullptr) {
51 LOG(ERROR) << "NULL VINTF MANIFEST!: " << mwd.description;
52 // note, we explicitly do not retry here, so that we can detect VINTF
53 // or other bugs (b/151696835)
54 continue;
55 }
56 if (func(mwd)) return true;
57 }
58 return false;
59}
60
Steven Morelandb82b8f82019-10-28 10:52:34 -070061static bool isVintfDeclared(const std::string& name) {
Steven Moreland86a17f82019-09-10 10:18:00 -070062 size_t firstSlash = name.find('/');
63 size_t lastDot = name.rfind('.', firstSlash);
64 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
65 LOG(ERROR) << "VINTF HALs require names in the format type/instance (e.g. "
66 << "some.package.foo.IFoo/default) but got: " << name;
67 return false;
68 }
69 const std::string package = name.substr(0, lastDot);
70 const std::string iface = name.substr(lastDot+1, firstSlash-lastDot-1);
71 const std::string instance = name.substr(firstSlash+1);
72
Steven Moreland2e293aa2020-09-23 00:25:16 +000073 bool found = forEachManifest([&] (const ManifestWithDescription& mwd) {
Steven Moreland2edde8e2020-04-30 17:04:54 -070074 if (mwd.manifest->hasAidlInstance(package, iface, instance)) {
75 LOG(INFO) << "Found " << name << " in " << mwd.description << " VINTF manifest.";
Steven Moreland86a17f82019-09-10 10:18:00 -070076 return true;
77 }
Steven Moreland2e293aa2020-09-23 00:25:16 +000078 return false; // continue
79 });
80
81 if (!found) {
82 // Although it is tested, explicitly rebuilding qualified name, in case it
83 // becomes something unexpected.
84 LOG(ERROR) << "Could not find " << package << "." << iface << "/" << instance
85 << " in the VINTF manifest.";
Steven Moreland86a17f82019-09-10 10:18:00 -070086 }
Steven Moreland2edde8e2020-04-30 17:04:54 -070087
Steven Moreland2e293aa2020-09-23 00:25:16 +000088 return found;
89}
90
91static std::vector<std::string> getVintfInstances(const std::string& interface) {
92 size_t lastDot = interface.rfind('.');
93 if (lastDot == std::string::npos) {
94 LOG(ERROR) << "VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) but got: " << interface;
95 return {};
96 }
97 const std::string package = interface.substr(0, lastDot);
98 const std::string iface = interface.substr(lastDot+1);
99
100 std::vector<std::string> ret;
101 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
102 auto instances = mwd.manifest->getAidlInstances(package, iface);
103 ret.insert(ret.end(), instances.begin(), instances.end());
104 return false; // continue
105 });
106
107 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700108}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700109
110static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
111 if (!Stability::requiresVintfDeclaration(binder)) {
112 return true;
113 }
114
115 return isVintfDeclared(name);
116}
Steven Moreland86a17f82019-09-10 10:18:00 -0700117#endif // !VENDORSERVICEMANAGER
118
Steven Morelandd13f08b2019-11-18 14:23:09 -0800119ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700120// TODO(b/151696835): reenable performance hack when we solve bug, since with
121// this hack and other fixes, it is unlikely we will see even an ephemeral
122// failure when the manifest parse fails. The goal is that the manifest will
123// be read incorrectly and cause the process trying to register a HAL to
124// fail. If this is in fact an early boot kernel contention issue, then we
125// will get no failure, and by its absence, be signalled to invest more
126// effort in re-adding this performance hack.
127// #ifndef VENDORSERVICEMANAGER
128// // can process these at any times, don't want to delay first VINTF client
129// std::thread([] {
130// vintf::VintfObject::GetDeviceHalManifest();
131// vintf::VintfObject::GetFrameworkHalManifest();
132// }).detach();
133// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800134}
Steven Moreland130242d2019-08-26 17:41:32 -0700135ServiceManager::~ServiceManager() {
136 // this should only happen in tests
137
Jon Spivackf288b1d2019-12-19 17:15:51 -0800138 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700139 CHECK(!callbacks.empty()) << name;
140 for (const auto& callback : callbacks) {
141 CHECK(callback != nullptr) << name;
142 }
143 }
144
Steven Moreland130242d2019-08-26 17:41:32 -0700145 for (const auto& [name, service] : mNameToService) {
146 CHECK(service.binder != nullptr) << name;
147 }
148}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700149
150Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700151 *outBinder = tryGetService(name, true);
152 // returns ok regardless of result for legacy reasons
153 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700154}
155
156Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700157 *outBinder = tryGetService(name, false);
158 // returns ok regardless of result for legacy reasons
159 return Status::ok();
160}
161
162sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700163 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700164
Jon Spivack0d844302019-07-22 18:40:34 -0700165 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700166 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700167 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700168 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700169
Jon Spivack9f503a42019-10-22 16:49:19 -0700170 if (!service->allowIsolated) {
Jon Spivack0d844302019-07-22 18:40:34 -0700171 uid_t appid = multiuser_get_app_id(ctx.uid);
172 bool isIsolated = appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700173
Jon Spivack0d844302019-07-22 18:40:34 -0700174 if (isIsolated) {
175 return nullptr;
176 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700177 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700178 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700179 }
180
Steven Morelanda9fe4742019-07-18 14:45:20 -0700181 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700182 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700183 }
184
Jon Spivack0d844302019-07-22 18:40:34 -0700185 if (!out && startIfNotFound) {
186 tryStartService(name);
187 }
188
Jon Spivack9f503a42019-10-22 16:49:19 -0700189 if (out) {
190 // Setting this guarantee each time we hand out a binder ensures that the client-checking
191 // loop knows about the event even if the client immediately drops the service
192 service->guaranteeClient = true;
193 }
194
Jon Spivack0d844302019-07-22 18:40:34 -0700195 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700196}
197
Steven Moreland905e2e82019-07-17 11:05:45 -0700198bool isValidServiceName(const std::string& name) {
199 if (name.size() == 0) return false;
200 if (name.size() > 127) return false;
201
202 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700203 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700204 if (c >= 'a' && c <= 'z') continue;
205 if (c >= 'A' && c <= 'Z') continue;
206 if (c >= '0' && c <= '9') continue;
207 return false;
208 }
209
210 return true;
211}
212
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700213Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700214 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700215
216 // apps cannot add services
217 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
218 return Status::fromExceptionCode(Status::EX_SECURITY);
219 }
220
Steven Morelanda9fe4742019-07-18 14:45:20 -0700221 if (!mAccess->canAdd(ctx, name)) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700222 return Status::fromExceptionCode(Status::EX_SECURITY);
223 }
224
225 if (binder == nullptr) {
226 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
227 }
228
Steven Moreland905e2e82019-07-17 11:05:45 -0700229 if (!isValidServiceName(name)) {
230 LOG(ERROR) << "Invalid service name: " << name;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700231 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
232 }
233
Steven Moreland86a17f82019-09-10 10:18:00 -0700234#ifndef VENDORSERVICEMANAGER
235 if (!meetsDeclarationRequirements(binder, name)) {
236 // already logged
237 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
238 }
239#endif // !VENDORSERVICEMANAGER
240
Steven Moreland88860b02019-08-12 14:24:14 -0700241 // implicitly unlinked when the binder is removed
Steven Moreland46f380b2019-10-16 16:28:21 -0700242 if (binder->remoteBinder() != nullptr && binder->linkToDeath(this) != OK) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700243 LOG(ERROR) << "Could not linkToDeath when adding " << name;
244 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
245 }
246
Devin Moore05ffe522020-08-06 13:58:29 -0700247 // Overwrite the old service if it exists
248 mNameToService[name] = Service {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700249 .binder = binder,
250 .allowIsolated = allowIsolated,
251 .dumpPriority = dumpPriority,
Jon Spivack9f503a42019-10-22 16:49:19 -0700252 .debugPid = ctx.debugPid,
Devin Moore05ffe522020-08-06 13:58:29 -0700253 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700254
Jon Spivackf288b1d2019-12-19 17:15:51 -0800255 auto it = mNameToRegistrationCallback.find(name);
256 if (it != mNameToRegistrationCallback.end()) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700257 for (const sp<IServiceCallback>& cb : it->second) {
Devin Moore05ffe522020-08-06 13:58:29 -0700258 mNameToService[name].guaranteeClient = true;
Steven Moreland27cfab02019-08-12 14:34:16 -0700259 // permission checked in registerForNotifications
260 cb->onRegistration(name, binder);
261 }
262 }
263
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700264 return Status::ok();
265}
266
267Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700268 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700269 return Status::fromExceptionCode(Status::EX_SECURITY);
270 }
271
272 size_t toReserve = 0;
273 for (auto const& [name, service] : mNameToService) {
274 (void) name;
275
276 if (service.dumpPriority & dumpPriority) ++toReserve;
277 }
278
279 CHECK(outList->empty());
280
281 outList->reserve(toReserve);
282 for (auto const& [name, service] : mNameToService) {
283 (void) service;
284
285 if (service.dumpPriority & dumpPriority) {
286 outList->push_back(name);
287 }
288 }
289
290 return Status::ok();
291}
292
Steven Moreland27cfab02019-08-12 14:34:16 -0700293Status ServiceManager::registerForNotifications(
294 const std::string& name, const sp<IServiceCallback>& callback) {
295 auto ctx = mAccess->getCallingContext();
296
297 if (!mAccess->canFind(ctx, name)) {
298 return Status::fromExceptionCode(Status::EX_SECURITY);
299 }
300
301 if (!isValidServiceName(name)) {
302 LOG(ERROR) << "Invalid service name: " << name;
303 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
304 }
305
306 if (callback == nullptr) {
307 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
308 }
309
310 if (OK != IInterface::asBinder(callback)->linkToDeath(this)) {
311 LOG(ERROR) << "Could not linkToDeath when adding " << name;
312 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
313 }
314
Jon Spivackf288b1d2019-12-19 17:15:51 -0800315 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700316
317 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
318 const sp<IBinder>& binder = it->second.binder;
319
320 // never null if an entry exists
321 CHECK(binder != nullptr) << name;
322 callback->onRegistration(name, binder);
323 }
324
325 return Status::ok();
326}
327Status ServiceManager::unregisterForNotifications(
328 const std::string& name, const sp<IServiceCallback>& callback) {
329 auto ctx = mAccess->getCallingContext();
330
331 if (!mAccess->canFind(ctx, name)) {
332 return Status::fromExceptionCode(Status::EX_SECURITY);
333 }
334
335 bool found = false;
336
Jon Spivackf288b1d2019-12-19 17:15:51 -0800337 auto it = mNameToRegistrationCallback.find(name);
338 if (it != mNameToRegistrationCallback.end()) {
339 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700340 }
341
342 if (!found) {
343 LOG(ERROR) << "Trying to unregister callback, but none exists " << name;
344 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
345 }
346
347 return Status::ok();
348}
349
Steven Morelandb82b8f82019-10-28 10:52:34 -0700350Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
351 auto ctx = mAccess->getCallingContext();
352
353 if (!mAccess->canFind(ctx, name)) {
354 return Status::fromExceptionCode(Status::EX_SECURITY);
355 }
356
357 *outReturn = false;
358
359#ifndef VENDORSERVICEMANAGER
360 *outReturn = isVintfDeclared(name);
361#endif
362 return Status::ok();
363}
364
Steven Moreland2e293aa2020-09-23 00:25:16 +0000365binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
366 auto ctx = mAccess->getCallingContext();
367
368 std::vector<std::string> allInstances;
369#ifndef VENDORSERVICEMANAGER
370 allInstances = getVintfInstances(interface);
371#endif
372
373 outReturn->clear();
374
375 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000376 if (mAccess->canFind(ctx, interface + "/" + instance)) {
377 outReturn->push_back(instance);
378 }
379 }
380
381 if (outReturn->size() == 0 && allInstances.size() != 0) {
382 return Status::fromExceptionCode(Status::EX_SECURITY);
383 }
384
385 return Status::ok();
386}
387
Jon Spivackf288b1d2019-12-19 17:15:51 -0800388void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
389 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700390 bool* found) {
391 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
392
393 for (auto lit = listeners.begin(); lit != listeners.end();) {
394 if (IInterface::asBinder(*lit) == who) {
395 if(found) *found = true;
396 lit = listeners.erase(lit);
397 } else {
398 ++lit;
399 }
400 }
401
402 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800403 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700404 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800405 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700406 }
407}
408
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700409void ServiceManager::binderDied(const wp<IBinder>& who) {
410 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
411 if (who == it->second.binder) {
412 it = mNameToService.erase(it);
413 } else {
414 ++it;
415 }
416 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700417
Jon Spivackf288b1d2019-12-19 17:15:51 -0800418 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
419 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700420 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700421
422 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
423 removeClientCallback(who, &it);
424 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700425}
426
Jon Spivack0d844302019-07-22 18:40:34 -0700427void ServiceManager::tryStartService(const std::string& name) {
428 ALOGI("Since '%s' could not be found, trying to start it as a lazy AIDL service",
429 name.c_str());
430
431 std::thread([=] {
432 (void)base::SetProperty("ctl.interface_start", "aidl/" + name);
433 }).detach();
434}
435
Jon Spivack9f503a42019-10-22 16:49:19 -0700436Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
437 const sp<IClientCallback>& cb) {
438 if (cb == nullptr) {
439 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
440 }
441
442 auto ctx = mAccess->getCallingContext();
443 if (!mAccess->canAdd(ctx, name)) {
444 return Status::fromExceptionCode(Status::EX_SECURITY);
445 }
446
447 auto serviceIt = mNameToService.find(name);
448 if (serviceIt == mNameToService.end()) {
449 LOG(ERROR) << "Could not add callback for nonexistent service: " << name;
450 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
451 }
452
453 if (serviceIt->second.debugPid != IPCThreadState::self()->getCallingPid()) {
454 LOG(WARNING) << "Only a server can register for client callbacks (for " << name << ")";
455 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
456 }
457
458 if (serviceIt->second.binder != service) {
459 LOG(WARNING) << "Tried to register client callback for " << name
460 << " but a different service is registered under this name.";
461 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
462 }
463
464 if (OK != IInterface::asBinder(cb)->linkToDeath(this)) {
465 LOG(ERROR) << "Could not linkToDeath when adding client callback for " << name;
466 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
467 }
468
469 mNameToClientCallback[name].push_back(cb);
470
471 return Status::ok();
472}
473
474void ServiceManager::removeClientCallback(const wp<IBinder>& who,
475 ClientCallbackMap::iterator* it) {
476 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
477
478 for (auto lit = listeners.begin(); lit != listeners.end();) {
479 if (IInterface::asBinder(*lit) == who) {
480 lit = listeners.erase(lit);
481 } else {
482 ++lit;
483 }
484 }
485
486 if (listeners.empty()) {
487 *it = mNameToClientCallback.erase(*it);
488 } else {
489 (*it)++;
490 }
491}
492
493ssize_t ServiceManager::Service::getNodeStrongRefCount() {
494 sp<BpBinder> bpBinder = binder->remoteBinder();
495 if (bpBinder == nullptr) return -1;
496
Steven Morelande8393882020-12-18 02:27:20 +0000497 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700498}
499
500void ServiceManager::handleClientCallbacks() {
501 for (const auto& [name, service] : mNameToService) {
Jon Spivackd9533c22020-01-27 22:19:22 +0000502 handleServiceClientCallback(name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700503 }
504}
505
Jon Spivackd9533c22020-01-27 22:19:22 +0000506ssize_t ServiceManager::handleServiceClientCallback(const std::string& serviceName,
507 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700508 auto serviceIt = mNameToService.find(serviceName);
509 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
510 return -1;
511 }
512
513 Service& service = serviceIt->second;
514 ssize_t count = service.getNodeStrongRefCount();
515
516 // binder driver doesn't support this feature
517 if (count == -1) return count;
518
519 bool hasClients = count > 1; // this process holds a strong count
520
521 if (service.guaranteeClient) {
522 // we have no record of this client
523 if (!service.hasClients && !hasClients) {
524 sendClientCallbackNotifications(serviceName, true);
525 }
526
527 // guarantee is temporary
528 service.guaranteeClient = false;
529 }
530
Jon Spivackd9533c22020-01-27 22:19:22 +0000531 // only send notifications if this was called via the interval checking workflow
532 if (isCalledOnInterval) {
533 if (hasClients && !service.hasClients) {
534 // client was retrieved in some other way
535 sendClientCallbackNotifications(serviceName, true);
536 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700537
Jon Spivackd9533c22020-01-27 22:19:22 +0000538 // there are no more clients, but the callback has not been called yet
539 if (!hasClients && service.hasClients) {
540 sendClientCallbackNotifications(serviceName, false);
541 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700542 }
543
544 return count;
545}
546
547void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName, bool hasClients) {
548 auto serviceIt = mNameToService.find(serviceName);
549 if (serviceIt == mNameToService.end()) {
550 LOG(WARNING) << "sendClientCallbackNotifications could not find service " << serviceName;
551 return;
552 }
553 Service& service = serviceIt->second;
554
555 CHECK(hasClients != service.hasClients) << "Record shows: " << service.hasClients
556 << " so we can't tell clients again that we have client: " << hasClients;
557
558 LOG(INFO) << "Notifying " << serviceName << " they have clients: " << hasClients;
559
560 auto ccIt = mNameToClientCallback.find(serviceName);
561 CHECK(ccIt != mNameToClientCallback.end())
562 << "sendClientCallbackNotifications could not find callbacks for service ";
563
564 for (const auto& callback : ccIt->second) {
565 callback->onClients(service.binder, hasClients);
566 }
567
568 service.hasClients = hasClients;
569}
570
571Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
572 if (binder == nullptr) {
573 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
574 }
575
576 auto ctx = mAccess->getCallingContext();
577 if (!mAccess->canAdd(ctx, name)) {
578 return Status::fromExceptionCode(Status::EX_SECURITY);
579 }
580
581 auto serviceIt = mNameToService.find(name);
582 if (serviceIt == mNameToService.end()) {
583 LOG(WARNING) << "Tried to unregister " << name
584 << ", but that service wasn't registered to begin with.";
585 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
586 }
587
588 if (serviceIt->second.debugPid != IPCThreadState::self()->getCallingPid()) {
589 LOG(WARNING) << "Only a server can unregister itself (for " << name << ")";
590 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
591 }
592
593 sp<IBinder> storedBinder = serviceIt->second.binder;
594
595 if (binder != storedBinder) {
596 LOG(WARNING) << "Tried to unregister " << name
597 << ", but a different service is registered under this name.";
598 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
599 }
600
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700601 if (serviceIt->second.guaranteeClient) {
602 LOG(INFO) << "Tried to unregister " << name << ", but there is about to be a client.";
603 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
604 }
605
Jon Spivackd9533c22020-01-27 22:19:22 +0000606 int clients = handleServiceClientCallback(name, false);
Jon Spivack9f503a42019-10-22 16:49:19 -0700607
608 // clients < 0: feature not implemented or other error. Assume clients.
609 // Otherwise:
610 // - kernel driver will hold onto one refcount (during this transaction)
611 // - servicemanager has a refcount (guaranteed by this transaction)
612 // So, if clients > 2, then at least one other service on the system must hold a refcount.
613 if (clients < 0 || clients > 2) {
614 // client callbacks are either disabled or there are other clients
Jon Spivackd9533c22020-01-27 22:19:22 +0000615 LOG(INFO) << "Tried to unregister " << name << ", but there are clients: " << clients;
Jon Spivack620d2dc2020-03-06 13:58:01 -0800616 // Set this flag to ensure the clients are acknowledged in the next callback
617 serviceIt->second.guaranteeClient = true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700618 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
619 }
620
621 mNameToService.erase(name);
622
623 return Status::ok();
624}
625
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700626} // namespace android