blob: 1333599bf2b111fd03fe327fa031b3f733b096d9 [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
Devin Moore5e4c2f12021-09-09 22:36:33 +0000252static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
253 AidlName aname;
254 if (!AidlName::fill(name, &aname)) return std::nullopt;
255
256 std::optional<std::string> ip;
257 std::optional<uint64_t> port;
258 forEachManifest([&](const ManifestWithDescription& mwd) {
259 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
260 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
261 if (manifestInstance.package() != aname.package) return true;
262 if (manifestInstance.interface() != aname.iface) return true;
263 if (manifestInstance.instance() != aname.instance) return true;
264 ip = manifestInstance.ip();
265 port = manifestInstance.port();
266 return false; // break (libvintf uses opposite convention)
267 });
268 return false; // continue
269 });
270
271 if (ip.has_value() && port.has_value()) {
272 ConnectionInfo info;
273 info.ipAddress = *ip;
274 info.port = *port;
275 return std::make_optional<ConnectionInfo>(info);
276 } else {
277 return std::nullopt;
278 }
279}
280
Steven Moreland2e293aa2020-09-23 00:25:16 +0000281static std::vector<std::string> getVintfInstances(const std::string& interface) {
282 size_t lastDot = interface.rfind('.');
283 if (lastDot == std::string::npos) {
Jooyung Han205e2822023-12-19 16:59:39 +0900284 // This might be a package for native instance.
285 std::vector<std::string> ret;
286 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
287 auto instances = mwd.manifest->getNativeInstances(interface);
288 ret.insert(ret.end(), instances.begin(), instances.end());
289 return false; // continue
290 });
291 // If found, return it without error log.
292 if (!ret.empty()) {
293 return ret;
294 }
295
Pawan Wagh37526162022-09-29 21:55:26 +0000296 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
297 "but got: %s",
298 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000299 return {};
300 }
301 const std::string package = interface.substr(0, lastDot);
302 const std::string iface = interface.substr(lastDot+1);
303
304 std::vector<std::string> ret;
305 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
306 auto instances = mwd.manifest->getAidlInstances(package, iface);
307 ret.insert(ret.end(), instances.begin(), instances.end());
308 return false; // continue
309 });
310
311 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700312}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700313
Steven Moreland5759db02024-03-27 00:03:05 +0000314static bool meetsDeclarationRequirements(const Access::CallingContext& ctx,
315 const sp<IBinder>& binder, const std::string& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700316 if (!Stability::requiresVintfDeclaration(binder)) {
317 return true;
318 }
319
Steven Moreland5759db02024-03-27 00:03:05 +0000320 return isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700321}
Steven Moreland86a17f82019-09-10 10:18:00 -0700322#endif // !VENDORSERVICEMANAGER
323
Steven Morelandb8361902023-02-01 23:18:04 +0000324ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000325 if (hasClients) {
326 // only expected to happen on process death, we don't store the service
327 // name this late (it's in the map that holds this service), but if it
328 // is happening, we might want to change 'unlinkToDeath' to explicitly
329 // clear this bit so that we can abort in other cases, where it would
330 // mean inconsistent logic in servicemanager (unexpected and tested, but
331 // the original lazy service impl here had that bug).
Steven Moreland5759db02024-03-27 00:03:05 +0000332 ALOGW("A service was removed when there are clients");
Steven Morelandb8361902023-02-01 23:18:04 +0000333 }
334}
335
Steven Morelandd13f08b2019-11-18 14:23:09 -0800336ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700337// TODO(b/151696835): reenable performance hack when we solve bug, since with
338// this hack and other fixes, it is unlikely we will see even an ephemeral
339// failure when the manifest parse fails. The goal is that the manifest will
340// be read incorrectly and cause the process trying to register a HAL to
341// fail. If this is in fact an early boot kernel contention issue, then we
342// will get no failure, and by its absence, be signalled to invest more
343// effort in re-adding this performance hack.
344// #ifndef VENDORSERVICEMANAGER
345// // can process these at any times, don't want to delay first VINTF client
346// std::thread([] {
347// vintf::VintfObject::GetDeviceHalManifest();
348// vintf::VintfObject::GetFrameworkHalManifest();
349// }).detach();
350// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800351}
Steven Moreland130242d2019-08-26 17:41:32 -0700352ServiceManager::~ServiceManager() {
353 // this should only happen in tests
354
Jon Spivackf288b1d2019-12-19 17:15:51 -0800355 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700356 CHECK(!callbacks.empty()) << name;
357 for (const auto& callback : callbacks) {
358 CHECK(callback != nullptr) << name;
359 }
360 }
361
Steven Moreland130242d2019-08-26 17:41:32 -0700362 for (const auto& [name, service] : mNameToService) {
363 CHECK(service.binder != nullptr) << name;
364 }
365}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700366
367Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000368 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
369
Jon Spivack0d844302019-07-22 18:40:34 -0700370 *outBinder = tryGetService(name, true);
371 // returns ok regardless of result for legacy reasons
372 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700373}
374
375Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000376 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
377
Jon Spivack0d844302019-07-22 18:40:34 -0700378 *outBinder = tryGetService(name, false);
379 // returns ok regardless of result for legacy reasons
380 return Status::ok();
381}
382
383sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000384 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
385
Steven Morelanda9fe4742019-07-18 14:45:20 -0700386 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700387
Jon Spivack0d844302019-07-22 18:40:34 -0700388 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700389 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700390 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700391 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700392
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000393 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
Steven Morelandbad75882023-06-16 20:59:06 +0000394 LOG(WARNING) << "Isolated app with UID " << ctx.uid << " requested '" << name
395 << "', but the service is not allowed for isolated apps.";
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000396 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700397 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700398 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700399 }
400
Steven Morelanda9fe4742019-07-18 14:45:20 -0700401 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700402 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700403 }
404
Jon Spivack0d844302019-07-22 18:40:34 -0700405 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000406 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700407 }
408
Jon Spivack9f503a42019-10-22 16:49:19 -0700409 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000410 // Force onClients to get sent, and then make sure the timerfd won't clear it
411 // by setting guaranteeClient again. This logic could be simplified by using
412 // a time-based guarantee. However, forcing onClients(true) to get sent
413 // right here is always going to be important for processes serving multiple
414 // lazy interfaces.
415 service->guaranteeClient = true;
416 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700417 service->guaranteeClient = true;
418 }
419
Jon Spivack0d844302019-07-22 18:40:34 -0700420 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700421}
422
Steven Moreland905e2e82019-07-17 11:05:45 -0700423bool isValidServiceName(const std::string& name) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000424 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
425
Steven Moreland905e2e82019-07-17 11:05:45 -0700426 if (name.size() == 0) return false;
427 if (name.size() > 127) return false;
428
429 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700430 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700431 if (c >= 'a' && c <= 'z') continue;
432 if (c >= 'A' && c <= 'Z') continue;
433 if (c >= '0' && c <= '9') continue;
434 return false;
435 }
436
437 return true;
438}
439
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700440Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000441 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
442
Steven Morelanda9fe4742019-07-18 14:45:20 -0700443 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700444
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700445 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000446 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700447 }
448
Steven Morelanda9fe4742019-07-18 14:45:20 -0700449 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000450 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700451 }
452
453 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000454 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700455 }
456
Steven Moreland905e2e82019-07-17 11:05:45 -0700457 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000458 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000459 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700460 }
461
Steven Moreland86a17f82019-09-10 10:18:00 -0700462#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000463 if (!meetsDeclarationRequirements(ctx, binder, name)) {
Steven Moreland86a17f82019-09-10 10:18:00 -0700464 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000465 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700466 }
467#endif // !VENDORSERVICEMANAGER
468
Devin Moore4e21def2023-02-24 21:54:14 +0000469 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
Steven Moreland5759db02024-03-27 00:03:05 +0000470 ALOGW("%s Dump flag priority is not set when adding %s", ctx.toDebugString().c_str(),
471 name.c_str());
Devin Moore4e21def2023-02-24 21:54:14 +0000472 }
473
Steven Moreland88860b02019-08-12 14:24:14 -0700474 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000475 if (binder->remoteBinder() != nullptr &&
476 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Steven Moreland5759db02024-03-27 00:03:05 +0000477 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000478 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700479 }
480
Steven Moreland7ee423b2022-09-24 03:52:08 +0000481 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000482 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000483 if (it != mNameToService.end()) {
484 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000485 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000486
487 // We could do better than this because if the other service dies, it
488 // may not have an entry here. However, this case is unlikely. We are
489 // only trying to detect when two different services are accidentally installed.
490
491 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000492 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
493 "from UID %u. Multiple instances installed?",
494 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000495 }
496
497 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000498 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
499 "from SID %s. Multiple instances installed?",
500 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000501 }
502
Pawan Wagh37526162022-09-29 21:55:26 +0000503 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
504 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
505 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000506 }
507
Devin Moore05ffe522020-08-06 13:58:29 -0700508 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000509 mNameToService[name] = Service{
510 .binder = binder,
511 .allowIsolated = allowIsolated,
512 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000513 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000514 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000515 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700516 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700517
Steven Moreland7ee423b2022-09-24 03:52:08 +0000518 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000519 // If someone is currently waiting on the service, notify the service that
520 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000521 mNameToService[name].guaranteeClient = true;
522 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
523 mNameToService[name].guaranteeClient = true;
524
Steven Moreland27cfab02019-08-12 14:34:16 -0700525 for (const sp<IServiceCallback>& cb : it->second) {
526 // permission checked in registerForNotifications
527 cb->onRegistration(name, binder);
528 }
529 }
530
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700531 return Status::ok();
532}
533
534Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000535 SM_PERFETTO_TRACE_FUNC();
536
Steven Morelanda9fe4742019-07-18 14:45:20 -0700537 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000538 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700539 }
540
541 size_t toReserve = 0;
542 for (auto const& [name, service] : mNameToService) {
543 (void) name;
544
545 if (service.dumpPriority & dumpPriority) ++toReserve;
546 }
547
548 CHECK(outList->empty());
549
550 outList->reserve(toReserve);
551 for (auto const& [name, service] : mNameToService) {
552 (void) service;
553
554 if (service.dumpPriority & dumpPriority) {
555 outList->push_back(name);
556 }
557 }
558
559 return Status::ok();
560}
561
Steven Moreland27cfab02019-08-12 14:34:16 -0700562Status ServiceManager::registerForNotifications(
563 const std::string& name, const sp<IServiceCallback>& callback) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000564 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
565
Steven Moreland27cfab02019-08-12 14:34:16 -0700566 auto ctx = mAccess->getCallingContext();
567
568 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000569 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
570 }
571
572 // note - we could allow isolated apps to get notifications if we
573 // keep track of isolated callbacks and non-isolated callbacks, but
574 // this is done since isolated apps shouldn't access lazy services
575 // so we should be able to use different APIs to keep things simple.
576 // Here, we disallow everything, because the service might not be
577 // registered yet.
578 if (is_multiuser_uid_isolated(ctx.uid)) {
579 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700580 }
581
582 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000583 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000584 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700585 }
586
587 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000588 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700589 }
590
Steven Morelandb0983182021-04-02 03:14:04 +0000591 if (OK !=
592 IInterface::asBinder(callback)->linkToDeath(
593 sp<ServiceManager>::fromExisting(this))) {
Steven Moreland5759db02024-03-27 00:03:05 +0000594 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000595 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700596 }
597
Jon Spivackf288b1d2019-12-19 17:15:51 -0800598 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700599
600 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
601 const sp<IBinder>& binder = it->second.binder;
602
603 // never null if an entry exists
604 CHECK(binder != nullptr) << name;
605 callback->onRegistration(name, binder);
606 }
607
608 return Status::ok();
609}
610Status ServiceManager::unregisterForNotifications(
611 const std::string& name, const sp<IServiceCallback>& callback) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000612 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
613
Steven Moreland27cfab02019-08-12 14:34:16 -0700614 auto ctx = mAccess->getCallingContext();
615
616 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000617 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700618 }
619
620 bool found = false;
621
Jon Spivackf288b1d2019-12-19 17:15:51 -0800622 auto it = mNameToRegistrationCallback.find(name);
623 if (it != mNameToRegistrationCallback.end()) {
624 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700625 }
626
627 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000628 ALOGE("%s Trying to unregister callback, but none exists %s", ctx.toDebugString().c_str(),
629 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000630 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700631 }
632
633 return Status::ok();
634}
635
Steven Morelandb82b8f82019-10-28 10:52:34 -0700636Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000637 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
638
Steven Morelandb82b8f82019-10-28 10:52:34 -0700639 auto ctx = mAccess->getCallingContext();
640
641 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000642 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700643 }
644
645 *outReturn = false;
646
647#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000648 *outReturn = isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700649#endif
650 return Status::ok();
651}
652
Steven Moreland2e293aa2020-09-23 00:25:16 +0000653binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000654 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("interface", interface.c_str()));
655
Steven Moreland2e293aa2020-09-23 00:25:16 +0000656 auto ctx = mAccess->getCallingContext();
657
658 std::vector<std::string> allInstances;
659#ifndef VENDORSERVICEMANAGER
660 allInstances = getVintfInstances(interface);
661#endif
662
663 outReturn->clear();
664
665 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000666 if (mAccess->canFind(ctx, interface + "/" + instance)) {
667 outReturn->push_back(instance);
668 }
669 }
670
671 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000672 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000673 }
674
675 return Status::ok();
676}
677
Steven Morelandedd4e072021-04-21 00:27:29 +0000678Status ServiceManager::updatableViaApex(const std::string& name,
679 std::optional<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000680 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
681
Steven Morelandedd4e072021-04-21 00:27:29 +0000682 auto ctx = mAccess->getCallingContext();
683
684 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000685 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000686 }
687
688 *outReturn = std::nullopt;
689
690#ifndef VENDORSERVICEMANAGER
691 *outReturn = getVintfUpdatableApex(name);
692#endif
693 return Status::ok();
694}
695
Jooyung Han76944fe2022-10-25 17:02:45 +0900696Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
697 std::vector<std::string>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000698 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("apexName", apexName.c_str()));
699
Jooyung Han76944fe2022-10-25 17:02:45 +0900700 auto ctx = mAccess->getCallingContext();
701
Jooyung Han205e2822023-12-19 16:59:39 +0900702 std::vector<std::string> apexUpdatableNames;
Jooyung Han76944fe2022-10-25 17:02:45 +0900703#ifndef VENDORSERVICEMANAGER
Jooyung Han205e2822023-12-19 16:59:39 +0900704 apexUpdatableNames = getVintfUpdatableNames(apexName);
Jooyung Han76944fe2022-10-25 17:02:45 +0900705#endif
706
707 outReturn->clear();
708
Jooyung Han205e2822023-12-19 16:59:39 +0900709 for (const std::string& name : apexUpdatableNames) {
710 if (mAccess->canFind(ctx, name)) {
711 outReturn->push_back(name);
Jooyung Han76944fe2022-10-25 17:02:45 +0900712 }
713 }
714
Jooyung Han205e2822023-12-19 16:59:39 +0900715 if (outReturn->size() == 0 && apexUpdatableNames.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000716 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900717 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900718 return Status::ok();
719}
720
Devin Moore5e4c2f12021-09-09 22:36:33 +0000721Status ServiceManager::getConnectionInfo(const std::string& name,
722 std::optional<ConnectionInfo>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000723 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
724
Devin Moore5e4c2f12021-09-09 22:36:33 +0000725 auto ctx = mAccess->getCallingContext();
726
727 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000728 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000729 }
730
731 *outReturn = std::nullopt;
732
733#ifndef VENDORSERVICEMANAGER
734 *outReturn = getVintfConnectionInfo(name);
735#endif
736 return Status::ok();
737}
738
Jon Spivackf288b1d2019-12-19 17:15:51 -0800739void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
740 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700741 bool* found) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000742 SM_PERFETTO_TRACE_FUNC();
743
Steven Moreland27cfab02019-08-12 14:34:16 -0700744 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
745
746 for (auto lit = listeners.begin(); lit != listeners.end();) {
747 if (IInterface::asBinder(*lit) == who) {
748 if(found) *found = true;
749 lit = listeners.erase(lit);
750 } else {
751 ++lit;
752 }
753 }
754
755 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800756 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700757 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800758 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700759 }
760}
761
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700762void ServiceManager::binderDied(const wp<IBinder>& who) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000763 SM_PERFETTO_TRACE_FUNC();
764
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700765 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
766 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000767 // TODO: currently, this entry contains the state also
768 // associated with mNameToClientCallback. If we allowed
769 // other processes to register client callbacks, we
770 // would have to preserve hasClients (perhaps moving
771 // that state into mNameToClientCallback, which is complicated
772 // because those callbacks are associated w/ particular binder
773 // objects, though they are indexed by name now, they may
774 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700775 it = mNameToService.erase(it);
776 } else {
777 ++it;
778 }
779 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700780
Jon Spivackf288b1d2019-12-19 17:15:51 -0800781 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
782 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700783 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700784
785 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
786 removeClientCallback(who, &it);
787 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700788}
789
Steven Morelandaa33e852023-05-10 16:42:15 +0000790void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
Steven Moreland5759db02024-03-27 00:03:05 +0000791 ALOGI("%s Since '%s' could not be found trying to start it as a lazy AIDL service. (if it's "
792 "not configured to be a lazy service, it may be stuck starting or still starting).",
793 ctx.toDebugString().c_str(), name.c_str());
Jon Spivack0d844302019-07-22 18:40:34 -0700794
795 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000796 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000797 ALOGI("%s Tried to start aidl service %s as a lazy service, but was unable to. Usually "
798 "this happens when a service is not installed, but if the service is intended to "
799 "be used as a lazy service, then it may be configured incorrectly.",
800 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000801 }
Jon Spivack0d844302019-07-22 18:40:34 -0700802 }).detach();
803}
804
Jon Spivack9f503a42019-10-22 16:49:19 -0700805Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
806 const sp<IClientCallback>& cb) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000807 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
808
Jon Spivack9f503a42019-10-22 16:49:19 -0700809 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000810 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700811 }
812
813 auto ctx = mAccess->getCallingContext();
814 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000815 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700816 }
817
818 auto serviceIt = mNameToService.find(name);
819 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000820 ALOGE("%s Could not add callback for nonexistent service: %s", ctx.toDebugString().c_str(),
821 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000822 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700823 }
824
Steven Moreland7ee423b2022-09-24 03:52:08 +0000825 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000826 ALOGW("%s Only a server can register for client callbacks (for %s)",
827 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000828 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
829 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700830 }
831
832 if (serviceIt->second.binder != service) {
Steven Moreland5759db02024-03-27 00:03:05 +0000833 ALOGW("%s Tried to register client callback for %s but a different service is registered "
Pawan Wagh37526162022-09-29 21:55:26 +0000834 "under this name.",
Steven Moreland5759db02024-03-27 00:03:05 +0000835 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000836 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700837 }
838
Steven Morelandb0983182021-04-02 03:14:04 +0000839 if (OK !=
840 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
David Duarte67d65282024-04-10 23:54:36 +0000841 ALOGE("%s Could not linkToDeath when adding client callback for %s",
842 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000843 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700844 }
845
Steven Moreland79578672023-04-27 19:38:00 +0000846 // WARNING: binderDied makes an assumption about this. If we open up client
847 // callbacks to other services, certain race conditions may lead to services
848 // getting extra client callback notifications.
849 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000850 if (serviceIt->second.hasClients) {
851 cb->onClients(service, true);
852 }
853
Jon Spivack9f503a42019-10-22 16:49:19 -0700854 mNameToClientCallback[name].push_back(cb);
855
Steven Morelandefea66b2023-06-17 01:59:34 +0000856 // Flush updated info to client callbacks (especially if guaranteeClient
857 // and !hasClient, see b/285202885). We may or may not have clients at
858 // this point, so ignore the return value.
859 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
860
Jon Spivack9f503a42019-10-22 16:49:19 -0700861 return Status::ok();
862}
863
864void ServiceManager::removeClientCallback(const wp<IBinder>& who,
865 ClientCallbackMap::iterator* it) {
866 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
867
868 for (auto lit = listeners.begin(); lit != listeners.end();) {
869 if (IInterface::asBinder(*lit) == who) {
870 lit = listeners.erase(lit);
871 } else {
872 ++lit;
873 }
874 }
875
876 if (listeners.empty()) {
877 *it = mNameToClientCallback.erase(*it);
878 } else {
879 (*it)++;
880 }
881}
882
883ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000884 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700885 if (bpBinder == nullptr) return -1;
886
Steven Morelande8393882020-12-18 02:27:20 +0000887 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700888}
889
890void ServiceManager::handleClientCallbacks() {
891 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000892 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700893 }
894}
895
Steven Morelandb8361902023-02-01 23:18:04 +0000896bool ServiceManager::handleServiceClientCallback(size_t knownClients,
897 const std::string& serviceName,
898 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700899 auto serviceIt = mNameToService.find(serviceName);
900 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000901 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700902 }
903
904 Service& service = serviceIt->second;
905 ssize_t count = service.getNodeStrongRefCount();
906
Steven Morelandb8361902023-02-01 23:18:04 +0000907 // binder driver doesn't support this feature, consider we have clients
908 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700909
Steven Morelandb8361902023-02-01 23:18:04 +0000910 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700911
912 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000913 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000914 sendClientCallbackNotifications(serviceName, true,
915 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700916 }
917
918 // guarantee is temporary
919 service.guaranteeClient = false;
920 }
921
Steven Morelandb8361902023-02-01 23:18:04 +0000922 // Regardless of this situation, we want to give this notification as soon as possible.
923 // This way, we have a chance of preventing further thrashing.
924 if (hasKernelReportedClients && !service.hasClients) {
925 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
926 }
Steven Moreland66417652023-02-01 22:19:41 +0000927
Steven Morelandb8361902023-02-01 23:18:04 +0000928 // But limit rate of shutting down service.
929 if (isCalledOnInterval) {
930 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000931 sendClientCallbackNotifications(serviceName, false,
932 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000933 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700934 }
935
Steven Morelandb8361902023-02-01 23:18:04 +0000936 // May be different than 'hasKernelReportedClients'. We intentionally delay
937 // information about clients going away to reduce thrashing.
938 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700939}
940
Steven Moreland3e083b22023-01-26 00:46:30 +0000941void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
942 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700943 auto serviceIt = mNameToService.find(serviceName);
944 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000945 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
946 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700947 return;
948 }
949 Service& service = serviceIt->second;
950
Steven Morelandb8361902023-02-01 23:18:04 +0000951 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700952
Steven Morelandb8361902023-02-01 23:18:04 +0000953 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
954 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700955
956 auto ccIt = mNameToClientCallback.find(serviceName);
957 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000958 << "sendClientCallbackNotifications could not find callbacks for service when "
959 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700960
961 for (const auto& callback : ccIt->second) {
962 callback->onClients(service.binder, hasClients);
963 }
964
965 service.hasClients = hasClients;
966}
967
968Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
Parth Sane5ade9f12024-05-19 13:02:07 +0000969 SM_PERFETTO_TRACE_FUNC(PERFETTO_TE_ARG_STRING("name", name.c_str()));
970
Jon Spivack9f503a42019-10-22 16:49:19 -0700971 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000972 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700973 }
974
975 auto ctx = mAccess->getCallingContext();
976 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000977 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700978 }
979
980 auto serviceIt = mNameToService.find(name);
981 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000982 ALOGW("%s Tried to unregister %s, but that service wasn't registered to begin with.",
983 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000984 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700985 }
986
Steven Moreland7ee423b2022-09-24 03:52:08 +0000987 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000988 ALOGW("%s Only a server can unregister itself (for %s)", ctx.toDebugString().c_str(),
989 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000990 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
991 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700992 }
993
994 sp<IBinder> storedBinder = serviceIt->second.binder;
995
996 if (binder != storedBinder) {
Steven Moreland5759db02024-03-27 00:03:05 +0000997 ALOGW("%s Tried to unregister %s, but a different service is registered under this name.",
998 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000999 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1000 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001001 }
1002
Steven Morelandb8361902023-02-01 23:18:04 +00001003 // important because we don't have timer-based guarantees, we don't want to clear
1004 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -07001005 if (serviceIt->second.guaranteeClient) {
Steven Moreland5759db02024-03-27 00:03:05 +00001006 ALOGI("%s Tried to unregister %s, but there is about to be a client.",
1007 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +00001008 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1009 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -07001010 }
1011
Jon Spivack9f503a42019-10-22 16:49:19 -07001012 // - kernel driver will hold onto one refcount (during this transaction)
1013 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +00001014 constexpr size_t kKnownClients = 2;
1015
1016 if (handleServiceClientCallback(kKnownClients, name, false)) {
Steven Moreland5759db02024-03-27 00:03:05 +00001017 ALOGI("%s Tried to unregister %s, but there are clients.", ctx.toDebugString().c_str(),
1018 name.c_str());
Steven Morelandb8361902023-02-01 23:18:04 +00001019
1020 // Since we had a failed registration attempt, and the HIDL implementation of
1021 // delaying service shutdown for multiple periods wasn't ported here... this may
1022 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -08001023 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +00001024
Steven Morelandffb905b2023-03-28 18:24:37 +00001025 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
1026 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -07001027 }
1028
Steven Moreland5759db02024-03-27 00:03:05 +00001029 ALOGI("%s Unregistering %s", ctx.toDebugString().c_str(), name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -07001030 mNameToService.erase(name);
1031
1032 return Status::ok();
1033}
1034
Steven Moreland3ea43272021-01-28 22:49:28 +00001035Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
Parth Sane5ade9f12024-05-19 13:02:07 +00001036 SM_PERFETTO_TRACE_FUNC();
Steven Moreland3ea43272021-01-28 22:49:28 +00001037 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +00001038 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +00001039 }
1040
1041 outReturn->reserve(mNameToService.size());
1042 for (auto const& [name, service] : mNameToService) {
1043 ServiceDebugInfo info;
1044 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +00001045 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +00001046
1047 outReturn->push_back(std::move(info));
1048 }
1049
1050 return Status::ok();
1051}
1052
Pawan Wagh243888e2022-09-20 19:37:35 +00001053void ServiceManager::clear() {
1054 mNameToService.clear();
1055 mNameToRegistrationCallback.clear();
1056 mNameToClientCallback.clear();
1057}
1058
Steven Moreland8d0c9a72020-04-30 16:51:56 -07001059} // namespace android