blob: 95a05cdcdec0e672032d4f10f801e3db9f7e8d27 [file] [log] [blame]
Steven Moreland80e1e6d2019-06-21 12:35:59 -07001/*
2 * Copyright (C) 2019 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "ServiceManager.h"
18
19#include <android-base/logging.h>
Jon Spivack0d844302019-07-22 18:40:34 -070020#include <android-base/properties.h>
Devin Moore42407bc2023-09-26 21:30:39 +000021#include <android-base/strings.h>
Jon Spivack9f503a42019-10-22 16:49:19 -070022#include <binder/BpBinder.h>
23#include <binder/IPCThreadState.h>
24#include <binder/ProcessState.h>
Steven Moreland86a17f82019-09-10 10:18:00 -070025#include <binder/Stability.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070026#include <cutils/android_filesystem_config.h>
27#include <cutils/multiuser.h>
Jon Spivack0d844302019-07-22 18:40:34 -070028#include <thread>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070029
Steven Moreland86a17f82019-09-10 10:18:00 -070030#ifndef VENDORSERVICEMANAGER
31#include <vintf/VintfObject.h>
Yifan Hong0a9b56e2021-11-30 16:45:40 -080032#ifdef __ANDROID_RECOVERY__
33#include <vintf/VintfObjectRecovery.h>
34#endif // __ANDROID_RECOVERY__
Steven Moreland86a17f82019-09-10 10:18:00 -070035#include <vintf/constants.h>
36#endif // !VENDORSERVICEMANAGER
37
Jooyung Han205e2822023-12-19 16:59:39 +090038#include "NameUtil.h"
39
Steven Moreland80e1e6d2019-06-21 12:35:59 -070040using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070041using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070042
43namespace android {
44
Steven Morelandb9e1cbe2023-02-01 22:44:45 +000045bool is_multiuser_uid_isolated(uid_t uid) {
46 uid_t appid = multiuser_get_app_id(uid);
47 return appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
48}
49
Steven Moreland86a17f82019-09-10 10:18:00 -070050#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080051
Steven Moreland2e293aa2020-09-23 00:25:16 +000052struct ManifestWithDescription {
53 std::shared_ptr<const vintf::HalManifest> manifest;
54 const char* description;
55};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080056static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
57#ifdef __ANDROID_RECOVERY__
58 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
59 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000060 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080061 return {};
62 }
63 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
64#else
65 auto vintfObject = vintf::VintfObject::GetInstance();
66 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000067 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080068 return {};
69 }
70 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
71 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
72#endif
73}
74
Steven Moreland2e293aa2020-09-23 00:25:16 +000075// func true -> stop search and forEachManifest will return true
76static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080077 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000078 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000079 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
80 // note, we explicitly do not retry here, so that we can detect VINTF
81 // or other bugs (b/151696835)
82 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +000083 }
84 if (func(mwd)) return true;
85 }
86 return false;
87}
88
Jooyung Han205e2822023-12-19 16:59:39 +090089static std::string getNativeInstanceName(const vintf::ManifestInstance& instance) {
90 return instance.package() + "/" + instance.instance();
91}
92
Steven Morelandedd4e072021-04-21 00:27:29 +000093struct AidlName {
94 std::string package;
95 std::string iface;
96 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070097
Steven Morelandedd4e072021-04-21 00:27:29 +000098 static bool fill(const std::string& name, AidlName* aname) {
99 size_t firstSlash = name.find('/');
100 size_t lastDot = name.rfind('.', firstSlash);
101 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000102 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
103 "some.package.foo.IFoo/default) but got: %s",
104 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +0000105 return false;
106 }
107 aname->package = name.substr(0, lastDot);
108 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
109 aname->instance = name.substr(firstSlash + 1);
110 return true;
111 }
112};
113
Jooyung Han205e2822023-12-19 16:59:39 +0900114static std::string getAidlInstanceName(const vintf::ManifestInstance& instance) {
115 return instance.package() + "." + instance.interface() + "/" + instance.instance();
116}
117
Steven Moreland5759db02024-03-27 00:03:05 +0000118static bool isVintfDeclared(const Access::CallingContext& ctx, const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900119 NativeName nname;
120 if (NativeName::fill(name, &nname)) {
121 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
122 if (mwd.manifest->hasNativeInstance(nname.package, nname.instance)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000123 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(),
124 name.c_str(), mwd.description);
Jooyung Han205e2822023-12-19 16:59:39 +0900125 return true; // break
126 }
127 return false; // continue
128 });
129 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000130 ALOGI("%s Could not find %s in the VINTF manifest.", ctx.toDebugString().c_str(),
131 name.c_str());
Jooyung Han205e2822023-12-19 16:59:39 +0900132 }
133 return found;
134 }
135
Steven Morelandedd4e072021-04-21 00:27:29 +0000136 AidlName aname;
137 if (!AidlName::fill(name, &aname)) return false;
138
139 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
140 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000141 ALOGI("%s Found %s in %s VINTF manifest.", ctx.toDebugString().c_str(), name.c_str(),
142 mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000143 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700144 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000145 return false; // continue
146 });
147
148 if (!found) {
Devin Moore42407bc2023-09-26 21:30:39 +0000149 std::set<std::string> instances;
150 forEachManifest([&](const ManifestWithDescription& mwd) {
151 std::set<std::string> res = mwd.manifest->getAidlInstances(aname.package, aname.iface);
152 instances.insert(res.begin(), res.end());
153 return true;
154 });
155
156 std::string available;
157 if (instances.empty()) {
158 available = "No alternative instances declared in VINTF";
159 } else {
160 // for logging only. We can't return this information to the client
161 // because they may not have permissions to find or list those
162 // instances
163 available = "VINTF declared instances: " + base::Join(instances, ", ");
164 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000165 // Although it is tested, explicitly rebuilding qualified name, in case it
166 // becomes something unexpected.
Steven Moreland5759db02024-03-27 00:03:05 +0000167 ALOGI("%s Could not find %s.%s/%s in the VINTF manifest. %s.", ctx.toDebugString().c_str(),
168 aname.package.c_str(), aname.iface.c_str(), aname.instance.c_str(),
169 available.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700170 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700171
Steven Moreland2e293aa2020-09-23 00:25:16 +0000172 return found;
173}
174
Steven Morelandedd4e072021-04-21 00:27:29 +0000175static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
Jooyung Han205e2822023-12-19 16:59:39 +0900176 NativeName nname;
177 if (NativeName::fill(name, &nname)) {
178 std::optional<std::string> updatableViaApex;
179
180 forEachManifest([&](const ManifestWithDescription& mwd) {
181 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
182 if (manifestInstance.format() != vintf::HalFormat::NATIVE) return true;
183 if (manifestInstance.package() != nname.package) return true;
184 if (manifestInstance.instance() != nname.instance) return true;
185 updatableViaApex = manifestInstance.updatableViaApex();
186 return false; // break (libvintf uses opposite convention)
187 });
188 return !cont;
189 });
190
191 return updatableViaApex;
192 }
193
Steven Morelandedd4e072021-04-21 00:27:29 +0000194 AidlName aname;
195 if (!AidlName::fill(name, &aname)) return std::nullopt;
196
197 std::optional<std::string> updatableViaApex;
198
199 forEachManifest([&](const ManifestWithDescription& mwd) {
Jooyung Han9f1c6872024-01-23 06:42:02 +0900200 bool cont = mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Steven Morelandedd4e072021-04-21 00:27:29 +0000201 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
202 if (manifestInstance.package() != aname.package) return true;
203 if (manifestInstance.interface() != aname.iface) return true;
204 if (manifestInstance.instance() != aname.instance) return true;
205 updatableViaApex = manifestInstance.updatableViaApex();
206 return false; // break (libvintf uses opposite convention)
207 });
Jooyung Han9f1c6872024-01-23 06:42:02 +0900208 return !cont;
Steven Morelandedd4e072021-04-21 00:27:29 +0000209 });
210
211 return updatableViaApex;
212}
213
Jooyung Han205e2822023-12-19 16:59:39 +0900214static std::vector<std::string> getVintfUpdatableNames(const std::string& apexName) {
215 std::vector<std::string> names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900216
217 forEachManifest([&](const ManifestWithDescription& mwd) {
218 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
Jooyung Han205e2822023-12-19 16:59:39 +0900219 if (manifestInstance.updatableViaApex().has_value() &&
Jooyung Han76944fe2022-10-25 17:02:45 +0900220 manifestInstance.updatableViaApex().value() == apexName) {
Jooyung Han205e2822023-12-19 16:59:39 +0900221 if (manifestInstance.format() == vintf::HalFormat::NATIVE) {
222 names.push_back(getNativeInstanceName(manifestInstance));
223 } else if (manifestInstance.format() == vintf::HalFormat::AIDL) {
224 names.push_back(getAidlInstanceName(manifestInstance));
225 }
Jooyung Han76944fe2022-10-25 17:02:45 +0900226 }
Jooyung Hance94b752022-11-14 18:55:06 +0900227 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900228 });
229 return false; // continue
230 });
231
Jooyung Han205e2822023-12-19 16:59:39 +0900232 return names;
Jooyung Han76944fe2022-10-25 17:02:45 +0900233}
234
Devin Moore5e4c2f12021-09-09 22:36:33 +0000235static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
236 AidlName aname;
237 if (!AidlName::fill(name, &aname)) return std::nullopt;
238
239 std::optional<std::string> ip;
240 std::optional<uint64_t> port;
241 forEachManifest([&](const ManifestWithDescription& mwd) {
242 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
243 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
244 if (manifestInstance.package() != aname.package) return true;
245 if (manifestInstance.interface() != aname.iface) return true;
246 if (manifestInstance.instance() != aname.instance) return true;
247 ip = manifestInstance.ip();
248 port = manifestInstance.port();
249 return false; // break (libvintf uses opposite convention)
250 });
251 return false; // continue
252 });
253
254 if (ip.has_value() && port.has_value()) {
255 ConnectionInfo info;
256 info.ipAddress = *ip;
257 info.port = *port;
258 return std::make_optional<ConnectionInfo>(info);
259 } else {
260 return std::nullopt;
261 }
262}
263
Steven Moreland2e293aa2020-09-23 00:25:16 +0000264static std::vector<std::string> getVintfInstances(const std::string& interface) {
265 size_t lastDot = interface.rfind('.');
266 if (lastDot == std::string::npos) {
Jooyung Han205e2822023-12-19 16:59:39 +0900267 // This might be a package for native instance.
268 std::vector<std::string> ret;
269 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
270 auto instances = mwd.manifest->getNativeInstances(interface);
271 ret.insert(ret.end(), instances.begin(), instances.end());
272 return false; // continue
273 });
274 // If found, return it without error log.
275 if (!ret.empty()) {
276 return ret;
277 }
278
Pawan Wagh37526162022-09-29 21:55:26 +0000279 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
280 "but got: %s",
281 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000282 return {};
283 }
284 const std::string package = interface.substr(0, lastDot);
285 const std::string iface = interface.substr(lastDot+1);
286
287 std::vector<std::string> ret;
288 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
289 auto instances = mwd.manifest->getAidlInstances(package, iface);
290 ret.insert(ret.end(), instances.begin(), instances.end());
291 return false; // continue
292 });
293
294 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700295}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700296
Steven Moreland5759db02024-03-27 00:03:05 +0000297static bool meetsDeclarationRequirements(const Access::CallingContext& ctx,
298 const sp<IBinder>& binder, const std::string& name) {
Steven Morelandb82b8f82019-10-28 10:52:34 -0700299 if (!Stability::requiresVintfDeclaration(binder)) {
300 return true;
301 }
302
Steven Moreland5759db02024-03-27 00:03:05 +0000303 return isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700304}
Steven Moreland86a17f82019-09-10 10:18:00 -0700305#endif // !VENDORSERVICEMANAGER
306
Steven Morelandb8361902023-02-01 23:18:04 +0000307ServiceManager::Service::~Service() {
Steven Morelandcb591562023-03-06 15:53:44 +0000308 if (hasClients) {
309 // only expected to happen on process death, we don't store the service
310 // name this late (it's in the map that holds this service), but if it
311 // is happening, we might want to change 'unlinkToDeath' to explicitly
312 // clear this bit so that we can abort in other cases, where it would
313 // mean inconsistent logic in servicemanager (unexpected and tested, but
314 // the original lazy service impl here had that bug).
Steven Moreland5759db02024-03-27 00:03:05 +0000315 ALOGW("A service was removed when there are clients");
Steven Morelandb8361902023-02-01 23:18:04 +0000316 }
317}
318
Steven Morelandd13f08b2019-11-18 14:23:09 -0800319ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700320// TODO(b/151696835): reenable performance hack when we solve bug, since with
321// this hack and other fixes, it is unlikely we will see even an ephemeral
322// failure when the manifest parse fails. The goal is that the manifest will
323// be read incorrectly and cause the process trying to register a HAL to
324// fail. If this is in fact an early boot kernel contention issue, then we
325// will get no failure, and by its absence, be signalled to invest more
326// effort in re-adding this performance hack.
327// #ifndef VENDORSERVICEMANAGER
328// // can process these at any times, don't want to delay first VINTF client
329// std::thread([] {
330// vintf::VintfObject::GetDeviceHalManifest();
331// vintf::VintfObject::GetFrameworkHalManifest();
332// }).detach();
333// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800334}
Steven Moreland130242d2019-08-26 17:41:32 -0700335ServiceManager::~ServiceManager() {
336 // this should only happen in tests
337
Jon Spivackf288b1d2019-12-19 17:15:51 -0800338 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700339 CHECK(!callbacks.empty()) << name;
340 for (const auto& callback : callbacks) {
341 CHECK(callback != nullptr) << name;
342 }
343 }
344
Steven Moreland130242d2019-08-26 17:41:32 -0700345 for (const auto& [name, service] : mNameToService) {
346 CHECK(service.binder != nullptr) << name;
347 }
348}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700349
350Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700351 *outBinder = tryGetService(name, true);
352 // returns ok regardless of result for legacy reasons
353 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700354}
355
356Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700357 *outBinder = tryGetService(name, false);
358 // returns ok regardless of result for legacy reasons
359 return Status::ok();
360}
361
362sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700363 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700364
Jon Spivack0d844302019-07-22 18:40:34 -0700365 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700366 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700367 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700368 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700369
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000370 if (!service->allowIsolated && is_multiuser_uid_isolated(ctx.uid)) {
Steven Morelandbad75882023-06-16 20:59:06 +0000371 LOG(WARNING) << "Isolated app with UID " << ctx.uid << " requested '" << name
372 << "', but the service is not allowed for isolated apps.";
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000373 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700374 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700375 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700376 }
377
Steven Morelanda9fe4742019-07-18 14:45:20 -0700378 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700379 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700380 }
381
Jon Spivack0d844302019-07-22 18:40:34 -0700382 if (!out && startIfNotFound) {
Steven Morelandaa33e852023-05-10 16:42:15 +0000383 tryStartService(ctx, name);
Jon Spivack0d844302019-07-22 18:40:34 -0700384 }
385
Jon Spivack9f503a42019-10-22 16:49:19 -0700386 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000387 // Force onClients to get sent, and then make sure the timerfd won't clear it
388 // by setting guaranteeClient again. This logic could be simplified by using
389 // a time-based guarantee. However, forcing onClients(true) to get sent
390 // right here is always going to be important for processes serving multiple
391 // lazy interfaces.
392 service->guaranteeClient = true;
393 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700394 service->guaranteeClient = true;
395 }
396
Jon Spivack0d844302019-07-22 18:40:34 -0700397 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700398}
399
Steven Moreland905e2e82019-07-17 11:05:45 -0700400bool isValidServiceName(const std::string& name) {
401 if (name.size() == 0) return false;
402 if (name.size() > 127) return false;
403
404 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700405 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700406 if (c >= 'a' && c <= 'z') continue;
407 if (c >= 'A' && c <= 'Z') continue;
408 if (c >= '0' && c <= '9') continue;
409 return false;
410 }
411
412 return true;
413}
414
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700415Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700416 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700417
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700418 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000419 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700420 }
421
Steven Morelanda9fe4742019-07-18 14:45:20 -0700422 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000423 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700424 }
425
426 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000427 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700428 }
429
Steven Moreland905e2e82019-07-17 11:05:45 -0700430 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000431 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000432 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700433 }
434
Steven Moreland86a17f82019-09-10 10:18:00 -0700435#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000436 if (!meetsDeclarationRequirements(ctx, binder, name)) {
Steven Moreland86a17f82019-09-10 10:18:00 -0700437 // already logged
Steven Morelandffb905b2023-03-28 18:24:37 +0000438 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error.");
Steven Moreland86a17f82019-09-10 10:18:00 -0700439 }
440#endif // !VENDORSERVICEMANAGER
441
Devin Moore4e21def2023-02-24 21:54:14 +0000442 if ((dumpPriority & DUMP_FLAG_PRIORITY_ALL) == 0) {
Steven Moreland5759db02024-03-27 00:03:05 +0000443 ALOGW("%s Dump flag priority is not set when adding %s", ctx.toDebugString().c_str(),
444 name.c_str());
Devin Moore4e21def2023-02-24 21:54:14 +0000445 }
446
Steven Moreland88860b02019-08-12 14:24:14 -0700447 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000448 if (binder->remoteBinder() != nullptr &&
449 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Steven Moreland5759db02024-03-27 00:03:05 +0000450 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000451 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700452 }
453
Steven Moreland7ee423b2022-09-24 03:52:08 +0000454 auto it = mNameToService.find(name);
Steven Moreland79578672023-04-27 19:38:00 +0000455 bool prevClients = false;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000456 if (it != mNameToService.end()) {
457 const Service& existing = it->second;
Steven Moreland79578672023-04-27 19:38:00 +0000458 prevClients = existing.hasClients;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000459
460 // We could do better than this because if the other service dies, it
461 // may not have an entry here. However, this case is unlikely. We are
462 // only trying to detect when two different services are accidentally installed.
463
464 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000465 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
466 "from UID %u. Multiple instances installed?",
467 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000468 }
469
470 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000471 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
472 "from SID %s. Multiple instances installed?",
473 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000474 }
475
Pawan Wagh37526162022-09-29 21:55:26 +0000476 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
477 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
478 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000479 }
480
Devin Moore05ffe522020-08-06 13:58:29 -0700481 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000482 mNameToService[name] = Service{
483 .binder = binder,
484 .allowIsolated = allowIsolated,
485 .dumpPriority = dumpPriority,
Steven Moreland79578672023-04-27 19:38:00 +0000486 .hasClients = prevClients, // see b/279898063, matters if existing callbacks
Steven Morelandefea66b2023-06-17 01:59:34 +0000487 .guaranteeClient = false,
Steven Moreland7ee423b2022-09-24 03:52:08 +0000488 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700489 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700490
Steven Moreland7ee423b2022-09-24 03:52:08 +0000491 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandefea66b2023-06-17 01:59:34 +0000492 // If someone is currently waiting on the service, notify the service that
493 // we're waiting and flush it to the service.
Steven Morelandb8361902023-02-01 23:18:04 +0000494 mNameToService[name].guaranteeClient = true;
495 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
496 mNameToService[name].guaranteeClient = true;
497
Steven Moreland27cfab02019-08-12 14:34:16 -0700498 for (const sp<IServiceCallback>& cb : it->second) {
499 // permission checked in registerForNotifications
500 cb->onRegistration(name, binder);
501 }
502 }
503
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700504 return Status::ok();
505}
506
507Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700508 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000509 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700510 }
511
512 size_t toReserve = 0;
513 for (auto const& [name, service] : mNameToService) {
514 (void) name;
515
516 if (service.dumpPriority & dumpPriority) ++toReserve;
517 }
518
519 CHECK(outList->empty());
520
521 outList->reserve(toReserve);
522 for (auto const& [name, service] : mNameToService) {
523 (void) service;
524
525 if (service.dumpPriority & dumpPriority) {
526 outList->push_back(name);
527 }
528 }
529
530 return Status::ok();
531}
532
Steven Moreland27cfab02019-08-12 14:34:16 -0700533Status ServiceManager::registerForNotifications(
534 const std::string& name, const sp<IServiceCallback>& callback) {
535 auto ctx = mAccess->getCallingContext();
536
537 if (!mAccess->canFind(ctx, name)) {
Steven Morelandb9e1cbe2023-02-01 22:44:45 +0000538 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux");
539 }
540
541 // note - we could allow isolated apps to get notifications if we
542 // keep track of isolated callbacks and non-isolated callbacks, but
543 // this is done since isolated apps shouldn't access lazy services
544 // so we should be able to use different APIs to keep things simple.
545 // Here, we disallow everything, because the service might not be
546 // registered yet.
547 if (is_multiuser_uid_isolated(ctx.uid)) {
548 return Status::fromExceptionCode(Status::EX_SECURITY, "isolated app");
Steven Moreland27cfab02019-08-12 14:34:16 -0700549 }
550
551 if (!isValidServiceName(name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000552 ALOGE("%s Invalid service name: %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000553 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700554 }
555
556 if (callback == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000557 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null callback.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700558 }
559
Steven Morelandb0983182021-04-02 03:14:04 +0000560 if (OK !=
561 IInterface::asBinder(callback)->linkToDeath(
562 sp<ServiceManager>::fromExisting(this))) {
Steven Moreland5759db02024-03-27 00:03:05 +0000563 ALOGE("%s Could not linkToDeath when adding %s", ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000564 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't link to death.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700565 }
566
Jon Spivackf288b1d2019-12-19 17:15:51 -0800567 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700568
569 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
570 const sp<IBinder>& binder = it->second.binder;
571
572 // never null if an entry exists
573 CHECK(binder != nullptr) << name;
574 callback->onRegistration(name, binder);
575 }
576
577 return Status::ok();
578}
579Status ServiceManager::unregisterForNotifications(
580 const std::string& name, const sp<IServiceCallback>& callback) {
581 auto ctx = mAccess->getCallingContext();
582
583 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000584 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700585 }
586
587 bool found = false;
588
Jon Spivackf288b1d2019-12-19 17:15:51 -0800589 auto it = mNameToRegistrationCallback.find(name);
590 if (it != mNameToRegistrationCallback.end()) {
591 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700592 }
593
594 if (!found) {
Steven Moreland5759db02024-03-27 00:03:05 +0000595 ALOGE("%s Trying to unregister callback, but none exists %s", ctx.toDebugString().c_str(),
596 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000597 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Nothing to unregister.");
Steven Moreland27cfab02019-08-12 14:34:16 -0700598 }
599
600 return Status::ok();
601}
602
Steven Morelandb82b8f82019-10-28 10:52:34 -0700603Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
604 auto ctx = mAccess->getCallingContext();
605
606 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000607 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandb82b8f82019-10-28 10:52:34 -0700608 }
609
610 *outReturn = false;
611
612#ifndef VENDORSERVICEMANAGER
Steven Moreland5759db02024-03-27 00:03:05 +0000613 *outReturn = isVintfDeclared(ctx, name);
Steven Morelandb82b8f82019-10-28 10:52:34 -0700614#endif
615 return Status::ok();
616}
617
Steven Moreland2e293aa2020-09-23 00:25:16 +0000618binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
619 auto ctx = mAccess->getCallingContext();
620
621 std::vector<std::string> allInstances;
622#ifndef VENDORSERVICEMANAGER
623 allInstances = getVintfInstances(interface);
624#endif
625
626 outReturn->clear();
627
628 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000629 if (mAccess->canFind(ctx, interface + "/" + instance)) {
630 outReturn->push_back(instance);
631 }
632 }
633
634 if (outReturn->size() == 0 && allInstances.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000635 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland2e293aa2020-09-23 00:25:16 +0000636 }
637
638 return Status::ok();
639}
640
Steven Morelandedd4e072021-04-21 00:27:29 +0000641Status ServiceManager::updatableViaApex(const std::string& name,
642 std::optional<std::string>* outReturn) {
643 auto ctx = mAccess->getCallingContext();
644
645 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000646 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Morelandedd4e072021-04-21 00:27:29 +0000647 }
648
649 *outReturn = std::nullopt;
650
651#ifndef VENDORSERVICEMANAGER
652 *outReturn = getVintfUpdatableApex(name);
653#endif
654 return Status::ok();
655}
656
Jooyung Han76944fe2022-10-25 17:02:45 +0900657Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
658 std::vector<std::string>* outReturn) {
659 auto ctx = mAccess->getCallingContext();
660
Jooyung Han205e2822023-12-19 16:59:39 +0900661 std::vector<std::string> apexUpdatableNames;
Jooyung Han76944fe2022-10-25 17:02:45 +0900662#ifndef VENDORSERVICEMANAGER
Jooyung Han205e2822023-12-19 16:59:39 +0900663 apexUpdatableNames = getVintfUpdatableNames(apexName);
Jooyung Han76944fe2022-10-25 17:02:45 +0900664#endif
665
666 outReturn->clear();
667
Jooyung Han205e2822023-12-19 16:59:39 +0900668 for (const std::string& name : apexUpdatableNames) {
669 if (mAccess->canFind(ctx, name)) {
670 outReturn->push_back(name);
Jooyung Han76944fe2022-10-25 17:02:45 +0900671 }
672 }
673
Jooyung Han205e2822023-12-19 16:59:39 +0900674 if (outReturn->size() == 0 && apexUpdatableNames.size() != 0) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000675 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jooyung Han76944fe2022-10-25 17:02:45 +0900676 }
677
678 return Status::ok();
679}
680
Devin Moore5e4c2f12021-09-09 22:36:33 +0000681Status ServiceManager::getConnectionInfo(const std::string& name,
682 std::optional<ConnectionInfo>* outReturn) {
683 auto ctx = mAccess->getCallingContext();
684
685 if (!mAccess->canFind(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000686 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Devin Moore5e4c2f12021-09-09 22:36:33 +0000687 }
688
689 *outReturn = std::nullopt;
690
691#ifndef VENDORSERVICEMANAGER
692 *outReturn = getVintfConnectionInfo(name);
693#endif
694 return Status::ok();
695}
696
Jon Spivackf288b1d2019-12-19 17:15:51 -0800697void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
698 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700699 bool* found) {
700 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
701
702 for (auto lit = listeners.begin(); lit != listeners.end();) {
703 if (IInterface::asBinder(*lit) == who) {
704 if(found) *found = true;
705 lit = listeners.erase(lit);
706 } else {
707 ++lit;
708 }
709 }
710
711 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800712 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700713 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800714 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700715 }
716}
717
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700718void ServiceManager::binderDied(const wp<IBinder>& who) {
719 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
720 if (who == it->second.binder) {
Steven Moreland79578672023-04-27 19:38:00 +0000721 // TODO: currently, this entry contains the state also
722 // associated with mNameToClientCallback. If we allowed
723 // other processes to register client callbacks, we
724 // would have to preserve hasClients (perhaps moving
725 // that state into mNameToClientCallback, which is complicated
726 // because those callbacks are associated w/ particular binder
727 // objects, though they are indexed by name now, they may
728 // need to be indexed by binder at that point).
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700729 it = mNameToService.erase(it);
730 } else {
731 ++it;
732 }
733 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700734
Jon Spivackf288b1d2019-12-19 17:15:51 -0800735 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
736 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700737 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700738
739 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
740 removeClientCallback(who, &it);
741 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700742}
743
Steven Morelandaa33e852023-05-10 16:42:15 +0000744void ServiceManager::tryStartService(const Access::CallingContext& ctx, const std::string& name) {
Steven Moreland5759db02024-03-27 00:03:05 +0000745 ALOGI("%s Since '%s' could not be found trying to start it as a lazy AIDL service. (if it's "
746 "not configured to be a lazy service, it may be stuck starting or still starting).",
747 ctx.toDebugString().c_str(), name.c_str());
Jon Spivack0d844302019-07-22 18:40:34 -0700748
749 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000750 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000751 ALOGI("%s Tried to start aidl service %s as a lazy service, but was unable to. Usually "
752 "this happens when a service is not installed, but if the service is intended to "
753 "be used as a lazy service, then it may be configured incorrectly.",
754 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000755 }
Jon Spivack0d844302019-07-22 18:40:34 -0700756 }).detach();
757}
758
Jon Spivack9f503a42019-10-22 16:49:19 -0700759Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
760 const sp<IClientCallback>& cb) {
761 if (cb == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000762 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Callback null.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700763 }
764
765 auto ctx = mAccess->getCallingContext();
766 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000767 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700768 }
769
770 auto serviceIt = mNameToService.find(name);
771 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000772 ALOGE("%s Could not add callback for nonexistent service: %s", ctx.toDebugString().c_str(),
773 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000774 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service doesn't exist.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700775 }
776
Steven Moreland7ee423b2022-09-24 03:52:08 +0000777 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000778 ALOGW("%s Only a server can register for client callbacks (for %s)",
779 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000780 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
781 "Only service can register client callback for itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700782 }
783
784 if (serviceIt->second.binder != service) {
Steven Moreland5759db02024-03-27 00:03:05 +0000785 ALOGW("%s Tried to register client callback for %s but a different service is registered "
Pawan Wagh37526162022-09-29 21:55:26 +0000786 "under this name.",
Steven Moreland5759db02024-03-27 00:03:05 +0000787 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000788 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Service mismatch.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700789 }
790
Steven Morelandb0983182021-04-02 03:14:04 +0000791 if (OK !=
792 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
David Duarte67d65282024-04-10 23:54:36 +0000793 ALOGE("%s Could not linkToDeath when adding client callback for %s",
794 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000795 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Couldn't linkToDeath.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700796 }
797
Steven Moreland79578672023-04-27 19:38:00 +0000798 // WARNING: binderDied makes an assumption about this. If we open up client
799 // callbacks to other services, certain race conditions may lead to services
800 // getting extra client callback notifications.
801 // Make sure all callbacks have been told about a consistent state - b/278038751
Steven Moreland7bb4ab82023-04-13 20:29:33 +0000802 if (serviceIt->second.hasClients) {
803 cb->onClients(service, true);
804 }
805
Jon Spivack9f503a42019-10-22 16:49:19 -0700806 mNameToClientCallback[name].push_back(cb);
807
Steven Morelandefea66b2023-06-17 01:59:34 +0000808 // Flush updated info to client callbacks (especially if guaranteeClient
809 // and !hasClient, see b/285202885). We may or may not have clients at
810 // this point, so ignore the return value.
811 (void)handleServiceClientCallback(2 /* sm + transaction */, name, false);
812
Jon Spivack9f503a42019-10-22 16:49:19 -0700813 return Status::ok();
814}
815
816void ServiceManager::removeClientCallback(const wp<IBinder>& who,
817 ClientCallbackMap::iterator* it) {
818 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
819
820 for (auto lit = listeners.begin(); lit != listeners.end();) {
821 if (IInterface::asBinder(*lit) == who) {
822 lit = listeners.erase(lit);
823 } else {
824 ++lit;
825 }
826 }
827
828 if (listeners.empty()) {
829 *it = mNameToClientCallback.erase(*it);
830 } else {
831 (*it)++;
832 }
833}
834
835ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000836 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700837 if (bpBinder == nullptr) return -1;
838
Steven Morelande8393882020-12-18 02:27:20 +0000839 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700840}
841
842void ServiceManager::handleClientCallbacks() {
843 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000844 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700845 }
846}
847
Steven Morelandb8361902023-02-01 23:18:04 +0000848bool ServiceManager::handleServiceClientCallback(size_t knownClients,
849 const std::string& serviceName,
850 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700851 auto serviceIt = mNameToService.find(serviceName);
852 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000853 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700854 }
855
856 Service& service = serviceIt->second;
857 ssize_t count = service.getNodeStrongRefCount();
858
Steven Morelandb8361902023-02-01 23:18:04 +0000859 // binder driver doesn't support this feature, consider we have clients
860 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700861
Steven Morelandb8361902023-02-01 23:18:04 +0000862 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700863
864 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000865 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000866 sendClientCallbackNotifications(serviceName, true,
867 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700868 }
869
870 // guarantee is temporary
871 service.guaranteeClient = false;
872 }
873
Steven Morelandb8361902023-02-01 23:18:04 +0000874 // Regardless of this situation, we want to give this notification as soon as possible.
875 // This way, we have a chance of preventing further thrashing.
876 if (hasKernelReportedClients && !service.hasClients) {
877 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
878 }
Steven Moreland66417652023-02-01 22:19:41 +0000879
Steven Morelandb8361902023-02-01 23:18:04 +0000880 // But limit rate of shutting down service.
881 if (isCalledOnInterval) {
882 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000883 sendClientCallbackNotifications(serviceName, false,
884 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000885 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700886 }
887
Steven Morelandb8361902023-02-01 23:18:04 +0000888 // May be different than 'hasKernelReportedClients'. We intentionally delay
889 // information about clients going away to reduce thrashing.
890 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700891}
892
Steven Moreland3e083b22023-01-26 00:46:30 +0000893void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
894 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700895 auto serviceIt = mNameToService.find(serviceName);
896 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000897 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
898 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700899 return;
900 }
901 Service& service = serviceIt->second;
902
Steven Morelandb8361902023-02-01 23:18:04 +0000903 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700904
Steven Morelandb8361902023-02-01 23:18:04 +0000905 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
906 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700907
908 auto ccIt = mNameToClientCallback.find(serviceName);
909 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000910 << "sendClientCallbackNotifications could not find callbacks for service when "
911 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700912
913 for (const auto& callback : ccIt->second) {
914 callback->onClients(service.binder, hasClients);
915 }
916
917 service.hasClients = hasClients;
918}
919
920Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
921 if (binder == nullptr) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000922 return Status::fromExceptionCode(Status::EX_NULL_POINTER, "Null service.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700923 }
924
925 auto ctx = mAccess->getCallingContext();
926 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000927 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700928 }
929
930 auto serviceIt = mNameToService.find(name);
931 if (serviceIt == mNameToService.end()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000932 ALOGW("%s Tried to unregister %s, but that service wasn't registered to begin with.",
933 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000934 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "Service not registered.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700935 }
936
Steven Moreland7ee423b2022-09-24 03:52:08 +0000937 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Steven Moreland5759db02024-03-27 00:03:05 +0000938 ALOGW("%s Only a server can unregister itself (for %s)", ctx.toDebugString().c_str(),
939 name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000940 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION,
941 "Service can only unregister itself.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700942 }
943
944 sp<IBinder> storedBinder = serviceIt->second.binder;
945
946 if (binder != storedBinder) {
Steven Moreland5759db02024-03-27 00:03:05 +0000947 ALOGW("%s Tried to unregister %s, but a different service is registered under this name.",
948 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000949 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
950 "Different service registered under this name.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700951 }
952
Steven Morelandb8361902023-02-01 23:18:04 +0000953 // important because we don't have timer-based guarantees, we don't want to clear
954 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700955 if (serviceIt->second.guaranteeClient) {
Steven Moreland5759db02024-03-27 00:03:05 +0000956 ALOGI("%s Tried to unregister %s, but there is about to be a client.",
957 ctx.toDebugString().c_str(), name.c_str());
Steven Morelandffb905b2023-03-28 18:24:37 +0000958 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
959 "Can't unregister, pending client.");
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700960 }
961
Jon Spivack9f503a42019-10-22 16:49:19 -0700962 // - kernel driver will hold onto one refcount (during this transaction)
963 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000964 constexpr size_t kKnownClients = 2;
965
966 if (handleServiceClientCallback(kKnownClients, name, false)) {
Steven Moreland5759db02024-03-27 00:03:05 +0000967 ALOGI("%s Tried to unregister %s, but there are clients.", ctx.toDebugString().c_str(),
968 name.c_str());
Steven Morelandb8361902023-02-01 23:18:04 +0000969
970 // Since we had a failed registration attempt, and the HIDL implementation of
971 // delaying service shutdown for multiple periods wasn't ported here... this may
972 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800973 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000974
Steven Morelandffb905b2023-03-28 18:24:37 +0000975 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE,
976 "Can't unregister, known client.");
Jon Spivack9f503a42019-10-22 16:49:19 -0700977 }
978
Steven Moreland5759db02024-03-27 00:03:05 +0000979 ALOGI("%s Unregistering %s", ctx.toDebugString().c_str(), name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700980 mNameToService.erase(name);
981
982 return Status::ok();
983}
984
Steven Moreland3ea43272021-01-28 22:49:28 +0000985Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
986 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Morelandffb905b2023-03-28 18:24:37 +0000987 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denied.");
Steven Moreland3ea43272021-01-28 22:49:28 +0000988 }
989
990 outReturn->reserve(mNameToService.size());
991 for (auto const& [name, service] : mNameToService) {
992 ServiceDebugInfo info;
993 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000994 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000995
996 outReturn->push_back(std::move(info));
997 }
998
999 return Status::ok();
1000}
1001
Pawan Wagh243888e2022-09-20 19:37:35 +00001002void ServiceManager::clear() {
1003 mNameToService.clear();
1004 mNameToRegistrationCallback.clear();
1005 mNameToClientCallback.clear();
1006}
1007
Steven Moreland8d0c9a72020-04-30 16:51:56 -07001008} // namespace android