blob: bf85e61583538a6d52e76966d4265207fcdec648 [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
Jooyung Han205e2822023-12-19 16:59:39 +090038#include "NameUtil.h"
39
Steven Moreland80e1e6d2019-06-21 12:35:59 -070040using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070041using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070042
43namespace android {
44
Steven Morelandb9e1cbe2023-02-01 22:44:45 +000045bool is_multiuser_uid_isolated(uid_t uid) {
46 uid_t appid = multiuser_get_app_id(uid);
47 return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
48}
49
Steven Moreland86a17f82019-09-10 10:18:00 -070050#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080051
Steven Moreland2e293aa2020-09-23 00:25:16 +000052struct ManifestWithDescription {
53 std::shared_ptr<const vintf::HalManifest> manifest;
54 const char* description;
55};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080056static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
57#ifdef __ANDROID_RECOVERY__
58 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
59 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000060 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080061 return {};
62 }
63 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
64#else
65 auto vintfObject = vintf::VintfObject::GetInstance();
66 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000067 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080068 return {};
69 }
70 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
71 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
72#endif
73}
74
Steven Moreland2e293aa2020-09-23 00:25:16 +000075// func true -> stop search and forEachManifest will return true
76static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080077 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000078 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000079 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
80 // note, we explicitly do not retry here, so that we can detect VINTF
81 // or other bugs (b/151696835)
82 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +000083 }
84 if (func(mwd)) return true;
85 }
86 return false;
87}
88
Jooyung Han205e2822023-12-19 16:59:39 +090089static std::string getNativeInstanceName(const vintf::ManifestInstance& instance) {
90 return instance.package() + "/" + instance.instance();
91}
92
Steven Morelandedd4e072021-04-21 00:27:29 +000093struct AidlName {
94 std::string package;
95 std::string iface;
96 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070097
Steven Morelandedd4e072021-04-21 00:27:29 +000098 static bool fill(const std::string& name, AidlName* aname) {
99 size_t firstSlash = name.find('/');
100 size_t lastDot = name.rfind('.', firstSlash);
101 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000102 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
103 "some.package.foo.IFoo/default) but got: %s",
104 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000105 return false;
106 }
107 aname->package = name.substr(0, lastDot);
108 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
109 aname->instance = name.substr(firstSlash + 1);
110 return true;
111 }
112};
113
Jooyung Han205e2822023-12-19 16:59:39 +0900114static std::string getAidlInstanceName(const vintf::ManifestInstance& instance) {
115 return instance.package() + "." + instance.interface() + "/" + instance.instance();
116}
117
Steven Morelandedd4e072021-04-21 00:27:29 +0000118static bool isVintfDeclared(const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900119 NativeName nname;
120 if (NativeName::fill(name, &nname)) {
121 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
122 if (mwd.manifest->hasNativeInstance(nname.package, nname.instance)) {
123 ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
124 return true; // break
125 }
126 return false; // continue
127 });
128 if (!found) {
129 ALOGI("Could not find %s in the VINTF manifest.", name.c_str());
130 }
131 return found;
132 }
133
Steven Morelandedd4e072021-04-21 00:27:29 +0000134 AidlName aname;
135 if (!AidlName::fill(name, &aname)) return false;
136
137 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
138 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000139 ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000140 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700141 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000142 return false; // continue
143 });
144
145 if (!found) {
Devin Moore42407bc2023-09-26 21:30:39 +0000146 std::set<std::string> instances;
147 forEachManifest([&](const ManifestWithDescription& mwd) {
148 std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
149 instances.insert(res.begin(), res.end());
150 return true;
151 });
152
153 std::string available;
154 if (instances.empty()) {
155 available = "No alternative instances declared in VINTF";
156 } else {
157 // for logging only. We can't return this information to the client
158 // because they may not have permissions to find or list those
159 // instances
160 available = "VINTF declared instances: " + base::Join(instances, ", ");
161 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000162 // Although it is tested, explicitly rebuilding qualified name, in case it
163 // becomes something unexpected.
Devin Moore42407bc2023-09-26 21:30:39 +0000164 ALOGI("Could not find %s.%s/%s in the VINTF manifest. %s.", aname.package.c_str(),
165 aname.iface.c_str(), aname.instance.c_str(), available.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700166 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700167
Steven Moreland2e293aa2020-09-23 00:25:16 +0000168 return found;
169}
170
Steven Morelandedd4e072021-04-21 00:27:29 +0000171static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900172 NativeName nname;
173 if (NativeName::fill(name, &nname)) {
174 std::optional<std::string> updatableViaApex;
175
176 forEachManifest([&](const ManifestWithDescription& mwd) {
177 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
178 if (manifestInstance.format() != vintf::HalFormat::NATIVE) return true;
179 if (manifestInstance.package() != nname.package) return true;
180 if (manifestInstance.instance() != nname.instance) return true;
181 updatableViaApex = manifestInstance.updatableViaApex();
182 return false; // break (libvintf uses opposite convention)
183 });
184 return !cont;
185 });
186
187 return updatableViaApex;
188 }
189
Steven Morelandedd4e072021-04-21 00:27:29 +0000190 AidlName aname;
191 if (!AidlName::fill(name, &aname)) return std::nullopt;
192
193 std::optional<std::string> updatableViaApex;
194
195 forEachManifest([&](const ManifestWithDescription& mwd) {
Jooyung Han9f1c6872024-01-23 06:42:02 +0900196 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000197 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
198 if (manifestInstance.package() != aname.package) return true;
199 if (manifestInstance.interface() != aname.iface) return true;
200 if (manifestInstance.instance() != aname.instance) return true;
201 updatableViaApex = manifestInstance.updatableViaApex();
202 return false; // break (libvintf uses opposite convention)
203 });
Jooyung Han9f1c6872024-01-23 06:42:02 +0900204 return !cont;
Steven Morelandedd4e072021-04-21 00:27:29 +0000205 });
206
207 return updatableViaApex;
208}
209
Jooyung Han205e2822023-12-19 16:59:39 +0900210static std::vector<std::string> getVintfUpdatableNames(const std::string& apexName) {
211 std::vector<std::string> names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900212
213 forEachManifest([&](const ManifestWithDescription& mwd) {
214 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Jooyung Han205e2822023-12-19 16:59:39 +0900215 if (manifestInstance.updatableViaApex().has_value() &&
Jooyung Han76944fe2022-10-25 17:02:45 +0900216 manifestInstance.updatableViaApex().value() == apexName) {
Jooyung Han205e2822023-12-19 16:59:39 +0900217 if (manifestInstance.format() == vintf::HalFormat::NATIVE) {
218 names.push_back(getNativeInstanceName(manifestInstance));
219 } else if (manifestInstance.format() == vintf::HalFormat::AIDL) {
220 names.push_back(getAidlInstanceName(manifestInstance));
221 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900222 }
Jooyung Hance94b752022-11-14 18:55:06 +0900223 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900224 });
225 return false; // continue
226 });
227
Jooyung Han205e2822023-12-19 16:59:39 +0900228 return names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900229}
230
Devin Moore5e4c2f12021-09-09 22:36:33 +0000231static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
232 AidlName aname;
233 if (!AidlName::fill(name, &aname)) return std::nullopt;
234
235 std::optional<std::string> ip;
236 std::optional<uint64_t> port;
237 forEachManifest([&](const ManifestWithDescription& mwd) {
238 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
239 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
240 if (manifestInstance.package() != aname.package) return true;
241 if (manifestInstance.interface() != aname.iface) return true;
242 if (manifestInstance.instance() != aname.instance) return true;
243 ip = manifestInstance.ip();
244 port = manifestInstance.port();
245 return false; // break (libvintf uses opposite convention)
246 });
247 return false; // continue
248 });
249
250 if (ip.has_value() && port.has_value()) {
251 ConnectionInfo info;
252 info.ipAddress = *ip;
253 info.port = *port;
254 return std::make_optional<ConnectionInfo>(info);
255 } else {
256 return std::nullopt;
257 }
258}
259
Steven Moreland2e293aa2020-09-23 00:25:16 +0000260static std::vector<std::string> getVintfInstances(const std::string& interface) {
261 size_t lastDot = interface.rfind('.');
262 if (lastDot == std::string::npos) {
Jooyung Han205e2822023-12-19 16:59:39 +0900263 // This might be a package for native instance.
264 std::vector<std::string> ret;
265 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
266 auto instances = mwd.manifest->getNativeInstances(interface);
267 ret.insert(ret.end(), instances.begin(), instances.end());
268 return false; // continue
269 });
270 // If found, return it without error log.
271 if (!ret.empty()) {
272 return ret;
273 }
274
Pawan Wagh37526162022-09-29 21:55:26 +0000275 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
276 "but got: %s",
277 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000278 return {};
279 }
280 const std::string package = interface.substr(0, lastDot);
281 const std::string iface = interface.substr(lastDot+1);
282
283 std::vector<std::string> ret;
284 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
285 auto instances = mwd.manifest->getAidlInstances(package, iface);
286 ret.insert(ret.end(), instances.begin(), instances.end());
287 return false; // continue
288 });
289
290 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700291}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700292
293static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
294 if (!Stability::requiresVintfDeclaration(binder)) {
295 return true;
296 }
297
298 return isVintfDeclared(name);
299}
Steven Moreland86a17f82019-09-10 10:18:00 -0700300#endif // !VENDORSERVICEMANAGER
301
Steven Morelandb8361902023-02-01 23:18:04 +0000302ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000303 if (hasClients) {
304 // only expected to happen on process death, we don't store the service
305 // name this late (it's in the map that holds this service), but if it
306 // is happening, we might want to change 'unlinkToDeath' to explicitly
307 // clear this bit so that we can abort in other cases, where it would
308 // mean inconsistent logic in servicemanager (unexpected and tested, but
309 // the original lazy service impl here had that bug).
Steven Morelandb8361902023-02-01 23:18:04 +0000310 LOG(WARNING) << "a service was removed when there are clients";
311 }
312}
313
Steven Morelandd13f08b2019-11-18 14:23:09 -0800314ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700315// TODO(b/151696835): reenable performance hack when we solve bug, since with
316// this hack and other fixes, it is unlikely we will see even an ephemeral
317// failure when the manifest parse fails. The goal is that the manifest will
318// be read incorrectly and cause the process trying to register a HAL to
319// fail. If this is in fact an early boot kernel contention issue, then we
320// will get no failure, and by its absence, be signalled to invest more
321// effort in re-adding this performance hack.
322// #ifndef VENDORSERVICEMANAGER
323// // can process these at any times, don't want to delay first VINTF client
324// std::thread([] {
325// vintf::VintfObject::GetDeviceHalManifest();
326// vintf::VintfObject::GetFrameworkHalManifest();
327// }).detach();
328// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800329}
Steven Moreland130242d2019-08-26 17:41:32 -0700330ServiceManager::~ServiceManager() {
331 // this should only happen in tests
332
Jon Spivackf288b1d2019-12-19 17:15:51 -0800333 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700334 CHECK(!callbacks.empty()) << name;
335 for (const auto& callback : callbacks) {
336 CHECK(callback != nullptr) << name;
337 }
338 }
339
Steven Moreland130242d2019-08-26 17:41:32 -0700340 for (const auto& [name, service] : mNameToService) {
341 CHECK(service.binder != nullptr) << name;
342 }
343}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700344
345Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700346 *outBinder = tryGetService(name, true);
347 // returns ok regardless of result for legacy reasons
348 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700349}
350
351Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700352 *outBinder = tryGetService(name, false);
353 // returns ok regardless of result for legacy reasons
354 return Status::ok();
355}
356
357sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700358 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700359
Jon Spivack0d844302019-07-22 18:40:34 -0700360 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700361 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700362 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700363 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700364
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000365 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
366 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700367 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700368 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700369 }
370
Steven Morelanda9fe4742019-07-18 14:45:20 -0700371 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700372 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700373 }
374
Jon Spivack0d844302019-07-22 18:40:34 -0700375 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000376 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700377 }
378
Jon Spivack9f503a42019-10-22 16:49:19 -0700379 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000380 // Force onClients to get sent, and then make sure the timerfd won't clear it
381 // by setting guaranteeClient again. This logic could be simplified by using
382 // a time-based guarantee. However, forcing onClients(true) to get sent
383 // right here is always going to be important for processes serving multiple
384 // lazy interfaces.
385 service->guaranteeClient = true;
386 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700387 service->guaranteeClient = true;
388 }
389
Jon Spivack0d844302019-07-22 18:40:34 -0700390 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700391}
392
Steven Moreland905e2e82019-07-17 11:05:45 -0700393bool isValidServiceName(const std::string& name) {
394 if (name.size() == 0) return false;
395 if (name.size() > 127) return false;
396
397 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700398 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700399 if (c >= 'a' && c <= 'z') continue;
400 if (c >= 'A' && c <= 'Z') continue;
401 if (c >= '0' && c <= '9') continue;
402 return false;
403 }
404
405 return true;
406}
407
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700408Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700409 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700410
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700411 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000412 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700413 }
414
Steven Morelanda9fe4742019-07-18 14:45:20 -0700415 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000416 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700417 }
418
419 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000420 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700421 }
422
Steven Moreland905e2e82019-07-17 11:05:45 -0700423 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000424 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000425 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700426 }
427
Steven Moreland86a17f82019-09-10 10:18:00 -0700428#ifndef VENDORSERVICEMANAGER
429 if (!meetsDeclarationRequirements(binder, name)) {
430 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000431 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700432 }
433#endif // !VENDORSERVICEMANAGER
434
Devin Moore4e21def2023-02-24 21:54:14 +0000435 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
436 ALOGW("Dump flag priority is not set when adding %s", name.c_str());
437 }
438
Steven Moreland88860b02019-08-12 14:24:14 -0700439 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000440 if (binder->remoteBinder() != nullptr &&
441 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Pawan Wagh37526162022-09-29 21:55:26 +0000442 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000443 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700444 }
445
Steven Moreland7ee423b2022-09-24 03:52:08 +0000446 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000447 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000448 if (it != mNameToService.end()) {
449 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000450 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000451
452 // We could do better than this because if the other service dies, it
453 // may not have an entry here. However, this case is unlikely. We are
454 // only trying to detect when two different services are accidentally installed.
455
456 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000457 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
458 "from UID %u. Multiple instances installed?",
459 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000460 }
461
462 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000463 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
464 "from SID %s. Multiple instances installed?",
465 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000466 }
467
Pawan Wagh37526162022-09-29 21:55:26 +0000468 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
469 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
470 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000471 }
472
Devin Moore05ffe522020-08-06 13:58:29 -0700473 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000474 mNameToService[name] = Service{
475 .binder = binder,
476 .allowIsolated = allowIsolated,
477 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000478 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000479 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000480 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700481 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700482
Steven Moreland7ee423b2022-09-24 03:52:08 +0000483 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000484 // If someone is currently waiting on the service, notify the service that
485 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000486 mNameToService[name].guaranteeClient = true;
487 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
488 mNameToService[name].guaranteeClient = true;
489
Steven Moreland27cfab02019-08-12 14:34:16 -0700490 for (const sp<IServiceCallback>& cb : it->second) {
491 // permission checked in registerForNotifications
492 cb->onRegistration(name, binder);
493 }
494 }
495
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700496 return Status::ok();
497}
498
499Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700500 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000501 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700502 }
503
504 size_t toReserve = 0;
505 for (auto const& [name, service] : mNameToService) {
506 (void) name;
507
508 if (service.dumpPriority & dumpPriority) ++toReserve;
509 }
510
511 CHECK(outList->empty());
512
513 outList->reserve(toReserve);
514 for (auto const& [name, service] : mNameToService) {
515 (void) service;
516
517 if (service.dumpPriority & dumpPriority) {
518 outList->push_back(name);
519 }
520 }
521
522 return Status::ok();
523}
524
Steven Moreland27cfab02019-08-12 14:34:16 -0700525Status ServiceManager::registerForNotifications(
526 const std::string& name, const sp<IServiceCallback>& callback) {
527 auto ctx = mAccess->getCallingContext();
528
529 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000530 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
531 }
532
533 // note - we could allow isolated apps to get notifications if we
534 // keep track of isolated callbacks and non-isolated callbacks, but
535 // this is done since isolated apps shouldn't access lazy services
536 // so we should be able to use different APIs to keep things simple.
537 // Here, we disallow everything, because the service might not be
538 // registered yet.
539 if (is_multiuser_uid_isolated(ctx.uid)) {
540 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700541 }
542
543 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000544 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000545 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700546 }
547
548 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000549 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700550 }
551
Steven Morelandb0983182021-04-02 03:14:04 +0000552 if (OK !=
553 IInterface::asBinder(callback)->linkToDeath(
554 sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000555 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000556 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700557 }
558
Jon Spivackf288b1d2019-12-19 17:15:51 -0800559 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700560
561 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
562 const sp<IBinder>& binder = it->second.binder;
563
564 // never null if an entry exists
565 CHECK(binder != nullptr) << name;
566 callback->onRegistration(name, binder);
567 }
568
569 return Status::ok();
570}
571Status ServiceManager::unregisterForNotifications(
572 const std::string& name, const sp<IServiceCallback>& callback) {
573 auto ctx = mAccess->getCallingContext();
574
575 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000576 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700577 }
578
579 bool found = false;
580
Jon Spivackf288b1d2019-12-19 17:15:51 -0800581 auto it = mNameToRegistrationCallback.find(name);
582 if (it != mNameToRegistrationCallback.end()) {
583 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700584 }
585
586 if (!found) {
Pawan Wagh37526162022-09-29 21:55:26 +0000587 ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000588 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700589 }
590
591 return Status::ok();
592}
593
Steven Morelandb82b8f82019-10-28 10:52:34 -0700594Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
595 auto ctx = mAccess->getCallingContext();
596
597 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000598 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700599 }
600
601 *outReturn = false;
602
603#ifndef VENDORSERVICEMANAGER
604 *outReturn = isVintfDeclared(name);
605#endif
606 return Status::ok();
607}
608
Steven Moreland2e293aa2020-09-23 00:25:16 +0000609binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
610 auto ctx = mAccess->getCallingContext();
611
612 std::vector<std::string> allInstances;
613#ifndef VENDORSERVICEMANAGER
614 allInstances = getVintfInstances(interface);
615#endif
616
617 outReturn->clear();
618
619 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000620 if (mAccess->canFind(ctx, interface + "/" + instance)) {
621 outReturn->push_back(instance);
622 }
623 }
624
625 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000626 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000627 }
628
629 return Status::ok();
630}
631
Steven Morelandedd4e072021-04-21 00:27:29 +0000632Status ServiceManager::updatableViaApex(const std::string& name,
633 std::optional<std::string>* outReturn) {
634 auto ctx = mAccess->getCallingContext();
635
636 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000637 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000638 }
639
640 *outReturn = std::nullopt;
641
642#ifndef VENDORSERVICEMANAGER
643 *outReturn = getVintfUpdatableApex(name);
644#endif
645 return Status::ok();
646}
647
Jooyung Han76944fe2022-10-25 17:02:45 +0900648Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
649 std::vector<std::string>* outReturn) {
650 auto ctx = mAccess->getCallingContext();
651
Jooyung Han205e2822023-12-19 16:59:39 +0900652 std::vector<std::string> apexUpdatableNames;
Jooyung Han76944fe2022-10-25 17:02:45 +0900653#ifndef VENDORSERVICEMANAGER
Jooyung Han205e2822023-12-19 16:59:39 +0900654 apexUpdatableNames = getVintfUpdatableNames(apexName);
Jooyung Han76944fe2022-10-25 17:02:45 +0900655#endif
656
657 outReturn->clear();
658
Jooyung Han205e2822023-12-19 16:59:39 +0900659 for (const std::string& name : apexUpdatableNames) {
660 if (mAccess->canFind(ctx, name)) {
661 outReturn->push_back(name);
Jooyung Han76944fe2022-10-25 17:02:45 +0900662 }
663 }
664
Jooyung Han205e2822023-12-19 16:59:39 +0900665 if (outReturn->size() == 0 && apexUpdatableNames.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000666 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900667 }
668
669 return Status::ok();
670}
671
Devin Moore5e4c2f12021-09-09 22:36:33 +0000672Status ServiceManager::getConnectionInfo(const std::string& name,
673 std::optional<ConnectionInfo>* outReturn) {
674 auto ctx = mAccess->getCallingContext();
675
676 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000677 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000678 }
679
680 *outReturn = std::nullopt;
681
682#ifndef VENDORSERVICEMANAGER
683 *outReturn = getVintfConnectionInfo(name);
684#endif
685 return Status::ok();
686}
687
Jon Spivackf288b1d2019-12-19 17:15:51 -0800688void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
689 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700690 bool* found) {
691 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
692
693 for (auto lit = listeners.begin(); lit != listeners.end();) {
694 if (IInterface::asBinder(*lit) == who) {
695 if(found) *found = true;
696 lit = listeners.erase(lit);
697 } else {
698 ++lit;
699 }
700 }
701
702 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800703 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700704 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800705 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700706 }
707}
708
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700709void ServiceManager::binderDied(const wp<IBinder>& who) {
710 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
711 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000712 // TODO: currently, this entry contains the state also
713 // associated with mNameToClientCallback. If we allowed
714 // other processes to register client callbacks, we
715 // would have to preserve hasClients (perhaps moving
716 // that state into mNameToClientCallback, which is complicated
717 // because those callbacks are associated w/ particular binder
718 // objects, though they are indexed by name now, they may
719 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700720 it = mNameToService.erase(it);
721 } else {
722 ++it;
723 }
724 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700725
Jon Spivackf288b1d2019-12-19 17:15:51 -0800726 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
727 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700728 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700729
730 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
731 removeClientCallback(who, &it);
732 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700733}
734
Steven Morelandaa33e852023-05-10 16:42:15 +0000735void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
736 ALOGI("Since '%s' could not be found (requested by debug pid %d), trying to start it as a lazy "
737 "AIDL service. (if it's not configured to be a lazy service, it may be stuck starting or "
738 "still starting).",
739 name.c_str(), ctx.debugPid);
Jon Spivack0d844302019-07-22 18:40:34 -0700740
741 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000742 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000743 ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
744 "this happens when a "
745 "service is not installed, but if the service is intended to be used as a "
746 "lazy service, then it may be configured incorrectly.",
747 name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000748 }
Jon Spivack0d844302019-07-22 18:40:34 -0700749 }).detach();
750}
751
Jon Spivack9f503a42019-10-22 16:49:19 -0700752Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
753 const sp<IClientCallback>& cb) {
754 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000755 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700756 }
757
758 auto ctx = mAccess->getCallingContext();
759 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000760 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700761 }
762
763 auto serviceIt = mNameToService.find(name);
764 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000765 ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000766 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700767 }
768
Steven Moreland7ee423b2022-09-24 03:52:08 +0000769 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000770 ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000771 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
772 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700773 }
774
775 if (serviceIt->second.binder != service) {
Pawan Wagh37526162022-09-29 21:55:26 +0000776 ALOGW("Tried to register client callback for %s but a different service is registered "
777 "under this name.",
778 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000779 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700780 }
781
Steven Morelandb0983182021-04-02 03:14:04 +0000782 if (OK !=
783 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000784 ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000785 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700786 }
787
Steven Moreland79578672023-04-27 19:38:00 +0000788 // WARNING: binderDied makes an assumption about this. If we open up client
789 // callbacks to other services, certain race conditions may lead to services
790 // getting extra client callback notifications.
791 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000792 if (serviceIt->second.hasClients) {
793 cb->onClients(service, true);
794 }
795
Jon Spivack9f503a42019-10-22 16:49:19 -0700796 mNameToClientCallback[name].push_back(cb);
797
Steven Morelandefea66b2023-06-17 01:59:34 +0000798 // Flush updated info to client callbacks (especially if guaranteeClient
799 // and !hasClient, see b/285202885). We may or may not have clients at
800 // this point, so ignore the return value.
801 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
802
Jon Spivack9f503a42019-10-22 16:49:19 -0700803 return Status::ok();
804}
805
806void ServiceManager::removeClientCallback(const wp<IBinder>& who,
807 ClientCallbackMap::iterator* it) {
808 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
809
810 for (auto lit = listeners.begin(); lit != listeners.end();) {
811 if (IInterface::asBinder(*lit) == who) {
812 lit = listeners.erase(lit);
813 } else {
814 ++lit;
815 }
816 }
817
818 if (listeners.empty()) {
819 *it = mNameToClientCallback.erase(*it);
820 } else {
821 (*it)++;
822 }
823}
824
825ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000826 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700827 if (bpBinder == nullptr) return -1;
828
Steven Morelande8393882020-12-18 02:27:20 +0000829 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700830}
831
832void ServiceManager::handleClientCallbacks() {
833 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000834 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700835 }
836}
837
Steven Morelandb8361902023-02-01 23:18:04 +0000838bool ServiceManager::handleServiceClientCallback(size_t knownClients,
839 const std::string& serviceName,
840 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700841 auto serviceIt = mNameToService.find(serviceName);
842 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000843 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700844 }
845
846 Service& service = serviceIt->second;
847 ssize_t count = service.getNodeStrongRefCount();
848
Steven Morelandb8361902023-02-01 23:18:04 +0000849 // binder driver doesn't support this feature, consider we have clients
850 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700851
Steven Morelandb8361902023-02-01 23:18:04 +0000852 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700853
854 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000855 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000856 sendClientCallbackNotifications(serviceName, true,
857 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700858 }
859
860 // guarantee is temporary
861 service.guaranteeClient = false;
862 }
863
Steven Morelandb8361902023-02-01 23:18:04 +0000864 // Regardless of this situation, we want to give this notification as soon as possible.
865 // This way, we have a chance of preventing further thrashing.
866 if (hasKernelReportedClients && !service.hasClients) {
867 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
868 }
Steven Moreland66417652023-02-01 22:19:41 +0000869
Steven Morelandb8361902023-02-01 23:18:04 +0000870 // But limit rate of shutting down service.
871 if (isCalledOnInterval) {
872 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000873 sendClientCallbackNotifications(serviceName, false,
874 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000875 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700876 }
877
Steven Morelandb8361902023-02-01 23:18:04 +0000878 // May be different than 'hasKernelReportedClients'. We intentionally delay
879 // information about clients going away to reduce thrashing.
880 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700881}
882
Steven Moreland3e083b22023-01-26 00:46:30 +0000883void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
884 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700885 auto serviceIt = mNameToService.find(serviceName);
886 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000887 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
888 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700889 return;
890 }
891 Service& service = serviceIt->second;
892
Steven Morelandb8361902023-02-01 23:18:04 +0000893 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700894
Steven Morelandb8361902023-02-01 23:18:04 +0000895 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
896 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700897
898 auto ccIt = mNameToClientCallback.find(serviceName);
899 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000900 << "sendClientCallbackNotifications could not find callbacks for service when "
901 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700902
903 for (const auto& callback : ccIt->second) {
904 callback->onClients(service.binder, hasClients);
905 }
906
907 service.hasClients = hasClients;
908}
909
910Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
911 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000912 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700913 }
914
915 auto ctx = mAccess->getCallingContext();
916 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000917 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700918 }
919
920 auto serviceIt = mNameToService.find(name);
921 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000922 ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
923 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000924 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700925 }
926
Steven Moreland7ee423b2022-09-24 03:52:08 +0000927 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000928 ALOGW("Only a server can unregister itself (for %s)", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000929 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
930 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700931 }
932
933 sp<IBinder> storedBinder = serviceIt->second.binder;
934
935 if (binder != storedBinder) {
Pawan Wagh37526162022-09-29 21:55:26 +0000936 ALOGW("Tried to unregister %s, but a different service is registered under this name.",
937 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000938 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
939 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700940 }
941
Steven Morelandb8361902023-02-01 23:18:04 +0000942 // important because we don't have timer-based guarantees, we don't want to clear
943 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700944 if (serviceIt->second.guaranteeClient) {
Pawan Wagh37526162022-09-29 21:55:26 +0000945 ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000946 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
947 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700948 }
949
Jon Spivack9f503a42019-10-22 16:49:19 -0700950 // - kernel driver will hold onto one refcount (during this transaction)
951 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000952 constexpr size_t kKnownClients = 2;
953
954 if (handleServiceClientCallback(kKnownClients, name, false)) {
955 ALOGI("Tried to unregister %s, but there are clients.", name.c_str());
956
957 // Since we had a failed registration attempt, and the HIDL implementation of
958 // delaying service shutdown for multiple periods wasn't ported here... this may
959 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800960 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000961
Steven Morelandffb905b2023-03-28 18:24:37 +0000962 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
963 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700964 }
965
Steven Morelandb8361902023-02-01 23:18:04 +0000966 ALOGI("Unregistering %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700967 mNameToService.erase(name);
968
969 return Status::ok();
970}
971
Steven Moreland3ea43272021-01-28 22:49:28 +0000972Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
973 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000974 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +0000975 }
976
977 outReturn->reserve(mNameToService.size());
978 for (auto const& [name, service] : mNameToService) {
979 ServiceDebugInfo info;
980 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000981 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000982
983 outReturn->push_back(std::move(info));
984 }
985
986 return Status::ok();
987}
988
Pawan Wagh243888e2022-09-20 19:37:35 +0000989void ServiceManager::clear() {
990 mNameToService.clear();
991 mNameToRegistrationCallback.clear();
992 mNameToClientCallback.clear();
993}
994
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700995} // namespace android