blob: a4018385c794cdeb09f7daf6d2747f686ac25c99 [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>
Devin Moore42407bc2023-09-26 21:30:39 +000021#include <android-base/strings.h>
Jon Spivack9f503a42019-10-22 16:49:19 -070022#include <binder/BpBinder.h>
23#include <binder/IPCThreadState.h>
24#include <binder/ProcessState.h>
Steven Moreland86a17f82019-09-10 10:18:00 -070025#include <binder/Stability.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070026#include <cutils/android_filesystem_config.h>
27#include <cutils/multiuser.h>
Jon Spivack0d844302019-07-22 18:40:34 -070028#include <thread>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070029
Steven Moreland86a17f82019-09-10 10:18:00 -070030#ifndef VENDORSERVICEMANAGER
31#include <vintf/VintfObject.h>
Yifan Hong0a9b56e2021-11-30 16:45:40 -080032#ifdef __ANDROID_RECOVERY__
33#include <vintf/VintfObjectRecovery.h>
34#endif // __ANDROID_RECOVERY__
Steven Moreland86a17f82019-09-10 10:18:00 -070035#include <vintf/constants.h>
36#endif // !VENDORSERVICEMANAGER
37
Steven Moreland80e1e6d2019-06-21 12:35:59 -070038using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070039using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070040
41namespace android {
42
Steven Morelandb9e1cbe2023-02-01 22:44:45 +000043bool is_multiuser_uid_isolated(uid_t uid) {
44 uid_t appid = multiuser_get_app_id(uid);
45 return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
46}
47
Steven Moreland86a17f82019-09-10 10:18:00 -070048#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080049
Steven Moreland2e293aa2020-09-23 00:25:16 +000050struct ManifestWithDescription {
51 std::shared_ptr<const vintf::HalManifest> manifest;
52 const char* description;
53};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080054static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
55#ifdef __ANDROID_RECOVERY__
56 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
57 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000058 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080059 return {};
60 }
61 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
62#else
63 auto vintfObject = vintf::VintfObject::GetInstance();
64 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000065 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080066 return {};
67 }
68 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
69 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
70#endif
71}
72
Steven Moreland2e293aa2020-09-23 00:25:16 +000073// func true -> stop search and forEachManifest will return true
74static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080075 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000076 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000077 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
78 // note, we explicitly do not retry here, so that we can detect VINTF
79 // or other bugs (b/151696835)
80 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +000081 }
82 if (func(mwd)) return true;
83 }
84 return false;
85}
86
Steven Morelandedd4e072021-04-21 00:27:29 +000087struct AidlName {
88 std::string package;
89 std::string iface;
90 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070091
Steven Morelandedd4e072021-04-21 00:27:29 +000092 static bool fill(const std::string& name, AidlName* aname) {
93 size_t firstSlash = name.find('/');
94 size_t lastDot = name.rfind('.', firstSlash);
95 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +000096 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
97 "some.package.foo.IFoo/default) but got: %s",
98 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +000099 return false;
100 }
101 aname->package = name.substr(0, lastDot);
102 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
103 aname->instance = name.substr(firstSlash + 1);
104 return true;
105 }
106};
107
108static bool isVintfDeclared(const std::string& name) {
109 AidlName aname;
110 if (!AidlName::fill(name, &aname)) return false;
111
112 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
113 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000114 ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000115 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700116 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000117 return false; // continue
118 });
119
120 if (!found) {
Devin Moore42407bc2023-09-26 21:30:39 +0000121 std::set<std::string> instances;
122 forEachManifest([&](const ManifestWithDescription& mwd) {
123 std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
124 instances.insert(res.begin(), res.end());
125 return true;
126 });
127
128 std::string available;
129 if (instances.empty()) {
130 available = "No alternative instances declared in VINTF";
131 } else {
132 // for logging only. We can't return this information to the client
133 // because they may not have permissions to find or list those
134 // instances
135 available = "VINTF declared instances: " + base::Join(instances, ", ");
136 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000137 // Although it is tested, explicitly rebuilding qualified name, in case it
138 // becomes something unexpected.
Devin Moore42407bc2023-09-26 21:30:39 +0000139 ALOGI("Could not find %s.%s/%s in the VINTF manifest. %s.", aname.package.c_str(),
140 aname.iface.c_str(), aname.instance.c_str(), available.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700141 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700142
Steven Moreland2e293aa2020-09-23 00:25:16 +0000143 return found;
144}
145
Steven Morelandedd4e072021-04-21 00:27:29 +0000146static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
147 AidlName aname;
148 if (!AidlName::fill(name, &aname)) return std::nullopt;
149
150 std::optional<std::string> updatableViaApex;
151
152 forEachManifest([&](const ManifestWithDescription& mwd) {
153 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
154 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
155 if (manifestInstance.package() != aname.package) return true;
156 if (manifestInstance.interface() != aname.iface) return true;
157 if (manifestInstance.instance() != aname.instance) return true;
158 updatableViaApex = manifestInstance.updatableViaApex();
159 return false; // break (libvintf uses opposite convention)
160 });
Jooyung Hance94b752022-11-14 18:55:06 +0900161 if (updatableViaApex.has_value()) return true; // break (found match)
Steven Morelandedd4e072021-04-21 00:27:29 +0000162 return false; // continue
163 });
164
165 return updatableViaApex;
166}
167
Jooyung Han76944fe2022-10-25 17:02:45 +0900168static std::vector<std::string> getVintfUpdatableInstances(const std::string& apexName) {
169 std::vector<std::string> instances;
170
171 forEachManifest([&](const ManifestWithDescription& mwd) {
172 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
173 if (manifestInstance.format() == vintf::HalFormat::AIDL &&
174 manifestInstance.updatableViaApex().has_value() &&
175 manifestInstance.updatableViaApex().value() == apexName) {
176 std::string aname = manifestInstance.package() + "." +
177 manifestInstance.interface() + "/" + manifestInstance.instance();
178 instances.push_back(aname);
179 }
Jooyung Hance94b752022-11-14 18:55:06 +0900180 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900181 });
182 return false; // continue
183 });
184
185 return instances;
186}
187
Devin Moore5e4c2f12021-09-09 22:36:33 +0000188static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
189 AidlName aname;
190 if (!AidlName::fill(name, &aname)) return std::nullopt;
191
192 std::optional<std::string> ip;
193 std::optional<uint64_t> port;
194 forEachManifest([&](const ManifestWithDescription& mwd) {
195 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
196 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
197 if (manifestInstance.package() != aname.package) return true;
198 if (manifestInstance.interface() != aname.iface) return true;
199 if (manifestInstance.instance() != aname.instance) return true;
200 ip = manifestInstance.ip();
201 port = manifestInstance.port();
202 return false; // break (libvintf uses opposite convention)
203 });
204 return false; // continue
205 });
206
207 if (ip.has_value() && port.has_value()) {
208 ConnectionInfo info;
209 info.ipAddress = *ip;
210 info.port = *port;
211 return std::make_optional<ConnectionInfo>(info);
212 } else {
213 return std::nullopt;
214 }
215}
216
Steven Moreland2e293aa2020-09-23 00:25:16 +0000217static std::vector<std::string> getVintfInstances(const std::string& interface) {
218 size_t lastDot = interface.rfind('.');
219 if (lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000220 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
221 "but got: %s",
222 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000223 return {};
224 }
225 const std::string package = interface.substr(0, lastDot);
226 const std::string iface = interface.substr(lastDot+1);
227
228 std::vector<std::string> ret;
229 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
230 auto instances = mwd.manifest->getAidlInstances(package, iface);
231 ret.insert(ret.end(), instances.begin(), instances.end());
232 return false; // continue
233 });
234
235 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700236}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700237
238static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
239 if (!Stability::requiresVintfDeclaration(binder)) {
240 return true;
241 }
242
243 return isVintfDeclared(name);
244}
Steven Moreland86a17f82019-09-10 10:18:00 -0700245#endif // !VENDORSERVICEMANAGER
246
Steven Morelandb8361902023-02-01 23:18:04 +0000247ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000248 if (hasClients) {
249 // only expected to happen on process death, we don't store the service
250 // name this late (it's in the map that holds this service), but if it
251 // is happening, we might want to change 'unlinkToDeath' to explicitly
252 // clear this bit so that we can abort in other cases, where it would
253 // mean inconsistent logic in servicemanager (unexpected and tested, but
254 // the original lazy service impl here had that bug).
Steven Morelandb8361902023-02-01 23:18:04 +0000255 LOG(WARNING) << "a service was removed when there are clients";
256 }
257}
258
Steven Morelandd13f08b2019-11-18 14:23:09 -0800259ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700260// TODO(b/151696835): reenable performance hack when we solve bug, since with
261// this hack and other fixes, it is unlikely we will see even an ephemeral
262// failure when the manifest parse fails. The goal is that the manifest will
263// be read incorrectly and cause the process trying to register a HAL to
264// fail. If this is in fact an early boot kernel contention issue, then we
265// will get no failure, and by its absence, be signalled to invest more
266// effort in re-adding this performance hack.
267// #ifndef VENDORSERVICEMANAGER
268// // can process these at any times, don't want to delay first VINTF client
269// std::thread([] {
270// vintf::VintfObject::GetDeviceHalManifest();
271// vintf::VintfObject::GetFrameworkHalManifest();
272// }).detach();
273// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800274}
Steven Moreland130242d2019-08-26 17:41:32 -0700275ServiceManager::~ServiceManager() {
276 // this should only happen in tests
277
Jon Spivackf288b1d2019-12-19 17:15:51 -0800278 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700279 CHECK(!callbacks.empty()) << name;
280 for (const auto& callback : callbacks) {
281 CHECK(callback != nullptr) << name;
282 }
283 }
284
Steven Moreland130242d2019-08-26 17:41:32 -0700285 for (const auto& [name, service] : mNameToService) {
286 CHECK(service.binder != nullptr) << name;
287 }
288}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700289
290Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700291 *outBinder = tryGetService(name, true);
292 // returns ok regardless of result for legacy reasons
293 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700294}
295
296Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700297 *outBinder = tryGetService(name, false);
298 // returns ok regardless of result for legacy reasons
299 return Status::ok();
300}
301
302sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700303 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700304
Jon Spivack0d844302019-07-22 18:40:34 -0700305 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700306 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700307 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700308 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700309
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000310 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
Steven Morelandbad75882023-06-16 20:59:06 +0000311 LOG(WARNING) << "Isolated app with UID " << ctx.uid << " requested '" << name
312 << "', but the service is not allowed for isolated apps.";
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000313 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700314 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700315 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700316 }
317
Steven Morelanda9fe4742019-07-18 14:45:20 -0700318 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700319 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700320 }
321
Jon Spivack0d844302019-07-22 18:40:34 -0700322 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000323 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700324 }
325
Jon Spivack9f503a42019-10-22 16:49:19 -0700326 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000327 // Force onClients to get sent, and then make sure the timerfd won't clear it
328 // by setting guaranteeClient again. This logic could be simplified by using
329 // a time-based guarantee. However, forcing onClients(true) to get sent
330 // right here is always going to be important for processes serving multiple
331 // lazy interfaces.
332 service->guaranteeClient = true;
333 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700334 service->guaranteeClient = true;
335 }
336
Jon Spivack0d844302019-07-22 18:40:34 -0700337 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700338}
339
Steven Moreland905e2e82019-07-17 11:05:45 -0700340bool isValidServiceName(const std::string& name) {
341 if (name.size() == 0) return false;
342 if (name.size() > 127) return false;
343
344 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700345 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700346 if (c >= 'a' && c <= 'z') continue;
347 if (c >= 'A' && c <= 'Z') continue;
348 if (c >= '0' && c <= '9') continue;
349 return false;
350 }
351
352 return true;
353}
354
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700355Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700356 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700357
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700358 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000359 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700360 }
361
Steven Morelanda9fe4742019-07-18 14:45:20 -0700362 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000363 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700364 }
365
366 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000367 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700368 }
369
Steven Moreland905e2e82019-07-17 11:05:45 -0700370 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000371 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000372 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700373 }
374
Steven Moreland86a17f82019-09-10 10:18:00 -0700375#ifndef VENDORSERVICEMANAGER
376 if (!meetsDeclarationRequirements(binder, name)) {
377 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000378 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700379 }
380#endif // !VENDORSERVICEMANAGER
381
Devin Moore4e21def2023-02-24 21:54:14 +0000382 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
383 ALOGW("Dump flag priority is not set when adding %s", name.c_str());
384 }
385
Steven Moreland88860b02019-08-12 14:24:14 -0700386 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000387 if (binder->remoteBinder() != nullptr &&
388 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Pawan Wagh37526162022-09-29 21:55:26 +0000389 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000390 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700391 }
392
Steven Moreland7ee423b2022-09-24 03:52:08 +0000393 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000394 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000395 if (it != mNameToService.end()) {
396 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000397 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000398
399 // We could do better than this because if the other service dies, it
400 // may not have an entry here. However, this case is unlikely. We are
401 // only trying to detect when two different services are accidentally installed.
402
403 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000404 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
405 "from UID %u. Multiple instances installed?",
406 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000407 }
408
409 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000410 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
411 "from SID %s. Multiple instances installed?",
412 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000413 }
414
Pawan Wagh37526162022-09-29 21:55:26 +0000415 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
416 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
417 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000418 }
419
Devin Moore05ffe522020-08-06 13:58:29 -0700420 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000421 mNameToService[name] = Service{
422 .binder = binder,
423 .allowIsolated = allowIsolated,
424 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000425 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000426 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000427 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700428 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700429
Steven Moreland7ee423b2022-09-24 03:52:08 +0000430 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000431 // If someone is currently waiting on the service, notify the service that
432 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000433 mNameToService[name].guaranteeClient = true;
434 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
435 mNameToService[name].guaranteeClient = true;
436
Steven Moreland27cfab02019-08-12 14:34:16 -0700437 for (const sp<IServiceCallback>& cb : it->second) {
438 // permission checked in registerForNotifications
439 cb->onRegistration(name, binder);
440 }
441 }
442
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700443 return Status::ok();
444}
445
446Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700447 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000448 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700449 }
450
451 size_t toReserve = 0;
452 for (auto const& [name, service] : mNameToService) {
453 (void) name;
454
455 if (service.dumpPriority & dumpPriority) ++toReserve;
456 }
457
458 CHECK(outList->empty());
459
460 outList->reserve(toReserve);
461 for (auto const& [name, service] : mNameToService) {
462 (void) service;
463
464 if (service.dumpPriority & dumpPriority) {
465 outList->push_back(name);
466 }
467 }
468
469 return Status::ok();
470}
471
Steven Moreland27cfab02019-08-12 14:34:16 -0700472Status ServiceManager::registerForNotifications(
473 const std::string& name, const sp<IServiceCallback>& callback) {
474 auto ctx = mAccess->getCallingContext();
475
476 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000477 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
478 }
479
480 // note - we could allow isolated apps to get notifications if we
481 // keep track of isolated callbacks and non-isolated callbacks, but
482 // this is done since isolated apps shouldn't access lazy services
483 // so we should be able to use different APIs to keep things simple.
484 // Here, we disallow everything, because the service might not be
485 // registered yet.
486 if (is_multiuser_uid_isolated(ctx.uid)) {
487 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700488 }
489
490 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000491 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000492 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700493 }
494
495 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000496 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700497 }
498
Steven Morelandb0983182021-04-02 03:14:04 +0000499 if (OK !=
500 IInterface::asBinder(callback)->linkToDeath(
501 sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000502 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000503 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700504 }
505
Jon Spivackf288b1d2019-12-19 17:15:51 -0800506 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700507
508 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
509 const sp<IBinder>& binder = it->second.binder;
510
511 // never null if an entry exists
512 CHECK(binder != nullptr) << name;
513 callback->onRegistration(name, binder);
514 }
515
516 return Status::ok();
517}
518Status ServiceManager::unregisterForNotifications(
519 const std::string& name, const sp<IServiceCallback>& callback) {
520 auto ctx = mAccess->getCallingContext();
521
522 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000523 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700524 }
525
526 bool found = false;
527
Jon Spivackf288b1d2019-12-19 17:15:51 -0800528 auto it = mNameToRegistrationCallback.find(name);
529 if (it != mNameToRegistrationCallback.end()) {
530 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700531 }
532
533 if (!found) {
Pawan Wagh37526162022-09-29 21:55:26 +0000534 ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000535 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700536 }
537
538 return Status::ok();
539}
540
Steven Morelandb82b8f82019-10-28 10:52:34 -0700541Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
542 auto ctx = mAccess->getCallingContext();
543
544 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000545 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700546 }
547
548 *outReturn = false;
549
550#ifndef VENDORSERVICEMANAGER
551 *outReturn = isVintfDeclared(name);
552#endif
553 return Status::ok();
554}
555
Steven Moreland2e293aa2020-09-23 00:25:16 +0000556binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
557 auto ctx = mAccess->getCallingContext();
558
559 std::vector<std::string> allInstances;
560#ifndef VENDORSERVICEMANAGER
561 allInstances = getVintfInstances(interface);
562#endif
563
564 outReturn->clear();
565
566 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000567 if (mAccess->canFind(ctx, interface + "/" + instance)) {
568 outReturn->push_back(instance);
569 }
570 }
571
572 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000573 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000574 }
575
576 return Status::ok();
577}
578
Steven Morelandedd4e072021-04-21 00:27:29 +0000579Status ServiceManager::updatableViaApex(const std::string& name,
580 std::optional<std::string>* outReturn) {
581 auto ctx = mAccess->getCallingContext();
582
583 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000584 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000585 }
586
587 *outReturn = std::nullopt;
588
589#ifndef VENDORSERVICEMANAGER
590 *outReturn = getVintfUpdatableApex(name);
591#endif
592 return Status::ok();
593}
594
Jooyung Han76944fe2022-10-25 17:02:45 +0900595Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
596 std::vector<std::string>* outReturn) {
597 auto ctx = mAccess->getCallingContext();
598
599 std::vector<std::string> apexUpdatableInstances;
600#ifndef VENDORSERVICEMANAGER
601 apexUpdatableInstances = getVintfUpdatableInstances(apexName);
602#endif
603
604 outReturn->clear();
605
606 for (const std::string& instance : apexUpdatableInstances) {
607 if (mAccess->canFind(ctx, instance)) {
608 outReturn->push_back(instance);
609 }
610 }
611
612 if (outReturn->size() == 0 && apexUpdatableInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000613 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900614 }
615
616 return Status::ok();
617}
618
Devin Moore5e4c2f12021-09-09 22:36:33 +0000619Status ServiceManager::getConnectionInfo(const std::string& name,
620 std::optional<ConnectionInfo>* outReturn) {
621 auto ctx = mAccess->getCallingContext();
622
623 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000624 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000625 }
626
627 *outReturn = std::nullopt;
628
629#ifndef VENDORSERVICEMANAGER
630 *outReturn = getVintfConnectionInfo(name);
631#endif
632 return Status::ok();
633}
634
Jon Spivackf288b1d2019-12-19 17:15:51 -0800635void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
636 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700637 bool* found) {
638 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
639
640 for (auto lit = listeners.begin(); lit != listeners.end();) {
641 if (IInterface::asBinder(*lit) == who) {
642 if(found) *found = true;
643 lit = listeners.erase(lit);
644 } else {
645 ++lit;
646 }
647 }
648
649 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800650 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700651 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800652 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700653 }
654}
655
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700656void ServiceManager::binderDied(const wp<IBinder>& who) {
657 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
658 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000659 // TODO: currently, this entry contains the state also
660 // associated with mNameToClientCallback. If we allowed
661 // other processes to register client callbacks, we
662 // would have to preserve hasClients (perhaps moving
663 // that state into mNameToClientCallback, which is complicated
664 // because those callbacks are associated w/ particular binder
665 // objects, though they are indexed by name now, they may
666 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700667 it = mNameToService.erase(it);
668 } else {
669 ++it;
670 }
671 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700672
Jon Spivackf288b1d2019-12-19 17:15:51 -0800673 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
674 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700675 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700676
677 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
678 removeClientCallback(who, &it);
679 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700680}
681
Steven Morelandaa33e852023-05-10 16:42:15 +0000682void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
683 ALOGI("Since '%s' could not be found (requested by debug pid %d), trying to start it as a lazy "
684 "AIDL service. (if it's not configured to be a lazy service, it may be stuck starting or "
685 "still starting).",
686 name.c_str(), ctx.debugPid);
Jon Spivack0d844302019-07-22 18:40:34 -0700687
688 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000689 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000690 ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
691 "this happens when a "
692 "service is not installed, but if the service is intended to be used as a "
693 "lazy service, then it may be configured incorrectly.",
694 name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000695 }
Jon Spivack0d844302019-07-22 18:40:34 -0700696 }).detach();
697}
698
Jon Spivack9f503a42019-10-22 16:49:19 -0700699Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
700 const sp<IClientCallback>& cb) {
701 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000702 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700703 }
704
705 auto ctx = mAccess->getCallingContext();
706 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000707 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700708 }
709
710 auto serviceIt = mNameToService.find(name);
711 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000712 ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000713 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700714 }
715
Steven Moreland7ee423b2022-09-24 03:52:08 +0000716 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000717 ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000718 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
719 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700720 }
721
722 if (serviceIt->second.binder != service) {
Pawan Wagh37526162022-09-29 21:55:26 +0000723 ALOGW("Tried to register client callback for %s but a different service is registered "
724 "under this name.",
725 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000726 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700727 }
728
Steven Morelandb0983182021-04-02 03:14:04 +0000729 if (OK !=
730 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000731 ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000732 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700733 }
734
Steven Moreland79578672023-04-27 19:38:00 +0000735 // WARNING: binderDied makes an assumption about this. If we open up client
736 // callbacks to other services, certain race conditions may lead to services
737 // getting extra client callback notifications.
738 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000739 if (serviceIt->second.hasClients) {
740 cb->onClients(service, true);
741 }
742
Jon Spivack9f503a42019-10-22 16:49:19 -0700743 mNameToClientCallback[name].push_back(cb);
744
Steven Morelandefea66b2023-06-17 01:59:34 +0000745 // Flush updated info to client callbacks (especially if guaranteeClient
746 // and !hasClient, see b/285202885). We may or may not have clients at
747 // this point, so ignore the return value.
748 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
749
Jon Spivack9f503a42019-10-22 16:49:19 -0700750 return Status::ok();
751}
752
753void ServiceManager::removeClientCallback(const wp<IBinder>& who,
754 ClientCallbackMap::iterator* it) {
755 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
756
757 for (auto lit = listeners.begin(); lit != listeners.end();) {
758 if (IInterface::asBinder(*lit) == who) {
759 lit = listeners.erase(lit);
760 } else {
761 ++lit;
762 }
763 }
764
765 if (listeners.empty()) {
766 *it = mNameToClientCallback.erase(*it);
767 } else {
768 (*it)++;
769 }
770}
771
772ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000773 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700774 if (bpBinder == nullptr) return -1;
775
Steven Morelande8393882020-12-18 02:27:20 +0000776 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700777}
778
779void ServiceManager::handleClientCallbacks() {
780 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000781 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700782 }
783}
784
Steven Morelandb8361902023-02-01 23:18:04 +0000785bool ServiceManager::handleServiceClientCallback(size_t knownClients,
786 const std::string& serviceName,
787 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700788 auto serviceIt = mNameToService.find(serviceName);
789 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000790 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700791 }
792
793 Service& service = serviceIt->second;
794 ssize_t count = service.getNodeStrongRefCount();
795
Steven Morelandb8361902023-02-01 23:18:04 +0000796 // binder driver doesn't support this feature, consider we have clients
797 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700798
Steven Morelandb8361902023-02-01 23:18:04 +0000799 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700800
801 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000802 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000803 sendClientCallbackNotifications(serviceName, true,
804 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700805 }
806
807 // guarantee is temporary
808 service.guaranteeClient = false;
809 }
810
Steven Morelandb8361902023-02-01 23:18:04 +0000811 // Regardless of this situation, we want to give this notification as soon as possible.
812 // This way, we have a chance of preventing further thrashing.
813 if (hasKernelReportedClients && !service.hasClients) {
814 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
815 }
Steven Moreland66417652023-02-01 22:19:41 +0000816
Steven Morelandb8361902023-02-01 23:18:04 +0000817 // But limit rate of shutting down service.
818 if (isCalledOnInterval) {
819 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000820 sendClientCallbackNotifications(serviceName, false,
821 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000822 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700823 }
824
Steven Morelandb8361902023-02-01 23:18:04 +0000825 // May be different than 'hasKernelReportedClients'. We intentionally delay
826 // information about clients going away to reduce thrashing.
827 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700828}
829
Steven Moreland3e083b22023-01-26 00:46:30 +0000830void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
831 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700832 auto serviceIt = mNameToService.find(serviceName);
833 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000834 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
835 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700836 return;
837 }
838 Service& service = serviceIt->second;
839
Steven Morelandb8361902023-02-01 23:18:04 +0000840 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700841
Steven Morelandb8361902023-02-01 23:18:04 +0000842 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
843 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700844
845 auto ccIt = mNameToClientCallback.find(serviceName);
846 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000847 << "sendClientCallbackNotifications could not find callbacks for service when "
848 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700849
850 for (const auto& callback : ccIt->second) {
851 callback->onClients(service.binder, hasClients);
852 }
853
854 service.hasClients = hasClients;
855}
856
857Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
858 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000859 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700860 }
861
862 auto ctx = mAccess->getCallingContext();
863 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000864 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700865 }
866
867 auto serviceIt = mNameToService.find(name);
868 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000869 ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
870 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000871 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700872 }
873
Steven Moreland7ee423b2022-09-24 03:52:08 +0000874 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000875 ALOGW("Only a server can unregister itself (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000876 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
877 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700878 }
879
880 sp<IBinder> storedBinder = serviceIt->second.binder;
881
882 if (binder != storedBinder) {
Pawan Wagh37526162022-09-29 21:55:26 +0000883 ALOGW("Tried to unregister %s, but a different service is registered under this name.",
884 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000885 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
886 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700887 }
888
Steven Morelandb8361902023-02-01 23:18:04 +0000889 // important because we don't have timer-based guarantees, we don't want to clear
890 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700891 if (serviceIt->second.guaranteeClient) {
Pawan Wagh37526162022-09-29 21:55:26 +0000892 ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000893 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
894 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700895 }
896
Jon Spivack9f503a42019-10-22 16:49:19 -0700897 // - kernel driver will hold onto one refcount (during this transaction)
898 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000899 constexpr size_t kKnownClients = 2;
900
901 if (handleServiceClientCallback(kKnownClients, name, false)) {
902 ALOGI("Tried to unregister %s, but there are clients.", name.c_str());
903
904 // Since we had a failed registration attempt, and the HIDL implementation of
905 // delaying service shutdown for multiple periods wasn't ported here... this may
906 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800907 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000908
Steven Morelandffb905b2023-03-28 18:24:37 +0000909 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
910 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700911 }
912
Steven Morelandb8361902023-02-01 23:18:04 +0000913 ALOGI("Unregistering %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700914 mNameToService.erase(name);
915
916 return Status::ok();
917}
918
Steven Moreland3ea43272021-01-28 22:49:28 +0000919Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
920 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000921 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +0000922 }
923
924 outReturn->reserve(mNameToService.size());
925 for (auto const& [name, service] : mNameToService) {
926 ServiceDebugInfo info;
927 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000928 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000929
930 outReturn->push_back(std::move(info));
931 }
932
933 return Status::ok();
934}
935
Pawan Wagh243888e2022-09-20 19:37:35 +0000936void ServiceManager::clear() {
937 mNameToService.clear();
938 mNameToRegistrationCallback.clear();
939 mNameToClientCallback.clear();
940}
941
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700942} // namespace android