blob: f2f0a0f0377d856b51cf04df850afd78451ea7da [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) {
Jooyung Han9f1c6872024-01-23 06:42:02 +0900153 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000154 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 Han9f1c6872024-01-23 06:42:02 +0900161 return !cont;
Steven Morelandedd4e072021-04-21 00:27:29 +0000162 });
163
164 return updatableViaApex;
165}
166
Jooyung Han76944fe2022-10-25 17:02:45 +0900167static std::vector<std::string> getVintfUpdatableInstances(const std::string& apexName) {
168 std::vector<std::string> instances;
169
170 forEachManifest([&](const ManifestWithDescription& mwd) {
171 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
172 if (manifestInstance.format() == vintf::HalFormat::AIDL &&
173 manifestInstance.updatableViaApex().has_value() &&
174 manifestInstance.updatableViaApex().value() == apexName) {
175 std::string aname = manifestInstance.package() + "." +
176 manifestInstance.interface() + "/" + manifestInstance.instance();
177 instances.push_back(aname);
178 }
Jooyung Hance94b752022-11-14 18:55:06 +0900179 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900180 });
181 return false; // continue
182 });
183
184 return instances;
185}
186
Devin Moore5e4c2f12021-09-09 22:36:33 +0000187static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
188 AidlName aname;
189 if (!AidlName::fill(name, &aname)) return std::nullopt;
190
191 std::optional<std::string> ip;
192 std::optional<uint64_t> port;
193 forEachManifest([&](const ManifestWithDescription& mwd) {
194 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
195 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
196 if (manifestInstance.package() != aname.package) return true;
197 if (manifestInstance.interface() != aname.iface) return true;
198 if (manifestInstance.instance() != aname.instance) return true;
199 ip = manifestInstance.ip();
200 port = manifestInstance.port();
201 return false; // break (libvintf uses opposite convention)
202 });
203 return false; // continue
204 });
205
206 if (ip.has_value() && port.has_value()) {
207 ConnectionInfo info;
208 info.ipAddress = *ip;
209 info.port = *port;
210 return std::make_optional<ConnectionInfo>(info);
211 } else {
212 return std::nullopt;
213 }
214}
215
Steven Moreland2e293aa2020-09-23 00:25:16 +0000216static std::vector<std::string> getVintfInstances(const std::string& interface) {
217 size_t lastDot = interface.rfind('.');
218 if (lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000219 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
220 "but got: %s",
221 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000222 return {};
223 }
224 const std::string package = interface.substr(0, lastDot);
225 const std::string iface = interface.substr(lastDot+1);
226
227 std::vector<std::string> ret;
228 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
229 auto instances = mwd.manifest->getAidlInstances(package, iface);
230 ret.insert(ret.end(), instances.begin(), instances.end());
231 return false; // continue
232 });
233
234 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700235}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700236
237static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
238 if (!Stability::requiresVintfDeclaration(binder)) {
239 return true;
240 }
241
242 return isVintfDeclared(name);
243}
Steven Moreland86a17f82019-09-10 10:18:00 -0700244#endif // !VENDORSERVICEMANAGER
245
Steven Morelandb8361902023-02-01 23:18:04 +0000246ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000247 if (hasClients) {
248 // only expected to happen on process death, we don't store the service
249 // name this late (it's in the map that holds this service), but if it
250 // is happening, we might want to change 'unlinkToDeath' to explicitly
251 // clear this bit so that we can abort in other cases, where it would
252 // mean inconsistent logic in servicemanager (unexpected and tested, but
253 // the original lazy service impl here had that bug).
Steven Morelandb8361902023-02-01 23:18:04 +0000254 LOG(WARNING) << "a service was removed when there are clients";
255 }
256}
257
Steven Morelandd13f08b2019-11-18 14:23:09 -0800258ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700259// TODO(b/151696835): reenable performance hack when we solve bug, since with
260// this hack and other fixes, it is unlikely we will see even an ephemeral
261// failure when the manifest parse fails. The goal is that the manifest will
262// be read incorrectly and cause the process trying to register a HAL to
263// fail. If this is in fact an early boot kernel contention issue, then we
264// will get no failure, and by its absence, be signalled to invest more
265// effort in re-adding this performance hack.
266// #ifndef VENDORSERVICEMANAGER
267// // can process these at any times, don't want to delay first VINTF client
268// std::thread([] {
269// vintf::VintfObject::GetDeviceHalManifest();
270// vintf::VintfObject::GetFrameworkHalManifest();
271// }).detach();
272// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800273}
Steven Moreland130242d2019-08-26 17:41:32 -0700274ServiceManager::~ServiceManager() {
275 // this should only happen in tests
276
Jon Spivackf288b1d2019-12-19 17:15:51 -0800277 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700278 CHECK(!callbacks.empty()) << name;
279 for (const auto& callback : callbacks) {
280 CHECK(callback != nullptr) << name;
281 }
282 }
283
Steven Moreland130242d2019-08-26 17:41:32 -0700284 for (const auto& [name, service] : mNameToService) {
285 CHECK(service.binder != nullptr) << name;
286 }
287}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700288
289Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700290 *outBinder = tryGetService(name, true);
291 // returns ok regardless of result for legacy reasons
292 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700293}
294
295Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700296 *outBinder = tryGetService(name, false);
297 // returns ok regardless of result for legacy reasons
298 return Status::ok();
299}
300
301sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700302 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700303
Jon Spivack0d844302019-07-22 18:40:34 -0700304 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700305 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700306 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700307 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700308
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000309 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
310 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700311 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700312 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700313 }
314
Steven Morelanda9fe4742019-07-18 14:45:20 -0700315 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700316 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700317 }
318
Jon Spivack0d844302019-07-22 18:40:34 -0700319 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000320 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700321 }
322
Jon Spivack9f503a42019-10-22 16:49:19 -0700323 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000324 // Force onClients to get sent, and then make sure the timerfd won't clear it
325 // by setting guaranteeClient again. This logic could be simplified by using
326 // a time-based guarantee. However, forcing onClients(true) to get sent
327 // right here is always going to be important for processes serving multiple
328 // lazy interfaces.
329 service->guaranteeClient = true;
330 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700331 service->guaranteeClient = true;
332 }
333
Jon Spivack0d844302019-07-22 18:40:34 -0700334 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700335}
336
Steven Moreland905e2e82019-07-17 11:05:45 -0700337bool isValidServiceName(const std::string& name) {
338 if (name.size() == 0) return false;
339 if (name.size() > 127) return false;
340
341 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700342 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700343 if (c >= 'a' && c <= 'z') continue;
344 if (c >= 'A' && c <= 'Z') continue;
345 if (c >= '0' && c <= '9') continue;
346 return false;
347 }
348
349 return true;
350}
351
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700352Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700353 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700354
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700355 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000356 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700357 }
358
Steven Morelanda9fe4742019-07-18 14:45:20 -0700359 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000360 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700361 }
362
363 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000364 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700365 }
366
Steven Moreland905e2e82019-07-17 11:05:45 -0700367 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000368 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000369 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700370 }
371
Steven Moreland86a17f82019-09-10 10:18:00 -0700372#ifndef VENDORSERVICEMANAGER
373 if (!meetsDeclarationRequirements(binder, name)) {
374 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000375 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700376 }
377#endif // !VENDORSERVICEMANAGER
378
Devin Moore4e21def2023-02-24 21:54:14 +0000379 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
380 ALOGW("Dump flag priority is not set when adding %s", name.c_str());
381 }
382
Steven Moreland88860b02019-08-12 14:24:14 -0700383 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000384 if (binder->remoteBinder() != nullptr &&
385 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Pawan Wagh37526162022-09-29 21:55:26 +0000386 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000387 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700388 }
389
Steven Moreland7ee423b2022-09-24 03:52:08 +0000390 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000391 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000392 if (it != mNameToService.end()) {
393 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000394 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000395
396 // We could do better than this because if the other service dies, it
397 // may not have an entry here. However, this case is unlikely. We are
398 // only trying to detect when two different services are accidentally installed.
399
400 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000401 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
402 "from UID %u. Multiple instances installed?",
403 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000404 }
405
406 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000407 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
408 "from SID %s. Multiple instances installed?",
409 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000410 }
411
Pawan Wagh37526162022-09-29 21:55:26 +0000412 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
413 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
414 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000415 }
416
Devin Moore05ffe522020-08-06 13:58:29 -0700417 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000418 mNameToService[name] = Service{
419 .binder = binder,
420 .allowIsolated = allowIsolated,
421 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000422 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000423 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000424 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700425 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700426
Steven Moreland7ee423b2022-09-24 03:52:08 +0000427 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000428 // If someone is currently waiting on the service, notify the service that
429 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000430 mNameToService[name].guaranteeClient = true;
431 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
432 mNameToService[name].guaranteeClient = true;
433
Steven Moreland27cfab02019-08-12 14:34:16 -0700434 for (const sp<IServiceCallback>& cb : it->second) {
435 // permission checked in registerForNotifications
436 cb->onRegistration(name, binder);
437 }
438 }
439
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700440 return Status::ok();
441}
442
443Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700444 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000445 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700446 }
447
448 size_t toReserve = 0;
449 for (auto const& [name, service] : mNameToService) {
450 (void) name;
451
452 if (service.dumpPriority & dumpPriority) ++toReserve;
453 }
454
455 CHECK(outList->empty());
456
457 outList->reserve(toReserve);
458 for (auto const& [name, service] : mNameToService) {
459 (void) service;
460
461 if (service.dumpPriority & dumpPriority) {
462 outList->push_back(name);
463 }
464 }
465
466 return Status::ok();
467}
468
Steven Moreland27cfab02019-08-12 14:34:16 -0700469Status ServiceManager::registerForNotifications(
470 const std::string& name, const sp<IServiceCallback>& callback) {
471 auto ctx = mAccess->getCallingContext();
472
473 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000474 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
475 }
476
477 // note - we could allow isolated apps to get notifications if we
478 // keep track of isolated callbacks and non-isolated callbacks, but
479 // this is done since isolated apps shouldn't access lazy services
480 // so we should be able to use different APIs to keep things simple.
481 // Here, we disallow everything, because the service might not be
482 // registered yet.
483 if (is_multiuser_uid_isolated(ctx.uid)) {
484 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700485 }
486
487 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000488 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000489 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700490 }
491
492 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000493 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700494 }
495
Steven Morelandb0983182021-04-02 03:14:04 +0000496 if (OK !=
497 IInterface::asBinder(callback)->linkToDeath(
498 sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000499 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000500 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700501 }
502
Jon Spivackf288b1d2019-12-19 17:15:51 -0800503 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700504
505 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
506 const sp<IBinder>& binder = it->second.binder;
507
508 // never null if an entry exists
509 CHECK(binder != nullptr) << name;
510 callback->onRegistration(name, binder);
511 }
512
513 return Status::ok();
514}
515Status ServiceManager::unregisterForNotifications(
516 const std::string& name, const sp<IServiceCallback>& callback) {
517 auto ctx = mAccess->getCallingContext();
518
519 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000520 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700521 }
522
523 bool found = false;
524
Jon Spivackf288b1d2019-12-19 17:15:51 -0800525 auto it = mNameToRegistrationCallback.find(name);
526 if (it != mNameToRegistrationCallback.end()) {
527 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700528 }
529
530 if (!found) {
Pawan Wagh37526162022-09-29 21:55:26 +0000531 ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000532 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700533 }
534
535 return Status::ok();
536}
537
Steven Morelandb82b8f82019-10-28 10:52:34 -0700538Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
539 auto ctx = mAccess->getCallingContext();
540
541 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000542 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700543 }
544
545 *outReturn = false;
546
547#ifndef VENDORSERVICEMANAGER
548 *outReturn = isVintfDeclared(name);
549#endif
550 return Status::ok();
551}
552
Steven Moreland2e293aa2020-09-23 00:25:16 +0000553binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
554 auto ctx = mAccess->getCallingContext();
555
556 std::vector<std::string> allInstances;
557#ifndef VENDORSERVICEMANAGER
558 allInstances = getVintfInstances(interface);
559#endif
560
561 outReturn->clear();
562
563 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000564 if (mAccess->canFind(ctx, interface + "/" + instance)) {
565 outReturn->push_back(instance);
566 }
567 }
568
569 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000570 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000571 }
572
573 return Status::ok();
574}
575
Steven Morelandedd4e072021-04-21 00:27:29 +0000576Status ServiceManager::updatableViaApex(const std::string& name,
577 std::optional<std::string>* outReturn) {
578 auto ctx = mAccess->getCallingContext();
579
580 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000581 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000582 }
583
584 *outReturn = std::nullopt;
585
586#ifndef VENDORSERVICEMANAGER
587 *outReturn = getVintfUpdatableApex(name);
588#endif
589 return Status::ok();
590}
591
Jooyung Han76944fe2022-10-25 17:02:45 +0900592Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
593 std::vector<std::string>* outReturn) {
594 auto ctx = mAccess->getCallingContext();
595
596 std::vector<std::string> apexUpdatableInstances;
597#ifndef VENDORSERVICEMANAGER
598 apexUpdatableInstances = getVintfUpdatableInstances(apexName);
599#endif
600
601 outReturn->clear();
602
603 for (const std::string& instance : apexUpdatableInstances) {
604 if (mAccess->canFind(ctx, instance)) {
605 outReturn->push_back(instance);
606 }
607 }
608
609 if (outReturn->size() == 0 && apexUpdatableInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000610 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900611 }
612
613 return Status::ok();
614}
615
Devin Moore5e4c2f12021-09-09 22:36:33 +0000616Status ServiceManager::getConnectionInfo(const std::string& name,
617 std::optional<ConnectionInfo>* outReturn) {
618 auto ctx = mAccess->getCallingContext();
619
620 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000621 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000622 }
623
624 *outReturn = std::nullopt;
625
626#ifndef VENDORSERVICEMANAGER
627 *outReturn = getVintfConnectionInfo(name);
628#endif
629 return Status::ok();
630}
631
Jon Spivackf288b1d2019-12-19 17:15:51 -0800632void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
633 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700634 bool* found) {
635 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
636
637 for (auto lit = listeners.begin(); lit != listeners.end();) {
638 if (IInterface::asBinder(*lit) == who) {
639 if(found) *found = true;
640 lit = listeners.erase(lit);
641 } else {
642 ++lit;
643 }
644 }
645
646 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800647 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700648 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800649 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700650 }
651}
652
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700653void ServiceManager::binderDied(const wp<IBinder>& who) {
654 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
655 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000656 // TODO: currently, this entry contains the state also
657 // associated with mNameToClientCallback. If we allowed
658 // other processes to register client callbacks, we
659 // would have to preserve hasClients (perhaps moving
660 // that state into mNameToClientCallback, which is complicated
661 // because those callbacks are associated w/ particular binder
662 // objects, though they are indexed by name now, they may
663 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700664 it = mNameToService.erase(it);
665 } else {
666 ++it;
667 }
668 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700669
Jon Spivackf288b1d2019-12-19 17:15:51 -0800670 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
671 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700672 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700673
674 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
675 removeClientCallback(who, &it);
676 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700677}
678
Steven Morelandaa33e852023-05-10 16:42:15 +0000679void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
680 ALOGI("Since '%s' could not be found (requested by debug pid %d), trying to start it as a lazy "
681 "AIDL service. (if it's not configured to be a lazy service, it may be stuck starting or "
682 "still starting).",
683 name.c_str(), ctx.debugPid);
Jon Spivack0d844302019-07-22 18:40:34 -0700684
685 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000686 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000687 ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
688 "this happens when a "
689 "service is not installed, but if the service is intended to be used as a "
690 "lazy service, then it may be configured incorrectly.",
691 name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000692 }
Jon Spivack0d844302019-07-22 18:40:34 -0700693 }).detach();
694}
695
Jon Spivack9f503a42019-10-22 16:49:19 -0700696Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
697 const sp<IClientCallback>& cb) {
698 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000699 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700700 }
701
702 auto ctx = mAccess->getCallingContext();
703 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000704 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700705 }
706
707 auto serviceIt = mNameToService.find(name);
708 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000709 ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000710 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700711 }
712
Steven Moreland7ee423b2022-09-24 03:52:08 +0000713 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000714 ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000715 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
716 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700717 }
718
719 if (serviceIt->second.binder != service) {
Pawan Wagh37526162022-09-29 21:55:26 +0000720 ALOGW("Tried to register client callback for %s but a different service is registered "
721 "under this name.",
722 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000723 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700724 }
725
Steven Morelandb0983182021-04-02 03:14:04 +0000726 if (OK !=
727 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000728 ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000729 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700730 }
731
Steven Moreland79578672023-04-27 19:38:00 +0000732 // WARNING: binderDied makes an assumption about this. If we open up client
733 // callbacks to other services, certain race conditions may lead to services
734 // getting extra client callback notifications.
735 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000736 if (serviceIt->second.hasClients) {
737 cb->onClients(service, true);
738 }
739
Jon Spivack9f503a42019-10-22 16:49:19 -0700740 mNameToClientCallback[name].push_back(cb);
741
Steven Morelandefea66b2023-06-17 01:59:34 +0000742 // Flush updated info to client callbacks (especially if guaranteeClient
743 // and !hasClient, see b/285202885). We may or may not have clients at
744 // this point, so ignore the return value.
745 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
746
Jon Spivack9f503a42019-10-22 16:49:19 -0700747 return Status::ok();
748}
749
750void ServiceManager::removeClientCallback(const wp<IBinder>& who,
751 ClientCallbackMap::iterator* it) {
752 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
753
754 for (auto lit = listeners.begin(); lit != listeners.end();) {
755 if (IInterface::asBinder(*lit) == who) {
756 lit = listeners.erase(lit);
757 } else {
758 ++lit;
759 }
760 }
761
762 if (listeners.empty()) {
763 *it = mNameToClientCallback.erase(*it);
764 } else {
765 (*it)++;
766 }
767}
768
769ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000770 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700771 if (bpBinder == nullptr) return -1;
772
Steven Morelande8393882020-12-18 02:27:20 +0000773 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700774}
775
776void ServiceManager::handleClientCallbacks() {
777 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000778 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700779 }
780}
781
Steven Morelandb8361902023-02-01 23:18:04 +0000782bool ServiceManager::handleServiceClientCallback(size_t knownClients,
783 const std::string& serviceName,
784 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700785 auto serviceIt = mNameToService.find(serviceName);
786 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000787 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700788 }
789
790 Service& service = serviceIt->second;
791 ssize_t count = service.getNodeStrongRefCount();
792
Steven Morelandb8361902023-02-01 23:18:04 +0000793 // binder driver doesn't support this feature, consider we have clients
794 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700795
Steven Morelandb8361902023-02-01 23:18:04 +0000796 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700797
798 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000799 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000800 sendClientCallbackNotifications(serviceName, true,
801 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700802 }
803
804 // guarantee is temporary
805 service.guaranteeClient = false;
806 }
807
Steven Morelandb8361902023-02-01 23:18:04 +0000808 // Regardless of this situation, we want to give this notification as soon as possible.
809 // This way, we have a chance of preventing further thrashing.
810 if (hasKernelReportedClients && !service.hasClients) {
811 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
812 }
Steven Moreland66417652023-02-01 22:19:41 +0000813
Steven Morelandb8361902023-02-01 23:18:04 +0000814 // But limit rate of shutting down service.
815 if (isCalledOnInterval) {
816 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000817 sendClientCallbackNotifications(serviceName, false,
818 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000819 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700820 }
821
Steven Morelandb8361902023-02-01 23:18:04 +0000822 // May be different than 'hasKernelReportedClients'. We intentionally delay
823 // information about clients going away to reduce thrashing.
824 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700825}
826
Steven Moreland3e083b22023-01-26 00:46:30 +0000827void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
828 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700829 auto serviceIt = mNameToService.find(serviceName);
830 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000831 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
832 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700833 return;
834 }
835 Service& service = serviceIt->second;
836
Steven Morelandb8361902023-02-01 23:18:04 +0000837 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700838
Steven Morelandb8361902023-02-01 23:18:04 +0000839 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
840 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700841
842 auto ccIt = mNameToClientCallback.find(serviceName);
843 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000844 << "sendClientCallbackNotifications could not find callbacks for service when "
845 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700846
847 for (const auto& callback : ccIt->second) {
848 callback->onClients(service.binder, hasClients);
849 }
850
851 service.hasClients = hasClients;
852}
853
854Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
855 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000856 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700857 }
858
859 auto ctx = mAccess->getCallingContext();
860 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000861 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700862 }
863
864 auto serviceIt = mNameToService.find(name);
865 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000866 ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
867 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000868 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700869 }
870
Steven Moreland7ee423b2022-09-24 03:52:08 +0000871 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000872 ALOGW("Only a server can unregister itself (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000873 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
874 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700875 }
876
877 sp<IBinder> storedBinder = serviceIt->second.binder;
878
879 if (binder != storedBinder) {
Pawan Wagh37526162022-09-29 21:55:26 +0000880 ALOGW("Tried to unregister %s, but a different service is registered under this name.",
881 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000882 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
883 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700884 }
885
Steven Morelandb8361902023-02-01 23:18:04 +0000886 // important because we don't have timer-based guarantees, we don't want to clear
887 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700888 if (serviceIt->second.guaranteeClient) {
Pawan Wagh37526162022-09-29 21:55:26 +0000889 ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000890 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
891 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700892 }
893
Jon Spivack9f503a42019-10-22 16:49:19 -0700894 // - kernel driver will hold onto one refcount (during this transaction)
895 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000896 constexpr size_t kKnownClients = 2;
897
898 if (handleServiceClientCallback(kKnownClients, name, false)) {
899 ALOGI("Tried to unregister %s, but there are clients.", name.c_str());
900
901 // Since we had a failed registration attempt, and the HIDL implementation of
902 // delaying service shutdown for multiple periods wasn't ported here... this may
903 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800904 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000905
Steven Morelandffb905b2023-03-28 18:24:37 +0000906 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
907 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700908 }
909
Steven Morelandb8361902023-02-01 23:18:04 +0000910 ALOGI("Unregistering %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700911 mNameToService.erase(name);
912
913 return Status::ok();
914}
915
Steven Moreland3ea43272021-01-28 22:49:28 +0000916Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
917 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000918 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +0000919 }
920
921 outReturn->reserve(mNameToService.size());
922 for (auto const& [name, service] : mNameToService) {
923 ServiceDebugInfo info;
924 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000925 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000926
927 outReturn->push_back(std::move(info));
928 }
929
930 return Status::ok();
931}
932
Pawan Wagh243888e2022-09-20 19:37:35 +0000933void ServiceManager::clear() {
934 mNameToService.clear();
935 mNameToRegistrationCallback.clear();
936 mNameToClientCallback.clear();
937}
938
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700939} // namespace android