blob: 408151479e15c66a7370eb79ead5775aee7373eb [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>
Yifan Hong0a9b56e2021-11-30 16:45:40 -080031#ifdef __ANDROID_RECOVERY__
32#include <vintf/VintfObjectRecovery.h>
33#endif // __ANDROID_RECOVERY__
Steven Moreland86a17f82019-09-10 10:18:00 -070034#include <vintf/constants.h>
35#endif // !VENDORSERVICEMANAGER
36
Steven Moreland80e1e6d2019-06-21 12:35:59 -070037using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070038using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070039
40namespace android {
41
Steven Morelandb9e1cbe2023-02-01 22:44:45 +000042bool is_multiuser_uid_isolated(uid_t uid) {
43 uid_t appid = multiuser_get_app_id(uid);
44 return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
45}
46
Steven Moreland86a17f82019-09-10 10:18:00 -070047#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080048
Steven Moreland2e293aa2020-09-23 00:25:16 +000049struct ManifestWithDescription {
50 std::shared_ptr<const vintf::HalManifest> manifest;
51 const char* description;
52};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080053static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
54#ifdef __ANDROID_RECOVERY__
55 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
56 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000057 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080058 return {};
59 }
60 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
61#else
62 auto vintfObject = vintf::VintfObject::GetInstance();
63 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000064 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080065 return {};
66 }
67 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
68 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
69#endif
70}
71
Steven Moreland2e293aa2020-09-23 00:25:16 +000072// func true -> stop search and forEachManifest will return true
73static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080074 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000075 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000076 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
77 // note, we explicitly do not retry here, so that we can detect VINTF
78 // or other bugs (b/151696835)
79 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +000080 }
81 if (func(mwd)) return true;
82 }
83 return false;
84}
85
Steven Morelandedd4e072021-04-21 00:27:29 +000086struct AidlName {
87 std::string package;
88 std::string iface;
89 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070090
Steven Morelandedd4e072021-04-21 00:27:29 +000091 static bool fill(const std::string& name, AidlName* aname) {
92 size_t firstSlash = name.find('/');
93 size_t lastDot = name.rfind('.', firstSlash);
94 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +000095 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
96 "some.package.foo.IFoo/default) but got: %s",
97 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +000098 return false;
99 }
100 aname->package = name.substr(0, lastDot);
101 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
102 aname->instance = name.substr(firstSlash + 1);
103 return true;
104 }
105};
106
107static bool isVintfDeclared(const std::string& name) {
108 AidlName aname;
109 if (!AidlName::fill(name, &aname)) return false;
110
111 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
112 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000113 ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000114 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700115 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000116 return false; // continue
117 });
118
119 if (!found) {
120 // Although it is tested, explicitly rebuilding qualified name, in case it
121 // becomes something unexpected.
Pawan Wagh37526162022-09-29 21:55:26 +0000122 ALOGI("Could not find %s.%s/%s in the VINTF manifest.", aname.package.c_str(),
123 aname.iface.c_str(), aname.instance.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700124 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700125
Steven Moreland2e293aa2020-09-23 00:25:16 +0000126 return found;
127}
128
Steven Morelandedd4e072021-04-21 00:27:29 +0000129static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
130 AidlName aname;
131 if (!AidlName::fill(name, &aname)) return std::nullopt;
132
133 std::optional<std::string> updatableViaApex;
134
135 forEachManifest([&](const ManifestWithDescription& mwd) {
136 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
137 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
138 if (manifestInstance.package() != aname.package) return true;
139 if (manifestInstance.interface() != aname.iface) return true;
140 if (manifestInstance.instance() != aname.instance) return true;
141 updatableViaApex = manifestInstance.updatableViaApex();
142 return false; // break (libvintf uses opposite convention)
143 });
Jooyung Hance94b752022-11-14 18:55:06 +0900144 if (updatableViaApex.has_value()) return true; // break (found match)
Steven Morelandedd4e072021-04-21 00:27:29 +0000145 return false; // continue
146 });
147
148 return updatableViaApex;
149}
150
Jooyung Han76944fe2022-10-25 17:02:45 +0900151static std::vector<std::string> getVintfUpdatableInstances(const std::string& apexName) {
152 std::vector<std::string> instances;
153
154 forEachManifest([&](const ManifestWithDescription& mwd) {
155 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
156 if (manifestInstance.format() == vintf::HalFormat::AIDL &&
157 manifestInstance.updatableViaApex().has_value() &&
158 manifestInstance.updatableViaApex().value() == apexName) {
159 std::string aname = manifestInstance.package() + "." +
160 manifestInstance.interface() + "/" + manifestInstance.instance();
161 instances.push_back(aname);
162 }
Jooyung Hance94b752022-11-14 18:55:06 +0900163 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900164 });
165 return false; // continue
166 });
167
168 return instances;
169}
170
Devin Moore5e4c2f12021-09-09 22:36:33 +0000171static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
172 AidlName aname;
173 if (!AidlName::fill(name, &aname)) return std::nullopt;
174
175 std::optional<std::string> ip;
176 std::optional<uint64_t> port;
177 forEachManifest([&](const ManifestWithDescription& mwd) {
178 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
179 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
180 if (manifestInstance.package() != aname.package) return true;
181 if (manifestInstance.interface() != aname.iface) return true;
182 if (manifestInstance.instance() != aname.instance) return true;
183 ip = manifestInstance.ip();
184 port = manifestInstance.port();
185 return false; // break (libvintf uses opposite convention)
186 });
187 return false; // continue
188 });
189
190 if (ip.has_value() && port.has_value()) {
191 ConnectionInfo info;
192 info.ipAddress = *ip;
193 info.port = *port;
194 return std::make_optional<ConnectionInfo>(info);
195 } else {
196 return std::nullopt;
197 }
198}
199
Steven Moreland2e293aa2020-09-23 00:25:16 +0000200static std::vector<std::string> getVintfInstances(const std::string& interface) {
201 size_t lastDot = interface.rfind('.');
202 if (lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000203 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
204 "but got: %s",
205 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000206 return {};
207 }
208 const std::string package = interface.substr(0, lastDot);
209 const std::string iface = interface.substr(lastDot+1);
210
211 std::vector<std::string> ret;
212 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
213 auto instances = mwd.manifest->getAidlInstances(package, iface);
214 ret.insert(ret.end(), instances.begin(), instances.end());
215 return false; // continue
216 });
217
218 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700219}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700220
221static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
222 if (!Stability::requiresVintfDeclaration(binder)) {
223 return true;
224 }
225
226 return isVintfDeclared(name);
227}
Steven Moreland86a17f82019-09-10 10:18:00 -0700228#endif // !VENDORSERVICEMANAGER
229
Steven Morelandb8361902023-02-01 23:18:04 +0000230ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000231 if (hasClients) {
232 // only expected to happen on process death, we don't store the service
233 // name this late (it's in the map that holds this service), but if it
234 // is happening, we might want to change 'unlinkToDeath' to explicitly
235 // clear this bit so that we can abort in other cases, where it would
236 // mean inconsistent logic in servicemanager (unexpected and tested, but
237 // the original lazy service impl here had that bug).
Steven Morelandb8361902023-02-01 23:18:04 +0000238 LOG(WARNING) << "a service was removed when there are clients";
239 }
240}
241
Steven Morelandd13f08b2019-11-18 14:23:09 -0800242ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700243// TODO(b/151696835): reenable performance hack when we solve bug, since with
244// this hack and other fixes, it is unlikely we will see even an ephemeral
245// failure when the manifest parse fails. The goal is that the manifest will
246// be read incorrectly and cause the process trying to register a HAL to
247// fail. If this is in fact an early boot kernel contention issue, then we
248// will get no failure, and by its absence, be signalled to invest more
249// effort in re-adding this performance hack.
250// #ifndef VENDORSERVICEMANAGER
251// // can process these at any times, don't want to delay first VINTF client
252// std::thread([] {
253// vintf::VintfObject::GetDeviceHalManifest();
254// vintf::VintfObject::GetFrameworkHalManifest();
255// }).detach();
256// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800257}
Steven Moreland130242d2019-08-26 17:41:32 -0700258ServiceManager::~ServiceManager() {
259 // this should only happen in tests
260
Jon Spivackf288b1d2019-12-19 17:15:51 -0800261 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700262 CHECK(!callbacks.empty()) << name;
263 for (const auto& callback : callbacks) {
264 CHECK(callback != nullptr) << name;
265 }
266 }
267
Steven Moreland130242d2019-08-26 17:41:32 -0700268 for (const auto& [name, service] : mNameToService) {
269 CHECK(service.binder != nullptr) << name;
270 }
271}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700272
273Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700274 *outBinder = tryGetService(name, true);
275 // returns ok regardless of result for legacy reasons
276 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700277}
278
279Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700280 *outBinder = tryGetService(name, false);
281 // returns ok regardless of result for legacy reasons
282 return Status::ok();
283}
284
285sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700286 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700287
Jon Spivack0d844302019-07-22 18:40:34 -0700288 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700289 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700290 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700291 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700292
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000293 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
Steven Morelandbad75882023-06-16 20:59:06 +0000294 LOG(WARNING) << "Isolated app with UID " << ctx.uid << " requested '" << name
295 << "', but the service is not allowed for isolated apps.";
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000296 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700297 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700298 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700299 }
300
Steven Morelanda9fe4742019-07-18 14:45:20 -0700301 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700302 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700303 }
304
Jon Spivack0d844302019-07-22 18:40:34 -0700305 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000306 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700307 }
308
Jon Spivack9f503a42019-10-22 16:49:19 -0700309 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000310 // Force onClients to get sent, and then make sure the timerfd won't clear it
311 // by setting guaranteeClient again. This logic could be simplified by using
312 // a time-based guarantee. However, forcing onClients(true) to get sent
313 // right here is always going to be important for processes serving multiple
314 // lazy interfaces.
315 service->guaranteeClient = true;
316 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700317 service->guaranteeClient = true;
318 }
319
Jon Spivack0d844302019-07-22 18:40:34 -0700320 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700321}
322
Steven Moreland905e2e82019-07-17 11:05:45 -0700323bool isValidServiceName(const std::string& name) {
324 if (name.size() == 0) return false;
325 if (name.size() > 127) return false;
326
327 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700328 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700329 if (c >= 'a' && c <= 'z') continue;
330 if (c >= 'A' && c <= 'Z') continue;
331 if (c >= '0' && c <= '9') continue;
332 return false;
333 }
334
335 return true;
336}
337
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700338Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700339 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700340
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700341 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000342 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700343 }
344
Steven Morelanda9fe4742019-07-18 14:45:20 -0700345 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000346 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700347 }
348
349 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000350 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700351 }
352
Steven Moreland905e2e82019-07-17 11:05:45 -0700353 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000354 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000355 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700356 }
357
Steven Moreland86a17f82019-09-10 10:18:00 -0700358#ifndef VENDORSERVICEMANAGER
359 if (!meetsDeclarationRequirements(binder, name)) {
360 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000361 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700362 }
363#endif // !VENDORSERVICEMANAGER
364
Devin Moore4e21def2023-02-24 21:54:14 +0000365 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
366 ALOGW("Dump flag priority is not set when adding %s", name.c_str());
367 }
368
Steven Moreland88860b02019-08-12 14:24:14 -0700369 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000370 if (binder->remoteBinder() != nullptr &&
371 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Pawan Wagh37526162022-09-29 21:55:26 +0000372 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000373 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700374 }
375
Steven Moreland7ee423b2022-09-24 03:52:08 +0000376 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000377 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000378 if (it != mNameToService.end()) {
379 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000380 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000381
382 // We could do better than this because if the other service dies, it
383 // may not have an entry here. However, this case is unlikely. We are
384 // only trying to detect when two different services are accidentally installed.
385
386 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000387 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
388 "from UID %u. Multiple instances installed?",
389 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000390 }
391
392 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000393 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
394 "from SID %s. Multiple instances installed?",
395 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000396 }
397
Pawan Wagh37526162022-09-29 21:55:26 +0000398 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
399 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
400 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000401 }
402
Devin Moore05ffe522020-08-06 13:58:29 -0700403 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000404 mNameToService[name] = Service{
405 .binder = binder,
406 .allowIsolated = allowIsolated,
407 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000408 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000409 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000410 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700411 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700412
Steven Moreland7ee423b2022-09-24 03:52:08 +0000413 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000414 // If someone is currently waiting on the service, notify the service that
415 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000416 mNameToService[name].guaranteeClient = true;
417 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
418 mNameToService[name].guaranteeClient = true;
419
Steven Moreland27cfab02019-08-12 14:34:16 -0700420 for (const sp<IServiceCallback>& cb : it->second) {
421 // permission checked in registerForNotifications
422 cb->onRegistration(name, binder);
423 }
424 }
425
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700426 return Status::ok();
427}
428
429Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700430 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000431 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700432 }
433
434 size_t toReserve = 0;
435 for (auto const& [name, service] : mNameToService) {
436 (void) name;
437
438 if (service.dumpPriority & dumpPriority) ++toReserve;
439 }
440
441 CHECK(outList->empty());
442
443 outList->reserve(toReserve);
444 for (auto const& [name, service] : mNameToService) {
445 (void) service;
446
447 if (service.dumpPriority & dumpPriority) {
448 outList->push_back(name);
449 }
450 }
451
452 return Status::ok();
453}
454
Steven Moreland27cfab02019-08-12 14:34:16 -0700455Status ServiceManager::registerForNotifications(
456 const std::string& name, const sp<IServiceCallback>& callback) {
457 auto ctx = mAccess->getCallingContext();
458
459 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000460 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
461 }
462
463 // note - we could allow isolated apps to get notifications if we
464 // keep track of isolated callbacks and non-isolated callbacks, but
465 // this is done since isolated apps shouldn't access lazy services
466 // so we should be able to use different APIs to keep things simple.
467 // Here, we disallow everything, because the service might not be
468 // registered yet.
469 if (is_multiuser_uid_isolated(ctx.uid)) {
470 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700471 }
472
473 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000474 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000475 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700476 }
477
478 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000479 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700480 }
481
Steven Morelandb0983182021-04-02 03:14:04 +0000482 if (OK !=
483 IInterface::asBinder(callback)->linkToDeath(
484 sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000485 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000486 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700487 }
488
Jon Spivackf288b1d2019-12-19 17:15:51 -0800489 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700490
491 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
492 const sp<IBinder>& binder = it->second.binder;
493
494 // never null if an entry exists
495 CHECK(binder != nullptr) << name;
496 callback->onRegistration(name, binder);
497 }
498
499 return Status::ok();
500}
501Status ServiceManager::unregisterForNotifications(
502 const std::string& name, const sp<IServiceCallback>& callback) {
503 auto ctx = mAccess->getCallingContext();
504
505 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000506 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700507 }
508
509 bool found = false;
510
Jon Spivackf288b1d2019-12-19 17:15:51 -0800511 auto it = mNameToRegistrationCallback.find(name);
512 if (it != mNameToRegistrationCallback.end()) {
513 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700514 }
515
516 if (!found) {
Pawan Wagh37526162022-09-29 21:55:26 +0000517 ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000518 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700519 }
520
521 return Status::ok();
522}
523
Steven Morelandb82b8f82019-10-28 10:52:34 -0700524Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
525 auto ctx = mAccess->getCallingContext();
526
527 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000528 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700529 }
530
531 *outReturn = false;
532
533#ifndef VENDORSERVICEMANAGER
534 *outReturn = isVintfDeclared(name);
535#endif
536 return Status::ok();
537}
538
Steven Moreland2e293aa2020-09-23 00:25:16 +0000539binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
540 auto ctx = mAccess->getCallingContext();
541
542 std::vector<std::string> allInstances;
543#ifndef VENDORSERVICEMANAGER
544 allInstances = getVintfInstances(interface);
545#endif
546
547 outReturn->clear();
548
549 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000550 if (mAccess->canFind(ctx, interface + "/" + instance)) {
551 outReturn->push_back(instance);
552 }
553 }
554
555 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000556 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000557 }
558
559 return Status::ok();
560}
561
Steven Morelandedd4e072021-04-21 00:27:29 +0000562Status ServiceManager::updatableViaApex(const std::string& name,
563 std::optional<std::string>* outReturn) {
564 auto ctx = mAccess->getCallingContext();
565
566 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000567 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000568 }
569
570 *outReturn = std::nullopt;
571
572#ifndef VENDORSERVICEMANAGER
573 *outReturn = getVintfUpdatableApex(name);
574#endif
575 return Status::ok();
576}
577
Jooyung Han76944fe2022-10-25 17:02:45 +0900578Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
579 std::vector<std::string>* outReturn) {
580 auto ctx = mAccess->getCallingContext();
581
582 std::vector<std::string> apexUpdatableInstances;
583#ifndef VENDORSERVICEMANAGER
584 apexUpdatableInstances = getVintfUpdatableInstances(apexName);
585#endif
586
587 outReturn->clear();
588
589 for (const std::string& instance : apexUpdatableInstances) {
590 if (mAccess->canFind(ctx, instance)) {
591 outReturn->push_back(instance);
592 }
593 }
594
595 if (outReturn->size() == 0 && apexUpdatableInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000596 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900597 }
598
599 return Status::ok();
600}
601
Devin Moore5e4c2f12021-09-09 22:36:33 +0000602Status ServiceManager::getConnectionInfo(const std::string& name,
603 std::optional<ConnectionInfo>* outReturn) {
604 auto ctx = mAccess->getCallingContext();
605
606 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000607 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000608 }
609
610 *outReturn = std::nullopt;
611
612#ifndef VENDORSERVICEMANAGER
613 *outReturn = getVintfConnectionInfo(name);
614#endif
615 return Status::ok();
616}
617
Jon Spivackf288b1d2019-12-19 17:15:51 -0800618void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
619 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700620 bool* found) {
621 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
622
623 for (auto lit = listeners.begin(); lit != listeners.end();) {
624 if (IInterface::asBinder(*lit) == who) {
625 if(found) *found = true;
626 lit = listeners.erase(lit);
627 } else {
628 ++lit;
629 }
630 }
631
632 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800633 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700634 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800635 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700636 }
637}
638
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700639void ServiceManager::binderDied(const wp<IBinder>& who) {
640 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
641 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000642 // TODO: currently, this entry contains the state also
643 // associated with mNameToClientCallback. If we allowed
644 // other processes to register client callbacks, we
645 // would have to preserve hasClients (perhaps moving
646 // that state into mNameToClientCallback, which is complicated
647 // because those callbacks are associated w/ particular binder
648 // objects, though they are indexed by name now, they may
649 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700650 it = mNameToService.erase(it);
651 } else {
652 ++it;
653 }
654 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700655
Jon Spivackf288b1d2019-12-19 17:15:51 -0800656 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
657 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700658 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700659
660 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
661 removeClientCallback(who, &it);
662 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700663}
664
Steven Morelandaa33e852023-05-10 16:42:15 +0000665void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
666 ALOGI("Since '%s' could not be found (requested by debug pid %d), trying to start it as a lazy "
667 "AIDL service. (if it's not configured to be a lazy service, it may be stuck starting or "
668 "still starting).",
669 name.c_str(), ctx.debugPid);
Jon Spivack0d844302019-07-22 18:40:34 -0700670
671 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000672 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000673 ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
674 "this happens when a "
675 "service is not installed, but if the service is intended to be used as a "
676 "lazy service, then it may be configured incorrectly.",
677 name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000678 }
Jon Spivack0d844302019-07-22 18:40:34 -0700679 }).detach();
680}
681
Jon Spivack9f503a42019-10-22 16:49:19 -0700682Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
683 const sp<IClientCallback>& cb) {
684 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000685 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700686 }
687
688 auto ctx = mAccess->getCallingContext();
689 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000690 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700691 }
692
693 auto serviceIt = mNameToService.find(name);
694 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000695 ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000696 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700697 }
698
Steven Moreland7ee423b2022-09-24 03:52:08 +0000699 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000700 ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000701 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
702 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700703 }
704
705 if (serviceIt->second.binder != service) {
Pawan Wagh37526162022-09-29 21:55:26 +0000706 ALOGW("Tried to register client callback for %s but a different service is registered "
707 "under this name.",
708 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000709 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700710 }
711
Steven Morelandb0983182021-04-02 03:14:04 +0000712 if (OK !=
713 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000714 ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000715 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700716 }
717
Steven Moreland79578672023-04-27 19:38:00 +0000718 // WARNING: binderDied makes an assumption about this. If we open up client
719 // callbacks to other services, certain race conditions may lead to services
720 // getting extra client callback notifications.
721 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000722 if (serviceIt->second.hasClients) {
723 cb->onClients(service, true);
724 }
725
Jon Spivack9f503a42019-10-22 16:49:19 -0700726 mNameToClientCallback[name].push_back(cb);
727
Steven Morelandefea66b2023-06-17 01:59:34 +0000728 // Flush updated info to client callbacks (especially if guaranteeClient
729 // and !hasClient, see b/285202885). We may or may not have clients at
730 // this point, so ignore the return value.
731 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
732
Jon Spivack9f503a42019-10-22 16:49:19 -0700733 return Status::ok();
734}
735
736void ServiceManager::removeClientCallback(const wp<IBinder>& who,
737 ClientCallbackMap::iterator* it) {
738 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
739
740 for (auto lit = listeners.begin(); lit != listeners.end();) {
741 if (IInterface::asBinder(*lit) == who) {
742 lit = listeners.erase(lit);
743 } else {
744 ++lit;
745 }
746 }
747
748 if (listeners.empty()) {
749 *it = mNameToClientCallback.erase(*it);
750 } else {
751 (*it)++;
752 }
753}
754
755ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000756 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700757 if (bpBinder == nullptr) return -1;
758
Steven Morelande8393882020-12-18 02:27:20 +0000759 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700760}
761
762void ServiceManager::handleClientCallbacks() {
763 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000764 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700765 }
766}
767
Steven Morelandb8361902023-02-01 23:18:04 +0000768bool ServiceManager::handleServiceClientCallback(size_t knownClients,
769 const std::string& serviceName,
770 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700771 auto serviceIt = mNameToService.find(serviceName);
772 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000773 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700774 }
775
776 Service& service = serviceIt->second;
777 ssize_t count = service.getNodeStrongRefCount();
778
Steven Morelandb8361902023-02-01 23:18:04 +0000779 // binder driver doesn't support this feature, consider we have clients
780 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700781
Steven Morelandb8361902023-02-01 23:18:04 +0000782 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700783
784 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000785 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000786 sendClientCallbackNotifications(serviceName, true,
787 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700788 }
789
790 // guarantee is temporary
791 service.guaranteeClient = false;
792 }
793
Steven Morelandb8361902023-02-01 23:18:04 +0000794 // Regardless of this situation, we want to give this notification as soon as possible.
795 // This way, we have a chance of preventing further thrashing.
796 if (hasKernelReportedClients && !service.hasClients) {
797 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
798 }
Steven Moreland66417652023-02-01 22:19:41 +0000799
Steven Morelandb8361902023-02-01 23:18:04 +0000800 // But limit rate of shutting down service.
801 if (isCalledOnInterval) {
802 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000803 sendClientCallbackNotifications(serviceName, false,
804 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000805 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700806 }
807
Steven Morelandb8361902023-02-01 23:18:04 +0000808 // May be different than 'hasKernelReportedClients'. We intentionally delay
809 // information about clients going away to reduce thrashing.
810 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700811}
812
Steven Moreland3e083b22023-01-26 00:46:30 +0000813void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
814 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700815 auto serviceIt = mNameToService.find(serviceName);
816 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000817 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
818 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700819 return;
820 }
821 Service& service = serviceIt->second;
822
Steven Morelandb8361902023-02-01 23:18:04 +0000823 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700824
Steven Morelandb8361902023-02-01 23:18:04 +0000825 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
826 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700827
828 auto ccIt = mNameToClientCallback.find(serviceName);
829 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000830 << "sendClientCallbackNotifications could not find callbacks for service when "
831 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700832
833 for (const auto& callback : ccIt->second) {
834 callback->onClients(service.binder, hasClients);
835 }
836
837 service.hasClients = hasClients;
838}
839
840Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
841 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000842 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700843 }
844
845 auto ctx = mAccess->getCallingContext();
846 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000847 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700848 }
849
850 auto serviceIt = mNameToService.find(name);
851 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000852 ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
853 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000854 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700855 }
856
Steven Moreland7ee423b2022-09-24 03:52:08 +0000857 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000858 ALOGW("Only a server can unregister itself (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000859 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
860 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700861 }
862
863 sp<IBinder> storedBinder = serviceIt->second.binder;
864
865 if (binder != storedBinder) {
Pawan Wagh37526162022-09-29 21:55:26 +0000866 ALOGW("Tried to unregister %s, but a different service is registered under this name.",
867 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000868 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
869 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700870 }
871
Steven Morelandb8361902023-02-01 23:18:04 +0000872 // important because we don't have timer-based guarantees, we don't want to clear
873 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700874 if (serviceIt->second.guaranteeClient) {
Pawan Wagh37526162022-09-29 21:55:26 +0000875 ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000876 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
877 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700878 }
879
Jon Spivack9f503a42019-10-22 16:49:19 -0700880 // - kernel driver will hold onto one refcount (during this transaction)
881 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000882 constexpr size_t kKnownClients = 2;
883
884 if (handleServiceClientCallback(kKnownClients, name, false)) {
885 ALOGI("Tried to unregister %s, but there are clients.", name.c_str());
886
887 // Since we had a failed registration attempt, and the HIDL implementation of
888 // delaying service shutdown for multiple periods wasn't ported here... this may
889 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800890 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000891
Steven Morelandffb905b2023-03-28 18:24:37 +0000892 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
893 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700894 }
895
Steven Morelandb8361902023-02-01 23:18:04 +0000896 ALOGI("Unregistering %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700897 mNameToService.erase(name);
898
899 return Status::ok();
900}
901
Steven Moreland3ea43272021-01-28 22:49:28 +0000902Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
903 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000904 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +0000905 }
906
907 outReturn->reserve(mNameToService.size());
908 for (auto const& [name, service] : mNameToService) {
909 ServiceDebugInfo info;
910 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000911 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000912
913 outReturn->push_back(std::move(info));
914 }
915
916 return Status::ok();
917}
918
Pawan Wagh243888e2022-09-20 19:37:35 +0000919void ServiceManager::clear() {
920 mNameToService.clear();
921 mNameToRegistrationCallback.clear();
922 mNameToClientCallback.clear();
923}
924
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700925} // namespace android