blob: eadf67821fd6f75609c815fa79aaf1ef1e6186b6 [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>
Jon Spivack9f503a42019-10-22 16:49:19 -070021#include <binder/BpBinder.h>
22#include <binder/IPCThreadState.h>
23#include <binder/ProcessState.h>
Steven Moreland86a17f82019-09-10 10:18:00 -070024#include <binder/Stability.h>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070025#include <cutils/android_filesystem_config.h>
26#include <cutils/multiuser.h>
Jon Spivack0d844302019-07-22 18:40:34 -070027#include <thread>
Steven Moreland80e1e6d2019-06-21 12:35:59 -070028
Steven Moreland86a17f82019-09-10 10:18:00 -070029#ifndef VENDORSERVICEMANAGER
30#include <vintf/VintfObject.h>
Yifan Hong0a9b56e2021-11-30 16:45:40 -080031#ifdef __ANDROID_RECOVERY__
32#include <vintf/VintfObjectRecovery.h>
33#endif // __ANDROID_RECOVERY__
Steven Moreland86a17f82019-09-10 10:18:00 -070034#include <vintf/constants.h>
35#endif // !VENDORSERVICEMANAGER
36
Steven Moreland80e1e6d2019-06-21 12:35:59 -070037using ::android::binder::Status;
Steven Moreland86a17f82019-09-10 10:18:00 -070038using ::android::internal::Stability;
Steven Moreland80e1e6d2019-06-21 12:35:59 -070039
40namespace android {
41
Steven Moreland86a17f82019-09-10 10:18:00 -070042#ifndef VENDORSERVICEMANAGER
Yifan Hong0a9b56e2021-11-30 16:45:40 -080043
Steven Moreland2e293aa2020-09-23 00:25:16 +000044struct ManifestWithDescription {
45 std::shared_ptr<const vintf::HalManifest> manifest;
46 const char* description;
47};
Yifan Hong0a9b56e2021-11-30 16:45:40 -080048static std::vector<ManifestWithDescription> GetManifestsWithDescription() {
49#ifdef __ANDROID_RECOVERY__
50 auto vintfObject = vintf::VintfObjectRecovery::GetInstance();
51 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000052 ALOGE("NULL VintfObjectRecovery!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080053 return {};
54 }
55 return {ManifestWithDescription{vintfObject->getRecoveryHalManifest(), "recovery"}};
56#else
57 auto vintfObject = vintf::VintfObject::GetInstance();
58 if (vintfObject == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000059 ALOGE("NULL VintfObject!");
Yifan Hong0a9b56e2021-11-30 16:45:40 -080060 return {};
61 }
62 return {ManifestWithDescription{vintfObject->getDeviceHalManifest(), "device"},
63 ManifestWithDescription{vintfObject->getFrameworkHalManifest(), "framework"}};
64#endif
65}
66
Steven Moreland2e293aa2020-09-23 00:25:16 +000067// func true -> stop search and forEachManifest will return true
68static bool forEachManifest(const std::function<bool(const ManifestWithDescription&)>& func) {
Yifan Hong0a9b56e2021-11-30 16:45:40 -080069 for (const ManifestWithDescription& mwd : GetManifestsWithDescription()) {
Steven Moreland2e293aa2020-09-23 00:25:16 +000070 if (mwd.manifest == nullptr) {
Pawan Wagh37526162022-09-29 21:55:26 +000071 ALOGE("NULL VINTF MANIFEST!: %s", mwd.description);
72 // note, we explicitly do not retry here, so that we can detect VINTF
73 // or other bugs (b/151696835)
74 continue;
Steven Moreland2e293aa2020-09-23 00:25:16 +000075 }
76 if (func(mwd)) return true;
77 }
78 return false;
79}
80
Steven Morelandedd4e072021-04-21 00:27:29 +000081struct AidlName {
82 std::string package;
83 std::string iface;
84 std::string instance;
Steven Moreland86a17f82019-09-10 10:18:00 -070085
Steven Morelandedd4e072021-04-21 00:27:29 +000086 static bool fill(const std::string& name, AidlName* aname) {
87 size_t firstSlash = name.find('/');
88 size_t lastDot = name.rfind('.', firstSlash);
89 if (firstSlash == std::string::npos || lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +000090 ALOGE("VINTF HALs require names in the format type/instance (e.g. "
91 "some.package.foo.IFoo/default) but got: %s",
92 name.c_str());
Steven Morelandedd4e072021-04-21 00:27:29 +000093 return false;
94 }
95 aname->package = name.substr(0, lastDot);
96 aname->iface = name.substr(lastDot + 1, firstSlash - lastDot - 1);
97 aname->instance = name.substr(firstSlash + 1);
98 return true;
99 }
100};
101
102static bool isVintfDeclared(const std::string& name) {
103 AidlName aname;
104 if (!AidlName::fill(name, &aname)) return false;
105
106 bool found = forEachManifest([&](const ManifestWithDescription& mwd) {
107 if (mwd.manifest->hasAidlInstance(aname.package, aname.iface, aname.instance)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000108 ALOGI("Found %s in %s VINTF manifest.", name.c_str(), mwd.description);
Steven Morelandedd4e072021-04-21 00:27:29 +0000109 return true; // break
Steven Moreland86a17f82019-09-10 10:18:00 -0700110 }
Steven Moreland2e293aa2020-09-23 00:25:16 +0000111 return false; // continue
112 });
113
114 if (!found) {
115 // Although it is tested, explicitly rebuilding qualified name, in case it
116 // becomes something unexpected.
Pawan Wagh37526162022-09-29 21:55:26 +0000117 ALOGI("Could not find %s.%s/%s in the VINTF manifest.", aname.package.c_str(),
118 aname.iface.c_str(), aname.instance.c_str());
Steven Moreland86a17f82019-09-10 10:18:00 -0700119 }
Steven Moreland2edde8e2020-04-30 17:04:54 -0700120
Steven Moreland2e293aa2020-09-23 00:25:16 +0000121 return found;
122}
123
Steven Morelandedd4e072021-04-21 00:27:29 +0000124static std::optional<std::string> getVintfUpdatableApex(const std::string& name) {
125 AidlName aname;
126 if (!AidlName::fill(name, &aname)) return std::nullopt;
127
128 std::optional<std::string> updatableViaApex;
129
130 forEachManifest([&](const ManifestWithDescription& mwd) {
131 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
132 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
133 if (manifestInstance.package() != aname.package) return true;
134 if (manifestInstance.interface() != aname.iface) return true;
135 if (manifestInstance.instance() != aname.instance) return true;
136 updatableViaApex = manifestInstance.updatableViaApex();
137 return false; // break (libvintf uses opposite convention)
138 });
Jooyung Hance94b752022-11-14 18:55:06 +0900139 if (updatableViaApex.has_value()) return true; // break (found match)
Steven Morelandedd4e072021-04-21 00:27:29 +0000140 return false; // continue
141 });
142
143 return updatableViaApex;
144}
145
Jooyung Han76944fe2022-10-25 17:02:45 +0900146static std::vector<std::string> getVintfUpdatableInstances(const std::string& apexName) {
147 std::vector<std::string> instances;
148
149 forEachManifest([&](const ManifestWithDescription& mwd) {
150 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
151 if (manifestInstance.format() == vintf::HalFormat::AIDL &&
152 manifestInstance.updatableViaApex().has_value() &&
153 manifestInstance.updatableViaApex().value() == apexName) {
154 std::string aname = manifestInstance.package() + "." +
155 manifestInstance.interface() + "/" + manifestInstance.instance();
156 instances.push_back(aname);
157 }
Jooyung Hance94b752022-11-14 18:55:06 +0900158 return true; // continue (libvintf uses opposite convention)
Jooyung Han76944fe2022-10-25 17:02:45 +0900159 });
160 return false; // continue
161 });
162
163 return instances;
164}
165
Devin Moore5e4c2f12021-09-09 22:36:33 +0000166static std::optional<ConnectionInfo> getVintfConnectionInfo(const std::string& name) {
167 AidlName aname;
168 if (!AidlName::fill(name, &aname)) return std::nullopt;
169
170 std::optional<std::string> ip;
171 std::optional<uint64_t> port;
172 forEachManifest([&](const ManifestWithDescription& mwd) {
173 mwd.manifest->forEachInstance([&](const auto& manifestInstance) {
174 if (manifestInstance.format() != vintf::HalFormat::AIDL) return true;
175 if (manifestInstance.package() != aname.package) return true;
176 if (manifestInstance.interface() != aname.iface) return true;
177 if (manifestInstance.instance() != aname.instance) return true;
178 ip = manifestInstance.ip();
179 port = manifestInstance.port();
180 return false; // break (libvintf uses opposite convention)
181 });
182 return false; // continue
183 });
184
185 if (ip.has_value() && port.has_value()) {
186 ConnectionInfo info;
187 info.ipAddress = *ip;
188 info.port = *port;
189 return std::make_optional<ConnectionInfo>(info);
190 } else {
191 return std::nullopt;
192 }
193}
194
Steven Moreland2e293aa2020-09-23 00:25:16 +0000195static std::vector<std::string> getVintfInstances(const std::string& interface) {
196 size_t lastDot = interface.rfind('.');
197 if (lastDot == std::string::npos) {
Pawan Wagh37526162022-09-29 21:55:26 +0000198 ALOGE("VINTF interfaces require names in Java package format (e.g. some.package.foo.IFoo) "
199 "but got: %s",
200 interface.c_str());
Steven Moreland2e293aa2020-09-23 00:25:16 +0000201 return {};
202 }
203 const std::string package = interface.substr(0, lastDot);
204 const std::string iface = interface.substr(lastDot+1);
205
206 std::vector<std::string> ret;
207 (void)forEachManifest([&](const ManifestWithDescription& mwd) {
208 auto instances = mwd.manifest->getAidlInstances(package, iface);
209 ret.insert(ret.end(), instances.begin(), instances.end());
210 return false; // continue
211 });
212
213 return ret;
Steven Moreland86a17f82019-09-10 10:18:00 -0700214}
Steven Morelandb82b8f82019-10-28 10:52:34 -0700215
216static bool meetsDeclarationRequirements(const sp<IBinder>& binder, const std::string& name) {
217 if (!Stability::requiresVintfDeclaration(binder)) {
218 return true;
219 }
220
221 return isVintfDeclared(name);
222}
Steven Moreland86a17f82019-09-10 10:18:00 -0700223#endif // !VENDORSERVICEMANAGER
224
Steven Morelandb8361902023-02-01 23:18:04 +0000225ServiceManager::Service::~Service() {
226 if (!hasClients) {
227 // only expected to happen on process death
228 LOG(WARNING) << "a service was removed when there are clients";
229 }
230}
231
Steven Morelandd13f08b2019-11-18 14:23:09 -0800232ServiceManager::ServiceManager(std::unique_ptr<Access>&& access) : mAccess(std::move(access)) {
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700233// TODO(b/151696835): reenable performance hack when we solve bug, since with
234// this hack and other fixes, it is unlikely we will see even an ephemeral
235// failure when the manifest parse fails. The goal is that the manifest will
236// be read incorrectly and cause the process trying to register a HAL to
237// fail. If this is in fact an early boot kernel contention issue, then we
238// will get no failure, and by its absence, be signalled to invest more
239// effort in re-adding this performance hack.
240// #ifndef VENDORSERVICEMANAGER
241// // can process these at any times, don't want to delay first VINTF client
242// std::thread([] {
243// vintf::VintfObject::GetDeviceHalManifest();
244// vintf::VintfObject::GetFrameworkHalManifest();
245// }).detach();
246// #endif // !VENDORSERVICEMANAGER
Steven Morelandd13f08b2019-11-18 14:23:09 -0800247}
Steven Moreland130242d2019-08-26 17:41:32 -0700248ServiceManager::~ServiceManager() {
249 // this should only happen in tests
250
Jon Spivackf288b1d2019-12-19 17:15:51 -0800251 for (const auto& [name, callbacks] : mNameToRegistrationCallback) {
Steven Moreland27cfab02019-08-12 14:34:16 -0700252 CHECK(!callbacks.empty()) << name;
253 for (const auto& callback : callbacks) {
254 CHECK(callback != nullptr) << name;
255 }
256 }
257
Steven Moreland130242d2019-08-26 17:41:32 -0700258 for (const auto& [name, service] : mNameToService) {
259 CHECK(service.binder != nullptr) << name;
260 }
261}
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700262
263Status ServiceManager::getService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700264 *outBinder = tryGetService(name, true);
265 // returns ok regardless of result for legacy reasons
266 return Status::ok();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700267}
268
269Status ServiceManager::checkService(const std::string& name, sp<IBinder>* outBinder) {
Jon Spivack0d844302019-07-22 18:40:34 -0700270 *outBinder = tryGetService(name, false);
271 // returns ok regardless of result for legacy reasons
272 return Status::ok();
273}
274
275sp<IBinder> ServiceManager::tryGetService(const std::string& name, bool startIfNotFound) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700276 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700277
Jon Spivack0d844302019-07-22 18:40:34 -0700278 sp<IBinder> out;
Jon Spivack9f503a42019-10-22 16:49:19 -0700279 Service* service = nullptr;
Jon Spivack0d844302019-07-22 18:40:34 -0700280 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700281 service = &(it->second);
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700282
Jon Spivack9f503a42019-10-22 16:49:19 -0700283 if (!service->allowIsolated) {
Jon Spivack0d844302019-07-22 18:40:34 -0700284 uid_t appid = multiuser_get_app_id(ctx.uid);
285 bool isIsolated = appid >= AID_ISOLATED_START && appid <= AID_ISOLATED_END;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700286
Jon Spivack0d844302019-07-22 18:40:34 -0700287 if (isIsolated) {
288 return nullptr;
289 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700290 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700291 out = service->binder;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700292 }
293
Steven Morelanda9fe4742019-07-18 14:45:20 -0700294 if (!mAccess->canFind(ctx, name)) {
Jon Spivack0d844302019-07-22 18:40:34 -0700295 return nullptr;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700296 }
297
Jon Spivack0d844302019-07-22 18:40:34 -0700298 if (!out && startIfNotFound) {
299 tryStartService(name);
300 }
301
Jon Spivack9f503a42019-10-22 16:49:19 -0700302 if (out) {
Steven Morelandb8361902023-02-01 23:18:04 +0000303 // Force onClients to get sent, and then make sure the timerfd won't clear it
304 // by setting guaranteeClient again. This logic could be simplified by using
305 // a time-based guarantee. However, forcing onClients(true) to get sent
306 // right here is always going to be important for processes serving multiple
307 // lazy interfaces.
308 service->guaranteeClient = true;
309 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
Jon Spivack9f503a42019-10-22 16:49:19 -0700310 service->guaranteeClient = true;
311 }
312
Jon Spivack0d844302019-07-22 18:40:34 -0700313 return out;
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700314}
315
Steven Moreland905e2e82019-07-17 11:05:45 -0700316bool isValidServiceName(const std::string& name) {
317 if (name.size() == 0) return false;
318 if (name.size() > 127) return false;
319
320 for (char c : name) {
Steven Morelandbb7951d2019-08-20 16:58:25 -0700321 if (c == '_' || c == '-' || c == '.' || c == '/') continue;
Steven Moreland905e2e82019-07-17 11:05:45 -0700322 if (c >= 'a' && c <= 'z') continue;
323 if (c >= 'A' && c <= 'Z') continue;
324 if (c >= '0' && c <= '9') continue;
325 return false;
326 }
327
328 return true;
329}
330
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700331Status ServiceManager::addService(const std::string& name, const sp<IBinder>& binder, bool allowIsolated, int32_t dumpPriority) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700332 auto ctx = mAccess->getCallingContext();
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700333
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700334 if (multiuser_get_app_id(ctx.uid) >= AID_APP) {
Steven Morelandac2d2852022-03-18 18:15:20 +0000335 return Status::fromExceptionCode(Status::EX_SECURITY, "App UIDs cannot add services");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700336 }
337
Steven Morelanda9fe4742019-07-18 14:45:20 -0700338 if (!mAccess->canAdd(ctx, name)) {
Steven Morelandac2d2852022-03-18 18:15:20 +0000339 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denial");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700340 }
341
342 if (binder == nullptr) {
Steven Morelandac2d2852022-03-18 18:15:20 +0000343 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Null binder");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700344 }
345
Steven Moreland905e2e82019-07-17 11:05:45 -0700346 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000347 ALOGE("Invalid service name: %s", name.c_str());
Steven Morelandac2d2852022-03-18 18:15:20 +0000348 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "Invalid service name");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700349 }
350
Steven Moreland86a17f82019-09-10 10:18:00 -0700351#ifndef VENDORSERVICEMANAGER
352 if (!meetsDeclarationRequirements(binder, name)) {
353 // already logged
Steven Morelandac2d2852022-03-18 18:15:20 +0000354 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT, "VINTF declaration error");
Steven Moreland86a17f82019-09-10 10:18:00 -0700355 }
356#endif // !VENDORSERVICEMANAGER
357
Steven Moreland88860b02019-08-12 14:24:14 -0700358 // implicitly unlinked when the binder is removed
Steven Morelandb0983182021-04-02 03:14:04 +0000359 if (binder->remoteBinder() != nullptr &&
360 binder->linkToDeath(sp<ServiceManager>::fromExisting(this)) != OK) {
Pawan Wagh37526162022-09-29 21:55:26 +0000361 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Morelandac2d2852022-03-18 18:15:20 +0000362 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE, "linkToDeath failure");
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700363 }
364
Steven Moreland7ee423b2022-09-24 03:52:08 +0000365 auto it = mNameToService.find(name);
366 if (it != mNameToService.end()) {
367 const Service& existing = it->second;
368
369 // We could do better than this because if the other service dies, it
370 // may not have an entry here. However, this case is unlikely. We are
371 // only trying to detect when two different services are accidentally installed.
372
373 if (existing.ctx.uid != ctx.uid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000374 ALOGW("Service '%s' originally registered from UID %u but it is now being registered "
375 "from UID %u. Multiple instances installed?",
376 name.c_str(), existing.ctx.uid, ctx.uid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000377 }
378
379 if (existing.ctx.sid != ctx.sid) {
Pawan Wagh37526162022-09-29 21:55:26 +0000380 ALOGW("Service '%s' originally registered from SID %s but it is now being registered "
381 "from SID %s. Multiple instances installed?",
382 name.c_str(), existing.ctx.sid.c_str(), ctx.sid.c_str());
Steven Moreland7ee423b2022-09-24 03:52:08 +0000383 }
384
Pawan Wagh37526162022-09-29 21:55:26 +0000385 ALOGI("Service '%s' originally registered from PID %d but it is being registered again "
386 "from PID %d. Bad state? Late death notification? Multiple instances installed?",
387 name.c_str(), existing.ctx.debugPid, ctx.debugPid);
Steven Moreland7ee423b2022-09-24 03:52:08 +0000388 }
389
Devin Moore05ffe522020-08-06 13:58:29 -0700390 // Overwrite the old service if it exists
Steven Moreland7ee423b2022-09-24 03:52:08 +0000391 mNameToService[name] = Service{
392 .binder = binder,
393 .allowIsolated = allowIsolated,
394 .dumpPriority = dumpPriority,
395 .ctx = ctx,
Devin Moore05ffe522020-08-06 13:58:29 -0700396 };
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700397
Steven Moreland7ee423b2022-09-24 03:52:08 +0000398 if (auto it = mNameToRegistrationCallback.find(name); it != mNameToRegistrationCallback.end()) {
Steven Morelandb8361902023-02-01 23:18:04 +0000399 // See also getService - handles case where client never gets the service,
400 // we want the service to quit.
401 mNameToService[name].guaranteeClient = true;
402 CHECK(handleServiceClientCallback(2 /* sm + transaction */, name, false));
403 mNameToService[name].guaranteeClient = true;
404
Steven Moreland27cfab02019-08-12 14:34:16 -0700405 for (const sp<IServiceCallback>& cb : it->second) {
406 // permission checked in registerForNotifications
407 cb->onRegistration(name, binder);
408 }
409 }
410
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700411 return Status::ok();
412}
413
414Status ServiceManager::listServices(int32_t dumpPriority, std::vector<std::string>* outList) {
Steven Morelanda9fe4742019-07-18 14:45:20 -0700415 if (!mAccess->canList(mAccess->getCallingContext())) {
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700416 return Status::fromExceptionCode(Status::EX_SECURITY);
417 }
418
419 size_t toReserve = 0;
420 for (auto const& [name, service] : mNameToService) {
421 (void) name;
422
423 if (service.dumpPriority & dumpPriority) ++toReserve;
424 }
425
426 CHECK(outList->empty());
427
428 outList->reserve(toReserve);
429 for (auto const& [name, service] : mNameToService) {
430 (void) service;
431
432 if (service.dumpPriority & dumpPriority) {
433 outList->push_back(name);
434 }
435 }
436
437 return Status::ok();
438}
439
Steven Moreland27cfab02019-08-12 14:34:16 -0700440Status ServiceManager::registerForNotifications(
441 const std::string& name, const sp<IServiceCallback>& callback) {
442 auto ctx = mAccess->getCallingContext();
443
444 if (!mAccess->canFind(ctx, name)) {
445 return Status::fromExceptionCode(Status::EX_SECURITY);
446 }
447
448 if (!isValidServiceName(name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000449 ALOGE("Invalid service name: %s", name.c_str());
Steven Moreland27cfab02019-08-12 14:34:16 -0700450 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
451 }
452
453 if (callback == nullptr) {
454 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
455 }
456
Steven Morelandb0983182021-04-02 03:14:04 +0000457 if (OK !=
458 IInterface::asBinder(callback)->linkToDeath(
459 sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000460 ALOGE("Could not linkToDeath when adding %s", name.c_str());
Steven Moreland27cfab02019-08-12 14:34:16 -0700461 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
462 }
463
Jon Spivackf288b1d2019-12-19 17:15:51 -0800464 mNameToRegistrationCallback[name].push_back(callback);
Steven Moreland27cfab02019-08-12 14:34:16 -0700465
466 if (auto it = mNameToService.find(name); it != mNameToService.end()) {
467 const sp<IBinder>& binder = it->second.binder;
468
469 // never null if an entry exists
470 CHECK(binder != nullptr) << name;
471 callback->onRegistration(name, binder);
472 }
473
474 return Status::ok();
475}
476Status ServiceManager::unregisterForNotifications(
477 const std::string& name, const sp<IServiceCallback>& callback) {
478 auto ctx = mAccess->getCallingContext();
479
480 if (!mAccess->canFind(ctx, name)) {
481 return Status::fromExceptionCode(Status::EX_SECURITY);
482 }
483
484 bool found = false;
485
Jon Spivackf288b1d2019-12-19 17:15:51 -0800486 auto it = mNameToRegistrationCallback.find(name);
487 if (it != mNameToRegistrationCallback.end()) {
488 removeRegistrationCallback(IInterface::asBinder(callback), &it, &found);
Steven Moreland27cfab02019-08-12 14:34:16 -0700489 }
490
491 if (!found) {
Pawan Wagh37526162022-09-29 21:55:26 +0000492 ALOGE("Trying to unregister callback, but none exists %s", name.c_str());
Steven Moreland27cfab02019-08-12 14:34:16 -0700493 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
494 }
495
496 return Status::ok();
497}
498
Steven Morelandb82b8f82019-10-28 10:52:34 -0700499Status ServiceManager::isDeclared(const std::string& name, bool* outReturn) {
500 auto ctx = mAccess->getCallingContext();
501
502 if (!mAccess->canFind(ctx, name)) {
503 return Status::fromExceptionCode(Status::EX_SECURITY);
504 }
505
506 *outReturn = false;
507
508#ifndef VENDORSERVICEMANAGER
509 *outReturn = isVintfDeclared(name);
510#endif
511 return Status::ok();
512}
513
Steven Moreland2e293aa2020-09-23 00:25:16 +0000514binder::Status ServiceManager::getDeclaredInstances(const std::string& interface, std::vector<std::string>* outReturn) {
515 auto ctx = mAccess->getCallingContext();
516
517 std::vector<std::string> allInstances;
518#ifndef VENDORSERVICEMANAGER
519 allInstances = getVintfInstances(interface);
520#endif
521
522 outReturn->clear();
523
524 for (const std::string& instance : allInstances) {
Steven Moreland2e293aa2020-09-23 00:25:16 +0000525 if (mAccess->canFind(ctx, interface + "/" + instance)) {
526 outReturn->push_back(instance);
527 }
528 }
529
530 if (outReturn->size() == 0 && allInstances.size() != 0) {
531 return Status::fromExceptionCode(Status::EX_SECURITY);
532 }
533
534 return Status::ok();
535}
536
Steven Morelandedd4e072021-04-21 00:27:29 +0000537Status ServiceManager::updatableViaApex(const std::string& name,
538 std::optional<std::string>* outReturn) {
539 auto ctx = mAccess->getCallingContext();
540
541 if (!mAccess->canFind(ctx, name)) {
542 return Status::fromExceptionCode(Status::EX_SECURITY);
543 }
544
545 *outReturn = std::nullopt;
546
547#ifndef VENDORSERVICEMANAGER
548 *outReturn = getVintfUpdatableApex(name);
549#endif
550 return Status::ok();
551}
552
Jooyung Han76944fe2022-10-25 17:02:45 +0900553Status ServiceManager::getUpdatableNames([[maybe_unused]] const std::string& apexName,
554 std::vector<std::string>* outReturn) {
555 auto ctx = mAccess->getCallingContext();
556
557 std::vector<std::string> apexUpdatableInstances;
558#ifndef VENDORSERVICEMANAGER
559 apexUpdatableInstances = getVintfUpdatableInstances(apexName);
560#endif
561
562 outReturn->clear();
563
564 for (const std::string& instance : apexUpdatableInstances) {
565 if (mAccess->canFind(ctx, instance)) {
566 outReturn->push_back(instance);
567 }
568 }
569
570 if (outReturn->size() == 0 && apexUpdatableInstances.size() != 0) {
571 return Status::fromExceptionCode(Status::EX_SECURITY, "SELinux denial");
572 }
573
574 return Status::ok();
575}
576
Devin Moore5e4c2f12021-09-09 22:36:33 +0000577Status ServiceManager::getConnectionInfo(const std::string& name,
578 std::optional<ConnectionInfo>* outReturn) {
579 auto ctx = mAccess->getCallingContext();
580
581 if (!mAccess->canFind(ctx, name)) {
582 return Status::fromExceptionCode(Status::EX_SECURITY);
583 }
584
585 *outReturn = std::nullopt;
586
587#ifndef VENDORSERVICEMANAGER
588 *outReturn = getVintfConnectionInfo(name);
589#endif
590 return Status::ok();
591}
592
Jon Spivackf288b1d2019-12-19 17:15:51 -0800593void ServiceManager::removeRegistrationCallback(const wp<IBinder>& who,
594 ServiceCallbackMap::iterator* it,
Steven Moreland27cfab02019-08-12 14:34:16 -0700595 bool* found) {
596 std::vector<sp<IServiceCallback>>& listeners = (*it)->second;
597
598 for (auto lit = listeners.begin(); lit != listeners.end();) {
599 if (IInterface::asBinder(*lit) == who) {
600 if(found) *found = true;
601 lit = listeners.erase(lit);
602 } else {
603 ++lit;
604 }
605 }
606
607 if (listeners.empty()) {
Jon Spivackf288b1d2019-12-19 17:15:51 -0800608 *it = mNameToRegistrationCallback.erase(*it);
Steven Moreland27cfab02019-08-12 14:34:16 -0700609 } else {
Jon Spivacke223f082019-11-19 16:21:20 -0800610 (*it)++;
Steven Moreland27cfab02019-08-12 14:34:16 -0700611 }
612}
613
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700614void ServiceManager::binderDied(const wp<IBinder>& who) {
615 for (auto it = mNameToService.begin(); it != mNameToService.end();) {
616 if (who == it->second.binder) {
617 it = mNameToService.erase(it);
618 } else {
619 ++it;
620 }
621 }
Steven Moreland27cfab02019-08-12 14:34:16 -0700622
Jon Spivackf288b1d2019-12-19 17:15:51 -0800623 for (auto it = mNameToRegistrationCallback.begin(); it != mNameToRegistrationCallback.end();) {
624 removeRegistrationCallback(who, &it, nullptr /*found*/);
Steven Moreland27cfab02019-08-12 14:34:16 -0700625 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700626
627 for (auto it = mNameToClientCallback.begin(); it != mNameToClientCallback.end();) {
628 removeClientCallback(who, &it);
629 }
Steven Moreland80e1e6d2019-06-21 12:35:59 -0700630}
631
Jon Spivack0d844302019-07-22 18:40:34 -0700632void ServiceManager::tryStartService(const std::string& name) {
Steven Morelandba0f33c2022-11-04 22:24:31 +0000633 ALOGI("Since '%s' could not be found, trying to start it as a lazy AIDL service. (if it's not "
634 "configured to be a lazy service, it may be stuck starting or still starting).",
Jon Spivack0d844302019-07-22 18:40:34 -0700635 name.c_str());
636
637 std::thread([=] {
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000638 if (!base::SetProperty("ctl.interface_start", "aidl/" + name)) {
Pawan Wagh37526162022-09-29 21:55:26 +0000639 ALOGI("Tried to start aidl service %s as a lazy service, but was unable to. Usually "
640 "this happens when a "
641 "service is not installed, but if the service is intended to be used as a "
642 "lazy service, then it may be configured incorrectly.",
643 name.c_str());
Steven Morelandbfe9fba2021-04-27 18:39:57 +0000644 }
Jon Spivack0d844302019-07-22 18:40:34 -0700645 }).detach();
646}
647
Jon Spivack9f503a42019-10-22 16:49:19 -0700648Status ServiceManager::registerClientCallback(const std::string& name, const sp<IBinder>& service,
649 const sp<IClientCallback>& cb) {
650 if (cb == nullptr) {
651 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
652 }
653
654 auto ctx = mAccess->getCallingContext();
655 if (!mAccess->canAdd(ctx, name)) {
656 return Status::fromExceptionCode(Status::EX_SECURITY);
657 }
658
659 auto serviceIt = mNameToService.find(name);
660 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000661 ALOGE("Could not add callback for nonexistent service: %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700662 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
663 }
664
Steven Moreland7ee423b2022-09-24 03:52:08 +0000665 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000666 ALOGW("Only a server can register for client callbacks (for %s)", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700667 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
668 }
669
670 if (serviceIt->second.binder != service) {
Pawan Wagh37526162022-09-29 21:55:26 +0000671 ALOGW("Tried to register client callback for %s but a different service is registered "
672 "under this name.",
673 name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700674 return Status::fromExceptionCode(Status::EX_ILLEGAL_ARGUMENT);
675 }
676
Steven Morelandb0983182021-04-02 03:14:04 +0000677 if (OK !=
678 IInterface::asBinder(cb)->linkToDeath(sp<ServiceManager>::fromExisting(this))) {
Pawan Wagh37526162022-09-29 21:55:26 +0000679 ALOGE("Could not linkToDeath when adding client callback for %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700680 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
681 }
682
683 mNameToClientCallback[name].push_back(cb);
684
685 return Status::ok();
686}
687
688void ServiceManager::removeClientCallback(const wp<IBinder>& who,
689 ClientCallbackMap::iterator* it) {
690 std::vector<sp<IClientCallback>>& listeners = (*it)->second;
691
692 for (auto lit = listeners.begin(); lit != listeners.end();) {
693 if (IInterface::asBinder(*lit) == who) {
694 lit = listeners.erase(lit);
695 } else {
696 ++lit;
697 }
698 }
699
700 if (listeners.empty()) {
701 *it = mNameToClientCallback.erase(*it);
702 } else {
703 (*it)++;
704 }
705}
706
707ssize_t ServiceManager::Service::getNodeStrongRefCount() {
Steven Morelandb0983182021-04-02 03:14:04 +0000708 sp<BpBinder> bpBinder = sp<BpBinder>::fromExisting(binder->remoteBinder());
Jon Spivack9f503a42019-10-22 16:49:19 -0700709 if (bpBinder == nullptr) return -1;
710
Steven Morelande8393882020-12-18 02:27:20 +0000711 return ProcessState::self()->getStrongRefCountForNode(bpBinder);
Jon Spivack9f503a42019-10-22 16:49:19 -0700712}
713
714void ServiceManager::handleClientCallbacks() {
715 for (const auto& [name, service] : mNameToService) {
Steven Morelandb8361902023-02-01 23:18:04 +0000716 handleServiceClientCallback(1 /* sm has one refcount */, name, true);
Jon Spivack9f503a42019-10-22 16:49:19 -0700717 }
718}
719
Steven Morelandb8361902023-02-01 23:18:04 +0000720bool ServiceManager::handleServiceClientCallback(size_t knownClients,
721 const std::string& serviceName,
722 bool isCalledOnInterval) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700723 auto serviceIt = mNameToService.find(serviceName);
724 if (serviceIt == mNameToService.end() || mNameToClientCallback.count(serviceName) < 1) {
Steven Morelandb8361902023-02-01 23:18:04 +0000725 return true; // return we do have clients a.k.a. DON'T DO ANYTHING
Jon Spivack9f503a42019-10-22 16:49:19 -0700726 }
727
728 Service& service = serviceIt->second;
729 ssize_t count = service.getNodeStrongRefCount();
730
Steven Morelandb8361902023-02-01 23:18:04 +0000731 // binder driver doesn't support this feature, consider we have clients
732 if (count == -1) return true;
Jon Spivack9f503a42019-10-22 16:49:19 -0700733
Steven Morelandb8361902023-02-01 23:18:04 +0000734 bool hasKernelReportedClients = static_cast<size_t>(count) > knownClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700735
736 if (service.guaranteeClient) {
Steven Morelandb8361902023-02-01 23:18:04 +0000737 if (!service.hasClients && !hasKernelReportedClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000738 sendClientCallbackNotifications(serviceName, true,
739 "service is guaranteed to be in use");
Jon Spivack9f503a42019-10-22 16:49:19 -0700740 }
741
742 // guarantee is temporary
743 service.guaranteeClient = false;
744 }
745
Steven Morelandb8361902023-02-01 23:18:04 +0000746 // Regardless of this situation, we want to give this notification as soon as possible.
747 // This way, we have a chance of preventing further thrashing.
748 if (hasKernelReportedClients && !service.hasClients) {
749 sendClientCallbackNotifications(serviceName, true, "we now have a record of a client");
750 }
Steven Moreland66417652023-02-01 22:19:41 +0000751
Steven Morelandb8361902023-02-01 23:18:04 +0000752 // But limit rate of shutting down service.
753 if (isCalledOnInterval) {
754 if (!hasKernelReportedClients && service.hasClients) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000755 sendClientCallbackNotifications(serviceName, false,
756 "we now have no record of a client");
Jon Spivackd9533c22020-01-27 22:19:22 +0000757 }
Jon Spivack9f503a42019-10-22 16:49:19 -0700758 }
759
Steven Morelandb8361902023-02-01 23:18:04 +0000760 // May be different than 'hasKernelReportedClients'. We intentionally delay
761 // information about clients going away to reduce thrashing.
762 return service.hasClients;
Jon Spivack9f503a42019-10-22 16:49:19 -0700763}
764
Steven Moreland3e083b22023-01-26 00:46:30 +0000765void ServiceManager::sendClientCallbackNotifications(const std::string& serviceName,
766 bool hasClients, const char* context) {
Jon Spivack9f503a42019-10-22 16:49:19 -0700767 auto serviceIt = mNameToService.find(serviceName);
768 if (serviceIt == mNameToService.end()) {
Steven Moreland3e083b22023-01-26 00:46:30 +0000769 ALOGW("sendClientCallbackNotifications could not find service %s when %s",
770 serviceName.c_str(), context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700771 return;
772 }
773 Service& service = serviceIt->second;
774
Steven Morelandb8361902023-02-01 23:18:04 +0000775 CHECK_NE(hasClients, service.hasClients) << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700776
Steven Morelandb8361902023-02-01 23:18:04 +0000777 ALOGI("Notifying %s they %s (previously: %s) have clients when %s", serviceName.c_str(),
778 hasClients ? "do" : "don't", service.hasClients ? "do" : "don't", context);
Jon Spivack9f503a42019-10-22 16:49:19 -0700779
780 auto ccIt = mNameToClientCallback.find(serviceName);
781 CHECK(ccIt != mNameToClientCallback.end())
Steven Moreland3e083b22023-01-26 00:46:30 +0000782 << "sendClientCallbackNotifications could not find callbacks for service when "
783 << context;
Jon Spivack9f503a42019-10-22 16:49:19 -0700784
785 for (const auto& callback : ccIt->second) {
786 callback->onClients(service.binder, hasClients);
787 }
788
789 service.hasClients = hasClients;
790}
791
792Status ServiceManager::tryUnregisterService(const std::string& name, const sp<IBinder>& binder) {
793 if (binder == nullptr) {
794 return Status::fromExceptionCode(Status::EX_NULL_POINTER);
795 }
796
797 auto ctx = mAccess->getCallingContext();
798 if (!mAccess->canAdd(ctx, name)) {
799 return Status::fromExceptionCode(Status::EX_SECURITY);
800 }
801
802 auto serviceIt = mNameToService.find(name);
803 if (serviceIt == mNameToService.end()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000804 ALOGW("Tried to unregister %s, but that service wasn't registered to begin with.",
805 name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700806 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
807 }
808
Steven Moreland7ee423b2022-09-24 03:52:08 +0000809 if (serviceIt->second.ctx.debugPid != IPCThreadState::self()->getCallingPid()) {
Pawan Wagh37526162022-09-29 21:55:26 +0000810 ALOGW("Only a server can unregister itself (for %s)", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700811 return Status::fromExceptionCode(Status::EX_UNSUPPORTED_OPERATION);
812 }
813
814 sp<IBinder> storedBinder = serviceIt->second.binder;
815
816 if (binder != storedBinder) {
Pawan Wagh37526162022-09-29 21:55:26 +0000817 ALOGW("Tried to unregister %s, but a different service is registered under this name.",
818 name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700819 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
820 }
821
Steven Morelandb8361902023-02-01 23:18:04 +0000822 // important because we don't have timer-based guarantees, we don't want to clear
823 // this
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700824 if (serviceIt->second.guaranteeClient) {
Pawan Wagh37526162022-09-29 21:55:26 +0000825 ALOGI("Tried to unregister %s, but there is about to be a client.", name.c_str());
Jon Spivack0f18f2c2020-03-13 20:45:18 -0700826 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
827 }
828
Jon Spivack9f503a42019-10-22 16:49:19 -0700829 // - kernel driver will hold onto one refcount (during this transaction)
830 // - servicemanager has a refcount (guaranteed by this transaction)
Steven Morelandb8361902023-02-01 23:18:04 +0000831 constexpr size_t kKnownClients = 2;
832
833 if (handleServiceClientCallback(kKnownClients, name, false)) {
834 ALOGI("Tried to unregister %s, but there are clients.", name.c_str());
835
836 // Since we had a failed registration attempt, and the HIDL implementation of
837 // delaying service shutdown for multiple periods wasn't ported here... this may
838 // help reduce thrashing, but we should be able to remove it.
Jon Spivack620d2dc2020-03-06 13:58:01 -0800839 serviceIt->second.guaranteeClient = true;
Steven Morelandb8361902023-02-01 23:18:04 +0000840
Jon Spivack9f503a42019-10-22 16:49:19 -0700841 return Status::fromExceptionCode(Status::EX_ILLEGAL_STATE);
842 }
843
Steven Morelandb8361902023-02-01 23:18:04 +0000844 ALOGI("Unregistering %s", name.c_str());
Jon Spivack9f503a42019-10-22 16:49:19 -0700845 mNameToService.erase(name);
846
847 return Status::ok();
848}
849
Steven Moreland3ea43272021-01-28 22:49:28 +0000850Status ServiceManager::getServiceDebugInfo(std::vector<ServiceDebugInfo>* outReturn) {
851 if (!mAccess->canList(mAccess->getCallingContext())) {
852 return Status::fromExceptionCode(Status::EX_SECURITY);
853 }
854
855 outReturn->reserve(mNameToService.size());
856 for (auto const& [name, service] : mNameToService) {
857 ServiceDebugInfo info;
858 info.name = name;
Steven Moreland7ee423b2022-09-24 03:52:08 +0000859 info.debugPid = service.ctx.debugPid;
Steven Moreland3ea43272021-01-28 22:49:28 +0000860
861 outReturn->push_back(std::move(info));
862 }
863
864 return Status::ok();
865}
866
Pawan Wagh243888e2022-09-20 19:37:35 +0000867void ServiceManager::clear() {
868 mNameToService.clear();
869 mNameToRegistrationCallback.clear();
870 mNameToClientCallback.clear();
871}
872
Steven Moreland8d0c9a72020-04-30 16:51:56 -0700873} // namespace android