blob: facb8b133bc80f7e85412269e6e7119162609558 [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 Moreland86a17f82019-09-10 10:18:00 -070043#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080044
Steven Moreland2e293aa2020-09-23 00:25:16 +000045struct ManifestWithDescription {
46 std::shared_ptr<const vintf::HalManifest> manifest;
47 const char* description;
48};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080049static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
50#ifdef __ANDROID_RECOVERY__
51 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
52 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000053 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080054 return {};
55 }
56 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
57#else
58 auto vintfObject = vintf::VintfObject::GetInstance();
59 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000060 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080061 return {};
62 }
63 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
64 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
65#endif
66}
67
Steven Moreland2e293aa2020-09-23 00:25:16 +000068// func true -> stop search and forEachManifest will return true
69static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080070 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000071 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000072 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
73 // note, we explicitly do not retry here, so that we can detect VINTF
74 // or other bugs (b/151696835)
75 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +000076 }
77 if (func(mwd)) return true;
78 }
79 return false;
80}
81
Steven Morelandedd4e072021-04-21 00:27:29 +000082struct AidlName {
83 std::string package;
84 std::string iface;
85 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070086
Steven Morelandedd4e072021-04-21 00:27:29 +000087 static bool fill(const std::string& name, AidlName* aname) {
88 size_t firstSlash = name.find('/');
89 size_t lastDot = name.rfind('.', firstSlash);
90 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +000091 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
92 "some.package.foo.IFoo/default) but got: %s",
93 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +000094 return false;
95 }
96 aname->package = name.substr(0, lastDot);
97 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
98 aname->instance = name.substr(firstSlash + 1);
99 return true;
100 }
101};
102
103static bool isVintfDeclared(const std::string& name) {
104 AidlName aname;
105 if (!AidlName::fill(name, &aname)) return false;
106
107 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
108 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000109 ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000110 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700111 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000112 return false; // continue
113 });
114
115 if (!found) {
Devin Moore42407bc2023-09-26 21:30:39 +0000116 std::set<std::string> instances;
117 forEachManifest([&](const ManifestWithDescription& mwd) {
118 std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
119 instances.insert(res.begin(), res.end());
120 return true;
121 });
122
123 std::string available;
124 if (instances.empty()) {
125 available = "No alternative instances declared in VINTF";
126 } else {
127 // for logging only. We can't return this information to the client
128 // because they may not have permissions to find or list those
129 // instances
130 available = "VINTF declared instances: " + base::Join(instances, ", ");
131 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000132 // Although it is tested, explicitly rebuilding qualified name, in case it
133 // becomes something unexpected.
Devin Moore42407bc2023-09-26 21:30:39 +0000134 ALOGI("Could not find %s.%s/%s in the VINTF manifest. %s.", aname.package.c_str(),
135 aname.iface.c_str(), aname.instance.c_str(), available.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700136 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700137
Steven Moreland2e293aa2020-09-23 00:25:16 +0000138 return found;
139}
140
Steven Morelandedd4e072021-04-21 00:27:29 +0000141static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
142 AidlName aname;
143 if (!AidlName::fill(name, &aname)) return std::nullopt;
144
145 std::optional<std::string> updatableViaApex;
146
147 forEachManifest([&](const ManifestWithDescription& mwd) {
148 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
149 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
150 if (manifestInstance.package() != aname.package) return true;
151 if (manifestInstance.interface() != aname.iface) return true;
152 if (manifestInstance.instance() != aname.instance) return true;
153 updatableViaApex = manifestInstance.updatableViaApex();
154 return false; // break (libvintf uses opposite convention)
155 });
Jooyung Hance94b752022-11-14 18:55:06 +0900156 if (updatableViaApex.has_value()) return true; // break (found match)
Steven Morelandedd4e072021-04-21 00:27:29 +0000157 return false; // continue
158 });
159
160 return updatableViaApex;
161}
162
Jooyung Han76944fe2022-10-25 17:02:45 +0900163static std::vector<std::string> getVintfUpdatableInstances(const std::string& apexName) {
164 std::vector<std::string> instances;
165
166 forEachManifest([&](const ManifestWithDescription& mwd) {
167 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
168 if (manifestInstance.format() == vintf::HalFormat::AIDL &&
169 manifestInstance.updatableViaApex().has_value() &&
170 manifestInstance.updatableViaApex().value() == apexName) {
171 std::string aname = manifestInstance.package() + "." +
172 manifestInstance.interface() + "/" + manifestInstance.instance();
173 instances.push_back(aname);
174 }
Jooyung Hance94b752022-11-14 18:55:06 +0900175 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900176 });
177 return false; // continue
178 });
179
180 return instances;
181}
182
Devin Moore5e4c2f12021-09-09 22:36:33 +0000183static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
184 AidlName aname;
185 if (!AidlName::fill(name, &aname)) return std::nullopt;
186
187 std::optional<std::string> ip;
188 std::optional<uint64_t> port;
189 forEachManifest([&](const ManifestWithDescription& mwd) {
190 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
191 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
192 if (manifestInstance.package() != aname.package) return true;
193 if (manifestInstance.interface() != aname.iface) return true;
194 if (manifestInstance.instance() != aname.instance) return true;
195 ip = manifestInstance.ip();
196 port = manifestInstance.port();
197 return false; // break (libvintf uses opposite convention)
198 });
199 return false; // continue
200 });
201
202 if (ip.has_value() && port.has_value()) {
203 ConnectionInfo info;
204 info.ipAddress = *ip;
205 info.port = *port;
206 return std::make_optional<ConnectionInfo>(info);
207 } else {
208 return std::nullopt;
209 }
210}
211
Steven Moreland2e293aa2020-09-23 00:25:16 +0000212static std::vector<std::string> getVintfInstances(const std::string& interface) {
213 size_t lastDot = interface.rfind('.');
214 if (lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000215 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
216 "but got: %s",
217 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000218 return {};
219 }
220 const std::string package = interface.substr(0, lastDot);
221 const std::string iface = interface.substr(lastDot+1);
222
223 std::vector<std::string> ret;
224 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
225 auto instances = mwd.manifest->getAidlInstances(package, iface);
226 ret.insert(ret.end(), instances.begin(), instances.end());
227 return false; // continue
228 });
229
230 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700231}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700232
233static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
234 if (!Stability::requiresVintfDeclaration(binder)) {
235 return true;
236 }
237
238 return isVintfDeclared(name);
239}
Steven Moreland86a17f82019-09-10 10:18:00 -0700240#endif // !VENDORSERVICEMANAGER
241
Steven Morelandb8361902023-02-01 23:18:04 +0000242ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000243 if (hasClients) {
244 // only expected to happen on process death, we don't store the service
245 // name this late (it's in the map that holds this service), but if it
246 // is happening, we might want to change 'unlinkToDeath' to explicitly
247 // clear this bit so that we can abort in other cases, where it would
248 // mean inconsistent logic in servicemanager (unexpected and tested, but
249 // the original lazy service impl here had that bug).
Steven Morelandb8361902023-02-01 23:18:04 +0000250 LOG(WARNING) << "a service was removed when there are clients";
251 }
252}
253
Steven Morelandd13f08b2019-11-18 14:23:09 -0800254ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700255// TODO(b/151696835): reenable performance hack when we solve bug, since with
256// this hack and other fixes, it is unlikely we will see even an ephemeral
257// failure when the manifest parse fails. The goal is that the manifest will
258// be read incorrectly and cause the process trying to register a HAL to
259// fail. If this is in fact an early boot kernel contention issue, then we
260// will get no failure, and by its absence, be signalled to invest more
261// effort in re-adding this performance hack.
262// #ifndef VENDORSERVICEMANAGER
263// // can process these at any times, don't want to delay first VINTF client
264// std::thread([] {
265// vintf::VintfObject::GetDeviceHalManifest();
266// vintf::VintfObject::GetFrameworkHalManifest();
267// }).detach();
268// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800269}
Steven Moreland130242d2019-08-26 17:41:32 -0700270ServiceManager::~ServiceManager() {
271 // this should only happen in tests
272
Jon Spivackf288b1d2019-12-19 17:15:51 -0800273 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700274 CHECK(!callbacks.empty()) << name;
275 for (const auto& callback : callbacks) {
276 CHECK(callback != nullptr) << name;
277 }
278 }
279
Steven Moreland130242d2019-08-26 17:41:32 -0700280 for (const auto& [name, service] : mNameToService) {
281 CHECK(service.binder != nullptr) << name;
282 }
283}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700284
285Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700286 *outBinder = tryGetService(name, true);
287 // returns ok regardless of result for legacy reasons
288 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700289}
290
291Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700292 *outBinder = tryGetService(name, false);
293 // returns ok regardless of result for legacy reasons
294 return Status::ok();
295}
296
297sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700298 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700299
Jon Spivack0d844302019-07-22 18:40:34 -0700300 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700301 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700302 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700303 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700304
Jon Spivack9f503a42019-10-22 16:49:19 -0700305 if (!service->allowIsolated) {
Jon Spivack0d844302019-07-22 18:40:34 -0700306 uid_t appid = multiuser_get_app_id(ctx.uid);
307 bool isIsolated = appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700308
Jon Spivack0d844302019-07-22 18:40:34 -0700309 if (isIsolated) {
310 return nullptr;
311 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700312 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700313 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700314 }
315
Steven Morelanda9fe4742019-07-18 14:45:20 -0700316 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700317 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700318 }
319
Jon Spivack0d844302019-07-22 18:40:34 -0700320 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000321 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700322 }
323
Jon Spivack9f503a42019-10-22 16:49:19 -0700324 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000325 // Force onClients to get sent, and then make sure the timerfd won't clear it
326 // by setting guaranteeClient again. This logic could be simplified by using
327 // a time-based guarantee. However, forcing onClients(true) to get sent
328 // right here is always going to be important for processes serving multiple
329 // lazy interfaces.
330 service->guaranteeClient = true;
331 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700332 service->guaranteeClient = true;
333 }
334
Jon Spivack0d844302019-07-22 18:40:34 -0700335 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700336}
337
Steven Moreland905e2e82019-07-17 11:05:45 -0700338bool isValidServiceName(const std::string& name) {
339 if (name.size() == 0) return false;
340 if (name.size() > 127) return false;
341
342 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700343 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700344 if (c >= 'a' && c <= 'z') continue;
345 if (c >= 'A' && c <= 'Z') continue;
346 if (c >= '0' && c <= '9') continue;
347 return false;
348 }
349
350 return true;
351}
352
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700353Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700354 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700355
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700356 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000357 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700358 }
359
Steven Morelanda9fe4742019-07-18 14:45:20 -0700360 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000361 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700362 }
363
364 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000365 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700366 }
367
Steven Moreland905e2e82019-07-17 11:05:45 -0700368 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000369 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000370 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700371 }
372
Steven Moreland86a17f82019-09-10 10:18:00 -0700373#ifndef VENDORSERVICEMANAGER
374 if (!meetsDeclarationRequirements(binder, name)) {
375 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000376 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700377 }
378#endif // !VENDORSERVICEMANAGER
379
Devin Moore4e21def2023-02-24 21:54:14 +0000380 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
381 ALOGW("Dump flag priority is not set when adding %s", name.c_str());
382 }
383
Steven Moreland88860b02019-08-12 14:24:14 -0700384 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000385 if (binder->remoteBinder() != nullptr &&
386 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Pawan Wagh37526162022-09-29 21:55:26 +0000387 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000388 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700389 }
390
Steven Moreland7ee423b2022-09-24 03:52:08 +0000391 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000392 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000393 if (it != mNameToService.end()) {
394 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000395 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000396
397 // We could do better than this because if the other service dies, it
398 // may not have an entry here. However, this case is unlikely. We are
399 // only trying to detect when two different services are accidentally installed.
400
401 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000402 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
403 "from UID %u. Multiple instances installed?",
404 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000405 }
406
407 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000408 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
409 "from SID %s. Multiple instances installed?",
410 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000411 }
412
Pawan Wagh37526162022-09-29 21:55:26 +0000413 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
414 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
415 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000416 }
417
Devin Moore05ffe522020-08-06 13:58:29 -0700418 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000419 mNameToService[name] = Service{
420 .binder = binder,
421 .allowIsolated = allowIsolated,
422 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000423 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000424 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000425 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700426 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700427
Steven Moreland7ee423b2022-09-24 03:52:08 +0000428 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000429 // If someone is currently waiting on the service, notify the service that
430 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000431 mNameToService[name].guaranteeClient = true;
432 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
433 mNameToService[name].guaranteeClient = true;
434
Steven Moreland27cfab02019-08-12 14:34:16 -0700435 for (const sp<IServiceCallback>& cb : it->second) {
436 // permission checked in registerForNotifications
437 cb->onRegistration(name, binder);
438 }
439 }
440
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700441 return Status::ok();
442}
443
444Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700445 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000446 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700447 }
448
449 size_t toReserve = 0;
450 for (auto const& [name, service] : mNameToService) {
451 (void) name;
452
453 if (service.dumpPriority & dumpPriority) ++toReserve;
454 }
455
456 CHECK(outList->empty());
457
458 outList->reserve(toReserve);
459 for (auto const& [name, service] : mNameToService) {
460 (void) service;
461
462 if (service.dumpPriority & dumpPriority) {
463 outList->push_back(name);
464 }
465 }
466
467 return Status::ok();
468}
469
Steven Moreland27cfab02019-08-12 14:34:16 -0700470Status ServiceManager::registerForNotifications(
471 const std::string& name, const sp<IServiceCallback>& callback) {
472 auto ctx = mAccess->getCallingContext();
473
474 if (!mAccess->canFind(ctx, name)) {
475 return Status::fromExceptionCode(Status::EX_SECURITY);
476 }
477
478 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000479 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000480 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700481 }
482
483 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000484 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700485 }
486
Steven Morelandb0983182021-04-02 03:14:04 +0000487 if (OK !=
488 IInterface::asBinder(callback)->linkToDeath(
489 sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000490 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000491 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700492 }
493
Jon Spivackf288b1d2019-12-19 17:15:51 -0800494 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700495
496 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
497 const sp<IBinder>& binder = it->second.binder;
498
499 // never null if an entry exists
500 CHECK(binder != nullptr) << name;
501 callback->onRegistration(name, binder);
502 }
503
504 return Status::ok();
505}
506Status ServiceManager::unregisterForNotifications(
507 const std::string& name, const sp<IServiceCallback>& callback) {
508 auto ctx = mAccess->getCallingContext();
509
510 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000511 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700512 }
513
514 bool found = false;
515
Jon Spivackf288b1d2019-12-19 17:15:51 -0800516 auto it = mNameToRegistrationCallback.find(name);
517 if (it != mNameToRegistrationCallback.end()) {
518 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700519 }
520
521 if (!found) {
Pawan Wagh37526162022-09-29 21:55:26 +0000522 ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000523 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700524 }
525
526 return Status::ok();
527}
528
Steven Morelandb82b8f82019-10-28 10:52:34 -0700529Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
530 auto ctx = mAccess->getCallingContext();
531
532 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000533 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700534 }
535
536 *outReturn = false;
537
538#ifndef VENDORSERVICEMANAGER
539 *outReturn = isVintfDeclared(name);
540#endif
541 return Status::ok();
542}
543
Steven Moreland2e293aa2020-09-23 00:25:16 +0000544binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
545 auto ctx = mAccess->getCallingContext();
546
547 std::vector<std::string> allInstances;
548#ifndef VENDORSERVICEMANAGER
549 allInstances = getVintfInstances(interface);
550#endif
551
552 outReturn->clear();
553
554 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000555 if (mAccess->canFind(ctx, interface + "/" + instance)) {
556 outReturn->push_back(instance);
557 }
558 }
559
560 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000561 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000562 }
563
564 return Status::ok();
565}
566
Steven Morelandedd4e072021-04-21 00:27:29 +0000567Status ServiceManager::updatableViaApex(const std::string& name,
568 std::optional<std::string>* outReturn) {
569 auto ctx = mAccess->getCallingContext();
570
571 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000572 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000573 }
574
575 *outReturn = std::nullopt;
576
577#ifndef VENDORSERVICEMANAGER
578 *outReturn = getVintfUpdatableApex(name);
579#endif
580 return Status::ok();
581}
582
Jooyung Han76944fe2022-10-25 17:02:45 +0900583Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
584 std::vector<std::string>* outReturn) {
585 auto ctx = mAccess->getCallingContext();
586
587 std::vector<std::string> apexUpdatableInstances;
588#ifndef VENDORSERVICEMANAGER
589 apexUpdatableInstances = getVintfUpdatableInstances(apexName);
590#endif
591
592 outReturn->clear();
593
594 for (const std::string& instance : apexUpdatableInstances) {
595 if (mAccess->canFind(ctx, instance)) {
596 outReturn->push_back(instance);
597 }
598 }
599
600 if (outReturn->size() == 0 && apexUpdatableInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000601 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900602 }
603
604 return Status::ok();
605}
606
Devin Moore5e4c2f12021-09-09 22:36:33 +0000607Status ServiceManager::getConnectionInfo(const std::string& name,
608 std::optional<ConnectionInfo>* outReturn) {
609 auto ctx = mAccess->getCallingContext();
610
611 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000612 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000613 }
614
615 *outReturn = std::nullopt;
616
617#ifndef VENDORSERVICEMANAGER
618 *outReturn = getVintfConnectionInfo(name);
619#endif
620 return Status::ok();
621}
622
Jon Spivackf288b1d2019-12-19 17:15:51 -0800623void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
624 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700625 bool* found) {
626 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
627
628 for (auto lit = listeners.begin(); lit != listeners.end();) {
629 if (IInterface::asBinder(*lit) == who) {
630 if(found) *found = true;
631 lit = listeners.erase(lit);
632 } else {
633 ++lit;
634 }
635 }
636
637 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800638 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700639 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800640 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700641 }
642}
643
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700644void ServiceManager::binderDied(const wp<IBinder>& who) {
645 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
646 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000647 // TODO: currently, this entry contains the state also
648 // associated with mNameToClientCallback. If we allowed
649 // other processes to register client callbacks, we
650 // would have to preserve hasClients (perhaps moving
651 // that state into mNameToClientCallback, which is complicated
652 // because those callbacks are associated w/ particular binder
653 // objects, though they are indexed by name now, they may
654 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700655 it = mNameToService.erase(it);
656 } else {
657 ++it;
658 }
659 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700660
Jon Spivackf288b1d2019-12-19 17:15:51 -0800661 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
662 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700663 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700664
665 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
666 removeClientCallback(who, &it);
667 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700668}
669
Steven Morelandaa33e852023-05-10 16:42:15 +0000670void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
671 ALOGI("Since '%s' could not be found (requested by debug pid %d), trying to start it as a lazy "
672 "AIDL service. (if it's not configured to be a lazy service, it may be stuck starting or "
673 "still starting).",
674 name.c_str(), ctx.debugPid);
Jon Spivack0d844302019-07-22 18:40:34 -0700675
676 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000677 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000678 ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
679 "this happens when a "
680 "service is not installed, but if the service is intended to be used as a "
681 "lazy service, then it may be configured incorrectly.",
682 name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000683 }
Jon Spivack0d844302019-07-22 18:40:34 -0700684 }).detach();
685}
686
Jon Spivack9f503a42019-10-22 16:49:19 -0700687Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
688 const sp<IClientCallback>& cb) {
689 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000690 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700691 }
692
693 auto ctx = mAccess->getCallingContext();
694 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000695 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700696 }
697
698 auto serviceIt = mNameToService.find(name);
699 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000700 ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000701 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700702 }
703
Steven Moreland7ee423b2022-09-24 03:52:08 +0000704 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000705 ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000706 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
707 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700708 }
709
710 if (serviceIt->second.binder != service) {
Pawan Wagh37526162022-09-29 21:55:26 +0000711 ALOGW("Tried to register client callback for %s but a different service is registered "
712 "under this name.",
713 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000714 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700715 }
716
Steven Morelandb0983182021-04-02 03:14:04 +0000717 if (OK !=
718 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000719 ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000720 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700721 }
722
Steven Moreland79578672023-04-27 19:38:00 +0000723 // WARNING: binderDied makes an assumption about this. If we open up client
724 // callbacks to other services, certain race conditions may lead to services
725 // getting extra client callback notifications.
726 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000727 if (serviceIt->second.hasClients) {
728 cb->onClients(service, true);
729 }
730
Jon Spivack9f503a42019-10-22 16:49:19 -0700731 mNameToClientCallback[name].push_back(cb);
732
Steven Morelandefea66b2023-06-17 01:59:34 +0000733 // Flush updated info to client callbacks (especially if guaranteeClient
734 // and !hasClient, see b/285202885). We may or may not have clients at
735 // this point, so ignore the return value.
736 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
737
Jon Spivack9f503a42019-10-22 16:49:19 -0700738 return Status::ok();
739}
740
741void ServiceManager::removeClientCallback(const wp<IBinder>& who,
742 ClientCallbackMap::iterator* it) {
743 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
744
745 for (auto lit = listeners.begin(); lit != listeners.end();) {
746 if (IInterface::asBinder(*lit) == who) {
747 lit = listeners.erase(lit);
748 } else {
749 ++lit;
750 }
751 }
752
753 if (listeners.empty()) {
754 *it = mNameToClientCallback.erase(*it);
755 } else {
756 (*it)++;
757 }
758}
759
760ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000761 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700762 if (bpBinder == nullptr) return -1;
763
Steven Morelande8393882020-12-18 02:27:20 +0000764 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700765}
766
767void ServiceManager::handleClientCallbacks() {
768 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000769 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700770 }
771}
772
Steven Morelandb8361902023-02-01 23:18:04 +0000773bool ServiceManager::handleServiceClientCallback(size_t knownClients,
774 const std::string& serviceName,
775 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700776 auto serviceIt = mNameToService.find(serviceName);
777 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000778 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700779 }
780
781 Service& service = serviceIt->second;
782 ssize_t count = service.getNodeStrongRefCount();
783
Steven Morelandb8361902023-02-01 23:18:04 +0000784 // binder driver doesn't support this feature, consider we have clients
785 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700786
Steven Morelandb8361902023-02-01 23:18:04 +0000787 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700788
789 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000790 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000791 sendClientCallbackNotifications(serviceName, true,
792 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700793 }
794
795 // guarantee is temporary
796 service.guaranteeClient = false;
797 }
798
Steven Morelandb8361902023-02-01 23:18:04 +0000799 // Regardless of this situation, we want to give this notification as soon as possible.
800 // This way, we have a chance of preventing further thrashing.
801 if (hasKernelReportedClients && !service.hasClients) {
802 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
803 }
Steven Moreland66417652023-02-01 22:19:41 +0000804
Steven Morelandb8361902023-02-01 23:18:04 +0000805 // But limit rate of shutting down service.
806 if (isCalledOnInterval) {
807 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000808 sendClientCallbackNotifications(serviceName, false,
809 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000810 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700811 }
812
Steven Morelandb8361902023-02-01 23:18:04 +0000813 // May be different than 'hasKernelReportedClients'. We intentionally delay
814 // information about clients going away to reduce thrashing.
815 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700816}
817
Steven Moreland3e083b22023-01-26 00:46:30 +0000818void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
819 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700820 auto serviceIt = mNameToService.find(serviceName);
821 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000822 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
823 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700824 return;
825 }
826 Service& service = serviceIt->second;
827
Steven Morelandb8361902023-02-01 23:18:04 +0000828 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700829
Steven Morelandb8361902023-02-01 23:18:04 +0000830 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
831 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700832
833 auto ccIt = mNameToClientCallback.find(serviceName);
834 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000835 << "sendClientCallbackNotifications could not find callbacks for service when "
836 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700837
838 for (const auto& callback : ccIt->second) {
839 callback->onClients(service.binder, hasClients);
840 }
841
842 service.hasClients = hasClients;
843}
844
845Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
846 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000847 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700848 }
849
850 auto ctx = mAccess->getCallingContext();
851 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000852 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700853 }
854
855 auto serviceIt = mNameToService.find(name);
856 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000857 ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
858 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000859 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700860 }
861
Steven Moreland7ee423b2022-09-24 03:52:08 +0000862 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000863 ALOGW("Only a server can unregister itself (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000864 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
865 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700866 }
867
868 sp<IBinder> storedBinder = serviceIt->second.binder;
869
870 if (binder != storedBinder) {
Pawan Wagh37526162022-09-29 21:55:26 +0000871 ALOGW("Tried to unregister %s, but a different service is registered under this name.",
872 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000873 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
874 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700875 }
876
Steven Morelandb8361902023-02-01 23:18:04 +0000877 // important because we don't have timer-based guarantees, we don't want to clear
878 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700879 if (serviceIt->second.guaranteeClient) {
Pawan Wagh37526162022-09-29 21:55:26 +0000880 ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000881 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
882 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700883 }
884
Jon Spivack9f503a42019-10-22 16:49:19 -0700885 // - kernel driver will hold onto one refcount (during this transaction)
886 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000887 constexpr size_t kKnownClients = 2;
888
889 if (handleServiceClientCallback(kKnownClients, name, false)) {
890 ALOGI("Tried to unregister %s, but there are clients.", name.c_str());
891
892 // Since we had a failed registration attempt, and the HIDL implementation of
893 // delaying service shutdown for multiple periods wasn't ported here... this may
894 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800895 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000896
Steven Morelandffb905b2023-03-28 18:24:37 +0000897 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
898 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700899 }
900
Steven Morelandb8361902023-02-01 23:18:04 +0000901 ALOGI("Unregistering %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700902 mNameToService.erase(name);
903
904 return Status::ok();
905}
906
Steven Moreland3ea43272021-01-28 22:49:28 +0000907Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
908 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000909 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +0000910 }
911
912 outReturn->reserve(mNameToService.size());
913 for (auto const& [name, service] : mNameToService) {
914 ServiceDebugInfo info;
915 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000916 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000917
918 outReturn->push_back(std::move(info));
919 }
920
921 return Status::ok();
922}
923
Pawan Wagh243888e2022-09-20 19:37:35 +0000924void ServiceManager::clear() {
925 mNameToService.clear();
926 mNameToRegistrationCallback.clear();
927 mNameToClientCallback.clear();
928}
929
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700930} // namespace android