1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "system_ability_manager.h"
17
18 #include <cinttypes>
19 #include <unistd.h>
20
21 #include "ability_death_recipient.h"
22 #include "datetime_ex.h"
23 #include "directory_ex.h"
24 #include "errors.h"
25 #include "if_local_ability_manager.h"
26 #include "ipc_skeleton.h"
27 #include "local_ability_manager_proxy.h"
28 #include "parse_util.h"
29 #include "sam_log.h"
30 #include "service_control.h"
31 #include "string_ex.h"
32 #include "system_ability_definition.h"
33 #include "tools.h"
34
35 using namespace std;
36
37 namespace OHOS {
38 namespace {
39 const string PREFIX = "/system/profile/";
40 constexpr int32_t MAX_NAME_SIZE = 200;
41 constexpr int32_t SPLIT_NAME_VECTOR_SIZE = 2;
42
43 constexpr int32_t UID_ROOT = 0;
44 constexpr int32_t UID_SYSTEM = 1000;
45 constexpr int32_t MAX_SUBSCRIBE_COUNT = 256;
46 constexpr int64_t CHECK_LOADED_DELAY_TIME = 60 * 1000; // ms
47 }
48
49 std::mutex SystemAbilityManager::instanceLock;
50 sptr<SystemAbilityManager> SystemAbilityManager::instance;
51
SystemAbilityManager()52 SystemAbilityManager::SystemAbilityManager()
53 {
54 dBinderService_ = DBinderService::GetInstance();
55 }
56
~SystemAbilityManager()57 SystemAbilityManager::~SystemAbilityManager()
58 {
59 }
60
Init()61 void SystemAbilityManager::Init()
62 {
63 abilityDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityDeathRecipient());
64 systemProcessDeath_ = sptr<IRemoteObject::DeathRecipient>(new SystemProcessDeathRecipient());
65 abilityStatusDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityStatusDeathRecipient());
66 abilityCallbackDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityCallbackDeathRecipient());
67 rpcCallbackImp_ = make_shared<RpcCallbackImp>();
68 if (workHandler_ == nullptr) {
69 auto runner = AppExecFwk::EventRunner::Create("workHandler");
70 workHandler_ = make_shared<AppExecFwk::EventHandler>(runner);
71 }
72 InitSaProfile();
73 }
74
GetDBinder() const75 const sptr<DBinderService> SystemAbilityManager::GetDBinder() const
76 {
77 return dBinderService_;
78 }
79
GetInstance()80 sptr<SystemAbilityManager> SystemAbilityManager::GetInstance()
81 {
82 std::lock_guard<std::mutex> autoLock(instanceLock);
83 if (instance == nullptr) {
84 instance = new SystemAbilityManager;
85 }
86 return instance;
87 }
88
InitSaProfile()89 void SystemAbilityManager::InitSaProfile()
90 {
91 if (workHandler_ == nullptr) {
92 HILOGE("InitSaProfile parseHandler_ not init!");
93 return;
94 }
95
96 auto callback = [this] () {
97 int64_t begin = GetTickCount();
98 std::vector<std::string> fileNames;
99 GetDirFiles(PREFIX, fileNames);
100 auto parser = std::make_shared<ParseUtil>();
101 for (const auto& file : fileNames) {
102 if (file.empty() || file.find(".xml") == std::string::npos
103 || file.find("_trust.xml") != std::string::npos) {
104 continue;
105 }
106 parser->ParseSaProfiles(file);
107 }
108 auto saInfos = parser->GetAllSaProfiles();
109 lock_guard<mutex> autoLock(saProfileMapLock_);
110 for (const auto& saInfo : saInfos) {
111 saProfileMap_[saInfo.saId] = saInfo;
112 }
113 HILOGI("[PerformanceTest] InitSaProfile spend %{public}" PRId64 " ms", GetTickCount() - begin);
114 };
115 bool ret = workHandler_->PostTask(callback);
116 if (!ret) {
117 HILOGW("SystemAbilityManager::InitSaProfile PostTask fail");
118 }
119 }
120
GetSaProfile(int32_t saId,SaProfile & saProfile)121 bool SystemAbilityManager::GetSaProfile(int32_t saId, SaProfile& saProfile)
122 {
123 lock_guard<mutex> autoLock(saProfileMapLock_);
124 auto iter = saProfileMap_.find(saId);
125 if (iter == saProfileMap_.end()) {
126 return false;
127 } else {
128 saProfile = iter->second;
129 }
130 return true;
131 }
132
GetSystemAbility(int32_t systemAbilityId)133 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId)
134 {
135 return CheckSystemAbility(systemAbilityId);
136 }
137
GetSystemAbility(int32_t systemAbilityId,const std::string & deviceId)138 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
139 {
140 return CheckSystemAbility(systemAbilityId, deviceId);
141 }
142
GetSystemAbilityFromRemote(int32_t systemAbilityId)143 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbilityFromRemote(int32_t systemAbilityId)
144 {
145 HILOGD("%{public}s called, systemAbilityId = %{public}d", __func__, systemAbilityId);
146 if (!CheckInputSysAbilityId(systemAbilityId)) {
147 HILOGW("GetSystemAbilityFromRemote invalid!");
148 return nullptr;
149 }
150
151 shared_lock<shared_mutex> readLock(abilityMapLock_);
152 auto iter = abilityMap_.find(systemAbilityId);
153 if (iter == abilityMap_.end()) {
154 HILOGI("GetSystemAbilityFromRemote not found service : %{public}d.", systemAbilityId);
155 return nullptr;
156 }
157 if (!(iter->second.isDistributed)) {
158 HILOGW("GetSystemAbilityFromRemote service : %{public}d not distributed", systemAbilityId);
159 return nullptr;
160 }
161 HILOGI("GetSystemAbilityFromRemote found service : %{public}d.", systemAbilityId);
162 return iter->second.remoteObj;
163 }
164
CheckSystemAbility(int32_t systemAbilityId)165 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId)
166 {
167 HILOGD("%{public}s called, systemAbilityId = %{public}d", __func__, systemAbilityId);
168 if (!CheckInputSysAbilityId(systemAbilityId)) {
169 HILOGW("CheckSystemAbility CheckSystemAbility invalid!");
170 return nullptr;
171 }
172
173 shared_lock<shared_mutex> readLock(abilityMapLock_);
174 auto iter = abilityMap_.find(systemAbilityId);
175 if (iter != abilityMap_.end()) {
176 HILOGI("found service : %{public}d.", systemAbilityId);
177 return iter->second.remoteObj;
178 }
179 HILOGI("NOT found service : %{public}d", systemAbilityId);
180 return nullptr;
181 }
182
CheckDistributedPermission()183 bool SystemAbilityManager::CheckDistributedPermission()
184 {
185 auto callingUid = IPCSkeleton::GetCallingUid();
186 if (callingUid != UID_ROOT && callingUid != UID_SYSTEM) {
187 return false;
188 }
189 return true;
190 }
191
CheckSystemAbility(int32_t systemAbilityId,const std::string & deviceId)192 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId,
193 const std::string& deviceId)
194 {
195 sptr<DBinderServiceStub> remoteBinder = nullptr;
196 if (dBinderService_ != nullptr) {
197 string strName = to_string(systemAbilityId);
198 remoteBinder = dBinderService_->MakeRemoteBinder(Str8ToStr16(strName), deviceId, systemAbilityId, 0);
199 HILOGI("CheckSystemAbility, MakeRemoteBinder, systemAbilityId is %{public}d, deviceId is %s",
200 systemAbilityId, deviceId.c_str());
201 if (remoteBinder == nullptr) {
202 HILOGE("MakeRemoteBinder error, remoteBinder is null");
203 }
204 }
205 return remoteBinder;
206 }
207
FindSystemAbilityNotify(int32_t systemAbilityId,int32_t code)208 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, int32_t code)
209 {
210 return FindSystemAbilityNotify(systemAbilityId, "", code);
211 }
212
NotifySystemAbilityChanged(int32_t systemAbilityId,const std::string & deviceId,int32_t code,const sptr<ISystemAbilityStatusChange> & listener)213 void SystemAbilityManager::NotifySystemAbilityChanged(int32_t systemAbilityId, const std::string& deviceId,
214 int32_t code, const sptr<ISystemAbilityStatusChange>& listener)
215 {
216 if (listener == nullptr) {
217 HILOGE("%s listener null pointer!", __func__);
218 return;
219 }
220
221 switch (code) {
222 case ADD_SYSTEM_ABILITY_TRANSACTION: {
223 listener->OnAddSystemAbility(systemAbilityId, deviceId);
224 break;
225 }
226 case REMOVE_SYSTEM_ABILITY_TRANSACTION: {
227 listener->OnRemoveSystemAbility(systemAbilityId, deviceId);
228 break;
229 }
230 default:
231 break;
232 }
233 }
234
FindSystemAbilityNotify(int32_t systemAbilityId,const std::string & deviceId,int32_t code)235 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, const std::string& deviceId,
236 int32_t code)
237 {
238 HILOGI("%s called:systemAbilityId = %{public}d, code = %{public}d", __func__, systemAbilityId, code);
239 lock_guard<recursive_mutex> autoLock(listenerMapLock_);
240 auto iter = listenerMap_.find(systemAbilityId);
241 if (iter != listenerMap_.end()) {
242 auto& listeners = iter->second;
243 for (const auto& item : listeners) {
244 NotifySystemAbilityChanged(systemAbilityId, deviceId, code, item.first);
245 }
246 }
247
248 return ERR_OK;
249 }
250
IsNameInValid(const std::u16string & name)251 bool SystemAbilityManager::IsNameInValid(const std::u16string& name)
252 {
253 HILOGI("%{public}s called:name = %{public}s", __func__, Str16ToStr8(name).c_str());
254 bool ret = false;
255 if (name.empty() || name.size() > MAX_NAME_SIZE || DeleteBlank(name).empty()) {
256 ret = true;
257 }
258
259 return ret;
260 }
261
StartOnDemandAbility(const std::u16string & procName,int32_t systemAbilityId)262 void SystemAbilityManager::StartOnDemandAbility(const std::u16string& procName, int32_t systemAbilityId)
263 {
264 lock_guard<recursive_mutex> autoLock(onDemandLock_);
265 auto iter = startingAbilityMap_.find(systemAbilityId);
266 if (iter == startingAbilityMap_.end()) {
267 return;
268 }
269 auto& abilityItem = iter->second;
270 StartOnDemandAbilityInner(procName, systemAbilityId, abilityItem);
271 }
272
StartOnDemandAbilityInner(const std::u16string & procName,int32_t systemAbilityId,AbilityItem & abilityItem)273 void SystemAbilityManager::StartOnDemandAbilityInner(const std::u16string& procName, int32_t systemAbilityId,
274 AbilityItem& abilityItem)
275 {
276 if (abilityItem.state != AbilityState::INIT) {
277 return;
278 }
279 sptr<ILocalAbilityManager> procObject =
280 iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
281 if (procObject == nullptr) {
282 HILOGI("get process:%{public}s fail", Str16ToStr8(procName).c_str());
283 return;
284 }
285 procObject->StartAbility(systemAbilityId);
286 abilityItem.state = AbilityState::STARTING;
287 }
288
AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,const std::u16string & procName)289 int32_t SystemAbilityManager::AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,
290 const std::u16string& procName)
291 {
292 HILOGI("%{public}s called", __func__);
293 if (!CheckInputSysAbilityId(systemAbilityId) || IsNameInValid(procName)) {
294 HILOGW("AddOnDemandSystemAbilityInfo systemAbilityId or procName invalid.");
295 return ERR_INVALID_VALUE;
296 }
297
298 lock_guard<recursive_mutex> autoLock(onDemandLock_);
299 auto onDemandSaSize = onDemandAbilityMap_.size();
300 if (onDemandSaSize >= MAX_SERVICES) {
301 HILOGE("map size error, (Has been greater than %{public}zu)",
302 onDemandAbilityMap_.size());
303 return ERR_INVALID_VALUE;
304 }
305
306 if (systemProcessMap_.count(procName) == 0) {
307 HILOGW("AddOnDemandSystemAbilityInfo procName:%{public}s not exist.", Str16ToStr8(procName).c_str());
308 return ERR_INVALID_VALUE;
309 }
310 onDemandAbilityMap_[systemAbilityId] = procName;
311 HILOGI("insert onDemand systemAbilityId:%{public}d. size : %{public}zu", systemAbilityId,
312 onDemandAbilityMap_.size());
313 if (startingAbilityMap_.count(systemAbilityId) != 0) {
314 if (workHandler_ != nullptr) {
315 auto pendingTask = [procName, systemAbilityId, this] () {
316 StartOnDemandAbility(procName, systemAbilityId);
317 };
318 bool ret = workHandler_->PostTask(pendingTask);
319 if (!ret) {
320 HILOGW("AddOnDemandSystemAbilityInfo PostTask failed!");
321 }
322 }
323 }
324 return ERR_OK;
325 }
326
StartOnDemandAbility(int32_t systemAbilityId)327 int32_t SystemAbilityManager::StartOnDemandAbility(int32_t systemAbilityId)
328 {
329 HILOGI("%{public}s called, systemAbilityId is %{public}d", __func__, systemAbilityId);
330 lock_guard<recursive_mutex> onDemandAbilityLock(onDemandLock_);
331 auto iter = onDemandAbilityMap_.find(systemAbilityId);
332 if (iter == onDemandAbilityMap_.end()) {
333 return ERR_INVALID_VALUE;
334 }
335 HILOGI("found onDemandAbility: %{public}d.", systemAbilityId);
336 AbilityItem& abilityItem = startingAbilityMap_[systemAbilityId];
337 StartOnDemandAbilityInner(iter->second, systemAbilityId, abilityItem);
338 return ERR_OK;
339 }
340
CheckSystemAbility(int32_t systemAbilityId,bool & isExist)341 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId, bool& isExist)
342 {
343 if (!CheckInputSysAbilityId(systemAbilityId)) {
344 return nullptr;
345 }
346 sptr<IRemoteObject> abilityProxy = CheckSystemAbility(systemAbilityId);
347 if (abilityProxy == nullptr) {
348 lock_guard<recursive_mutex> autoLock(onDemandLock_);
349 auto iter = startingAbilityMap_.find(systemAbilityId);
350 if (iter != startingAbilityMap_.end() && iter->second.state == AbilityState::STARTING) {
351 isExist = true;
352 return nullptr;
353 }
354
355 int32_t ret = StartOnDemandAbility(systemAbilityId);
356 if (ret == ERR_OK) {
357 isExist = true;
358 return nullptr;
359 }
360
361 HILOGI("ability %{public}d is not found", systemAbilityId);
362 isExist = false;
363 return nullptr;
364 }
365
366 isExist = true;
367 return abilityProxy;
368 }
369
RemoveSystemAbility(int32_t systemAbilityId)370 int32_t SystemAbilityManager::RemoveSystemAbility(int32_t systemAbilityId)
371 {
372 HILOGI("%s called (name)", __func__);
373 if (!CheckInputSysAbilityId(systemAbilityId)) {
374 HILOGW("RemoveSystemAbility systemAbilityId:%{public}d", systemAbilityId);
375 return ERR_INVALID_VALUE;
376 }
377 {
378 unique_lock<shared_mutex> writeLock(abilityMapLock_);
379 auto itSystemAbility = abilityMap_.find(systemAbilityId);
380 if (itSystemAbility == abilityMap_.end()) {
381 HILOGI("SystemAbilityManager::RemoveSystemAbility not found!");
382 return ERR_INVALID_VALUE;
383 }
384 sptr<IRemoteObject> ability = itSystemAbility->second.remoteObj;
385 if (ability != nullptr && abilityDeath_ != nullptr) {
386 ability->RemoveDeathRecipient(abilityDeath_);
387 }
388 (void)abilityMap_.erase(itSystemAbility);
389 HILOGI("%s called, systemAbilityId : %{public}d, size : %{public}zu", __func__, systemAbilityId,
390 abilityMap_.size());
391 }
392 SendSystemAbilityRemovedMsg(systemAbilityId);
393 return ERR_OK;
394 }
395
RemoveSystemAbility(const sptr<IRemoteObject> & ability)396 int32_t SystemAbilityManager::RemoveSystemAbility(const sptr<IRemoteObject>& ability)
397 {
398 HILOGI("%s called, (ability)", __func__);
399 if (ability == nullptr) {
400 HILOGW("ability is nullptr ");
401 return ERR_INVALID_VALUE;
402 }
403
404 int32_t saId = 0;
405 {
406 unique_lock<shared_mutex> writeLock(abilityMapLock_);
407 for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); ++iter) {
408 if (iter->second.remoteObj == ability) {
409 saId = iter->first;
410 (void)abilityMap_.erase(iter);
411 if (abilityDeath_ != nullptr) {
412 ability->RemoveDeathRecipient(abilityDeath_);
413 }
414 HILOGI("%s called, systemAbilityId:%{public}d removed, size : %{public}zu", __func__, saId,
415 abilityMap_.size());
416 break;
417 }
418 }
419 }
420
421 if (saId != 0) {
422 SendSystemAbilityRemovedMsg(saId);
423 }
424 return ERR_OK;
425 }
426
ListSystemAbilities(uint32_t dumpFlags)427 vector<u16string> SystemAbilityManager::ListSystemAbilities(uint32_t dumpFlags)
428 {
429 vector<u16string> list;
430 shared_lock<shared_mutex> readLock(abilityMapLock_);
431 for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); iter++) {
432 list.emplace_back(Str8ToStr16(to_string(iter->first)));
433 }
434 return list;
435 }
436
SubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)437 int32_t SystemAbilityManager::SubscribeSystemAbility(int32_t systemAbilityId,
438 const sptr<ISystemAbilityStatusChange>& listener)
439 {
440 HILOGI("%s called", __func__);
441 if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
442 HILOGW("SubscribeSystemAbility systemAbilityId or listener invalid!");
443 return ERR_INVALID_VALUE;
444 }
445
446 auto callingPid = IPCSkeleton::GetCallingPid();
447 {
448 lock_guard<recursive_mutex> autoLock(listenerMapLock_);
449 auto& listeners = listenerMap_[systemAbilityId];
450 for (const auto& itemListener : listeners) {
451 if (listener->AsObject() == itemListener.first->AsObject()) {
452 HILOGI("already exist listener object systemAbilityId = %{public}d", systemAbilityId);
453 return ERR_OK;
454 }
455 }
456 auto& count = subscribeCountMap_[callingPid];
457 if (count >= MAX_SUBSCRIBE_COUNT) {
458 HILOGE("SubscribeSystemAbility pid:%{public}d overflow max subscribe count!", callingPid);
459 return ERR_PERMISSION_DENIED;
460 }
461 ++count;
462 if (abilityStatusDeath_ != nullptr) {
463 bool ret = listener->AsObject()->AddDeathRecipient(abilityStatusDeath_);
464 listeners.emplace_back(listener, callingPid);
465 HILOGI("SubscribeSystemAbility systemAbilityId = %{public}d AddDeathRecipient %{public}s",
466 systemAbilityId, ret ? "succeed" : "failed");
467 }
468 HILOGI("SubscribeSystemAbility systemAbilityId = %{public}d, size = %{public}zu", systemAbilityId,
469 listeners.size());
470 }
471 sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
472 if (targetObject != nullptr) {
473 NotifySystemAbilityChanged(systemAbilityId, "", ADD_SYSTEM_ABILITY_TRANSACTION, listener);
474 }
475 return ERR_OK;
476 }
477
UnSubscribeSystemAbilityLocked(std::list<std::pair<sptr<ISystemAbilityStatusChange>,int32_t>> & listenerList,const sptr<IRemoteObject> & listener)478 void SystemAbilityManager::UnSubscribeSystemAbilityLocked(
479 std::list<std::pair<sptr<ISystemAbilityStatusChange>, int32_t>>& listenerList,
480 const sptr<IRemoteObject>& listener)
481 {
482 auto iter = listenerList.begin();
483 while (iter != listenerList.end()) {
484 auto& item = *iter;
485 if (item.first->AsObject() != listener) {
486 ++iter;
487 continue;
488 }
489
490 if (abilityStatusDeath_ != nullptr) {
491 listener->RemoveDeathRecipient(abilityStatusDeath_);
492 }
493 auto iterPair = subscribeCountMap_.find(item.second);
494 if (iterPair != subscribeCountMap_.end()) {
495 --iterPair->second;
496 if (iterPair->second == 0) {
497 subscribeCountMap_.erase(iterPair);
498 }
499 }
500 iter = listenerList.erase(iter);
501 break;
502 }
503 }
504
UnSubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)505 int32_t SystemAbilityManager::UnSubscribeSystemAbility(int32_t systemAbilityId,
506 const sptr<ISystemAbilityStatusChange>& listener)
507 {
508 HILOGI("%s called", __func__);
509 if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
510 HILOGW("UnSubscribeSystemAbility systemAbilityId or listener invalid!");
511 return ERR_INVALID_VALUE;
512 }
513
514 lock_guard<recursive_mutex> autoLock(listenerMapLock_);
515 auto& listeners = listenerMap_[systemAbilityId];
516 UnSubscribeSystemAbilityLocked(listeners, listener->AsObject());
517 HILOGI("UnSubscribeSystemAbility systemAbilityId = %{public}d, size = %{public}zu", systemAbilityId,
518 listeners.size());
519 return ERR_OK;
520 }
521
UnSubscribeSystemAbility(const sptr<IRemoteObject> & remoteObject)522 void SystemAbilityManager::UnSubscribeSystemAbility(const sptr<IRemoteObject>& remoteObject)
523 {
524 lock_guard<recursive_mutex> autoLock(listenerMapLock_);
525 for (auto& item : listenerMap_) {
526 auto& listeners = item.second;
527 UnSubscribeSystemAbilityLocked(listeners, remoteObject);
528 }
529 HILOGI("UnSubscribeSystemAbility remote object dead!");
530 }
531
SetDeviceName(const u16string & name)532 void SystemAbilityManager::SetDeviceName(const u16string &name)
533 {
534 deviceName_ = name;
535 }
536
GetDeviceName() const537 const u16string& SystemAbilityManager::GetDeviceName() const
538 {
539 return deviceName_;
540 }
541
NotifyRemoteSaDied(const std::u16string & name)542 void SystemAbilityManager::NotifyRemoteSaDied(const std::u16string& name)
543 {
544 std::u16string saName;
545 std::string deviceId;
546 ParseRemoteSaName(name, deviceId, saName);
547 if (dBinderService_ != nullptr) {
548 std::string nodeId = TransformDeviceId(deviceId, NODE_ID, false);
549 dBinderService_->NoticeServiceDie(saName, nodeId);
550 HILOGD("NotifyRemoteSaDied, serviceName is %s, deviceId is %s",
551 Str16ToStr8(saName).c_str(), nodeId.c_str());
552 }
553 }
554
NotifyRemoteDeviceOffline(const std::string & deviceId)555 void SystemAbilityManager::NotifyRemoteDeviceOffline(const std::string& deviceId)
556 {
557 if (dBinderService_ != nullptr) {
558 dBinderService_->NoticeDeviceDie(deviceId);
559 HILOGD("NotifyRemoteDeviceOffline, deviceId is %s", deviceId.c_str());
560 }
561 }
562
ParseRemoteSaName(const std::u16string & name,std::string & deviceId,std::u16string & saName)563 void SystemAbilityManager::ParseRemoteSaName(const std::u16string& name, std::string& deviceId, std::u16string& saName)
564 {
565 vector<string> strVector;
566 SplitStr(Str16ToStr8(name), "_", strVector);
567 if (strVector.size() == SPLIT_NAME_VECTOR_SIZE) {
568 deviceId = strVector[0];
569 saName = Str8ToStr16(strVector[1]);
570 }
571 }
572
AddSystemAbility(int32_t systemAbilityId,const sptr<IRemoteObject> & ability,const SAExtraProp & extraProp)573 int32_t SystemAbilityManager::AddSystemAbility(int32_t systemAbilityId, const sptr<IRemoteObject>& ability,
574 const SAExtraProp& extraProp)
575 {
576 HILOGI("%s called", __func__);
577 if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {
578 HILOGE("AddSystemAbilityExtra input params is invalid.");
579 return ERR_INVALID_VALUE;
580 }
581 {
582 unique_lock<shared_mutex> writeLock(abilityMapLock_);
583 auto saSize = abilityMap_.size();
584 if (saSize >= MAX_SERVICES) {
585 HILOGE("map size error, (Has been greater than %zu)", saSize);
586 return ERR_INVALID_VALUE;
587 }
588 SAInfo saInfo;
589 saInfo.remoteObj = ability;
590 saInfo.isDistributed = extraProp.isDistributed;
591 saInfo.capability = extraProp.capability;
592 saInfo.permission = Str16ToStr8(extraProp.permission);
593 abilityMap_[systemAbilityId] = std::move(saInfo);
594 HILOGI("insert %{public}d. size : %{public}zu", systemAbilityId, abilityMap_.size());
595 }
596 RemoveCheckLoadedMsg(systemAbilityId);
597 if (abilityDeath_ != nullptr) {
598 ability->AddDeathRecipient(abilityDeath_);
599 }
600
601 u16string strName = Str8ToStr16(to_string(systemAbilityId));
602 if (extraProp.isDistributed && dBinderService_ != nullptr) {
603 dBinderService_->RegisterRemoteProxy(strName, systemAbilityId);
604 HILOGD("AddSystemAbility RegisterRemoteProxy, serviceId is %{public}d", systemAbilityId);
605 }
606 if (systemAbilityId == SOFTBUS_SERVER_SA_ID && !isDbinderStart_) {
607 if (dBinderService_ != nullptr && rpcCallbackImp_ != nullptr) {
608 bool ret = dBinderService_->StartDBinderService(rpcCallbackImp_);
609 HILOGI("start result is %{public}s", ret ? "succeed" : "fail");
610 isDbinderStart_ = true;
611 }
612 }
613 SendSystemAbilityAddedMsg(systemAbilityId, ability);
614 return ERR_OK;
615 }
616
AddSystemProcess(const u16string & procName,const sptr<IRemoteObject> & procObject)617 int32_t SystemAbilityManager::AddSystemProcess(const u16string& procName,
618 const sptr<IRemoteObject>& procObject)
619 {
620 if (procName.empty() || procObject == nullptr) {
621 HILOGE("AddSystemProcess empty name or null object!");
622 return ERR_INVALID_VALUE;
623 }
624
625 lock_guard<recursive_mutex> autoLock(onDemandLock_);
626 size_t procNum = systemProcessMap_.size();
627 if (procNum >= MAX_SERVICES) {
628 HILOGE("AddSystemProcess map size reach MAX_SERVICES already");
629 return ERR_INVALID_VALUE;
630 }
631 systemProcessMap_[procName] = procObject;
632 if (systemProcessDeath_ != nullptr) {
633 bool ret = procObject->AddDeathRecipient(systemProcessDeath_);
634 HILOGW("AddSystemProcess AddDeathRecipient %{public}s!", ret ? "succeed" : "failed");
635 }
636 HILOGI("AddSystemProcess insert %{public}s. size : %{public}zu", Str16ToStr8(procName).c_str(),
637 systemProcessMap_.size());
638 auto iterStarting = startingProcessMap_.find(procName);
639 if (iterStarting != startingProcessMap_.end()) {
640 int64_t end = GetTickCount();
641 HILOGI("[PerformanceTest] AddSystemProcess start process:%{public}s spend %{public}" PRId64 " ms",
642 Str16ToStr8(procName).c_str(), (end - iterStarting->second));
643 startingProcessMap_.erase(iterStarting);
644 }
645 return ERR_OK;
646 }
647
RemoveSystemProcess(const sptr<IRemoteObject> & procObject)648 int32_t SystemAbilityManager::RemoveSystemProcess(const sptr<IRemoteObject>& procObject)
649 {
650 HILOGI("RemoveSystemProcess called");
651 if (procObject == nullptr) {
652 HILOGW("RemoveSystemProcess null object!");
653 return ERR_INVALID_VALUE;
654 }
655
656 lock_guard<recursive_mutex> autoLock(onDemandLock_);
657 for (const auto& [procName, object] : systemProcessMap_) {
658 if (object == procObject) {
659 if (systemProcessDeath_ != nullptr) {
660 procObject->RemoveDeathRecipient(systemProcessDeath_);
661 }
662 std::string name = Str16ToStr8(procName);
663 (void)systemProcessMap_.erase(procName);
664 HILOGI("RemoveSystemProcess process:%{public}s dead, size : %{public}zu", name.c_str(),
665 systemProcessMap_.size());
666 break;
667 }
668 }
669 return ERR_OK;
670 }
671
GetSystemProcess(const u16string & procName)672 sptr<IRemoteObject> SystemAbilityManager::GetSystemProcess(const u16string& procName)
673 {
674 if (procName.empty()) {
675 HILOGE("GetSystemProcess empty name!");
676 return nullptr;
677 }
678
679 lock_guard<recursive_mutex> autoLock(onDemandLock_);
680 auto iter = systemProcessMap_.find(procName);
681 if (iter != systemProcessMap_.end()) {
682 HILOGI("process:%{public}s found", Str16ToStr8(procName).c_str());
683 return iter->second;
684 }
685 HILOGE("process:%{public}s not exist", Str16ToStr8(procName).c_str());
686 return nullptr;
687 }
688
SendSystemAbilityAddedMsg(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)689 void SystemAbilityManager::SendSystemAbilityAddedMsg(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
690 {
691 if (workHandler_ == nullptr) {
692 HILOGE("SendSystemAbilityAddedMsg work handler not initialized!");
693 return;
694 }
695 auto notifyAddedTask = [systemAbilityId, remoteObject, this]() {
696 FindSystemAbilityNotify(systemAbilityId, ADD_SYSTEM_ABILITY_TRANSACTION);
697 NotifySystemAbilityLoaded(systemAbilityId, remoteObject);
698 };
699 bool ret = workHandler_->PostTask(notifyAddedTask);
700 if (!ret) {
701 HILOGW("SendSystemAbilityAddedMsg PostTask failed!");
702 }
703 }
704
SendSystemAbilityRemovedMsg(int32_t systemAbilityId)705 void SystemAbilityManager::SendSystemAbilityRemovedMsg(int32_t systemAbilityId)
706 {
707 if (workHandler_ == nullptr) {
708 HILOGE("SendSystemAbilityRemovedMsg work handler not initialized!");
709 return;
710 }
711 auto notifyRemovedTask = [systemAbilityId, this]() {
712 FindSystemAbilityNotify(systemAbilityId, REMOVE_SYSTEM_ABILITY_TRANSACTION);
713 };
714 bool ret = workHandler_->PostTask(notifyRemovedTask);
715 if (!ret) {
716 HILOGW("SendSystemAbilityRemovedMsg PostTask failed!");
717 }
718 }
719
SendCheckLoadedMsg(int32_t systemAbilityId,const std::u16string & name,const sptr<ISystemAbilityLoadCallback> & callback)720 void SystemAbilityManager::SendCheckLoadedMsg(int32_t systemAbilityId, const std::u16string& name,
721 const sptr<ISystemAbilityLoadCallback>& callback)
722 {
723 if (workHandler_ == nullptr) {
724 HILOGE("SendCheckLoadedMsg work handler not initialized!");
725 return;
726 }
727
728 auto delayTask = [systemAbilityId, name, callback, this]() {
729 HILOGI("SendCheckLoadedMsg handle for SA : %{public}d.", systemAbilityId);
730 if (CheckSystemAbility(systemAbilityId) != nullptr) {
731 HILOGI("SendCheckLoadedMsg SA : %{public}d loaded.", systemAbilityId);
732 return;
733 }
734 {
735 lock_guard<recursive_mutex> autoLock(onDemandLock_);
736 auto iter = startingAbilityMap_.find(systemAbilityId);
737 if (iter == startingAbilityMap_.end()) {
738 HILOGI("SendCheckLoadedMsg SA : %{public}d not in startingAbilityMap.", systemAbilityId);
739 return;
740 }
741 auto& abilityItem = iter->second;
742 for (auto& callbackItem : abilityItem.callbackList) {
743 if (callback->AsObject() == callbackItem.first->AsObject()) {
744 NotifySystemAbilityLoadFail(systemAbilityId, callbackItem.first);
745 RemoveStartingAbilityCallbackLocked(callbackItem);
746 abilityItem.callbackList.remove(callbackItem);
747 break;
748 }
749 }
750 if (abilityItem.callbackList.empty()) {
751 HILOGD("SendCheckLoadedMsg startingAbilityMap remove SA : %{public}d.", systemAbilityId);
752 startingAbilityMap_.erase(iter);
753 }
754 }
755 (void)GetSystemProcess(name);
756 };
757 HILOGI("SendCheckLoadedMsg PostTask name : %{public}d!", systemAbilityId);
758 bool ret = workHandler_->PostTask(delayTask, ToString(systemAbilityId), CHECK_LOADED_DELAY_TIME);
759 if (!ret) {
760 HILOGW("SendCheckLoadedMsg PostTask failed!");
761 }
762 }
763
RemoveCheckLoadedMsg(int32_t systemAbilityId)764 void SystemAbilityManager::RemoveCheckLoadedMsg(int32_t systemAbilityId)
765 {
766 if (workHandler_ == nullptr) {
767 HILOGE("RemoveCheckLoadedMsg work handler not initialized!");
768 return;
769 }
770 HILOGI("RemoveCheckLoadedMsg sa : %{public}d!", systemAbilityId);
771 workHandler_->RemoveTask(ToString(systemAbilityId));
772 }
773
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject,const sptr<ISystemAbilityLoadCallback> & callback)774 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject,
775 const sptr<ISystemAbilityLoadCallback>& callback)
776 {
777 if (callback == nullptr) {
778 HILOGE("NotifySystemAbilityLoaded callback null!");
779 return;
780 }
781 callback->OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject);
782 }
783
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)784 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
785 {
786 lock_guard<recursive_mutex> autoLock(onDemandLock_);
787 auto iter = startingAbilityMap_.find(systemAbilityId);
788 if (iter == startingAbilityMap_.end()) {
789 return;
790 }
791 auto& abilityItem = iter->second;
792 for (auto& callbackItem : abilityItem.callbackList) {
793 NotifySystemAbilityLoaded(systemAbilityId, remoteObject, callbackItem.first);
794 RemoveStartingAbilityCallbackLocked(callbackItem);
795 }
796 startingAbilityMap_.erase(iter);
797 }
798
NotifySystemAbilityLoadFail(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)799 void SystemAbilityManager::NotifySystemAbilityLoadFail(int32_t systemAbilityId,
800 const sptr<ISystemAbilityLoadCallback>& callback)
801 {
802 if (callback == nullptr) {
803 HILOGE("NotifySystemAbilityLoadFail callback null!");
804 return;
805 }
806 callback->OnLoadSystemAbilityFail(systemAbilityId);
807 }
808
StartDynamicSystemProcess(const std::u16string & name,int32_t systemAbilityId)809 int32_t SystemAbilityManager::StartDynamicSystemProcess(const std::u16string& name, int32_t systemAbilityId)
810 {
811 std::string strExtra = std::to_string(systemAbilityId);
812 auto extraArgv = strExtra.c_str();
813 auto result = ServiceControlWithExtra(Str16ToStr8(name).c_str(), START, &extraArgv, 1);
814 HILOGI("StartDynamicSystemProcess call ServiceControlWithExtra result:%{public}d!", result);
815 if (result == 0) {
816 return ERR_OK;
817 }
818 return ERR_INVALID_VALUE;
819 }
820
StartingSystemProcess(const std::u16string & procName,int32_t systemAbilityId)821 int32_t SystemAbilityManager::StartingSystemProcess(const std::u16string& procName, int32_t systemAbilityId)
822 {
823 lock_guard<recursive_mutex> autoLock(onDemandLock_);
824 if (startingProcessMap_.count(procName) != 0) {
825 HILOGI("StartingSystemProcess process:%{public}s already starting!", Str16ToStr8(procName).c_str());
826 return ERR_OK;
827 }
828 auto iter = systemProcessMap_.find(procName);
829 if (iter != systemProcessMap_.end()) {
830 StartOnDemandAbility(systemAbilityId);
831 return ERR_OK;
832 }
833 // call init start process
834 int64_t begin = GetTickCount();
835 int32_t result = StartDynamicSystemProcess(procName, systemAbilityId);
836 if (result == ERR_OK) {
837 startingProcessMap_.emplace(procName, begin);
838 }
839 return result;
840 }
841
LoadSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)842 int32_t SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId,
843 const sptr<ISystemAbilityLoadCallback>& callback)
844 {
845 if (!CheckInputSysAbilityId(systemAbilityId) || callback == nullptr) {
846 HILOGW("LoadSystemAbility systemAbilityId or callback invalid!");
847 return ERR_INVALID_VALUE;
848 }
849 SaProfile saProfile;
850 bool ret = GetSaProfile(systemAbilityId, saProfile);
851 if (!ret) {
852 HILOGE("LoadSystemAbility systemAbilityId:%{public}d not supported!", systemAbilityId);
853 return ERR_INVALID_VALUE;
854 }
855
856 sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
857 if (targetObject != nullptr) {
858 NotifySystemAbilityLoaded(systemAbilityId, targetObject, callback);
859 return ERR_OK;
860 }
861 int32_t result = ERR_INVALID_VALUE;
862 auto callingPid = IPCSkeleton::GetCallingPid();
863 {
864 lock_guard<recursive_mutex> autoLock(onDemandLock_);
865 auto& abilityItem = startingAbilityMap_[systemAbilityId];
866 for (const auto& itemCallback : abilityItem.callbackList) {
867 if (callback->AsObject() == itemCallback.first->AsObject()) {
868 HILOGI("LoadSystemAbility already existed callback object systemAbilityId:%{public}d", systemAbilityId);
869 return ERR_OK;
870 }
871 }
872 auto& count = callbackCountMap_[callingPid];
873 if (count >= MAX_SUBSCRIBE_COUNT) {
874 HILOGE("LoadSystemAbility pid:%{public}d overflow max callback count!", callingPid);
875 return ERR_PERMISSION_DENIED;
876 }
877 ++count;
878 abilityItem.callbackList.emplace_back(callback, callingPid);
879 if (abilityCallbackDeath_ != nullptr) {
880 ret = callback->AsObject()->AddDeathRecipient(abilityCallbackDeath_);
881 HILOGI("LoadSystemAbility systemAbilityId:%{public}d AddDeathRecipient %{public}s",
882 systemAbilityId, ret ? "succeed" : "failed");
883 }
884 result = StartingSystemProcess(saProfile.process, systemAbilityId);
885 HILOGI("LoadSystemAbility systemAbilityId:%{public}d size : %{public}zu",
886 systemAbilityId, abilityItem.callbackList.size());
887 }
888 SendCheckLoadedMsg(systemAbilityId, saProfile.process, callback);
889 return result;
890 }
891
RemoveStartingAbilityCallbackLocked(std::pair<sptr<ISystemAbilityLoadCallback>,int32_t> & itemPair)892 void SystemAbilityManager::RemoveStartingAbilityCallbackLocked(
893 std::pair<sptr<ISystemAbilityLoadCallback>, int32_t>& itemPair)
894 {
895 if (abilityCallbackDeath_ != nullptr) {
896 itemPair.first->AsObject()->RemoveDeathRecipient(abilityCallbackDeath_);
897 }
898 auto iterCount = callbackCountMap_.find(itemPair.second);
899 if (iterCount != callbackCountMap_.end()) {
900 --iterCount->second;
901 if (iterCount->second == 0) {
902 callbackCountMap_.erase(iterCount);
903 }
904 }
905 }
906
RemoveStartingAbilityCallback(AbilityItem & abilityItem,const sptr<IRemoteObject> & remoteObject)907 void SystemAbilityManager::RemoveStartingAbilityCallback(AbilityItem& abilityItem,
908 const sptr<IRemoteObject>& remoteObject)
909 {
910 auto& callbacks = abilityItem.callbackList;
911 auto iterCallback = callbacks.begin();
912 while (iterCallback != callbacks.end()) {
913 auto& callbackPair = *iterCallback;
914 if (callbackPair.first->AsObject() == remoteObject) {
915 RemoveStartingAbilityCallbackLocked(callbackPair);
916 iterCallback = callbacks.erase(iterCallback);
917 break;
918 } else {
919 ++iterCallback;
920 }
921 }
922 }
923
OnAbilityCallbackDied(const sptr<IRemoteObject> & remoteObject)924 void SystemAbilityManager::OnAbilityCallbackDied(const sptr<IRemoteObject>& remoteObject)
925 {
926 HILOGI("OnAbilityCallbackDied received remoteObject died message!");
927 lock_guard<recursive_mutex> autoLock(onDemandLock_);
928 auto iter = startingAbilityMap_.begin();
929 while (iter != startingAbilityMap_.end()) {
930 AbilityItem& abilityItem = iter->second;
931 RemoveStartingAbilityCallback(abilityItem, remoteObject);
932 if (abilityItem.callbackList.empty()) {
933 iter = startingAbilityMap_.erase(iter);
934 } else {
935 ++iter;
936 }
937 }
938 }
939
TransformDeviceId(const std::string & deviceId,int32_t type,bool isPrivate)940 std::string SystemAbilityManager::TransformDeviceId(const std::string& deviceId, int32_t type, bool isPrivate)
941 {
942 return isPrivate ? std::string() : deviceId;
943 }
944
GetLocalNodeId()945 std::string SystemAbilityManager::GetLocalNodeId()
946 {
947 return std::string();
948 }
949 } // namespace OHOS
950