blob: d85182d91546a552ffd270eca2462e3c26af1264 [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>
Parth Sane5ade9f12024-05-19 13:02:07 +000021#include <android-base/scopeguard.h>
Devin Moore42407bc2023-09-26 21:30:39 +000022#include <android-base/strings.h>
Jon Spivack9f503a42019-10-22 16:49:19 -070023#include <binder/BpBinder.h>
24#include <binder/IPCThreadState.h>
25#include <binder/ProcessState.h>
Steven Moreland86a17f82019-09-10 10:18:00 -070026#include <binder/Stability.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070027#include <cutils/android_filesystem_config.h>
28#include <cutils/multiuser.h>
Jon Spivack0d844302019-07-22 18:40:34 -070029#include <thread>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070030
Parth Sane5ade9f12024-05-19 13:02:07 +000031#if !defined(VENDORSERVICEMANAGER) && !defined(__ANDROID_RECOVERY__)
32#include "perfetto/public/te_category_macros.h"
33#include "perfetto/public/te_macros.h"
34#endif // !defined(VENDORSERVICEMANAGER) && !defined(__ANDROID_RECOVERY__)
35
Steven Moreland86a17f82019-09-10 10:18:00 -070036#ifndef VENDORSERVICEMANAGER
37#include <vintf/VintfObject.h>
Yifan Hong0a9b56e2021-11-30 16:45:40 -080038#ifdef __ANDROID_RECOVERY__
39#include <vintf/VintfObjectRecovery.h>
40#endif // __ANDROID_RECOVERY__
Steven Moreland86a17f82019-09-10 10:18:00 -070041#include <vintf/constants.h>
42#endif // !VENDORSERVICEMANAGER
43
Jooyung Han205e2822023-12-19 16:59:39 +090044#include "NameUtil.h"
45
Steven Moreland80e1e6d2019-06-21 12:35:59 -070046using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070047using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070048
49namespace android {
50
Parth Sane5ade9f12024-05-19 13:02:07 +000051#if defined(VENDORSERVICEMANAGER) || defined(__ANDROID_RECOVERY__)
52#define SM_PERFETTO_TRACE_FUNC(...)
53#else
54
55PERFETTO_TE_CATEGORIES_DEFINE(PERFETTO_SM_CATEGORIES);
56
57#define SM_PERFETTO_TRACE_FUNC(...) \
58 PERFETTO_TE_SCOPED(servicemanager, PERFETTO_TE_SLICE_BEGIN(__func__) __VA_OPT__(, ) __VA_ARGS__)
59
60#endif // !(defined(VENDORSERVICEMANAGER) || defined(__ANDROID_RECOVERY__))
61
Steven Morelandb9e1cbe2023-02-01 22:44:45 +000062bool is_multiuser_uid_isolated(uid_t uid) {
63 uid_t appid = multiuser_get_app_id(uid);
64 return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
65}
66
Steven Moreland86a17f82019-09-10 10:18:00 -070067#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080068
Steven Moreland2e293aa2020-09-23 00:25:16 +000069struct ManifestWithDescription {
70 std::shared_ptr<const vintf::HalManifest> manifest;
71 const char* description;
72};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080073static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
74#ifdef __ANDROID_RECOVERY__
75 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
76 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000077 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080078 return {};
79 }
80 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
81#else
82 auto vintfObject = vintf::VintfObject::GetInstance();
83 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000084 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080085 return {};
86 }
87 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
88 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
89#endif
90}
91
Steven Moreland2e293aa2020-09-23 00:25:16 +000092// func true -> stop search and forEachManifest will return true
93static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080094 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000095 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000096 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
97 // note, we explicitly do not retry here, so that we can detect VINTF
98 // or other bugs (b/151696835)
99 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +0000100 }
101 if (func(mwd)) return true;
102 }
103 return false;
104}
105
Jooyung Han205e2822023-12-19 16:59:39 +0900106static std::string getNativeInstanceName(const vintf::ManifestInstance& instance) {
107 return instance.package() + "/" + instance.instance();
108}
109
Steven Morelandedd4e072021-04-21 00:27:29 +0000110struct AidlName {
111 std::string package;
112 std::string iface;
113 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -0700114
Devin Moore9d1dfa02024-07-23 21:40:05 +0000115 static bool fill(const std::string& name, AidlName* aname, bool logError) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000116 size_t firstSlash = name.find('/');
117 size_t lastDot = name.rfind('.', firstSlash);
118 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Devin Moore9d1dfa02024-07-23 21:40:05 +0000119 if (logError) {
120 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
121 "some.package.foo.IFoo/default) but got: %s",
122 name.c_str());
123 }
Steven Morelandedd4e072021-04-21 00:27:29 +0000124 return false;
125 }
126 aname->package = name.substr(0, lastDot);
127 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
128 aname->instance = name.substr(firstSlash + 1);
129 return true;
130 }
131};
132
Jooyung Han205e2822023-12-19 16:59:39 +0900133static std::string getAidlInstanceName(const vintf::ManifestInstance& instance) {
134 return instance.package() + "." + instance.interface() + "/" + instance.instance();
135}
136
Steven Moreland5759db02024-03-27 00:03:05 +0000137static bool isVintfDeclared(const Access::CallingContext& ctx, const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900138 NativeName nname;
139 if (NativeName::fill(name, &nname)) {
140 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
141 if (mwd.manifest->hasNativeInstance(nname.package, nname.instance)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000142 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(),
143 name.c_str(), mwd.description);
Jooyung Han205e2822023-12-19 16:59:39 +0900144 return true; // break
145 }
146 return false; // continue
147 });
148 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000149 ALOGI("%s Could not find %s in the VINTF manifest.", ctx.toDebugString().c_str(),
150 name.c_str());
Jooyung Han205e2822023-12-19 16:59:39 +0900151 }
152 return found;
153 }
154
Steven Morelandedd4e072021-04-21 00:27:29 +0000155 AidlName aname;
Devin Moore9d1dfa02024-07-23 21:40:05 +0000156 if (!AidlName::fill(name, &aname, true)) return false;
Steven Morelandedd4e072021-04-21 00:27:29 +0000157
158 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
159 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000160 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(), name.c_str(),
161 mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000162 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700163 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000164 return false; // continue
165 });
166
167 if (!found) {
Devin Moore42407bc2023-09-26 21:30:39 +0000168 std::set<std::string> instances;
169 forEachManifest([&](const ManifestWithDescription& mwd) {
170 std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
171 instances.insert(res.begin(), res.end());
172 return true;
173 });
174
175 std::string available;
176 if (instances.empty()) {
177 available = "No alternative instances declared in VINTF";
178 } else {
179 // for logging only. We can't return this information to the client
180 // because they may not have permissions to find or list those
181 // instances
182 available = "VINTF declared instances: " + base::Join(instances, ", ");
183 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000184 // Although it is tested, explicitly rebuilding qualified name, in case it
185 // becomes something unexpected.
Steven Moreland5759db02024-03-27 00:03:05 +0000186 ALOGI("%s Could not find %s.%s/%s in the VINTF manifest. %s.", ctx.toDebugString().c_str(),
187 aname.package.c_str(), aname.iface.c_str(), aname.instance.c_str(),
188 available.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700189 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700190
Steven Moreland2e293aa2020-09-23 00:25:16 +0000191 return found;
192}
193
Steven Morelandedd4e072021-04-21 00:27:29 +0000194static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900195 NativeName nname;
196 if (NativeName::fill(name, &nname)) {
197 std::optional<std::string> updatableViaApex;
198
199 forEachManifest([&](const ManifestWithDescription& mwd) {
200 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
201 if (manifestInstance.format() != vintf::HalFormat::NATIVE) return true;
202 if (manifestInstance.package() != nname.package) return true;
203 if (manifestInstance.instance() != nname.instance) return true;
204 updatableViaApex = manifestInstance.updatableViaApex();
205 return false; // break (libvintf uses opposite convention)
206 });
207 return !cont;
208 });
209
210 return updatableViaApex;
211 }
212
Steven Morelandedd4e072021-04-21 00:27:29 +0000213 AidlName aname;
Devin Moore9d1dfa02024-07-23 21:40:05 +0000214 if (!AidlName::fill(name, &aname, true)) return std::nullopt;
Steven Morelandedd4e072021-04-21 00:27:29 +0000215
216 std::optional<std::string> updatableViaApex;
217
218 forEachManifest([&](const ManifestWithDescription& mwd) {
Jooyung Han9f1c6872024-01-23 06:42:02 +0900219 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000220 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
221 if (manifestInstance.package() != aname.package) return true;
222 if (manifestInstance.interface() != aname.iface) return true;
223 if (manifestInstance.instance() != aname.instance) return true;
224 updatableViaApex = manifestInstance.updatableViaApex();
225 return false; // break (libvintf uses opposite convention)
226 });
Jooyung Han9f1c6872024-01-23 06:42:02 +0900227 return !cont;
Steven Morelandedd4e072021-04-21 00:27:29 +0000228 });
229
230 return updatableViaApex;
231}
232
Jooyung Han205e2822023-12-19 16:59:39 +0900233static std::vector<std::string> getVintfUpdatableNames(const std::string& apexName) {
234 std::vector<std::string> names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900235
236 forEachManifest([&](const ManifestWithDescription& mwd) {
237 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Jooyung Han205e2822023-12-19 16:59:39 +0900238 if (manifestInstance.updatableViaApex().has_value() &&
Jooyung Han76944fe2022-10-25 17:02:45 +0900239 manifestInstance.updatableViaApex().value() == apexName) {
Jooyung Han205e2822023-12-19 16:59:39 +0900240 if (manifestInstance.format() == vintf::HalFormat::NATIVE) {
241 names.push_back(getNativeInstanceName(manifestInstance));
242 } else if (manifestInstance.format() == vintf::HalFormat::AIDL) {
243 names.push_back(getAidlInstanceName(manifestInstance));
244 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900245 }
Jooyung Hance94b752022-11-14 18:55:06 +0900246 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900247 });
248 return false; // continue
249 });
250
Jooyung Han205e2822023-12-19 16:59:39 +0900251 return names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900252}
253
Alice Wang8578f132024-05-03 09:01:56 +0000254static std::optional<std::string> getVintfAccessorName(const std::string& name) {
255 AidlName aname;
Devin Moore9d1dfa02024-07-23 21:40:05 +0000256 if (!AidlName::fill(name, &aname, false)) return std::nullopt;
Alice Wang8578f132024-05-03 09:01:56 +0000257
258 std::optional<std::string> accessor;
259 forEachManifest([&](const ManifestWithDescription& mwd) {
260 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
261 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
262 if (manifestInstance.package() != aname.package) return true;
263 if (manifestInstance.interface() != aname.iface) return true;
264 if (manifestInstance.instance() != aname.instance) return true;
265 accessor = manifestInstance.accessor();
266 return false; // break (libvintf uses opposite convention)
267 });
268 return false; // continue
269 });
270 return accessor;
271}
272
Devin Moore5e4c2f12021-09-09 22:36:33 +0000273static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
274 AidlName aname;
Devin Moore9d1dfa02024-07-23 21:40:05 +0000275 if (!AidlName::fill(name, &aname, true)) return std::nullopt;
Devin Moore5e4c2f12021-09-09 22:36:33 +0000276
277 std::optional<std::string> ip;
278 std::optional<uint64_t> port;
279 forEachManifest([&](const ManifestWithDescription& mwd) {
280 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
281 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
282 if (manifestInstance.package() != aname.package) return true;
283 if (manifestInstance.interface() != aname.iface) return true;
284 if (manifestInstance.instance() != aname.instance) return true;
285 ip = manifestInstance.ip();
286 port = manifestInstance.port();
287 return false; // break (libvintf uses opposite convention)
288 });
289 return false; // continue
290 });
291
292 if (ip.has_value() && port.has_value()) {
293 ConnectionInfo info;
294 info.ipAddress = *ip;
295 info.port = *port;
296 return std::make_optional<ConnectionInfo>(info);
297 } else {
298 return std::nullopt;
299 }
300}
301
Steven Moreland2e293aa2020-09-23 00:25:16 +0000302static std::vector<std::string> getVintfInstances(const std::string& interface) {
303 size_t lastDot = interface.rfind('.');
304 if (lastDot == std::string::npos) {
Jooyung Han205e2822023-12-19 16:59:39 +0900305 // This might be a package for native instance.
306 std::vector<std::string> ret;
307 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
308 auto instances = mwd.manifest->getNativeInstances(interface);
309 ret.insert(ret.end(), instances.begin(), instances.end());
310 return false; // continue
311 });
312 // If found, return it without error log.
313 if (!ret.empty()) {
314 return ret;
315 }
316
Pawan Wagh37526162022-09-29 21:55:26 +0000317 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
318 "but got: %s",
319 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000320 return {};
321 }
322 const std::string package = interface.substr(0, lastDot);
323 const std::string iface = interface.substr(lastDot+1);
324
325 std::vector<std::string> ret;
326 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
327 auto instances = mwd.manifest->getAidlInstances(package, iface);
328 ret.insert(ret.end(), instances.begin(), instances.end());
329 return false; // continue
330 });
331
332 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700333}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700334
Steven Moreland5759db02024-03-27 00:03:05 +0000335static bool meetsDeclarationRequirements(const Access::CallingContext& ctx,
336 const sp<IBinder>& binder, const std::string& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700337 if (!Stability::requiresVintfDeclaration(binder)) {
338 return true;
339 }
340
Steven Moreland5759db02024-03-27 00:03:05 +0000341 return isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700342}
Steven Moreland86a17f82019-09-10 10:18:00 -0700343#endif // !VENDORSERVICEMANAGER
344
Steven Morelandb8361902023-02-01 23:18:04 +0000345ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000346 if (hasClients) {
347 // only expected to happen on process death, we don't store the service
348 // name this late (it's in the map that holds this service), but if it
349 // is happening, we might want to change 'unlinkToDeath' to explicitly
350 // clear this bit so that we can abort in other cases, where it would
351 // mean inconsistent logic in servicemanager (unexpected and tested, but
352 // the original lazy service impl here had that bug).
Steven Moreland5759db02024-03-27 00:03:05 +0000353 ALOGW("A service was removed when there are clients");
Steven Morelandb8361902023-02-01 23:18:04 +0000354 }
355}
356
Steven Morelandd13f08b2019-11-18 14:23:09 -0800357ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700358// TODO(b/151696835): reenable performance hack when we solve bug, since with
359// this hack and other fixes, it is unlikely we will see even an ephemeral
360// failure when the manifest parse fails. The goal is that the manifest will
361// be read incorrectly and cause the process trying to register a HAL to
362// fail. If this is in fact an early boot kernel contention issue, then we
363// will get no failure, and by its absence, be signalled to invest more
364// effort in re-adding this performance hack.
365// #ifndef VENDORSERVICEMANAGER
366// // can process these at any times, don't want to delay first VINTF client
367// std::thread([] {
368// vintf::VintfObject::GetDeviceHalManifest();
369// vintf::VintfObject::GetFrameworkHalManifest();
370// }).detach();
371// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800372}
Steven Moreland130242d2019-08-26 17:41:32 -0700373ServiceManager::~ServiceManager() {
374 // this should only happen in tests
375
Jon Spivackf288b1d2019-12-19 17:15:51 -0800376 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700377 CHECK(!callbacks.empty()) << name;
378 for (const auto& callback : callbacks) {
379 CHECK(callback != nullptr) << name;
380 }
381 }
382
Steven Moreland130242d2019-08-26 17:41:32 -0700383 for (const auto& [name, service] : mNameToService) {
384 CHECK(service.binder != nullptr) << name;
385 }
386}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700387
Alice Wang8578f132024-05-03 09:01:56 +0000388Status ServiceManager::getService(const std::string& name, os::Service* outService) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000389 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
390
Alice Wang8578f132024-05-03 09:01:56 +0000391 *outService = tryGetService(name, true);
Jon Spivack0d844302019-07-22 18:40:34 -0700392 // returns ok regardless of result for legacy reasons
393 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700394}
395
Alice Wang8578f132024-05-03 09:01:56 +0000396Status ServiceManager::checkService(const std::string& name, os::Service* outService) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000397 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
398
Alice Wang8578f132024-05-03 09:01:56 +0000399 *outService = tryGetService(name, false);
Jon Spivack0d844302019-07-22 18:40:34 -0700400 // returns ok regardless of result for legacy reasons
401 return Status::ok();
402}
403
Alice Wang8578f132024-05-03 09:01:56 +0000404os::Service ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
405 std::optional<std::string> accessorName;
406#ifndef VENDORSERVICEMANAGER
407 accessorName = getVintfAccessorName(name);
408#endif
409 if (accessorName.has_value()) {
410 auto ctx = mAccess->getCallingContext();
411 if (!mAccess->canFind(ctx, name)) {
412 return os::Service::make<os::Service::Tag::accessor>(nullptr);
413 }
414 return os::Service::make<os::Service::Tag::accessor>(
415 tryGetBinder(*accessorName, startIfNotFound));
416 } else {
417 return os::Service::make<os::Service::Tag::binder>(tryGetBinder(name, startIfNotFound));
418 }
419}
420
421sp<IBinder> ServiceManager::tryGetBinder(const std::string& name, bool startIfNotFound) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000422 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
423
Steven Morelanda9fe4742019-07-18 14:45:20 -0700424 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700425
Jon Spivack0d844302019-07-22 18:40:34 -0700426 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700427 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700428 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700429 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700430
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000431 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
Steven Morelandbad75882023-06-16 20:59:06 +0000432 LOG(WARNING) << "Isolated app with UID " << ctx.uid << " requested '" << name
433 << "', but the service is not allowed for isolated apps.";
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000434 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700435 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700436 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700437 }
438
Steven Morelanda9fe4742019-07-18 14:45:20 -0700439 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700440 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700441 }
442
Jon Spivack0d844302019-07-22 18:40:34 -0700443 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000444 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700445 }
446
Jon Spivack9f503a42019-10-22 16:49:19 -0700447 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000448 // Force onClients to get sent, and then make sure the timerfd won't clear it
449 // by setting guaranteeClient again. This logic could be simplified by using
450 // a time-based guarantee. However, forcing onClients(true) to get sent
451 // right here is always going to be important for processes serving multiple
452 // lazy interfaces.
453 service->guaranteeClient = true;
454 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700455 service->guaranteeClient = true;
456 }
457
Jon Spivack0d844302019-07-22 18:40:34 -0700458 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700459}
460
Steven Moreland905e2e82019-07-17 11:05:45 -0700461bool isValidServiceName(const std::string& name) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000462 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
463
Steven Moreland905e2e82019-07-17 11:05:45 -0700464 if (name.size() == 0) return false;
465 if (name.size() > 127) return false;
466
467 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700468 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700469 if (c >= 'a' && c <= 'z') continue;
470 if (c >= 'A' && c <= 'Z') continue;
471 if (c >= '0' && c <= '9') continue;
472 return false;
473 }
474
475 return true;
476}
477
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700478Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000479 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
480
Steven Morelanda9fe4742019-07-18 14:45:20 -0700481 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700482
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700483 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000484 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700485 }
486
Steven Morelanda9fe4742019-07-18 14:45:20 -0700487 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000488 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700489 }
490
491 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000492 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700493 }
494
Steven Moreland905e2e82019-07-17 11:05:45 -0700495 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000496 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000497 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700498 }
499
Steven Moreland86a17f82019-09-10 10:18:00 -0700500#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000501 if (!meetsDeclarationRequirements(ctx, binder, name)) {
Steven Moreland86a17f82019-09-10 10:18:00 -0700502 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000503 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700504 }
505#endif // !VENDORSERVICEMANAGER
506
Devin Moore4e21def2023-02-24 21:54:14 +0000507 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
Steven Moreland5759db02024-03-27 00:03:05 +0000508 ALOGW("%s Dump flag priority is not set when adding %s", ctx.toDebugString().c_str(),
509 name.c_str());
Devin Moore4e21def2023-02-24 21:54:14 +0000510 }
511
Steven Moreland88860b02019-08-12 14:24:14 -0700512 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000513 if (binder->remoteBinder() != nullptr &&
514 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Steven Moreland5759db02024-03-27 00:03:05 +0000515 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000516 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700517 }
518
Steven Moreland7ee423b2022-09-24 03:52:08 +0000519 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000520 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000521 if (it != mNameToService.end()) {
522 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000523 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000524
525 // We could do better than this because if the other service dies, it
526 // may not have an entry here. However, this case is unlikely. We are
527 // only trying to detect when two different services are accidentally installed.
528
529 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000530 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
531 "from UID %u. Multiple instances installed?",
532 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000533 }
534
535 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000536 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
537 "from SID %s. Multiple instances installed?",
538 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000539 }
540
Pawan Wagh37526162022-09-29 21:55:26 +0000541 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
542 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
543 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000544 }
545
Devin Moore05ffe522020-08-06 13:58:29 -0700546 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000547 mNameToService[name] = Service{
548 .binder = binder,
549 .allowIsolated = allowIsolated,
550 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000551 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000552 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000553 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700554 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700555
Steven Moreland7ee423b2022-09-24 03:52:08 +0000556 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000557 // If someone is currently waiting on the service, notify the service that
558 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000559 mNameToService[name].guaranteeClient = true;
560 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
561 mNameToService[name].guaranteeClient = true;
562
Steven Moreland27cfab02019-08-12 14:34:16 -0700563 for (const sp<IServiceCallback>& cb : it->second) {
564 // permission checked in registerForNotifications
565 cb->onRegistration(name, binder);
566 }
567 }
568
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700569 return Status::ok();
570}
571
572Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000573 SM_PERFETTO_TRACE_FUNC();
574
Steven Morelanda9fe4742019-07-18 14:45:20 -0700575 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000576 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700577 }
578
579 size_t toReserve = 0;
580 for (auto const& [name, service] : mNameToService) {
581 (void) name;
582
583 if (service.dumpPriority & dumpPriority) ++toReserve;
584 }
585
586 CHECK(outList->empty());
587
588 outList->reserve(toReserve);
589 for (auto const& [name, service] : mNameToService) {
590 (void) service;
591
592 if (service.dumpPriority & dumpPriority) {
593 outList->push_back(name);
594 }
595 }
596
597 return Status::ok();
598}
599
Steven Moreland27cfab02019-08-12 14:34:16 -0700600Status ServiceManager::registerForNotifications(
601 const std::string& name, const sp<IServiceCallback>& callback) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000602 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
603
Steven Moreland27cfab02019-08-12 14:34:16 -0700604 auto ctx = mAccess->getCallingContext();
605
Alice Wang8578f132024-05-03 09:01:56 +0000606 // TODO(b/338541373): Implement the notification mechanism for services accessed via
607 // IAccessor.
608 std::optional<std::string> accessorName;
609 if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
610 return status;
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000611 }
612
613 // note - we could allow isolated apps to get notifications if we
614 // keep track of isolated callbacks and non-isolated callbacks, but
615 // this is done since isolated apps shouldn't access lazy services
616 // so we should be able to use different APIs to keep things simple.
617 // Here, we disallow everything, because the service might not be
618 // registered yet.
619 if (is_multiuser_uid_isolated(ctx.uid)) {
620 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700621 }
622
623 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000624 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000625 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700626 }
627
628 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000629 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700630 }
631
Steven Morelandb0983182021-04-02 03:14:04 +0000632 if (OK !=
633 IInterface::asBinder(callback)->linkToDeath(
634 sp<ServiceManager>::fromExisting(this))) {
Steven Moreland5759db02024-03-27 00:03:05 +0000635 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000636 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700637 }
638
Jon Spivackf288b1d2019-12-19 17:15:51 -0800639 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700640
641 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
642 const sp<IBinder>& binder = it->second.binder;
643
644 // never null if an entry exists
645 CHECK(binder != nullptr) << name;
646 callback->onRegistration(name, binder);
647 }
648
649 return Status::ok();
650}
651Status ServiceManager::unregisterForNotifications(
652 const std::string& name, const sp<IServiceCallback>& callback) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000653 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
654
Steven Moreland27cfab02019-08-12 14:34:16 -0700655 auto ctx = mAccess->getCallingContext();
656
Alice Wang8578f132024-05-03 09:01:56 +0000657 std::optional<std::string> accessorName;
658 if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
659 return status;
Steven Moreland27cfab02019-08-12 14:34:16 -0700660 }
661
662 bool found = false;
663
Jon Spivackf288b1d2019-12-19 17:15:51 -0800664 auto it = mNameToRegistrationCallback.find(name);
665 if (it != mNameToRegistrationCallback.end()) {
666 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700667 }
668
669 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000670 ALOGE("%s Trying to unregister callback, but none exists %s", ctx.toDebugString().c_str(),
671 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000672 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700673 }
674
675 return Status::ok();
676}
677
Steven Morelandb82b8f82019-10-28 10:52:34 -0700678Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000679 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
680
Steven Morelandb82b8f82019-10-28 10:52:34 -0700681 auto ctx = mAccess->getCallingContext();
682
Alice Wang8578f132024-05-03 09:01:56 +0000683 std::optional<std::string> accessorName;
684 if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
685 return status;
Steven Morelandb82b8f82019-10-28 10:52:34 -0700686 }
687
688 *outReturn = false;
689
690#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000691 *outReturn = isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700692#endif
693 return Status::ok();
694}
695
Steven Moreland2e293aa2020-09-23 00:25:16 +0000696binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000697 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("interface", interface.c_str()));
698
Steven Moreland2e293aa2020-09-23 00:25:16 +0000699 auto ctx = mAccess->getCallingContext();
700
701 std::vector<std::string> allInstances;
702#ifndef VENDORSERVICEMANAGER
703 allInstances = getVintfInstances(interface);
704#endif
705
706 outReturn->clear();
707
Alice Wang8578f132024-05-03 09:01:56 +0000708 std::optional<std::string> _accessorName;
Steven Moreland2e293aa2020-09-23 00:25:16 +0000709 for (const std::string& instance : allInstances) {
Alice Wang8578f132024-05-03 09:01:56 +0000710 if (auto status = canFindService(ctx, interface + "/" + instance, &_accessorName);
711 status.isOk()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000712 outReturn->push_back(instance);
713 }
714 }
715
716 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000717 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000718 }
719
720 return Status::ok();
721}
722
Steven Morelandedd4e072021-04-21 00:27:29 +0000723Status ServiceManager::updatableViaApex(const std::string& name,
724 std::optional<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000725 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
726
Steven Morelandedd4e072021-04-21 00:27:29 +0000727 auto ctx = mAccess->getCallingContext();
728
Alice Wang8578f132024-05-03 09:01:56 +0000729 std::optional<std::string> _accessorName;
730 if (auto status = canFindService(ctx, name, &_accessorName); !status.isOk()) {
731 return status;
Steven Morelandedd4e072021-04-21 00:27:29 +0000732 }
733
734 *outReturn = std::nullopt;
735
736#ifndef VENDORSERVICEMANAGER
737 *outReturn = getVintfUpdatableApex(name);
738#endif
739 return Status::ok();
740}
741
Jooyung Han76944fe2022-10-25 17:02:45 +0900742Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
743 std::vector<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000744 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("apexName", apexName.c_str()));
745
Jooyung Han76944fe2022-10-25 17:02:45 +0900746 auto ctx = mAccess->getCallingContext();
747
Jooyung Han205e2822023-12-19 16:59:39 +0900748 std::vector<std::string> apexUpdatableNames;
Jooyung Han76944fe2022-10-25 17:02:45 +0900749#ifndef VENDORSERVICEMANAGER
Jooyung Han205e2822023-12-19 16:59:39 +0900750 apexUpdatableNames = getVintfUpdatableNames(apexName);
Jooyung Han76944fe2022-10-25 17:02:45 +0900751#endif
752
753 outReturn->clear();
754
Alice Wang8578f132024-05-03 09:01:56 +0000755 std::optional<std::string> _accessorName;
Jooyung Han205e2822023-12-19 16:59:39 +0900756 for (const std::string& name : apexUpdatableNames) {
Alice Wang8578f132024-05-03 09:01:56 +0000757 if (auto status = canFindService(ctx, name, &_accessorName); status.isOk()) {
Jooyung Han205e2822023-12-19 16:59:39 +0900758 outReturn->push_back(name);
Jooyung Han76944fe2022-10-25 17:02:45 +0900759 }
760 }
761
Jooyung Han205e2822023-12-19 16:59:39 +0900762 if (outReturn->size() == 0 && apexUpdatableNames.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000763 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900764 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900765 return Status::ok();
766}
767
Devin Moore5e4c2f12021-09-09 22:36:33 +0000768Status ServiceManager::getConnectionInfo(const std::string& name,
769 std::optional<ConnectionInfo>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000770 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
771
Devin Moore5e4c2f12021-09-09 22:36:33 +0000772 auto ctx = mAccess->getCallingContext();
773
Alice Wang8578f132024-05-03 09:01:56 +0000774 std::optional<std::string> _accessorName;
775 if (auto status = canFindService(ctx, name, &_accessorName); !status.isOk()) {
776 return status;
Devin Moore5e4c2f12021-09-09 22:36:33 +0000777 }
778
779 *outReturn = std::nullopt;
780
781#ifndef VENDORSERVICEMANAGER
782 *outReturn = getVintfConnectionInfo(name);
783#endif
784 return Status::ok();
785}
786
Jon Spivackf288b1d2019-12-19 17:15:51 -0800787void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
788 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700789 bool* found) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000790 SM_PERFETTO_TRACE_FUNC();
791
Steven Moreland27cfab02019-08-12 14:34:16 -0700792 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
793
794 for (auto lit = listeners.begin(); lit != listeners.end();) {
795 if (IInterface::asBinder(*lit) == who) {
796 if(found) *found = true;
797 lit = listeners.erase(lit);
798 } else {
799 ++lit;
800 }
801 }
802
803 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800804 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700805 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800806 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700807 }
808}
809
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700810void ServiceManager::binderDied(const wp<IBinder>& who) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000811 SM_PERFETTO_TRACE_FUNC();
812
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700813 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
814 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000815 // TODO: currently, this entry contains the state also
816 // associated with mNameToClientCallback. If we allowed
817 // other processes to register client callbacks, we
818 // would have to preserve hasClients (perhaps moving
819 // that state into mNameToClientCallback, which is complicated
820 // because those callbacks are associated w/ particular binder
821 // objects, though they are indexed by name now, they may
822 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700823 it = mNameToService.erase(it);
824 } else {
825 ++it;
826 }
827 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700828
Jon Spivackf288b1d2019-12-19 17:15:51 -0800829 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
830 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700831 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700832
833 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
834 removeClientCallback(who, &it);
835 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700836}
837
Steven Morelandaa33e852023-05-10 16:42:15 +0000838void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
Steven Moreland5759db02024-03-27 00:03:05 +0000839 ALOGI("%s Since '%s' could not be found trying to start it as a lazy AIDL service. (if it's "
840 "not configured to be a lazy service, it may be stuck starting or still starting).",
841 ctx.toDebugString().c_str(), name.c_str());
Jon Spivack0d844302019-07-22 18:40:34 -0700842
843 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000844 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000845 ALOGI("%s Tried to start aidl service %s as a lazy service, but was unable to. Usually "
846 "this happens when a service is not installed, but if the service is intended to "
847 "be used as a lazy service, then it may be configured incorrectly.",
848 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000849 }
Jon Spivack0d844302019-07-22 18:40:34 -0700850 }).detach();
851}
852
Jon Spivack9f503a42019-10-22 16:49:19 -0700853Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
854 const sp<IClientCallback>& cb) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000855 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
856
Jon Spivack9f503a42019-10-22 16:49:19 -0700857 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000858 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700859 }
860
861 auto ctx = mAccess->getCallingContext();
862 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000863 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700864 }
865
866 auto serviceIt = mNameToService.find(name);
867 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000868 ALOGE("%s Could not add callback for nonexistent service: %s", ctx.toDebugString().c_str(),
869 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000870 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700871 }
872
Steven Moreland7ee423b2022-09-24 03:52:08 +0000873 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000874 ALOGW("%s Only a server can register for client callbacks (for %s)",
875 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000876 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
877 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700878 }
879
880 if (serviceIt->second.binder != service) {
Steven Moreland5759db02024-03-27 00:03:05 +0000881 ALOGW("%s Tried to register client callback for %s but a different service is registered "
Pawan Wagh37526162022-09-29 21:55:26 +0000882 "under this name.",
Steven Moreland5759db02024-03-27 00:03:05 +0000883 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000884 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700885 }
886
Steven Morelandb0983182021-04-02 03:14:04 +0000887 if (OK !=
888 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
David Duarte67d65282024-04-10 23:54:36 +0000889 ALOGE("%s Could not linkToDeath when adding client callback for %s",
890 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000891 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700892 }
893
Steven Moreland79578672023-04-27 19:38:00 +0000894 // WARNING: binderDied makes an assumption about this. If we open up client
895 // callbacks to other services, certain race conditions may lead to services
896 // getting extra client callback notifications.
897 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000898 if (serviceIt->second.hasClients) {
899 cb->onClients(service, true);
900 }
901
Jon Spivack9f503a42019-10-22 16:49:19 -0700902 mNameToClientCallback[name].push_back(cb);
903
Steven Morelandefea66b2023-06-17 01:59:34 +0000904 // Flush updated info to client callbacks (especially if guaranteeClient
905 // and !hasClient, see b/285202885). We may or may not have clients at
906 // this point, so ignore the return value.
907 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
908
Jon Spivack9f503a42019-10-22 16:49:19 -0700909 return Status::ok();
910}
911
912void ServiceManager::removeClientCallback(const wp<IBinder>& who,
913 ClientCallbackMap::iterator* it) {
914 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
915
916 for (auto lit = listeners.begin(); lit != listeners.end();) {
917 if (IInterface::asBinder(*lit) == who) {
918 lit = listeners.erase(lit);
919 } else {
920 ++lit;
921 }
922 }
923
924 if (listeners.empty()) {
925 *it = mNameToClientCallback.erase(*it);
926 } else {
927 (*it)++;
928 }
929}
930
931ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000932 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700933 if (bpBinder == nullptr) return -1;
934
Steven Morelande8393882020-12-18 02:27:20 +0000935 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700936}
937
938void ServiceManager::handleClientCallbacks() {
939 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000940 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700941 }
942}
943
Steven Morelandb8361902023-02-01 23:18:04 +0000944bool ServiceManager::handleServiceClientCallback(size_t knownClients,
945 const std::string& serviceName,
946 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700947 auto serviceIt = mNameToService.find(serviceName);
948 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000949 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700950 }
951
952 Service& service = serviceIt->second;
953 ssize_t count = service.getNodeStrongRefCount();
954
Steven Morelandb8361902023-02-01 23:18:04 +0000955 // binder driver doesn't support this feature, consider we have clients
956 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700957
Steven Morelandb8361902023-02-01 23:18:04 +0000958 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700959
960 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000961 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000962 sendClientCallbackNotifications(serviceName, true,
963 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700964 }
965
966 // guarantee is temporary
967 service.guaranteeClient = false;
968 }
969
Steven Morelandb8361902023-02-01 23:18:04 +0000970 // Regardless of this situation, we want to give this notification as soon as possible.
971 // This way, we have a chance of preventing further thrashing.
972 if (hasKernelReportedClients && !service.hasClients) {
973 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
974 }
Steven Moreland66417652023-02-01 22:19:41 +0000975
Steven Morelandb8361902023-02-01 23:18:04 +0000976 // But limit rate of shutting down service.
977 if (isCalledOnInterval) {
978 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000979 sendClientCallbackNotifications(serviceName, false,
980 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000981 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700982 }
983
Steven Morelandb8361902023-02-01 23:18:04 +0000984 // May be different than 'hasKernelReportedClients'. We intentionally delay
985 // information about clients going away to reduce thrashing.
986 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700987}
988
Steven Moreland3e083b22023-01-26 00:46:30 +0000989void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
990 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700991 auto serviceIt = mNameToService.find(serviceName);
992 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000993 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
994 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700995 return;
996 }
997 Service& service = serviceIt->second;
998
Steven Morelandb8361902023-02-01 23:18:04 +0000999 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -07001000
Steven Morelandb8361902023-02-01 23:18:04 +00001001 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
1002 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -07001003
1004 auto ccIt = mNameToClientCallback.find(serviceName);
1005 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +00001006 << "sendClientCallbackNotifications could not find callbacks for service when "
1007 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -07001008
1009 for (const auto& callback : ccIt->second) {
1010 callback->onClients(service.binder, hasClients);
1011 }
1012
1013 service.hasClients = hasClients;
1014}
1015
1016Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
Parth Sane5ade9f12024-05-19 13:02:07 +00001017 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
1018
Jon Spivack9f503a42019-10-22 16:49:19 -07001019 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +00001020 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001021 }
1022
1023 auto ctx = mAccess->getCallingContext();
1024 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +00001025 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001026 }
1027
1028 auto serviceIt = mNameToService.find(name);
1029 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +00001030 ALOGW("%s Tried to unregister %s, but that service wasn't registered to begin with.",
1031 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001032 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001033 }
1034
Steven Moreland7ee423b2022-09-24 03:52:08 +00001035 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +00001036 ALOGW("%s Only a server can unregister itself (for %s)", ctx.toDebugString().c_str(),
1037 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001038 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
1039 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001040 }
1041
1042 sp<IBinder> storedBinder = serviceIt->second.binder;
1043
1044 if (binder != storedBinder) {
Steven Moreland5759db02024-03-27 00:03:05 +00001045 ALOGW("%s Tried to unregister %s, but a different service is registered under this name.",
1046 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001047 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1048 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001049 }
1050
Steven Morelandb8361902023-02-01 23:18:04 +00001051 // important because we don't have timer-based guarantees, we don't want to clear
1052 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -07001053 if (serviceIt->second.guaranteeClient) {
Steven Moreland5759db02024-03-27 00:03:05 +00001054 ALOGI("%s Tried to unregister %s, but there is about to be a client.",
1055 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001056 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1057 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -07001058 }
1059
Jon Spivack9f503a42019-10-22 16:49:19 -07001060 // - kernel driver will hold onto one refcount (during this transaction)
1061 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +00001062 constexpr size_t kKnownClients = 2;
1063
1064 if (handleServiceClientCallback(kKnownClients, name, false)) {
Steven Moreland5759db02024-03-27 00:03:05 +00001065 ALOGI("%s Tried to unregister %s, but there are clients.", ctx.toDebugString().c_str(),
1066 name.c_str());
Steven Morelandb8361902023-02-01 23:18:04 +00001067
1068 // Since we had a failed registration attempt, and the HIDL implementation of
1069 // delaying service shutdown for multiple periods wasn't ported here... this may
1070 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -08001071 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +00001072
Steven Morelandffb905b2023-03-28 18:24:37 +00001073 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1074 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001075 }
1076
Steven Moreland5759db02024-03-27 00:03:05 +00001077 ALOGI("%s Unregistering %s", ctx.toDebugString().c_str(), name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -07001078 mNameToService.erase(name);
1079
1080 return Status::ok();
1081}
1082
Alice Wang8578f132024-05-03 09:01:56 +00001083Status ServiceManager::canFindService(const Access::CallingContext& ctx, const std::string& name,
1084 std::optional<std::string>* accessor) {
1085 if (!mAccess->canFind(ctx, name)) {
1086 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied for service.");
1087 }
1088#ifndef VENDORSERVICEMANAGER
1089 *accessor = getVintfAccessorName(name);
1090#endif
1091 if (accessor->has_value()) {
1092 if (!mAccess->canFind(ctx, accessor->value())) {
1093 return Status::fromExceptionCode(Status::EX_SECURITY,
1094 "SELinux denied for the accessor of the service.");
1095 }
1096 }
1097 return Status::ok();
1098}
1099
Steven Moreland3ea43272021-01-28 22:49:28 +00001100Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +00001101 SM_PERFETTO_TRACE_FUNC();
Steven Moreland3ea43272021-01-28 22:49:28 +00001102 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +00001103 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +00001104 }
1105
1106 outReturn->reserve(mNameToService.size());
1107 for (auto const& [name, service] : mNameToService) {
1108 ServiceDebugInfo info;
1109 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +00001110 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +00001111
1112 outReturn->push_back(std::move(info));
1113 }
1114
1115 return Status::ok();
1116}
1117
Pawan Wagh243888e2022-09-20 19:37:35 +00001118void ServiceManager::clear() {
1119 mNameToService.clear();
1120 mNameToRegistrationCallback.clear();
1121 mNameToClientCallback.clear();
1122}
1123
Steven Moreland8d0c9a72020-04-30 16:51:56 -07001124} // namespace android