blob: 6ec924d94cd3255072ce9247979e53c227d687cd [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 Moreland5759db02024-03-27 00:03:05 +0000118static bool isVintfDeclared(const Access::CallingContext& ctx, 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)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000123 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(),
124 name.c_str(), mwd.description);
Jooyung Han205e2822023-12-19 16:59:39 +0900125 return true; // break
126 }
127 return false; // continue
128 });
129 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000130 ALOGI("%s Could not find %s in the VINTF manifest.", ctx.toDebugString().c_str(),
131 name.c_str());
Jooyung Han205e2822023-12-19 16:59:39 +0900132 }
133 return found;
134 }
135
Steven Morelandedd4e072021-04-21 00:27:29 +0000136 AidlName aname;
137 if (!AidlName::fill(name, &aname)) return false;
138
139 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
140 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000141 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(), name.c_str(),
142 mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000143 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700144 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000145 return false; // continue
146 });
147
148 if (!found) {
Devin Moore42407bc2023-09-26 21:30:39 +0000149 std::set<std::string> instances;
150 forEachManifest([&](const ManifestWithDescription& mwd) {
151 std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
152 instances.insert(res.begin(), res.end());
153 return true;
154 });
155
156 std::string available;
157 if (instances.empty()) {
158 available = "No alternative instances declared in VINTF";
159 } else {
160 // for logging only. We can't return this information to the client
161 // because they may not have permissions to find or list those
162 // instances
163 available = "VINTF declared instances: " + base::Join(instances, ", ");
164 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000165 // Although it is tested, explicitly rebuilding qualified name, in case it
166 // becomes something unexpected.
Steven Moreland5759db02024-03-27 00:03:05 +0000167 ALOGI("%s Could not find %s.%s/%s in the VINTF manifest. %s.", ctx.toDebugString().c_str(),
168 aname.package.c_str(), aname.iface.c_str(), aname.instance.c_str(),
169 available.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700170 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700171
Steven Moreland2e293aa2020-09-23 00:25:16 +0000172 return found;
173}
174
Steven Morelandedd4e072021-04-21 00:27:29 +0000175static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900176 NativeName nname;
177 if (NativeName::fill(name, &nname)) {
178 std::optional<std::string> updatableViaApex;
179
180 forEachManifest([&](const ManifestWithDescription& mwd) {
181 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
182 if (manifestInstance.format() != vintf::HalFormat::NATIVE) return true;
183 if (manifestInstance.package() != nname.package) return true;
184 if (manifestInstance.instance() != nname.instance) return true;
185 updatableViaApex = manifestInstance.updatableViaApex();
186 return false; // break (libvintf uses opposite convention)
187 });
188 return !cont;
189 });
190
191 return updatableViaApex;
192 }
193
Steven Morelandedd4e072021-04-21 00:27:29 +0000194 AidlName aname;
195 if (!AidlName::fill(name, &aname)) return std::nullopt;
196
197 std::optional<std::string> updatableViaApex;
198
199 forEachManifest([&](const ManifestWithDescription& mwd) {
Jooyung Han9f1c6872024-01-23 06:42:02 +0900200 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000201 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
202 if (manifestInstance.package() != aname.package) return true;
203 if (manifestInstance.interface() != aname.iface) return true;
204 if (manifestInstance.instance() != aname.instance) return true;
205 updatableViaApex = manifestInstance.updatableViaApex();
206 return false; // break (libvintf uses opposite convention)
207 });
Jooyung Han9f1c6872024-01-23 06:42:02 +0900208 return !cont;
Steven Morelandedd4e072021-04-21 00:27:29 +0000209 });
210
211 return updatableViaApex;
212}
213
Jooyung Han205e2822023-12-19 16:59:39 +0900214static std::vector<std::string> getVintfUpdatableNames(const std::string& apexName) {
215 std::vector<std::string> names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900216
217 forEachManifest([&](const ManifestWithDescription& mwd) {
218 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Jooyung Han205e2822023-12-19 16:59:39 +0900219 if (manifestInstance.updatableViaApex().has_value() &&
Jooyung Han76944fe2022-10-25 17:02:45 +0900220 manifestInstance.updatableViaApex().value() == apexName) {
Jooyung Han205e2822023-12-19 16:59:39 +0900221 if (manifestInstance.format() == vintf::HalFormat::NATIVE) {
222 names.push_back(getNativeInstanceName(manifestInstance));
223 } else if (manifestInstance.format() == vintf::HalFormat::AIDL) {
224 names.push_back(getAidlInstanceName(manifestInstance));
225 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900226 }
Jooyung Hance94b752022-11-14 18:55:06 +0900227 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900228 });
229 return false; // continue
230 });
231
Jooyung Han205e2822023-12-19 16:59:39 +0900232 return names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900233}
234
Devin Moore5e4c2f12021-09-09 22:36:33 +0000235static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
236 AidlName aname;
237 if (!AidlName::fill(name, &aname)) return std::nullopt;
238
239 std::optional<std::string> ip;
240 std::optional<uint64_t> port;
241 forEachManifest([&](const ManifestWithDescription& mwd) {
242 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
243 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
244 if (manifestInstance.package() != aname.package) return true;
245 if (manifestInstance.interface() != aname.iface) return true;
246 if (manifestInstance.instance() != aname.instance) return true;
247 ip = manifestInstance.ip();
248 port = manifestInstance.port();
249 return false; // break (libvintf uses opposite convention)
250 });
251 return false; // continue
252 });
253
254 if (ip.has_value() && port.has_value()) {
255 ConnectionInfo info;
256 info.ipAddress = *ip;
257 info.port = *port;
258 return std::make_optional<ConnectionInfo>(info);
259 } else {
260 return std::nullopt;
261 }
262}
263
Steven Moreland2e293aa2020-09-23 00:25:16 +0000264static std::vector<std::string> getVintfInstances(const std::string& interface) {
265 size_t lastDot = interface.rfind('.');
266 if (lastDot == std::string::npos) {
Jooyung Han205e2822023-12-19 16:59:39 +0900267 // This might be a package for native instance.
268 std::vector<std::string> ret;
269 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
270 auto instances = mwd.manifest->getNativeInstances(interface);
271 ret.insert(ret.end(), instances.begin(), instances.end());
272 return false; // continue
273 });
274 // If found, return it without error log.
275 if (!ret.empty()) {
276 return ret;
277 }
278
Pawan Wagh37526162022-09-29 21:55:26 +0000279 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
280 "but got: %s",
281 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000282 return {};
283 }
284 const std::string package = interface.substr(0, lastDot);
285 const std::string iface = interface.substr(lastDot+1);
286
287 std::vector<std::string> ret;
288 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
289 auto instances = mwd.manifest->getAidlInstances(package, iface);
290 ret.insert(ret.end(), instances.begin(), instances.end());
291 return false; // continue
292 });
293
294 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700295}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700296
Steven Moreland5759db02024-03-27 00:03:05 +0000297static bool meetsDeclarationRequirements(const Access::CallingContext& ctx,
298 const sp<IBinder>& binder, const std::string& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700299 if (!Stability::requiresVintfDeclaration(binder)) {
300 return true;
301 }
302
Steven Moreland5759db02024-03-27 00:03:05 +0000303 return isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700304}
Steven Moreland86a17f82019-09-10 10:18:00 -0700305#endif // !VENDORSERVICEMANAGER
306
Steven Morelandb8361902023-02-01 23:18:04 +0000307ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000308 if (hasClients) {
309 // only expected to happen on process death, we don't store the service
310 // name this late (it's in the map that holds this service), but if it
311 // is happening, we might want to change 'unlinkToDeath' to explicitly
312 // clear this bit so that we can abort in other cases, where it would
313 // mean inconsistent logic in servicemanager (unexpected and tested, but
314 // the original lazy service impl here had that bug).
Steven Moreland5759db02024-03-27 00:03:05 +0000315 ALOGW("A service was removed when there are clients");
Steven Morelandb8361902023-02-01 23:18:04 +0000316 }
317}
318
Steven Morelandd13f08b2019-11-18 14:23:09 -0800319ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700320// TODO(b/151696835): reenable performance hack when we solve bug, since with
321// this hack and other fixes, it is unlikely we will see even an ephemeral
322// failure when the manifest parse fails. The goal is that the manifest will
323// be read incorrectly and cause the process trying to register a HAL to
324// fail. If this is in fact an early boot kernel contention issue, then we
325// will get no failure, and by its absence, be signalled to invest more
326// effort in re-adding this performance hack.
327// #ifndef VENDORSERVICEMANAGER
328// // can process these at any times, don't want to delay first VINTF client
329// std::thread([] {
330// vintf::VintfObject::GetDeviceHalManifest();
331// vintf::VintfObject::GetFrameworkHalManifest();
332// }).detach();
333// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800334}
Steven Moreland130242d2019-08-26 17:41:32 -0700335ServiceManager::~ServiceManager() {
336 // this should only happen in tests
337
Jon Spivackf288b1d2019-12-19 17:15:51 -0800338 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700339 CHECK(!callbacks.empty()) << name;
340 for (const auto& callback : callbacks) {
341 CHECK(callback != nullptr) << name;
342 }
343 }
344
Steven Moreland130242d2019-08-26 17:41:32 -0700345 for (const auto& [name, service] : mNameToService) {
346 CHECK(service.binder != nullptr) << name;
347 }
348}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700349
350Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700351 *outBinder = tryGetService(name, true);
352 // returns ok regardless of result for legacy reasons
353 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700354}
355
356Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700357 *outBinder = tryGetService(name, false);
358 // returns ok regardless of result for legacy reasons
359 return Status::ok();
360}
361
362sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700363 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700364
Jon Spivack0d844302019-07-22 18:40:34 -0700365 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700366 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700367 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700368 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700369
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000370 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
371 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700372 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700373 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700374 }
375
Steven Morelanda9fe4742019-07-18 14:45:20 -0700376 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700377 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700378 }
379
Jon Spivack0d844302019-07-22 18:40:34 -0700380 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000381 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700382 }
383
Jon Spivack9f503a42019-10-22 16:49:19 -0700384 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000385 // Force onClients to get sent, and then make sure the timerfd won't clear it
386 // by setting guaranteeClient again. This logic could be simplified by using
387 // a time-based guarantee. However, forcing onClients(true) to get sent
388 // right here is always going to be important for processes serving multiple
389 // lazy interfaces.
390 service->guaranteeClient = true;
391 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700392 service->guaranteeClient = true;
393 }
394
Jon Spivack0d844302019-07-22 18:40:34 -0700395 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700396}
397
Steven Moreland905e2e82019-07-17 11:05:45 -0700398bool isValidServiceName(const std::string& name) {
399 if (name.size() == 0) return false;
400 if (name.size() > 127) return false;
401
402 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700403 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700404 if (c >= 'a' && c <= 'z') continue;
405 if (c >= 'A' && c <= 'Z') continue;
406 if (c >= '0' && c <= '9') continue;
407 return false;
408 }
409
410 return true;
411}
412
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700413Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700414 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700415
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700416 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000417 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700418 }
419
Steven Morelanda9fe4742019-07-18 14:45:20 -0700420 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000421 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700422 }
423
424 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000425 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700426 }
427
Steven Moreland905e2e82019-07-17 11:05:45 -0700428 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000429 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000430 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700431 }
432
Steven Moreland86a17f82019-09-10 10:18:00 -0700433#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000434 if (!meetsDeclarationRequirements(ctx, binder, name)) {
Steven Moreland86a17f82019-09-10 10:18:00 -0700435 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000436 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700437 }
438#endif // !VENDORSERVICEMANAGER
439
Devin Moore4e21def2023-02-24 21:54:14 +0000440 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
Steven Moreland5759db02024-03-27 00:03:05 +0000441 ALOGW("%s Dump flag priority is not set when adding %s", ctx.toDebugString().c_str(),
442 name.c_str());
Devin Moore4e21def2023-02-24 21:54:14 +0000443 }
444
Steven Moreland88860b02019-08-12 14:24:14 -0700445 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000446 if (binder->remoteBinder() != nullptr &&
447 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Steven Moreland5759db02024-03-27 00:03:05 +0000448 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000449 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700450 }
451
Steven Moreland7ee423b2022-09-24 03:52:08 +0000452 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000453 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000454 if (it != mNameToService.end()) {
455 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000456 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000457
458 // We could do better than this because if the other service dies, it
459 // may not have an entry here. However, this case is unlikely. We are
460 // only trying to detect when two different services are accidentally installed.
461
462 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000463 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
464 "from UID %u. Multiple instances installed?",
465 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000466 }
467
468 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000469 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
470 "from SID %s. Multiple instances installed?",
471 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000472 }
473
Pawan Wagh37526162022-09-29 21:55:26 +0000474 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
475 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
476 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000477 }
478
Devin Moore05ffe522020-08-06 13:58:29 -0700479 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000480 mNameToService[name] = Service{
481 .binder = binder,
482 .allowIsolated = allowIsolated,
483 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000484 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000485 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000486 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700487 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700488
Steven Moreland7ee423b2022-09-24 03:52:08 +0000489 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000490 // If someone is currently waiting on the service, notify the service that
491 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000492 mNameToService[name].guaranteeClient = true;
493 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
494 mNameToService[name].guaranteeClient = true;
495
Steven Moreland27cfab02019-08-12 14:34:16 -0700496 for (const sp<IServiceCallback>& cb : it->second) {
497 // permission checked in registerForNotifications
498 cb->onRegistration(name, binder);
499 }
500 }
501
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700502 return Status::ok();
503}
504
505Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700506 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000507 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700508 }
509
510 size_t toReserve = 0;
511 for (auto const& [name, service] : mNameToService) {
512 (void) name;
513
514 if (service.dumpPriority & dumpPriority) ++toReserve;
515 }
516
517 CHECK(outList->empty());
518
519 outList->reserve(toReserve);
520 for (auto const& [name, service] : mNameToService) {
521 (void) service;
522
523 if (service.dumpPriority & dumpPriority) {
524 outList->push_back(name);
525 }
526 }
527
528 return Status::ok();
529}
530
Steven Moreland27cfab02019-08-12 14:34:16 -0700531Status ServiceManager::registerForNotifications(
532 const std::string& name, const sp<IServiceCallback>& callback) {
533 auto ctx = mAccess->getCallingContext();
534
535 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000536 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
537 }
538
539 // note - we could allow isolated apps to get notifications if we
540 // keep track of isolated callbacks and non-isolated callbacks, but
541 // this is done since isolated apps shouldn't access lazy services
542 // so we should be able to use different APIs to keep things simple.
543 // Here, we disallow everything, because the service might not be
544 // registered yet.
545 if (is_multiuser_uid_isolated(ctx.uid)) {
546 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700547 }
548
549 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000550 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000551 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700552 }
553
554 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000555 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700556 }
557
Steven Morelandb0983182021-04-02 03:14:04 +0000558 if (OK !=
559 IInterface::asBinder(callback)->linkToDeath(
560 sp<ServiceManager>::fromExisting(this))) {
Steven Moreland5759db02024-03-27 00:03:05 +0000561 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000562 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700563 }
564
Jon Spivackf288b1d2019-12-19 17:15:51 -0800565 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700566
567 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
568 const sp<IBinder>& binder = it->second.binder;
569
570 // never null if an entry exists
571 CHECK(binder != nullptr) << name;
572 callback->onRegistration(name, binder);
573 }
574
575 return Status::ok();
576}
577Status ServiceManager::unregisterForNotifications(
578 const std::string& name, const sp<IServiceCallback>& callback) {
579 auto ctx = mAccess->getCallingContext();
580
581 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000582 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700583 }
584
585 bool found = false;
586
Jon Spivackf288b1d2019-12-19 17:15:51 -0800587 auto it = mNameToRegistrationCallback.find(name);
588 if (it != mNameToRegistrationCallback.end()) {
589 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700590 }
591
592 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000593 ALOGE("%s Trying to unregister callback, but none exists %s", ctx.toDebugString().c_str(),
594 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000595 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700596 }
597
598 return Status::ok();
599}
600
Steven Morelandb82b8f82019-10-28 10:52:34 -0700601Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
602 auto ctx = mAccess->getCallingContext();
603
604 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000605 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700606 }
607
608 *outReturn = false;
609
610#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000611 *outReturn = isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700612#endif
613 return Status::ok();
614}
615
Steven Moreland2e293aa2020-09-23 00:25:16 +0000616binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
617 auto ctx = mAccess->getCallingContext();
618
619 std::vector<std::string> allInstances;
620#ifndef VENDORSERVICEMANAGER
621 allInstances = getVintfInstances(interface);
622#endif
623
624 outReturn->clear();
625
626 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000627 if (mAccess->canFind(ctx, interface + "/" + instance)) {
628 outReturn->push_back(instance);
629 }
630 }
631
632 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000633 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000634 }
635
636 return Status::ok();
637}
638
Steven Morelandedd4e072021-04-21 00:27:29 +0000639Status ServiceManager::updatableViaApex(const std::string& name,
640 std::optional<std::string>* outReturn) {
641 auto ctx = mAccess->getCallingContext();
642
643 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000644 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000645 }
646
647 *outReturn = std::nullopt;
648
649#ifndef VENDORSERVICEMANAGER
650 *outReturn = getVintfUpdatableApex(name);
651#endif
652 return Status::ok();
653}
654
Jooyung Han76944fe2022-10-25 17:02:45 +0900655Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
656 std::vector<std::string>* outReturn) {
657 auto ctx = mAccess->getCallingContext();
658
Jooyung Han205e2822023-12-19 16:59:39 +0900659 std::vector<std::string> apexUpdatableNames;
Jooyung Han76944fe2022-10-25 17:02:45 +0900660#ifndef VENDORSERVICEMANAGER
Jooyung Han205e2822023-12-19 16:59:39 +0900661 apexUpdatableNames = getVintfUpdatableNames(apexName);
Jooyung Han76944fe2022-10-25 17:02:45 +0900662#endif
663
664 outReturn->clear();
665
Jooyung Han205e2822023-12-19 16:59:39 +0900666 for (const std::string& name : apexUpdatableNames) {
667 if (mAccess->canFind(ctx, name)) {
668 outReturn->push_back(name);
Jooyung Han76944fe2022-10-25 17:02:45 +0900669 }
670 }
671
Jooyung Han205e2822023-12-19 16:59:39 +0900672 if (outReturn->size() == 0 && apexUpdatableNames.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000673 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900674 }
675
676 return Status::ok();
677}
678
Devin Moore5e4c2f12021-09-09 22:36:33 +0000679Status ServiceManager::getConnectionInfo(const std::string& name,
680 std::optional<ConnectionInfo>* outReturn) {
681 auto ctx = mAccess->getCallingContext();
682
683 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000684 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000685 }
686
687 *outReturn = std::nullopt;
688
689#ifndef VENDORSERVICEMANAGER
690 *outReturn = getVintfConnectionInfo(name);
691#endif
692 return Status::ok();
693}
694
Jon Spivackf288b1d2019-12-19 17:15:51 -0800695void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
696 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700697 bool* found) {
698 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
699
700 for (auto lit = listeners.begin(); lit != listeners.end();) {
701 if (IInterface::asBinder(*lit) == who) {
702 if(found) *found = true;
703 lit = listeners.erase(lit);
704 } else {
705 ++lit;
706 }
707 }
708
709 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800710 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700711 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800712 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700713 }
714}
715
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700716void ServiceManager::binderDied(const wp<IBinder>& who) {
717 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
718 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000719 // TODO: currently, this entry contains the state also
720 // associated with mNameToClientCallback. If we allowed
721 // other processes to register client callbacks, we
722 // would have to preserve hasClients (perhaps moving
723 // that state into mNameToClientCallback, which is complicated
724 // because those callbacks are associated w/ particular binder
725 // objects, though they are indexed by name now, they may
726 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700727 it = mNameToService.erase(it);
728 } else {
729 ++it;
730 }
731 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700732
Jon Spivackf288b1d2019-12-19 17:15:51 -0800733 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
734 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700735 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700736
737 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
738 removeClientCallback(who, &it);
739 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700740}
741
Steven Morelandaa33e852023-05-10 16:42:15 +0000742void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
Steven Moreland5759db02024-03-27 00:03:05 +0000743 ALOGI("%s Since '%s' could not be found trying to start it as a lazy AIDL service. (if it's "
744 "not configured to be a lazy service, it may be stuck starting or still starting).",
745 ctx.toDebugString().c_str(), name.c_str());
Jon Spivack0d844302019-07-22 18:40:34 -0700746
747 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000748 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000749 ALOGI("%s Tried to start aidl service %s as a lazy service, but was unable to. Usually "
750 "this happens when a service is not installed, but if the service is intended to "
751 "be used as a lazy service, then it may be configured incorrectly.",
752 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000753 }
Jon Spivack0d844302019-07-22 18:40:34 -0700754 }).detach();
755}
756
Jon Spivack9f503a42019-10-22 16:49:19 -0700757Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
758 const sp<IClientCallback>& cb) {
759 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000760 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700761 }
762
763 auto ctx = mAccess->getCallingContext();
764 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000765 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700766 }
767
768 auto serviceIt = mNameToService.find(name);
769 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000770 ALOGE("%s Could not add callback for nonexistent service: %s", ctx.toDebugString().c_str(),
771 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000772 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700773 }
774
Steven Moreland7ee423b2022-09-24 03:52:08 +0000775 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000776 ALOGW("%s Only a server can register for client callbacks (for %s)",
777 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000778 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
779 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700780 }
781
782 if (serviceIt->second.binder != service) {
Steven Moreland5759db02024-03-27 00:03:05 +0000783 ALOGW("%s Tried to register client callback for %s but a different service is registered "
Pawan Wagh37526162022-09-29 21:55:26 +0000784 "under this name.",
Steven Moreland5759db02024-03-27 00:03:05 +0000785 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000786 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700787 }
788
Steven Morelandb0983182021-04-02 03:14:04 +0000789 if (OK !=
790 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Steven Moreland5759db02024-03-27 00:03:05 +0000791 ALOGE("%s Could not linkToDeath when adding client callback for %s", name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000792 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700793 }
794
Steven Moreland79578672023-04-27 19:38:00 +0000795 // WARNING: binderDied makes an assumption about this. If we open up client
796 // callbacks to other services, certain race conditions may lead to services
797 // getting extra client callback notifications.
798 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000799 if (serviceIt->second.hasClients) {
800 cb->onClients(service, true);
801 }
802
Jon Spivack9f503a42019-10-22 16:49:19 -0700803 mNameToClientCallback[name].push_back(cb);
804
Steven Morelandefea66b2023-06-17 01:59:34 +0000805 // Flush updated info to client callbacks (especially if guaranteeClient
806 // and !hasClient, see b/285202885). We may or may not have clients at
807 // this point, so ignore the return value.
808 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
809
Jon Spivack9f503a42019-10-22 16:49:19 -0700810 return Status::ok();
811}
812
813void ServiceManager::removeClientCallback(const wp<IBinder>& who,
814 ClientCallbackMap::iterator* it) {
815 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
816
817 for (auto lit = listeners.begin(); lit != listeners.end();) {
818 if (IInterface::asBinder(*lit) == who) {
819 lit = listeners.erase(lit);
820 } else {
821 ++lit;
822 }
823 }
824
825 if (listeners.empty()) {
826 *it = mNameToClientCallback.erase(*it);
827 } else {
828 (*it)++;
829 }
830}
831
832ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000833 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700834 if (bpBinder == nullptr) return -1;
835
Steven Morelande8393882020-12-18 02:27:20 +0000836 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700837}
838
839void ServiceManager::handleClientCallbacks() {
840 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000841 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700842 }
843}
844
Steven Morelandb8361902023-02-01 23:18:04 +0000845bool ServiceManager::handleServiceClientCallback(size_t knownClients,
846 const std::string& serviceName,
847 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700848 auto serviceIt = mNameToService.find(serviceName);
849 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000850 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700851 }
852
853 Service& service = serviceIt->second;
854 ssize_t count = service.getNodeStrongRefCount();
855
Steven Morelandb8361902023-02-01 23:18:04 +0000856 // binder driver doesn't support this feature, consider we have clients
857 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700858
Steven Morelandb8361902023-02-01 23:18:04 +0000859 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700860
861 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000862 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000863 sendClientCallbackNotifications(serviceName, true,
864 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700865 }
866
867 // guarantee is temporary
868 service.guaranteeClient = false;
869 }
870
Steven Morelandb8361902023-02-01 23:18:04 +0000871 // Regardless of this situation, we want to give this notification as soon as possible.
872 // This way, we have a chance of preventing further thrashing.
873 if (hasKernelReportedClients && !service.hasClients) {
874 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
875 }
Steven Moreland66417652023-02-01 22:19:41 +0000876
Steven Morelandb8361902023-02-01 23:18:04 +0000877 // But limit rate of shutting down service.
878 if (isCalledOnInterval) {
879 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000880 sendClientCallbackNotifications(serviceName, false,
881 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000882 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700883 }
884
Steven Morelandb8361902023-02-01 23:18:04 +0000885 // May be different than 'hasKernelReportedClients'. We intentionally delay
886 // information about clients going away to reduce thrashing.
887 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700888}
889
Steven Moreland3e083b22023-01-26 00:46:30 +0000890void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
891 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700892 auto serviceIt = mNameToService.find(serviceName);
893 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000894 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
895 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700896 return;
897 }
898 Service& service = serviceIt->second;
899
Steven Morelandb8361902023-02-01 23:18:04 +0000900 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700901
Steven Morelandb8361902023-02-01 23:18:04 +0000902 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
903 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700904
905 auto ccIt = mNameToClientCallback.find(serviceName);
906 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000907 << "sendClientCallbackNotifications could not find callbacks for service when "
908 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700909
910 for (const auto& callback : ccIt->second) {
911 callback->onClients(service.binder, hasClients);
912 }
913
914 service.hasClients = hasClients;
915}
916
917Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
918 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000919 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700920 }
921
922 auto ctx = mAccess->getCallingContext();
923 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000924 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700925 }
926
927 auto serviceIt = mNameToService.find(name);
928 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000929 ALOGW("%s Tried to unregister %s, but that service wasn't registered to begin with.",
930 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000931 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700932 }
933
Steven Moreland7ee423b2022-09-24 03:52:08 +0000934 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000935 ALOGW("%s Only a server can unregister itself (for %s)", ctx.toDebugString().c_str(),
936 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000937 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
938 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700939 }
940
941 sp<IBinder> storedBinder = serviceIt->second.binder;
942
943 if (binder != storedBinder) {
Steven Moreland5759db02024-03-27 00:03:05 +0000944 ALOGW("%s Tried to unregister %s, but a different service is registered under this name.",
945 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000946 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
947 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700948 }
949
Steven Morelandb8361902023-02-01 23:18:04 +0000950 // important because we don't have timer-based guarantees, we don't want to clear
951 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700952 if (serviceIt->second.guaranteeClient) {
Steven Moreland5759db02024-03-27 00:03:05 +0000953 ALOGI("%s Tried to unregister %s, but there is about to be a client.",
954 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000955 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
956 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700957 }
958
Jon Spivack9f503a42019-10-22 16:49:19 -0700959 // - kernel driver will hold onto one refcount (during this transaction)
960 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000961 constexpr size_t kKnownClients = 2;
962
963 if (handleServiceClientCallback(kKnownClients, name, false)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000964 ALOGI("%s Tried to unregister %s, but there are clients.", ctx.toDebugString().c_str(),
965 name.c_str());
Steven Morelandb8361902023-02-01 23:18:04 +0000966
967 // Since we had a failed registration attempt, and the HIDL implementation of
968 // delaying service shutdown for multiple periods wasn't ported here... this may
969 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800970 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000971
Steven Morelandffb905b2023-03-28 18:24:37 +0000972 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
973 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700974 }
975
Steven Moreland5759db02024-03-27 00:03:05 +0000976 ALOGI("%s Unregistering %s", ctx.toDebugString().c_str(), name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700977 mNameToService.erase(name);
978
979 return Status::ok();
980}
981
Steven Moreland3ea43272021-01-28 22:49:28 +0000982Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
983 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000984 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +0000985 }
986
987 outReturn->reserve(mNameToService.size());
988 for (auto const& [name, service] : mNameToService) {
989 ServiceDebugInfo info;
990 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000991 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000992
993 outReturn->push_back(std::move(info));
994 }
995
996 return Status::ok();
997}
998
Pawan Wagh243888e2022-09-20 19:37:35 +0000999void ServiceManager::clear() {
1000 mNameToService.clear();
1001 mNameToRegistrationCallback.clear();
1002 mNameToClientCallback.clear();
1003}
1004
Steven Moreland8d0c9a72020-04-30 16:51:56 -07001005} // namespace android