blob: 0f251d2b2afdd2359adb5f3f9f7d63e7f884b40d [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
Steven Morelandedd4e072021-04-21 00:27:29 +0000115 static bool fill(const std::string& name, AidlName* aname) {
116 size_t firstSlash = name.find('/');
117 size_t lastDot = name.rfind('.', firstSlash);
118 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000119 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
120 "some.package.foo.IFoo/default) but got: %s",
121 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000122 return false;
123 }
124 aname->package = name.substr(0, lastDot);
125 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
126 aname->instance = name.substr(firstSlash + 1);
127 return true;
128 }
129};
130
Jooyung Han205e2822023-12-19 16:59:39 +0900131static std::string getAidlInstanceName(const vintf::ManifestInstance& instance) {
132 return instance.package() + "." + instance.interface() + "/" + instance.instance();
133}
134
Steven Moreland5759db02024-03-27 00:03:05 +0000135static bool isVintfDeclared(const Access::CallingContext& ctx, const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900136 NativeName nname;
137 if (NativeName::fill(name, &nname)) {
138 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
139 if (mwd.manifest->hasNativeInstance(nname.package, nname.instance)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000140 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(),
141 name.c_str(), mwd.description);
Jooyung Han205e2822023-12-19 16:59:39 +0900142 return true; // break
143 }
144 return false; // continue
145 });
146 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000147 ALOGI("%s Could not find %s in the VINTF manifest.", ctx.toDebugString().c_str(),
148 name.c_str());
Jooyung Han205e2822023-12-19 16:59:39 +0900149 }
150 return found;
151 }
152
Steven Morelandedd4e072021-04-21 00:27:29 +0000153 AidlName aname;
154 if (!AidlName::fill(name, &aname)) return false;
155
156 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
157 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000158 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(), name.c_str(),
159 mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000160 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700161 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000162 return false; // continue
163 });
164
165 if (!found) {
Devin Moore42407bc2023-09-26 21:30:39 +0000166 std::set<std::string> instances;
167 forEachManifest([&](const ManifestWithDescription& mwd) {
168 std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
169 instances.insert(res.begin(), res.end());
170 return true;
171 });
172
173 std::string available;
174 if (instances.empty()) {
175 available = "No alternative instances declared in VINTF";
176 } else {
177 // for logging only. We can't return this information to the client
178 // because they may not have permissions to find or list those
179 // instances
180 available = "VINTF declared instances: " + base::Join(instances, ", ");
181 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000182 // Although it is tested, explicitly rebuilding qualified name, in case it
183 // becomes something unexpected.
Steven Moreland5759db02024-03-27 00:03:05 +0000184 ALOGI("%s Could not find %s.%s/%s in the VINTF manifest. %s.", ctx.toDebugString().c_str(),
185 aname.package.c_str(), aname.iface.c_str(), aname.instance.c_str(),
186 available.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700187 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700188
Steven Moreland2e293aa2020-09-23 00:25:16 +0000189 return found;
190}
191
Steven Morelandedd4e072021-04-21 00:27:29 +0000192static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900193 NativeName nname;
194 if (NativeName::fill(name, &nname)) {
195 std::optional<std::string> updatableViaApex;
196
197 forEachManifest([&](const ManifestWithDescription& mwd) {
198 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
199 if (manifestInstance.format() != vintf::HalFormat::NATIVE) return true;
200 if (manifestInstance.package() != nname.package) return true;
201 if (manifestInstance.instance() != nname.instance) return true;
202 updatableViaApex = manifestInstance.updatableViaApex();
203 return false; // break (libvintf uses opposite convention)
204 });
205 return !cont;
206 });
207
208 return updatableViaApex;
209 }
210
Steven Morelandedd4e072021-04-21 00:27:29 +0000211 AidlName aname;
212 if (!AidlName::fill(name, &aname)) return std::nullopt;
213
214 std::optional<std::string> updatableViaApex;
215
216 forEachManifest([&](const ManifestWithDescription& mwd) {
Jooyung Han9f1c6872024-01-23 06:42:02 +0900217 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000218 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
219 if (manifestInstance.package() != aname.package) return true;
220 if (manifestInstance.interface() != aname.iface) return true;
221 if (manifestInstance.instance() != aname.instance) return true;
222 updatableViaApex = manifestInstance.updatableViaApex();
223 return false; // break (libvintf uses opposite convention)
224 });
Jooyung Han9f1c6872024-01-23 06:42:02 +0900225 return !cont;
Steven Morelandedd4e072021-04-21 00:27:29 +0000226 });
227
228 return updatableViaApex;
229}
230
Jooyung Han205e2822023-12-19 16:59:39 +0900231static std::vector<std::string> getVintfUpdatableNames(const std::string& apexName) {
232 std::vector<std::string> names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900233
234 forEachManifest([&](const ManifestWithDescription& mwd) {
235 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Jooyung Han205e2822023-12-19 16:59:39 +0900236 if (manifestInstance.updatableViaApex().has_value() &&
Jooyung Han76944fe2022-10-25 17:02:45 +0900237 manifestInstance.updatableViaApex().value() == apexName) {
Jooyung Han205e2822023-12-19 16:59:39 +0900238 if (manifestInstance.format() == vintf::HalFormat::NATIVE) {
239 names.push_back(getNativeInstanceName(manifestInstance));
240 } else if (manifestInstance.format() == vintf::HalFormat::AIDL) {
241 names.push_back(getAidlInstanceName(manifestInstance));
242 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900243 }
Jooyung Hance94b752022-11-14 18:55:06 +0900244 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900245 });
246 return false; // continue
247 });
248
Jooyung Han205e2822023-12-19 16:59:39 +0900249 return names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900250}
251
Alice Wang8578f132024-05-03 09:01:56 +0000252static std::optional<std::string> getVintfAccessorName(const std::string& name) {
253 AidlName aname;
254 if (!AidlName::fill(name, &aname)) return std::nullopt;
255
256 std::optional<std::string> accessor;
257 forEachManifest([&](const ManifestWithDescription& mwd) {
258 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
259 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
260 if (manifestInstance.package() != aname.package) return true;
261 if (manifestInstance.interface() != aname.iface) return true;
262 if (manifestInstance.instance() != aname.instance) return true;
263 accessor = manifestInstance.accessor();
264 return false; // break (libvintf uses opposite convention)
265 });
266 return false; // continue
267 });
268 return accessor;
269}
270
Devin Moore5e4c2f12021-09-09 22:36:33 +0000271static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
272 AidlName aname;
273 if (!AidlName::fill(name, &aname)) return std::nullopt;
274
275 std::optional<std::string> ip;
276 std::optional<uint64_t> port;
277 forEachManifest([&](const ManifestWithDescription& mwd) {
278 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
279 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
280 if (manifestInstance.package() != aname.package) return true;
281 if (manifestInstance.interface() != aname.iface) return true;
282 if (manifestInstance.instance() != aname.instance) return true;
283 ip = manifestInstance.ip();
284 port = manifestInstance.port();
285 return false; // break (libvintf uses opposite convention)
286 });
287 return false; // continue
288 });
289
290 if (ip.has_value() && port.has_value()) {
291 ConnectionInfo info;
292 info.ipAddress = *ip;
293 info.port = *port;
294 return std::make_optional<ConnectionInfo>(info);
295 } else {
296 return std::nullopt;
297 }
298}
299
Steven Moreland2e293aa2020-09-23 00:25:16 +0000300static std::vector<std::string> getVintfInstances(const std::string& interface) {
301 size_t lastDot = interface.rfind('.');
302 if (lastDot == std::string::npos) {
Jooyung Han205e2822023-12-19 16:59:39 +0900303 // This might be a package for native instance.
304 std::vector<std::string> ret;
305 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
306 auto instances = mwd.manifest->getNativeInstances(interface);
307 ret.insert(ret.end(), instances.begin(), instances.end());
308 return false; // continue
309 });
310 // If found, return it without error log.
311 if (!ret.empty()) {
312 return ret;
313 }
314
Pawan Wagh37526162022-09-29 21:55:26 +0000315 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
316 "but got: %s",
317 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000318 return {};
319 }
320 const std::string package = interface.substr(0, lastDot);
321 const std::string iface = interface.substr(lastDot+1);
322
323 std::vector<std::string> ret;
324 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
325 auto instances = mwd.manifest->getAidlInstances(package, iface);
326 ret.insert(ret.end(), instances.begin(), instances.end());
327 return false; // continue
328 });
329
330 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700331}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700332
Steven Moreland5759db02024-03-27 00:03:05 +0000333static bool meetsDeclarationRequirements(const Access::CallingContext& ctx,
334 const sp<IBinder>& binder, const std::string& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700335 if (!Stability::requiresVintfDeclaration(binder)) {
336 return true;
337 }
338
Steven Moreland5759db02024-03-27 00:03:05 +0000339 return isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700340}
Steven Moreland86a17f82019-09-10 10:18:00 -0700341#endif // !VENDORSERVICEMANAGER
342
Steven Morelandb8361902023-02-01 23:18:04 +0000343ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000344 if (hasClients) {
345 // only expected to happen on process death, we don't store the service
346 // name this late (it's in the map that holds this service), but if it
347 // is happening, we might want to change 'unlinkToDeath' to explicitly
348 // clear this bit so that we can abort in other cases, where it would
349 // mean inconsistent logic in servicemanager (unexpected and tested, but
350 // the original lazy service impl here had that bug).
Steven Moreland5759db02024-03-27 00:03:05 +0000351 ALOGW("A service was removed when there are clients");
Steven Morelandb8361902023-02-01 23:18:04 +0000352 }
353}
354
Steven Morelandd13f08b2019-11-18 14:23:09 -0800355ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700356// TODO(b/151696835): reenable performance hack when we solve bug, since with
357// this hack and other fixes, it is unlikely we will see even an ephemeral
358// failure when the manifest parse fails. The goal is that the manifest will
359// be read incorrectly and cause the process trying to register a HAL to
360// fail. If this is in fact an early boot kernel contention issue, then we
361// will get no failure, and by its absence, be signalled to invest more
362// effort in re-adding this performance hack.
363// #ifndef VENDORSERVICEMANAGER
364// // can process these at any times, don't want to delay first VINTF client
365// std::thread([] {
366// vintf::VintfObject::GetDeviceHalManifest();
367// vintf::VintfObject::GetFrameworkHalManifest();
368// }).detach();
369// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800370}
Steven Moreland130242d2019-08-26 17:41:32 -0700371ServiceManager::~ServiceManager() {
372 // this should only happen in tests
373
Jon Spivackf288b1d2019-12-19 17:15:51 -0800374 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700375 CHECK(!callbacks.empty()) << name;
376 for (const auto& callback : callbacks) {
377 CHECK(callback != nullptr) << name;
378 }
379 }
380
Steven Moreland130242d2019-08-26 17:41:32 -0700381 for (const auto& [name, service] : mNameToService) {
382 CHECK(service.binder != nullptr) << name;
383 }
384}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700385
Alice Wang8578f132024-05-03 09:01:56 +0000386Status ServiceManager::getService(const std::string& name, os::Service* outService) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000387 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
388
Alice Wang8578f132024-05-03 09:01:56 +0000389 *outService = tryGetService(name, true);
Jon Spivack0d844302019-07-22 18:40:34 -0700390 // returns ok regardless of result for legacy reasons
391 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700392}
393
Alice Wang8578f132024-05-03 09:01:56 +0000394Status ServiceManager::checkService(const std::string& name, os::Service* outService) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000395 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
396
Alice Wang8578f132024-05-03 09:01:56 +0000397 *outService = tryGetService(name, false);
Jon Spivack0d844302019-07-22 18:40:34 -0700398 // returns ok regardless of result for legacy reasons
399 return Status::ok();
400}
401
Alice Wang8578f132024-05-03 09:01:56 +0000402os::Service ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
403 std::optional<std::string> accessorName;
404#ifndef VENDORSERVICEMANAGER
405 accessorName = getVintfAccessorName(name);
406#endif
407 if (accessorName.has_value()) {
408 auto ctx = mAccess->getCallingContext();
409 if (!mAccess->canFind(ctx, name)) {
410 return os::Service::make<os::Service::Tag::accessor>(nullptr);
411 }
412 return os::Service::make<os::Service::Tag::accessor>(
413 tryGetBinder(*accessorName, startIfNotFound));
414 } else {
415 return os::Service::make<os::Service::Tag::binder>(tryGetBinder(name, startIfNotFound));
416 }
417}
418
419sp<IBinder> ServiceManager::tryGetBinder(const std::string& name, bool startIfNotFound) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000420 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
421
Steven Morelanda9fe4742019-07-18 14:45:20 -0700422 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700423
Jon Spivack0d844302019-07-22 18:40:34 -0700424 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700425 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700426 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700427 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700428
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000429 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
Steven Morelandbad75882023-06-16 20:59:06 +0000430 LOG(WARNING) << "Isolated app with UID " << ctx.uid << " requested '" << name
431 << "', but the service is not allowed for isolated apps.";
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000432 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700433 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700434 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700435 }
436
Steven Morelanda9fe4742019-07-18 14:45:20 -0700437 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700438 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700439 }
440
Jon Spivack0d844302019-07-22 18:40:34 -0700441 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000442 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700443 }
444
Jon Spivack9f503a42019-10-22 16:49:19 -0700445 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000446 // Force onClients to get sent, and then make sure the timerfd won't clear it
447 // by setting guaranteeClient again. This logic could be simplified by using
448 // a time-based guarantee. However, forcing onClients(true) to get sent
449 // right here is always going to be important for processes serving multiple
450 // lazy interfaces.
451 service->guaranteeClient = true;
452 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700453 service->guaranteeClient = true;
454 }
455
Jon Spivack0d844302019-07-22 18:40:34 -0700456 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700457}
458
Steven Moreland905e2e82019-07-17 11:05:45 -0700459bool isValidServiceName(const std::string& name) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000460 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
461
Steven Moreland905e2e82019-07-17 11:05:45 -0700462 if (name.size() == 0) return false;
463 if (name.size() > 127) return false;
464
465 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700466 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700467 if (c >= 'a' && c <= 'z') continue;
468 if (c >= 'A' && c <= 'Z') continue;
469 if (c >= '0' && c <= '9') continue;
470 return false;
471 }
472
473 return true;
474}
475
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700476Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000477 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
478
Steven Morelanda9fe4742019-07-18 14:45:20 -0700479 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700480
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700481 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000482 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700483 }
484
Steven Morelanda9fe4742019-07-18 14:45:20 -0700485 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000486 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700487 }
488
489 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000490 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700491 }
492
Steven Moreland905e2e82019-07-17 11:05:45 -0700493 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000494 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000495 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700496 }
497
Steven Moreland86a17f82019-09-10 10:18:00 -0700498#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000499 if (!meetsDeclarationRequirements(ctx, binder, name)) {
Steven Moreland86a17f82019-09-10 10:18:00 -0700500 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000501 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700502 }
503#endif // !VENDORSERVICEMANAGER
504
Devin Moore4e21def2023-02-24 21:54:14 +0000505 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
Steven Moreland5759db02024-03-27 00:03:05 +0000506 ALOGW("%s Dump flag priority is not set when adding %s", ctx.toDebugString().c_str(),
507 name.c_str());
Devin Moore4e21def2023-02-24 21:54:14 +0000508 }
509
Steven Moreland88860b02019-08-12 14:24:14 -0700510 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000511 if (binder->remoteBinder() != nullptr &&
512 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Steven Moreland5759db02024-03-27 00:03:05 +0000513 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000514 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700515 }
516
Steven Moreland7ee423b2022-09-24 03:52:08 +0000517 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000518 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000519 if (it != mNameToService.end()) {
520 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000521 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000522
523 // We could do better than this because if the other service dies, it
524 // may not have an entry here. However, this case is unlikely. We are
525 // only trying to detect when two different services are accidentally installed.
526
527 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000528 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
529 "from UID %u. Multiple instances installed?",
530 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000531 }
532
533 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000534 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
535 "from SID %s. Multiple instances installed?",
536 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000537 }
538
Pawan Wagh37526162022-09-29 21:55:26 +0000539 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
540 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
541 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000542 }
543
Devin Moore05ffe522020-08-06 13:58:29 -0700544 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000545 mNameToService[name] = Service{
546 .binder = binder,
547 .allowIsolated = allowIsolated,
548 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000549 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000550 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000551 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700552 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700553
Steven Moreland7ee423b2022-09-24 03:52:08 +0000554 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000555 // If someone is currently waiting on the service, notify the service that
556 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000557 mNameToService[name].guaranteeClient = true;
558 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
559 mNameToService[name].guaranteeClient = true;
560
Steven Moreland27cfab02019-08-12 14:34:16 -0700561 for (const sp<IServiceCallback>& cb : it->second) {
562 // permission checked in registerForNotifications
563 cb->onRegistration(name, binder);
564 }
565 }
566
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700567 return Status::ok();
568}
569
570Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000571 SM_PERFETTO_TRACE_FUNC();
572
Steven Morelanda9fe4742019-07-18 14:45:20 -0700573 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000574 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700575 }
576
577 size_t toReserve = 0;
578 for (auto const& [name, service] : mNameToService) {
579 (void) name;
580
581 if (service.dumpPriority & dumpPriority) ++toReserve;
582 }
583
584 CHECK(outList->empty());
585
586 outList->reserve(toReserve);
587 for (auto const& [name, service] : mNameToService) {
588 (void) service;
589
590 if (service.dumpPriority & dumpPriority) {
591 outList->push_back(name);
592 }
593 }
594
595 return Status::ok();
596}
597
Steven Moreland27cfab02019-08-12 14:34:16 -0700598Status ServiceManager::registerForNotifications(
599 const std::string& name, const sp<IServiceCallback>& callback) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000600 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
601
Steven Moreland27cfab02019-08-12 14:34:16 -0700602 auto ctx = mAccess->getCallingContext();
603
Alice Wang8578f132024-05-03 09:01:56 +0000604 // TODO(b/338541373): Implement the notification mechanism for services accessed via
605 // IAccessor.
606 std::optional<std::string> accessorName;
607 if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
608 return status;
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000609 }
610
611 // note - we could allow isolated apps to get notifications if we
612 // keep track of isolated callbacks and non-isolated callbacks, but
613 // this is done since isolated apps shouldn't access lazy services
614 // so we should be able to use different APIs to keep things simple.
615 // Here, we disallow everything, because the service might not be
616 // registered yet.
617 if (is_multiuser_uid_isolated(ctx.uid)) {
618 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700619 }
620
621 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000622 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000623 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700624 }
625
626 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000627 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700628 }
629
Steven Morelandb0983182021-04-02 03:14:04 +0000630 if (OK !=
631 IInterface::asBinder(callback)->linkToDeath(
632 sp<ServiceManager>::fromExisting(this))) {
Steven Moreland5759db02024-03-27 00:03:05 +0000633 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000634 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700635 }
636
Jon Spivackf288b1d2019-12-19 17:15:51 -0800637 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700638
639 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
640 const sp<IBinder>& binder = it->second.binder;
641
642 // never null if an entry exists
643 CHECK(binder != nullptr) << name;
644 callback->onRegistration(name, binder);
645 }
646
647 return Status::ok();
648}
649Status ServiceManager::unregisterForNotifications(
650 const std::string& name, const sp<IServiceCallback>& callback) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000651 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
652
Steven Moreland27cfab02019-08-12 14:34:16 -0700653 auto ctx = mAccess->getCallingContext();
654
Alice Wang8578f132024-05-03 09:01:56 +0000655 std::optional<std::string> accessorName;
656 if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
657 return status;
Steven Moreland27cfab02019-08-12 14:34:16 -0700658 }
659
660 bool found = false;
661
Jon Spivackf288b1d2019-12-19 17:15:51 -0800662 auto it = mNameToRegistrationCallback.find(name);
663 if (it != mNameToRegistrationCallback.end()) {
664 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700665 }
666
667 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000668 ALOGE("%s Trying to unregister callback, but none exists %s", ctx.toDebugString().c_str(),
669 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000670 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700671 }
672
673 return Status::ok();
674}
675
Steven Morelandb82b8f82019-10-28 10:52:34 -0700676Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000677 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
678
Steven Morelandb82b8f82019-10-28 10:52:34 -0700679 auto ctx = mAccess->getCallingContext();
680
Alice Wang8578f132024-05-03 09:01:56 +0000681 std::optional<std::string> accessorName;
682 if (auto status = canFindService(ctx, name, &accessorName); !status.isOk()) {
683 return status;
Steven Morelandb82b8f82019-10-28 10:52:34 -0700684 }
685
686 *outReturn = false;
687
688#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000689 *outReturn = isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700690#endif
691 return Status::ok();
692}
693
Steven Moreland2e293aa2020-09-23 00:25:16 +0000694binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000695 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("interface", interface.c_str()));
696
Steven Moreland2e293aa2020-09-23 00:25:16 +0000697 auto ctx = mAccess->getCallingContext();
698
699 std::vector<std::string> allInstances;
700#ifndef VENDORSERVICEMANAGER
701 allInstances = getVintfInstances(interface);
702#endif
703
704 outReturn->clear();
705
Alice Wang8578f132024-05-03 09:01:56 +0000706 std::optional<std::string> _accessorName;
Steven Moreland2e293aa2020-09-23 00:25:16 +0000707 for (const std::string& instance : allInstances) {
Alice Wang8578f132024-05-03 09:01:56 +0000708 if (auto status = canFindService(ctx, interface + "/" + instance, &_accessorName);
709 status.isOk()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000710 outReturn->push_back(instance);
711 }
712 }
713
714 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000715 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000716 }
717
718 return Status::ok();
719}
720
Steven Morelandedd4e072021-04-21 00:27:29 +0000721Status ServiceManager::updatableViaApex(const std::string& name,
722 std::optional<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000723 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
724
Steven Morelandedd4e072021-04-21 00:27:29 +0000725 auto ctx = mAccess->getCallingContext();
726
Alice Wang8578f132024-05-03 09:01:56 +0000727 std::optional<std::string> _accessorName;
728 if (auto status = canFindService(ctx, name, &_accessorName); !status.isOk()) {
729 return status;
Steven Morelandedd4e072021-04-21 00:27:29 +0000730 }
731
732 *outReturn = std::nullopt;
733
734#ifndef VENDORSERVICEMANAGER
735 *outReturn = getVintfUpdatableApex(name);
736#endif
737 return Status::ok();
738}
739
Jooyung Han76944fe2022-10-25 17:02:45 +0900740Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
741 std::vector<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000742 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("apexName", apexName.c_str()));
743
Jooyung Han76944fe2022-10-25 17:02:45 +0900744 auto ctx = mAccess->getCallingContext();
745
Jooyung Han205e2822023-12-19 16:59:39 +0900746 std::vector<std::string> apexUpdatableNames;
Jooyung Han76944fe2022-10-25 17:02:45 +0900747#ifndef VENDORSERVICEMANAGER
Jooyung Han205e2822023-12-19 16:59:39 +0900748 apexUpdatableNames = getVintfUpdatableNames(apexName);
Jooyung Han76944fe2022-10-25 17:02:45 +0900749#endif
750
751 outReturn->clear();
752
Alice Wang8578f132024-05-03 09:01:56 +0000753 std::optional<std::string> _accessorName;
Jooyung Han205e2822023-12-19 16:59:39 +0900754 for (const std::string& name : apexUpdatableNames) {
Alice Wang8578f132024-05-03 09:01:56 +0000755 if (auto status = canFindService(ctx, name, &_accessorName); status.isOk()) {
Jooyung Han205e2822023-12-19 16:59:39 +0900756 outReturn->push_back(name);
Jooyung Han76944fe2022-10-25 17:02:45 +0900757 }
758 }
759
Jooyung Han205e2822023-12-19 16:59:39 +0900760 if (outReturn->size() == 0 && apexUpdatableNames.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000761 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900762 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900763 return Status::ok();
764}
765
Devin Moore5e4c2f12021-09-09 22:36:33 +0000766Status ServiceManager::getConnectionInfo(const std::string& name,
767 std::optional<ConnectionInfo>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000768 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
769
Devin Moore5e4c2f12021-09-09 22:36:33 +0000770 auto ctx = mAccess->getCallingContext();
771
Alice Wang8578f132024-05-03 09:01:56 +0000772 std::optional<std::string> _accessorName;
773 if (auto status = canFindService(ctx, name, &_accessorName); !status.isOk()) {
774 return status;
Devin Moore5e4c2f12021-09-09 22:36:33 +0000775 }
776
777 *outReturn = std::nullopt;
778
779#ifndef VENDORSERVICEMANAGER
780 *outReturn = getVintfConnectionInfo(name);
781#endif
782 return Status::ok();
783}
784
Jon Spivackf288b1d2019-12-19 17:15:51 -0800785void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
786 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700787 bool* found) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000788 SM_PERFETTO_TRACE_FUNC();
789
Steven Moreland27cfab02019-08-12 14:34:16 -0700790 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
791
792 for (auto lit = listeners.begin(); lit != listeners.end();) {
793 if (IInterface::asBinder(*lit) == who) {
794 if(found) *found = true;
795 lit = listeners.erase(lit);
796 } else {
797 ++lit;
798 }
799 }
800
801 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800802 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700803 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800804 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700805 }
806}
807
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700808void ServiceManager::binderDied(const wp<IBinder>& who) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000809 SM_PERFETTO_TRACE_FUNC();
810
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700811 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
812 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000813 // TODO: currently, this entry contains the state also
814 // associated with mNameToClientCallback. If we allowed
815 // other processes to register client callbacks, we
816 // would have to preserve hasClients (perhaps moving
817 // that state into mNameToClientCallback, which is complicated
818 // because those callbacks are associated w/ particular binder
819 // objects, though they are indexed by name now, they may
820 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700821 it = mNameToService.erase(it);
822 } else {
823 ++it;
824 }
825 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700826
Jon Spivackf288b1d2019-12-19 17:15:51 -0800827 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
828 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700829 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700830
831 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
832 removeClientCallback(who, &it);
833 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700834}
835
Steven Morelandaa33e852023-05-10 16:42:15 +0000836void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
Steven Moreland5759db02024-03-27 00:03:05 +0000837 ALOGI("%s Since '%s' could not be found trying to start it as a lazy AIDL service. (if it's "
838 "not configured to be a lazy service, it may be stuck starting or still starting).",
839 ctx.toDebugString().c_str(), name.c_str());
Jon Spivack0d844302019-07-22 18:40:34 -0700840
841 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000842 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000843 ALOGI("%s Tried to start aidl service %s as a lazy service, but was unable to. Usually "
844 "this happens when a service is not installed, but if the service is intended to "
845 "be used as a lazy service, then it may be configured incorrectly.",
846 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000847 }
Jon Spivack0d844302019-07-22 18:40:34 -0700848 }).detach();
849}
850
Jon Spivack9f503a42019-10-22 16:49:19 -0700851Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
852 const sp<IClientCallback>& cb) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000853 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
854
Jon Spivack9f503a42019-10-22 16:49:19 -0700855 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000856 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700857 }
858
859 auto ctx = mAccess->getCallingContext();
860 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000861 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700862 }
863
864 auto serviceIt = mNameToService.find(name);
865 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000866 ALOGE("%s Could not add callback for nonexistent service: %s", ctx.toDebugString().c_str(),
867 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000868 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700869 }
870
Steven Moreland7ee423b2022-09-24 03:52:08 +0000871 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000872 ALOGW("%s Only a server can register for client callbacks (for %s)",
873 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000874 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
875 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700876 }
877
878 if (serviceIt->second.binder != service) {
Steven Moreland5759db02024-03-27 00:03:05 +0000879 ALOGW("%s Tried to register client callback for %s but a different service is registered "
Pawan Wagh37526162022-09-29 21:55:26 +0000880 "under this name.",
Steven Moreland5759db02024-03-27 00:03:05 +0000881 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000882 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700883 }
884
Steven Morelandb0983182021-04-02 03:14:04 +0000885 if (OK !=
886 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
David Duarte67d65282024-04-10 23:54:36 +0000887 ALOGE("%s Could not linkToDeath when adding client callback for %s",
888 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000889 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700890 }
891
Steven Moreland79578672023-04-27 19:38:00 +0000892 // WARNING: binderDied makes an assumption about this. If we open up client
893 // callbacks to other services, certain race conditions may lead to services
894 // getting extra client callback notifications.
895 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000896 if (serviceIt->second.hasClients) {
897 cb->onClients(service, true);
898 }
899
Jon Spivack9f503a42019-10-22 16:49:19 -0700900 mNameToClientCallback[name].push_back(cb);
901
Steven Morelandefea66b2023-06-17 01:59:34 +0000902 // Flush updated info to client callbacks (especially if guaranteeClient
903 // and !hasClient, see b/285202885). We may or may not have clients at
904 // this point, so ignore the return value.
905 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
906
Jon Spivack9f503a42019-10-22 16:49:19 -0700907 return Status::ok();
908}
909
910void ServiceManager::removeClientCallback(const wp<IBinder>& who,
911 ClientCallbackMap::iterator* it) {
912 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
913
914 for (auto lit = listeners.begin(); lit != listeners.end();) {
915 if (IInterface::asBinder(*lit) == who) {
916 lit = listeners.erase(lit);
917 } else {
918 ++lit;
919 }
920 }
921
922 if (listeners.empty()) {
923 *it = mNameToClientCallback.erase(*it);
924 } else {
925 (*it)++;
926 }
927}
928
929ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000930 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700931 if (bpBinder == nullptr) return -1;
932
Steven Morelande8393882020-12-18 02:27:20 +0000933 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700934}
935
936void ServiceManager::handleClientCallbacks() {
937 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000938 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700939 }
940}
941
Steven Morelandb8361902023-02-01 23:18:04 +0000942bool ServiceManager::handleServiceClientCallback(size_t knownClients,
943 const std::string& serviceName,
944 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700945 auto serviceIt = mNameToService.find(serviceName);
946 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000947 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700948 }
949
950 Service& service = serviceIt->second;
951 ssize_t count = service.getNodeStrongRefCount();
952
Steven Morelandb8361902023-02-01 23:18:04 +0000953 // binder driver doesn't support this feature, consider we have clients
954 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700955
Steven Morelandb8361902023-02-01 23:18:04 +0000956 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700957
958 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000959 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000960 sendClientCallbackNotifications(serviceName, true,
961 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700962 }
963
964 // guarantee is temporary
965 service.guaranteeClient = false;
966 }
967
Steven Morelandb8361902023-02-01 23:18:04 +0000968 // Regardless of this situation, we want to give this notification as soon as possible.
969 // This way, we have a chance of preventing further thrashing.
970 if (hasKernelReportedClients && !service.hasClients) {
971 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
972 }
Steven Moreland66417652023-02-01 22:19:41 +0000973
Steven Morelandb8361902023-02-01 23:18:04 +0000974 // But limit rate of shutting down service.
975 if (isCalledOnInterval) {
976 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000977 sendClientCallbackNotifications(serviceName, false,
978 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000979 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700980 }
981
Steven Morelandb8361902023-02-01 23:18:04 +0000982 // May be different than 'hasKernelReportedClients'. We intentionally delay
983 // information about clients going away to reduce thrashing.
984 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700985}
986
Steven Moreland3e083b22023-01-26 00:46:30 +0000987void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
988 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700989 auto serviceIt = mNameToService.find(serviceName);
990 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000991 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
992 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700993 return;
994 }
995 Service& service = serviceIt->second;
996
Steven Morelandb8361902023-02-01 23:18:04 +0000997 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700998
Steven Morelandb8361902023-02-01 23:18:04 +0000999 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
1000 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -07001001
1002 auto ccIt = mNameToClientCallback.find(serviceName);
1003 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +00001004 << "sendClientCallbackNotifications could not find callbacks for service when "
1005 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -07001006
1007 for (const auto& callback : ccIt->second) {
1008 callback->onClients(service.binder, hasClients);
1009 }
1010
1011 service.hasClients = hasClients;
1012}
1013
1014Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
Parth Sane5ade9f12024-05-19 13:02:07 +00001015 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
1016
Jon Spivack9f503a42019-10-22 16:49:19 -07001017 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +00001018 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001019 }
1020
1021 auto ctx = mAccess->getCallingContext();
1022 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +00001023 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001024 }
1025
1026 auto serviceIt = mNameToService.find(name);
1027 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +00001028 ALOGW("%s Tried to unregister %s, but that service wasn't registered to begin with.",
1029 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001030 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001031 }
1032
Steven Moreland7ee423b2022-09-24 03:52:08 +00001033 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +00001034 ALOGW("%s Only a server can unregister itself (for %s)", ctx.toDebugString().c_str(),
1035 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001036 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
1037 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001038 }
1039
1040 sp<IBinder> storedBinder = serviceIt->second.binder;
1041
1042 if (binder != storedBinder) {
Steven Moreland5759db02024-03-27 00:03:05 +00001043 ALOGW("%s Tried to unregister %s, but a different service is registered under this name.",
1044 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001045 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1046 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001047 }
1048
Steven Morelandb8361902023-02-01 23:18:04 +00001049 // important because we don't have timer-based guarantees, we don't want to clear
1050 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -07001051 if (serviceIt->second.guaranteeClient) {
Steven Moreland5759db02024-03-27 00:03:05 +00001052 ALOGI("%s Tried to unregister %s, but there is about to be a client.",
1053 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001054 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1055 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -07001056 }
1057
Jon Spivack9f503a42019-10-22 16:49:19 -07001058 // - kernel driver will hold onto one refcount (during this transaction)
1059 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +00001060 constexpr size_t kKnownClients = 2;
1061
1062 if (handleServiceClientCallback(kKnownClients, name, false)) {
Steven Moreland5759db02024-03-27 00:03:05 +00001063 ALOGI("%s Tried to unregister %s, but there are clients.", ctx.toDebugString().c_str(),
1064 name.c_str());
Steven Morelandb8361902023-02-01 23:18:04 +00001065
1066 // Since we had a failed registration attempt, and the HIDL implementation of
1067 // delaying service shutdown for multiple periods wasn't ported here... this may
1068 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -08001069 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +00001070
Steven Morelandffb905b2023-03-28 18:24:37 +00001071 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1072 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001073 }
1074
Steven Moreland5759db02024-03-27 00:03:05 +00001075 ALOGI("%s Unregistering %s", ctx.toDebugString().c_str(), name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -07001076 mNameToService.erase(name);
1077
1078 return Status::ok();
1079}
1080
Alice Wang8578f132024-05-03 09:01:56 +00001081Status ServiceManager::canFindService(const Access::CallingContext& ctx, const std::string& name,
1082 std::optional<std::string>* accessor) {
1083 if (!mAccess->canFind(ctx, name)) {
1084 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied for service.");
1085 }
1086#ifndef VENDORSERVICEMANAGER
1087 *accessor = getVintfAccessorName(name);
1088#endif
1089 if (accessor->has_value()) {
1090 if (!mAccess->canFind(ctx, accessor->value())) {
1091 return Status::fromExceptionCode(Status::EX_SECURITY,
1092 "SELinux denied for the accessor of the service.");
1093 }
1094 }
1095 return Status::ok();
1096}
1097
Steven Moreland3ea43272021-01-28 22:49:28 +00001098Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +00001099 SM_PERFETTO_TRACE_FUNC();
Steven Moreland3ea43272021-01-28 22:49:28 +00001100 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +00001101 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +00001102 }
1103
1104 outReturn->reserve(mNameToService.size());
1105 for (auto const& [name, service] : mNameToService) {
1106 ServiceDebugInfo info;
1107 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +00001108 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +00001109
1110 outReturn->push_back(std::move(info));
1111 }
1112
1113 return Status::ok();
1114}
1115
Pawan Wagh243888e2022-09-20 19:37:35 +00001116void ServiceManager::clear() {
1117 mNameToService.clear();
1118 mNameToRegistrationCallback.clear();
1119 mNameToClientCallback.clear();
1120}
1121
Steven Moreland8d0c9a72020-04-30 16:51:56 -07001122} // namespace android