• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 "hisysevent_adapter.h"
26 #include "hitrace_meter.h"
27 #include "if_local_ability_manager.h"
28 #include "ipc_skeleton.h"
29 #include "local_ability_manager_proxy.h"
30 #include "parse_util.h"
31 #include "parameter.h"
32 #include "parameters.h"
33 #include "sam_log.h"
34 #include "service_control.h"
35 #include "string_ex.h"
36 #include "system_ability_definition.h"
37 #include "tools.h"
38 
39 using namespace std;
40 
41 namespace OHOS {
42 namespace {
43 const string PREFIX = "/system/profile/";
44 const string LOCAL_DEVICE = "local";
45 const string ONDEMAND_PARAM = "persist.samgr.perf.ondemand";
46 constexpr const char* ONDEMAND_PERF_PARAM = "persist.samgr.perf.ondemand";
47 
48 constexpr uint32_t REPORT_GET_SA_INTERVAL = 24 * 60 * 60 * 1000; // ms and is one day
49 constexpr int32_t MAX_NAME_SIZE = 200;
50 constexpr int32_t SPLIT_NAME_VECTOR_SIZE = 2;
51 
52 constexpr int32_t UID_ROOT = 0;
53 constexpr int32_t UID_SYSTEM = 1000;
54 constexpr int32_t MAX_SUBSCRIBE_COUNT = 256;
55 constexpr int32_t MAX_SA_FREQUENCY_COUNT = INT32_MAX - 1000000;
56 constexpr int32_t SHFIT_BIT = 32;
57 constexpr int64_t ONDEMAND_PERF_DELAY_TIME = 60 * 1000; // ms
58 constexpr int64_t CHECK_LOADED_DELAY_TIME = 4 * 1000; // ms
59 }
60 
61 std::mutex SystemAbilityManager::instanceLock;
62 sptr<SystemAbilityManager> SystemAbilityManager::instance;
63 
SystemAbilityManager()64 SystemAbilityManager::SystemAbilityManager()
65 {
66     dBinderService_ = DBinderService::GetInstance();
67 }
68 
~SystemAbilityManager()69 SystemAbilityManager::~SystemAbilityManager()
70 {
71     loadPool_.Stop();
72     if (reportEventTimer_ != nullptr)
73         reportEventTimer_->Shutdown();
74 }
75 
Init()76 void SystemAbilityManager::Init()
77 {
78     abilityDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityDeathRecipient());
79     systemProcessDeath_ = sptr<IRemoteObject::DeathRecipient>(new SystemProcessDeathRecipient());
80     abilityStatusDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityStatusDeathRecipient());
81     abilityCallbackDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityCallbackDeathRecipient());
82     remoteCallbackDeath_ = sptr<IRemoteObject::DeathRecipient>(new RemoteCallbackDeathRecipient());
83 
84     rpcCallbackImp_ = make_shared<RpcCallbackImp>();
85     if (workHandler_ == nullptr) {
86         auto runner = AppExecFwk::EventRunner::Create("workHandler");
87         workHandler_ = make_shared<AppExecFwk::EventHandler>(runner);
88     }
89     InitSaProfile();
90     loadPool_.Start(std::thread::hardware_concurrency());
91     loadPool_.SetMaxTaskNum(std::thread::hardware_concurrency());
92     reportEventTimer_ = std::make_unique<Utils::Timer>("DfxReporter");
93     OndemandLoadForPerf();
94 }
95 
GetDBinder() const96 const sptr<DBinderService> SystemAbilityManager::GetDBinder() const
97 {
98     return dBinderService_;
99 }
100 
StartDfxTimer()101 void SystemAbilityManager::StartDfxTimer()
102 {
103     reportEventTimer_->Setup();
104     uint32_t timerId = reportEventTimer_->Register(std::bind(&SystemAbilityManager::ReportGetSAPeriodically, this),
105         REPORT_GET_SA_INTERVAL);
106     HILOGI("StartDfxTimer timerId : %{public}u!", timerId);
107 }
108 
GetInstance()109 sptr<SystemAbilityManager> SystemAbilityManager::GetInstance()
110 {
111     std::lock_guard<std::mutex> autoLock(instanceLock);
112     if (instance == nullptr) {
113         instance = new SystemAbilityManager;
114     }
115     return instance;
116 }
117 
InitSaProfile()118 void SystemAbilityManager::InitSaProfile()
119 {
120     if (workHandler_ == nullptr) {
121         HILOGE("InitSaProfile parseHandler_ not init!");
122         return;
123     }
124 
125     auto callback = [this] () {
126         int64_t begin = GetTickCount();
127         std::vector<std::string> fileNames;
128         GetDirFiles(PREFIX, fileNames);
129         auto parser = std::make_shared<ParseUtil>();
130         for (const auto& file : fileNames) {
131             if (file.empty() || file.find(".xml") == std::string::npos
132                 || file.find("_trust.xml") != std::string::npos) {
133                 continue;
134             }
135             parser->ParseSaProfiles(file);
136         }
137         auto saInfos = parser->GetAllSaProfiles();
138         lock_guard<mutex> autoLock(saProfileMapLock_);
139         for (const auto& saInfo : saInfos) {
140             saProfileMap_[saInfo.saId] = saInfo;
141         }
142         HILOGI("[PerformanceTest] InitSaProfile spend %{public}" PRId64 " ms", GetTickCount() - begin);
143     };
144     bool ret = workHandler_->PostTask(callback);
145     if (!ret) {
146         HILOGW("SystemAbilityManager::InitSaProfile PostTask fail");
147     }
148 }
149 
OndemandLoadForPerf()150 void SystemAbilityManager::OndemandLoadForPerf()
151 {
152     if (workHandler_ == nullptr) {
153         HILOGE("LoadForPerf workHandler_ not init!");
154         return;
155     }
156     auto callback = [this] () {
157         OndemandLoad();
158     };
159     workHandler_->PostTask(callback, ONDEMAND_PERF_DELAY_TIME);
160 }
161 
OndemandLoad()162 void SystemAbilityManager::OndemandLoad()
163 {
164     auto bootEventCallback = [](const char *key, const char *value, void *context) {
165         int64_t begin = GetTickCount();
166         SystemAbilityManager::GetInstance()->DoLoadForPerf();
167         HILOGI("[PerformanceTest] DoLoadForPerf spend %{public}" PRId64 " ms", GetTickCount() - begin);
168     };
169 
170     int ret = WatchParameter(ONDEMAND_PERF_PARAM, bootEventCallback, nullptr);
171     HILOGD("OndemandLoad ret %{public}d", ret);
172 }
173 
GetAllOndemandSa()174 std::list<int32_t> SystemAbilityManager::GetAllOndemandSa()
175 {
176     std::list<int32_t> ondemandSaids;
177     {
178         lock_guard<mutex> autoLock(saProfileMapLock_);
179         for (const auto& [said, value] : saProfileMap_) {
180             shared_lock<shared_mutex> readLock(abilityMapLock_);
181             auto iter = abilityMap_.find(said);
182             if (iter == abilityMap_.end()) {
183                 ondemandSaids.emplace_back(said);
184             }
185         }
186     }
187     return ondemandSaids;
188 }
189 
DoLoadForPerf()190 void SystemAbilityManager::DoLoadForPerf()
191 {
192     bool value = system::GetBoolParameter(ONDEMAND_PARAM, false);
193     if (value) {
194         std::list<int32_t> saids = GetAllOndemandSa();
195         HILOGD("DoLoadForPerf ondemand size : %{public}zu.", saids.size());
196         sptr<ISystemAbilityLoadCallback> callback(new SystemAbilityLoadCallbackStub());
197         for (auto said : saids) {
198             LoadSystemAbility(said, callback);
199         }
200     }
201 }
202 
GetSaProfile(int32_t saId,SaProfile & saProfile)203 bool SystemAbilityManager::GetSaProfile(int32_t saId, SaProfile& saProfile)
204 {
205     lock_guard<mutex> autoLock(saProfileMapLock_);
206     auto iter = saProfileMap_.find(saId);
207     if (iter == saProfileMap_.end()) {
208         return false;
209     } else {
210         saProfile = iter->second;
211     }
212     return true;
213 }
214 
GetSystemAbility(int32_t systemAbilityId)215 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId)
216 {
217     return CheckSystemAbility(systemAbilityId);
218 }
219 
GetSystemAbility(int32_t systemAbilityId,const std::string & deviceId)220 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
221 {
222     return CheckSystemAbility(systemAbilityId, deviceId);
223 }
224 
GetSystemAbilityFromRemote(int32_t systemAbilityId)225 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbilityFromRemote(int32_t systemAbilityId)
226 {
227     HILOGD("%{public}s called, systemAbilityId = %{public}d", __func__, systemAbilityId);
228     if (!CheckInputSysAbilityId(systemAbilityId)) {
229         HILOGW("GetSystemAbilityFromRemote invalid!");
230         return nullptr;
231     }
232 
233     shared_lock<shared_mutex> readLock(abilityMapLock_);
234     auto iter = abilityMap_.find(systemAbilityId);
235     if (iter == abilityMap_.end()) {
236         HILOGI("GetSystemAbilityFromRemote not found service : %{public}d.", systemAbilityId);
237         return nullptr;
238     }
239     if (!(iter->second.isDistributed)) {
240         HILOGW("GetSystemAbilityFromRemote service : %{public}d not distributed", systemAbilityId);
241         return nullptr;
242     }
243     HILOGI("GetSystemAbilityFromRemote found service : %{public}d.", systemAbilityId);
244     return iter->second.remoteObj;
245 }
246 
CheckSystemAbility(int32_t systemAbilityId)247 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId)
248 {
249     HILOGD("%{public}s called, systemAbilityId = %{public}d", __func__, systemAbilityId);
250     if (!CheckInputSysAbilityId(systemAbilityId)) {
251         HILOGW("CheckSystemAbility CheckSystemAbility invalid!");
252         return nullptr;
253     }
254     UpdateSaFreMap(IPCSkeleton::GetCallingUid(), systemAbilityId);
255     shared_lock<shared_mutex> readLock(abilityMapLock_);
256     auto iter = abilityMap_.find(systemAbilityId);
257     if (iter != abilityMap_.end()) {
258         HILOGI("found service : %{public}d.", systemAbilityId);
259         return iter->second.remoteObj;
260     }
261     HILOGW("NOT found service : %{public}d", systemAbilityId);
262     return nullptr;
263 }
264 
CheckDistributedPermission()265 bool SystemAbilityManager::CheckDistributedPermission()
266 {
267     auto callingUid = IPCSkeleton::GetCallingUid();
268     if (callingUid != UID_ROOT && callingUid != UID_SYSTEM) {
269         return false;
270     }
271     return true;
272 }
273 
CheckSystemAbility(int32_t systemAbilityId,const std::string & deviceId)274 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId,
275     const std::string& deviceId)
276 {
277     return DoMakeRemoteBinder(systemAbilityId, IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), deviceId);
278 }
279 
FindSystemAbilityNotify(int32_t systemAbilityId,int32_t code)280 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, int32_t code)
281 {
282     return FindSystemAbilityNotify(systemAbilityId, "", code);
283 }
284 
NotifySystemAbilityChanged(int32_t systemAbilityId,const std::string & deviceId,int32_t code,const sptr<ISystemAbilityStatusChange> & listener)285 void SystemAbilityManager::NotifySystemAbilityChanged(int32_t systemAbilityId, const std::string& deviceId,
286     int32_t code, const sptr<ISystemAbilityStatusChange>& listener)
287 {
288     HILOGD("NotifySystemAbilityChanged, systemAbilityId = %{public}d", systemAbilityId);
289     if (listener == nullptr) {
290         HILOGE("%s listener null pointer!", __func__);
291         return;
292     }
293 
294     switch (code) {
295         case ADD_SYSTEM_ABILITY_TRANSACTION: {
296             listener->OnAddSystemAbility(systemAbilityId, deviceId);
297             break;
298         }
299         case REMOVE_SYSTEM_ABILITY_TRANSACTION: {
300             listener->OnRemoveSystemAbility(systemAbilityId, deviceId);
301             break;
302         }
303         default:
304             break;
305     }
306 }
307 
FindSystemAbilityNotify(int32_t systemAbilityId,const std::string & deviceId,int32_t code)308 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, const std::string& deviceId,
309     int32_t code)
310 {
311     HILOGI("%{public}s called:systemAbilityId = %{public}d, code = %{public}d", __func__, systemAbilityId, code);
312     lock_guard<recursive_mutex> autoLock(listenerMapLock_);
313     auto iter = listenerMap_.find(systemAbilityId);
314     if (iter != listenerMap_.end()) {
315         auto& listeners = iter->second;
316         for (const auto& item : listeners) {
317             NotifySystemAbilityChanged(systemAbilityId, deviceId, code, item.first);
318         }
319     }
320 
321     return ERR_OK;
322 }
323 
IsNameInValid(const std::u16string & name)324 bool SystemAbilityManager::IsNameInValid(const std::u16string& name)
325 {
326     HILOGI("%{public}s called:name = %{public}s", __func__, Str16ToStr8(name).c_str());
327     bool ret = false;
328     if (name.empty() || name.size() > MAX_NAME_SIZE || DeleteBlank(name).empty()) {
329         ret = true;
330     }
331 
332     return ret;
333 }
334 
StartOnDemandAbility(const std::u16string & procName,int32_t systemAbilityId)335 void SystemAbilityManager::StartOnDemandAbility(const std::u16string& procName, int32_t systemAbilityId)
336 {
337     lock_guard<recursive_mutex> autoLock(onDemandLock_);
338     auto iter = startingAbilityMap_.find(systemAbilityId);
339     if (iter == startingAbilityMap_.end()) {
340         return;
341     }
342     auto& abilityItem = iter->second;
343     StartOnDemandAbilityInner(procName, systemAbilityId, abilityItem);
344 }
345 
StartOnDemandAbilityInner(const std::u16string & procName,int32_t systemAbilityId,AbilityItem & abilityItem)346 void SystemAbilityManager::StartOnDemandAbilityInner(const std::u16string& procName, int32_t systemAbilityId,
347     AbilityItem& abilityItem)
348 {
349     if (abilityItem.state != AbilityState::INIT) {
350         return;
351     }
352     sptr<ILocalAbilityManager> procObject =
353         iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
354     if (procObject == nullptr) {
355         HILOGI("get process:%{public}s fail", Str16ToStr8(procName).c_str());
356         return;
357     }
358     procObject->StartAbility(systemAbilityId);
359     abilityItem.state = AbilityState::STARTING;
360 }
361 
AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,const std::u16string & procName)362 int32_t SystemAbilityManager::AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,
363     const std::u16string& procName)
364 {
365     HILOGD("%{public}s called", __func__);
366     if (!CheckInputSysAbilityId(systemAbilityId) || IsNameInValid(procName)) {
367         HILOGW("AddOnDemandSystemAbilityInfo systemAbilityId or procName invalid.");
368         return ERR_INVALID_VALUE;
369     }
370 
371     lock_guard<recursive_mutex> autoLock(onDemandLock_);
372     auto onDemandSaSize = onDemandAbilityMap_.size();
373     if (onDemandSaSize >= MAX_SERVICES) {
374         HILOGE("map size error, (Has been greater than %{public}zu)",
375             onDemandAbilityMap_.size());
376         return ERR_INVALID_VALUE;
377     }
378 
379     if (systemProcessMap_.count(procName) == 0) {
380         HILOGW("AddOnDemandSystemAbilityInfo procName:%{public}s not exist.", Str16ToStr8(procName).c_str());
381         return ERR_INVALID_VALUE;
382     }
383     onDemandAbilityMap_[systemAbilityId] = procName;
384     HILOGI("insert onDemand systemAbilityId:%{public}d. size : %{public}zu", systemAbilityId,
385         onDemandAbilityMap_.size());
386     if (startingAbilityMap_.count(systemAbilityId) != 0) {
387         if (workHandler_ != nullptr) {
388             auto pendingTask = [procName, systemAbilityId, this] () {
389                 StartOnDemandAbility(procName, systemAbilityId);
390             };
391             bool ret = workHandler_->PostTask(pendingTask);
392             if (!ret) {
393                 HILOGW("AddOnDemandSystemAbilityInfo PostTask failed!");
394             }
395         }
396     }
397     return ERR_OK;
398 }
399 
StartOnDemandAbility(int32_t systemAbilityId)400 int32_t SystemAbilityManager::StartOnDemandAbility(int32_t systemAbilityId)
401 {
402     lock_guard<recursive_mutex> onDemandAbilityLock(onDemandLock_);
403     auto iter = onDemandAbilityMap_.find(systemAbilityId);
404     if (iter == onDemandAbilityMap_.end()) {
405         return ERR_INVALID_VALUE;
406     }
407     HILOGI("found onDemandAbility: %{public}d.", systemAbilityId);
408     AbilityItem& abilityItem = startingAbilityMap_[systemAbilityId];
409     StartOnDemandAbilityInner(iter->second, systemAbilityId, abilityItem);
410     return ERR_OK;
411 }
412 
CheckSystemAbility(int32_t systemAbilityId,bool & isExist)413 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId, bool& isExist)
414 {
415     if (!CheckInputSysAbilityId(systemAbilityId)) {
416         return nullptr;
417     }
418     sptr<IRemoteObject> abilityProxy = CheckSystemAbility(systemAbilityId);
419     if (abilityProxy == nullptr) {
420         lock_guard<recursive_mutex> autoLock(onDemandLock_);
421         auto iter = startingAbilityMap_.find(systemAbilityId);
422         if (iter != startingAbilityMap_.end() && iter->second.state == AbilityState::STARTING) {
423             isExist = true;
424             return nullptr;
425         }
426 
427         int32_t ret = StartOnDemandAbility(systemAbilityId);
428         if (ret == ERR_OK) {
429             isExist = true;
430             return nullptr;
431         }
432 
433         isExist = false;
434         return nullptr;
435     }
436 
437     isExist = true;
438     return abilityProxy;
439 }
440 
RemoveSystemAbility(int32_t systemAbilityId)441 int32_t SystemAbilityManager::RemoveSystemAbility(int32_t systemAbilityId)
442 {
443     if (!CheckInputSysAbilityId(systemAbilityId)) {
444         HILOGW("RemoveSystemAbility systemAbilityId:%{public}d", systemAbilityId);
445         return ERR_INVALID_VALUE;
446     }
447     {
448         unique_lock<shared_mutex> writeLock(abilityMapLock_);
449         auto itSystemAbility = abilityMap_.find(systemAbilityId);
450         if (itSystemAbility == abilityMap_.end()) {
451             HILOGI("SystemAbilityManager::RemoveSystemAbility not found!");
452             return ERR_INVALID_VALUE;
453         }
454         sptr<IRemoteObject> ability = itSystemAbility->second.remoteObj;
455         if (ability != nullptr && abilityDeath_ != nullptr) {
456             ability->RemoveDeathRecipient(abilityDeath_);
457         }
458         (void)abilityMap_.erase(itSystemAbility);
459         HILOGI("%s called, systemAbilityId : %{public}d, size : %{public}zu", __func__, systemAbilityId,
460             abilityMap_.size());
461     }
462     SendSystemAbilityRemovedMsg(systemAbilityId);
463     return ERR_OK;
464 }
465 
RemoveSystemAbility(const sptr<IRemoteObject> & ability)466 int32_t SystemAbilityManager::RemoveSystemAbility(const sptr<IRemoteObject>& ability)
467 {
468     HILOGI("%s called, (ability)", __func__);
469     if (ability == nullptr) {
470         HILOGW("ability is nullptr ");
471         return ERR_INVALID_VALUE;
472     }
473 
474     int32_t saId = 0;
475     {
476         unique_lock<shared_mutex> writeLock(abilityMapLock_);
477         for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); ++iter) {
478             if (iter->second.remoteObj == ability) {
479                 saId = iter->first;
480                 (void)abilityMap_.erase(iter);
481                 if (abilityDeath_ != nullptr) {
482                     ability->RemoveDeathRecipient(abilityDeath_);
483                 }
484                 HILOGI("%s called, systemAbilityId:%{public}d removed, size : %{public}zu", __func__, saId,
485                     abilityMap_.size());
486                 break;
487             }
488         }
489     }
490 
491     if (saId != 0) {
492         SendSystemAbilityRemovedMsg(saId);
493     }
494     return ERR_OK;
495 }
496 
ListSystemAbilities(uint32_t dumpFlags)497 vector<u16string> SystemAbilityManager::ListSystemAbilities(uint32_t dumpFlags)
498 {
499     vector<u16string> list;
500     shared_lock<shared_mutex> readLock(abilityMapLock_);
501     for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); iter++) {
502         list.emplace_back(Str8ToStr16(to_string(iter->first)));
503     }
504     return list;
505 }
506 
SubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)507 int32_t SystemAbilityManager::SubscribeSystemAbility(int32_t systemAbilityId,
508     const sptr<ISystemAbilityStatusChange>& listener)
509 {
510     if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
511         HILOGW("SubscribeSystemAbility systemAbilityId or listener invalid!");
512         return ERR_INVALID_VALUE;
513     }
514 
515     auto callingPid = IPCSkeleton::GetCallingPid();
516     {
517         lock_guard<recursive_mutex> autoLock(listenerMapLock_);
518         auto& listeners = listenerMap_[systemAbilityId];
519         for (const auto& itemListener : listeners) {
520             if (listener->AsObject() == itemListener.first->AsObject()) {
521                 HILOGI("already exist listener object systemAbilityId = %{public}d", systemAbilityId);
522                 return ERR_OK;
523             }
524         }
525         auto& count = subscribeCountMap_[callingPid];
526         if (count >= MAX_SUBSCRIBE_COUNT) {
527             HILOGE("SubscribeSystemAbility pid:%{public}d overflow max subscribe count!", callingPid);
528             return ERR_PERMISSION_DENIED;
529         }
530         ++count;
531         if (abilityStatusDeath_ != nullptr) {
532             bool ret = listener->AsObject()->AddDeathRecipient(abilityStatusDeath_);
533             listeners.emplace_back(listener, callingPid);
534             HILOGI("SubscribeSystemAbility systemAbilityId = %{public}d AddDeathRecipient %{public}s",
535                 systemAbilityId, ret ? "succeed" : "failed");
536         }
537         HILOGI("SubscribeSystemAbility systemAbilityId = %{public}d, size = %{public}zu", systemAbilityId,
538             listeners.size());
539     }
540     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
541     if (targetObject != nullptr) {
542         NotifySystemAbilityChanged(systemAbilityId, "", ADD_SYSTEM_ABILITY_TRANSACTION, listener);
543     }
544     return ERR_OK;
545 }
546 
UnSubscribeSystemAbilityLocked(std::list<std::pair<sptr<ISystemAbilityStatusChange>,int32_t>> & listenerList,const sptr<IRemoteObject> & listener)547 void SystemAbilityManager::UnSubscribeSystemAbilityLocked(
548     std::list<std::pair<sptr<ISystemAbilityStatusChange>, int32_t>>& listenerList,
549     const sptr<IRemoteObject>& listener)
550 {
551     auto iter = listenerList.begin();
552     while (iter != listenerList.end()) {
553         auto& item = *iter;
554         if (item.first->AsObject() != listener) {
555             ++iter;
556             continue;
557         }
558 
559         if (abilityStatusDeath_ != nullptr) {
560             listener->RemoveDeathRecipient(abilityStatusDeath_);
561         }
562         auto iterPair = subscribeCountMap_.find(item.second);
563         if (iterPair != subscribeCountMap_.end()) {
564             --iterPair->second;
565             if (iterPair->second == 0) {
566                 subscribeCountMap_.erase(iterPair);
567             }
568         }
569         iter = listenerList.erase(iter);
570         break;
571     }
572 }
573 
UnSubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)574 int32_t SystemAbilityManager::UnSubscribeSystemAbility(int32_t systemAbilityId,
575     const sptr<ISystemAbilityStatusChange>& listener)
576 {
577     if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
578         HILOGW("UnSubscribeSystemAbility systemAbilityId or listener invalid!");
579         return ERR_INVALID_VALUE;
580     }
581 
582     lock_guard<recursive_mutex> autoLock(listenerMapLock_);
583     auto& listeners = listenerMap_[systemAbilityId];
584     UnSubscribeSystemAbilityLocked(listeners, listener->AsObject());
585     HILOGI("UnSubscribeSystemAbility systemAbilityId = %{public}d, size = %{public}zu", systemAbilityId,
586         listeners.size());
587     return ERR_OK;
588 }
589 
UnSubscribeSystemAbility(const sptr<IRemoteObject> & remoteObject)590 void SystemAbilityManager::UnSubscribeSystemAbility(const sptr<IRemoteObject>& remoteObject)
591 {
592     lock_guard<recursive_mutex> autoLock(listenerMapLock_);
593     for (auto& item : listenerMap_) {
594         auto& listeners = item.second;
595         UnSubscribeSystemAbilityLocked(listeners, remoteObject);
596     }
597     HILOGI("UnSubscribeSystemAbility remote object dead!");
598 }
599 
SetDeviceName(const u16string & name)600 void SystemAbilityManager::SetDeviceName(const u16string &name)
601 {
602     deviceName_ = name;
603 }
604 
GetDeviceName() const605 const u16string& SystemAbilityManager::GetDeviceName() const
606 {
607     return deviceName_;
608 }
609 
NotifyRemoteSaDied(const std::u16string & name)610 void SystemAbilityManager::NotifyRemoteSaDied(const std::u16string& name)
611 {
612     std::u16string saName;
613     std::string deviceId;
614     ParseRemoteSaName(name, deviceId, saName);
615     if (dBinderService_ != nullptr) {
616         std::string nodeId = TransformDeviceId(deviceId, NODE_ID, false);
617         dBinderService_->NoticeServiceDie(saName, nodeId);
618         HILOGI("NotifyRemoteSaDied, serviceName is %s, deviceId is %s",
619             Str16ToStr8(saName).c_str(), nodeId.c_str());
620     }
621 }
622 
NotifyRemoteDeviceOffline(const std::string & deviceId)623 void SystemAbilityManager::NotifyRemoteDeviceOffline(const std::string& deviceId)
624 {
625     if (dBinderService_ != nullptr) {
626         dBinderService_->NoticeDeviceDie(deviceId);
627         HILOGI("NotifyRemoteDeviceOffline, deviceId is %s", deviceId.c_str());
628     }
629 }
630 
ParseRemoteSaName(const std::u16string & name,std::string & deviceId,std::u16string & saName)631 void SystemAbilityManager::ParseRemoteSaName(const std::u16string& name, std::string& deviceId, std::u16string& saName)
632 {
633     vector<string> strVector;
634     SplitStr(Str16ToStr8(name), "_", strVector);
635     if (strVector.size() == SPLIT_NAME_VECTOR_SIZE) {
636         deviceId = strVector[0];
637         saName = Str8ToStr16(strVector[1]);
638     }
639 }
640 
AddSystemAbility(int32_t systemAbilityId,const sptr<IRemoteObject> & ability,const SAExtraProp & extraProp)641 int32_t SystemAbilityManager::AddSystemAbility(int32_t systemAbilityId, const sptr<IRemoteObject>& ability,
642     const SAExtraProp& extraProp)
643 {
644     if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {
645         HILOGE("AddSystemAbilityExtra input params is invalid.");
646         return ERR_INVALID_VALUE;
647     }
648     {
649         unique_lock<shared_mutex> writeLock(abilityMapLock_);
650         auto saSize = abilityMap_.size();
651         if (saSize >= MAX_SERVICES) {
652             HILOGE("map size error, (Has been greater than %zu)", saSize);
653             return ERR_INVALID_VALUE;
654         }
655         SAInfo saInfo;
656         saInfo.remoteObj = ability;
657         saInfo.isDistributed = extraProp.isDistributed;
658         saInfo.capability = extraProp.capability;
659         saInfo.permission = Str16ToStr8(extraProp.permission);
660         abilityMap_[systemAbilityId] = std::move(saInfo);
661         HILOGI("insert %{public}d. size : %{public}zu", systemAbilityId, abilityMap_.size());
662     }
663     RemoveCheckLoadedMsg(systemAbilityId);
664     if (abilityDeath_ != nullptr) {
665         ability->AddDeathRecipient(abilityDeath_);
666     }
667 
668     u16string strName = Str8ToStr16(to_string(systemAbilityId));
669     if (extraProp.isDistributed && dBinderService_ != nullptr) {
670         dBinderService_->RegisterRemoteProxy(strName, systemAbilityId);
671         HILOGI("AddSystemAbility RegisterRemoteProxy, serviceId is %{public}d", systemAbilityId);
672     }
673     if (systemAbilityId == SOFTBUS_SERVER_SA_ID) {
674         if (dBinderService_ != nullptr && rpcCallbackImp_ != nullptr) {
675             bool ret = dBinderService_->StartDBinderService(rpcCallbackImp_);
676             HILOGI("start result is %{public}s", ret ? "succeed" : "fail");
677         }
678     }
679     SendSystemAbilityAddedMsg(systemAbilityId, ability);
680     return ERR_OK;
681 }
682 
AddSystemProcess(const u16string & procName,const sptr<IRemoteObject> & procObject)683 int32_t SystemAbilityManager::AddSystemProcess(const u16string& procName,
684     const sptr<IRemoteObject>& procObject)
685 {
686     if (procName.empty() || procObject == nullptr) {
687         HILOGE("AddSystemProcess empty name or null object!");
688         return ERR_INVALID_VALUE;
689     }
690 
691     lock_guard<recursive_mutex> autoLock(onDemandLock_);
692     size_t procNum = systemProcessMap_.size();
693     if (procNum >= MAX_SERVICES) {
694         HILOGE("AddSystemProcess map size reach MAX_SERVICES already");
695         return ERR_INVALID_VALUE;
696     }
697     systemProcessMap_[procName] = procObject;
698     if (systemProcessDeath_ != nullptr) {
699         bool ret = procObject->AddDeathRecipient(systemProcessDeath_);
700         HILOGW("AddSystemProcess AddDeathRecipient %{public}s!", ret ? "succeed" : "failed");
701     }
702     HILOGI("AddSystemProcess insert %{public}s. size : %{public}zu", Str16ToStr8(procName).c_str(),
703         systemProcessMap_.size());
704     auto iterStarting = startingProcessMap_.find(procName);
705     if (iterStarting != startingProcessMap_.end()) {
706         int64_t end = GetTickCount();
707         HILOGI("[PerformanceTest] AddSystemProcess start process:%{public}s spend %{public}" PRId64 " ms",
708             Str16ToStr8(procName).c_str(), (end - iterStarting->second));
709         startingProcessMap_.erase(iterStarting);
710     }
711     return ERR_OK;
712 }
713 
RemoveSystemProcess(const sptr<IRemoteObject> & procObject)714 int32_t SystemAbilityManager::RemoveSystemProcess(const sptr<IRemoteObject>& procObject)
715 {
716     if (procObject == nullptr) {
717         HILOGW("RemoveSystemProcess null object!");
718         return ERR_INVALID_VALUE;
719     }
720 
721     lock_guard<recursive_mutex> autoLock(onDemandLock_);
722     for (const auto& [procName, object] : systemProcessMap_) {
723         if (object == procObject) {
724             if (systemProcessDeath_ != nullptr) {
725                 procObject->RemoveDeathRecipient(systemProcessDeath_);
726             }
727             std::string name = Str16ToStr8(procName);
728             (void)systemProcessMap_.erase(procName);
729             HILOGI("RemoveSystemProcess process:%{public}s dead, size : %{public}zu", name.c_str(),
730                 systemProcessMap_.size());
731             return ERR_OK;
732         }
733     }
734     HILOGW("RemoveSystemProcess called and not found process.");
735     return ERR_INVALID_VALUE;
736 }
737 
GetSystemProcess(const u16string & procName)738 sptr<IRemoteObject> SystemAbilityManager::GetSystemProcess(const u16string& procName)
739 {
740     if (procName.empty()) {
741         HILOGE("GetSystemProcess empty name!");
742         return nullptr;
743     }
744 
745     lock_guard<recursive_mutex> autoLock(onDemandLock_);
746     auto iter = systemProcessMap_.find(procName);
747     if (iter != systemProcessMap_.end()) {
748         HILOGI("process:%{public}s found", Str16ToStr8(procName).c_str());
749         return iter->second;
750     }
751     HILOGE("process:%{public}s not exist", Str16ToStr8(procName).c_str());
752     return nullptr;
753 }
754 
SendSystemAbilityAddedMsg(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)755 void SystemAbilityManager::SendSystemAbilityAddedMsg(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
756 {
757     if (workHandler_ == nullptr) {
758         HILOGE("SendSystemAbilityAddedMsg work handler not initialized!");
759         return;
760     }
761     auto notifyAddedTask = [systemAbilityId, remoteObject, this]() {
762         FindSystemAbilityNotify(systemAbilityId, ADD_SYSTEM_ABILITY_TRANSACTION);
763         NotifySystemAbilityLoaded(systemAbilityId, remoteObject);
764     };
765     bool ret = workHandler_->PostTask(notifyAddedTask);
766     if (!ret) {
767         HILOGW("SendSystemAbilityAddedMsg PostTask failed!");
768     }
769 }
770 
SendSystemAbilityRemovedMsg(int32_t systemAbilityId)771 void SystemAbilityManager::SendSystemAbilityRemovedMsg(int32_t systemAbilityId)
772 {
773     if (workHandler_ == nullptr) {
774         HILOGE("SendSystemAbilityRemovedMsg work handler not initialized!");
775         return;
776     }
777     auto notifyRemovedTask = [systemAbilityId, this]() {
778         FindSystemAbilityNotify(systemAbilityId, REMOVE_SYSTEM_ABILITY_TRANSACTION);
779     };
780     bool ret = workHandler_->PostTask(notifyRemovedTask);
781     if (!ret) {
782         HILOGW("SendSystemAbilityRemovedMsg PostTask failed!");
783     }
784 }
785 
SendCheckLoadedMsg(int32_t systemAbilityId,const std::u16string & name,const std::string & srcDeviceId,const sptr<ISystemAbilityLoadCallback> & callback)786 void SystemAbilityManager::SendCheckLoadedMsg(int32_t systemAbilityId, const std::u16string& name,
787     const std::string& srcDeviceId, const sptr<ISystemAbilityLoadCallback>& callback)
788 {
789     if (workHandler_ == nullptr) {
790         HILOGE("SendCheckLoadedMsg work handler not initialized!");
791         return;
792     }
793 
794     auto delayTask = [systemAbilityId, name, srcDeviceId, callback, this]() {
795         HILOGI("SendCheckLoadedMsg handle for SA : %{public}d.", systemAbilityId);
796         if (CheckSystemAbility(systemAbilityId) != nullptr) {
797             HILOGI("SendCheckLoadedMsg SA : %{public}d loaded.", systemAbilityId);
798             return;
799         }
800         CleanCallbackForLoadFailed(systemAbilityId, name, srcDeviceId, callback);
801         (void)GetSystemProcess(name);
802     };
803     bool ret = workHandler_->PostTask(delayTask, ToString(systemAbilityId), CHECK_LOADED_DELAY_TIME);
804     HILOGI("SendCheckLoadedMsg PostTask name : %{public}d!, ret : %{public}s",
805         systemAbilityId, ret ? "success" : "failed");
806 }
807 
CleanCallbackForLoadFailed(int32_t systemAbilityId,const std::u16string & name,const std::string & srcDeviceId,const sptr<ISystemAbilityLoadCallback> & callback)808 void SystemAbilityManager::CleanCallbackForLoadFailed(int32_t systemAbilityId, const std::u16string& name,
809     const std::string& srcDeviceId, const sptr<ISystemAbilityLoadCallback>& callback)
810 {
811     lock_guard<recursive_mutex> autoLock(onDemandLock_);
812     auto iterStarting = startingProcessMap_.find(name);
813     if (iterStarting != startingProcessMap_.end()) {
814         HILOGI("CleanCallback clean process:%{public}s", Str16ToStr8(name).c_str());
815         startingProcessMap_.erase(iterStarting);
816     }
817     auto iter = startingAbilityMap_.find(systemAbilityId);
818     if (iter == startingAbilityMap_.end()) {
819         HILOGI("CleanCallback SA : %{public}d not in startingAbilityMap.", systemAbilityId);
820         return;
821     }
822     auto& abilityItem = iter->second;
823     for (auto& callbackItem : abilityItem.callbackMap[srcDeviceId]) {
824         if (callback->AsObject() == callbackItem.first->AsObject()) {
825             NotifySystemAbilityLoadFail(systemAbilityId, callbackItem.first);
826             RemoveStartingAbilityCallbackLocked(callbackItem);
827             abilityItem.callbackMap[srcDeviceId].remove(callbackItem);
828             break;
829         }
830     }
831     if (abilityItem.callbackMap[srcDeviceId].empty()) {
832         HILOGI("CleanCallback startingAbilityMap remove SA : %{public}d. with deviceId", systemAbilityId);
833         abilityItem.callbackMap.erase(srcDeviceId);
834     }
835 
836     if (abilityItem.callbackMap.empty()) {
837         HILOGI("CleanCallback startingAbilityMap remove SA : %{public}d.", systemAbilityId);
838         startingAbilityMap_.erase(iter);
839     }
840 }
841 
RemoveCheckLoadedMsg(int32_t systemAbilityId)842 void SystemAbilityManager::RemoveCheckLoadedMsg(int32_t systemAbilityId)
843 {
844     if (workHandler_ == nullptr) {
845         HILOGE("RemoveCheckLoadedMsg work handler not initialized!");
846         return;
847     }
848     workHandler_->RemoveTask(ToString(systemAbilityId));
849 }
850 
SendLoadedSystemAblityMsg(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject,const sptr<ISystemAbilityLoadCallback> & callback)851 void SystemAbilityManager::SendLoadedSystemAblityMsg(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject,
852     const sptr<ISystemAbilityLoadCallback>& callback)
853 {
854     if (workHandler_ == nullptr) {
855         HILOGE("SendLoadedSystemAblityMsg work handler not initialized!");
856         return;
857     }
858     auto notifyLoadedTask = [systemAbilityId, remoteObject, callback, this]() {
859         NotifySystemAbilityLoaded(systemAbilityId, remoteObject, callback);
860     };
861     bool ret = workHandler_->PostTask(notifyLoadedTask);
862     if (!ret) {
863         HILOGW("SendLoadedSystemAblityMsg PostTask failed!");
864     }
865 }
866 
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject,const sptr<ISystemAbilityLoadCallback> & callback)867 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject,
868     const sptr<ISystemAbilityLoadCallback>& callback)
869 {
870     if (callback == nullptr) {
871         HILOGE("NotifySystemAbilityLoaded callback null!");
872         return;
873     }
874     HILOGI("NotifySystemAbilityLoaded systemAbilityId : %{public}d", systemAbilityId);
875     callback->OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject);
876 }
877 
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)878 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
879 {
880     lock_guard<recursive_mutex> autoLock(onDemandLock_);
881     auto iter = startingAbilityMap_.find(systemAbilityId);
882     if (iter == startingAbilityMap_.end()) {
883         return;
884     }
885     auto& abilityItem = iter->second;
886     for (auto& [deviceId, callbackList] : abilityItem.callbackMap) {
887         for (auto& callbackItem : callbackList) {
888             NotifySystemAbilityLoaded(systemAbilityId, remoteObject, callbackItem.first);
889             RemoveStartingAbilityCallbackLocked(callbackItem);
890         }
891     }
892     startingAbilityMap_.erase(iter);
893 }
894 
NotifySystemAbilityLoadFail(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)895 void SystemAbilityManager::NotifySystemAbilityLoadFail(int32_t systemAbilityId,
896     const sptr<ISystemAbilityLoadCallback>& callback)
897 {
898     if (callback == nullptr) {
899         HILOGE("NotifySystemAbilityLoadFail callback null!");
900         return;
901     }
902     HILOGI("NotifySystemAbilityLoadFailed systemAbilityId : %{public}d", systemAbilityId);
903     callback->OnLoadSystemAbilityFail(systemAbilityId);
904 }
905 
StartDynamicSystemProcess(const std::u16string & name,int32_t systemAbilityId)906 int32_t SystemAbilityManager::StartDynamicSystemProcess(const std::u16string& name, int32_t systemAbilityId)
907 {
908     std::string strExtra = std::to_string(systemAbilityId);
909     auto extraArgv = strExtra.c_str();
910     auto result = ServiceControlWithExtra(Str16ToStr8(name).c_str(), START, &extraArgv, 1);
911     HILOGI("StartDynamicSystemProcess call ServiceControlWithExtra result:%{public}d!", result);
912     return (result == 0) ? ERR_OK : ERR_INVALID_VALUE;
913 }
914 
StartingSystemProcess(const std::u16string & procName,int32_t systemAbilityId)915 int32_t SystemAbilityManager::StartingSystemProcess(const std::u16string& procName, int32_t systemAbilityId)
916 {
917     lock_guard<recursive_mutex> autoLock(onDemandLock_);
918     if (startingProcessMap_.count(procName) != 0) {
919         HILOGI("StartingSystemProcess process:%{public}s already starting!", Str16ToStr8(procName).c_str());
920         return ERR_OK;
921     }
922     auto iter = systemProcessMap_.find(procName);
923     if (iter != systemProcessMap_.end()) {
924         StartOnDemandAbility(systemAbilityId);
925         return ERR_OK;
926     }
927     // call init start process
928     int64_t begin = GetTickCount();
929     int32_t result = StartDynamicSystemProcess(procName, systemAbilityId);
930     if (result == ERR_OK) {
931         startingProcessMap_.emplace(procName, begin);
932     }
933     return result;
934 }
935 
LoadSystemAbilityFromRpc(const std::string & srcDeviceId,int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)936 bool SystemAbilityManager::LoadSystemAbilityFromRpc(const std::string& srcDeviceId, int32_t systemAbilityId,
937     const sptr<ISystemAbilityLoadCallback>& callback)
938 {
939     if (!CheckInputSysAbilityId(systemAbilityId) || callback == nullptr) {
940         HILOGW("LoadSystemAbility said or callback invalid!");
941         return false;
942     }
943     SaProfile saProfile;
944     bool ret = GetSaProfile(systemAbilityId, saProfile);
945     if (!ret) {
946         HILOGE("LoadSystemAbilityFromRpc said:%{public}d not supported!", systemAbilityId);
947         return false;
948     }
949 
950     if (!saProfile.distributed) {
951         HILOGE("LoadSystemAbilityFromRpc said:%{public}d not distributed!", systemAbilityId);
952         return false;
953     }
954 
955     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
956     if (targetObject != nullptr) {
957         SendLoadedSystemAblityMsg(systemAbilityId, targetObject, callback);
958         return true;
959     }
960     {
961         lock_guard<recursive_mutex> autoLock(onDemandLock_);
962         auto& abilityItem = startingAbilityMap_[systemAbilityId];
963         abilityItem.callbackMap[srcDeviceId].emplace_back(callback, 0);
964         StartingSystemProcess(saProfile.process, systemAbilityId);
965     }
966     SendCheckLoadedMsg(systemAbilityId, saProfile.process, srcDeviceId, callback);
967     return true;
968 }
969 
LoadSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)970 int32_t SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId,
971     const sptr<ISystemAbilityLoadCallback>& callback)
972 {
973     if (!CheckInputSysAbilityId(systemAbilityId) || callback == nullptr) {
974         HILOGW("LoadSystemAbility systemAbilityId or callback invalid!");
975         return ERR_INVALID_VALUE;
976     }
977     SaProfile saProfile;
978     bool ret = GetSaProfile(systemAbilityId, saProfile);
979     if (!ret) {
980         HILOGE("LoadSystemAbility systemAbilityId:%{public}d not supported!", systemAbilityId);
981         return ERR_INVALID_VALUE;
982     }
983 
984     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
985     if (targetObject != nullptr) {
986         NotifySystemAbilityLoaded(systemAbilityId, targetObject, callback);
987         return ERR_OK;
988     }
989     int32_t result = ERR_INVALID_VALUE;
990     auto callingPid = IPCSkeleton::GetCallingPid();
991     {
992         lock_guard<recursive_mutex> autoLock(onDemandLock_);
993         auto& abilityItem = startingAbilityMap_[systemAbilityId];
994         for (const auto& itemCallback : abilityItem.callbackMap[LOCAL_DEVICE]) {
995             if (callback->AsObject() == itemCallback.first->AsObject()) {
996                 HILOGI("LoadSystemAbility already existed callback object systemAbilityId:%{public}d", systemAbilityId);
997                 return ERR_OK;
998             }
999         }
1000         auto& count = callbackCountMap_[callingPid];
1001         if (count >= MAX_SUBSCRIBE_COUNT) {
1002             HILOGE("LoadSystemAbility pid:%{public}d overflow max callback count!", callingPid);
1003             return ERR_PERMISSION_DENIED;
1004         }
1005         ++count;
1006         abilityItem.callbackMap[LOCAL_DEVICE].emplace_back(callback, callingPid);
1007         if (abilityCallbackDeath_ != nullptr) {
1008             ret = callback->AsObject()->AddDeathRecipient(abilityCallbackDeath_);
1009             HILOGI("LoadSystemAbility systemAbilityId:%{public}d AddDeathRecipient %{public}s",
1010                 systemAbilityId, ret ? "succeed" : "failed");
1011         }
1012         result = StartingSystemProcess(saProfile.process, systemAbilityId);
1013         HILOGI("LoadSystemAbility systemAbilityId:%{public}d size : %{public}zu",
1014             systemAbilityId, abilityItem.callbackMap[LOCAL_DEVICE].size());
1015     }
1016     SendCheckLoadedMsg(systemAbilityId, saProfile.process, LOCAL_DEVICE, callback);
1017     return result;
1018 }
1019 
LoadSystemAbility(int32_t systemAbilityId,const std::string & deviceId,const sptr<ISystemAbilityLoadCallback> & callback)1020 int32_t SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId, const std::string& deviceId,
1021     const sptr<ISystemAbilityLoadCallback>& callback)
1022 {
1023     std::string key = ToString(systemAbilityId) + "_" + deviceId;
1024     {
1025         lock_guard<mutex> autoLock(loadRemoteLock_);
1026         auto& callbacks = remoteCallbacks_[key];
1027         auto iter = std::find_if(callbacks.begin(), callbacks.end(), [callback](auto itemCallback) {
1028             return callback->AsObject() == itemCallback->AsObject();
1029         });
1030         if (iter != callbacks.end()) {
1031             HILOGI("LoadSystemAbility already existed callback object systemAbilityId:%{public}d", systemAbilityId);
1032             return ERR_OK;
1033         }
1034         if (remoteCallbackDeath_ != nullptr) {
1035             bool ret = callback->AsObject()->AddDeathRecipient(remoteCallbackDeath_);
1036             HILOGI("LoadSystemAbility systemAbilityId:%{public}d AddDeathRecipient %{public}s",
1037                 systemAbilityId, ret ? "succeed" : "failed");
1038         }
1039         callbacks.emplace_back(callback);
1040     }
1041     auto callingPid = IPCSkeleton::GetCallingPid();
1042     auto callingUid = IPCSkeleton::GetCallingUid();
1043     auto task = std::bind(&SystemAbilityManager::DoLoadRemoteSystemAbility, this,
1044         systemAbilityId, callingPid, callingUid, deviceId, callback);
1045     loadPool_.AddTask(task);
1046     return ERR_OK;
1047 }
1048 
DoLoadRemoteSystemAbility(int32_t systemAbilityId,int32_t callingPid,int32_t callingUid,const std::string & deviceId,const sptr<ISystemAbilityLoadCallback> & callback)1049 void SystemAbilityManager::DoLoadRemoteSystemAbility(int32_t systemAbilityId, int32_t callingPid,
1050     int32_t callingUid, const std::string& deviceId, const sptr<ISystemAbilityLoadCallback>& callback)
1051 {
1052     sptr<DBinderServiceStub> remoteBinder = DoMakeRemoteBinder(systemAbilityId, callingPid, callingUid, deviceId);
1053 
1054     if (callback == nullptr) {
1055         HILOGI("DoLoadRemoteSystemAbility return, callback is nullptr, said : %{public}d", systemAbilityId);
1056         return;
1057     }
1058     callback->OnLoadSACompleteForRemote(deviceId, systemAbilityId, remoteBinder);
1059     std::string key = ToString(systemAbilityId) + "_" + deviceId;
1060     {
1061         lock_guard<mutex> autoLock(loadRemoteLock_);
1062         if (remoteCallbackDeath_ != nullptr) {
1063             callback->AsObject()->RemoveDeathRecipient(remoteCallbackDeath_);
1064         }
1065         auto& callbacks = remoteCallbacks_[key];
1066         callbacks.remove(callback);
1067         if (callbacks.empty()) {
1068             remoteCallbacks_.erase(key);
1069         }
1070     }
1071 }
1072 
DoMakeRemoteBinder(int32_t systemAbilityId,int32_t callingPid,int32_t callingUid,const std::string & deviceId)1073 sptr<DBinderServiceStub> SystemAbilityManager::DoMakeRemoteBinder(int32_t systemAbilityId, int32_t callingPid,
1074     int32_t callingUid, const std::string& deviceId)
1075 {
1076     HILOGI("MakeRemoteBinder begin, said : %{public}d", systemAbilityId);
1077     sptr<DBinderServiceStub> remoteBinder = nullptr;
1078     if (dBinderService_ != nullptr) {
1079         string strName = to_string(systemAbilityId);
1080         remoteBinder = dBinderService_->MakeRemoteBinder(Str8ToStr16(strName),
1081             deviceId, systemAbilityId, callingPid, callingUid);
1082     }
1083     HILOGI("MakeRemoteBinder end, result %{public}s, said : %{public}d, deviceId : %{public}s",
1084         remoteBinder == nullptr ? " failed" : "succeed", systemAbilityId, AnonymizeDeviceId(deviceId).c_str());
1085     return remoteBinder;
1086 }
1087 
NotifyRpcLoadCompleted(const std::string & srcDeviceId,int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)1088 void SystemAbilityManager::NotifyRpcLoadCompleted(const std::string& srcDeviceId, int32_t systemAbilityId,
1089     const sptr<IRemoteObject>& remoteObject)
1090 {
1091     if (dBinderService_ != nullptr) {
1092         dBinderService_->LoadSystemAbilityComplete(srcDeviceId, systemAbilityId, remoteObject);
1093         return;
1094     }
1095     HILOGW("NotifyRpcLoadCompleted failed, said: %{public}d, deviceId : %{public}s",
1096         systemAbilityId, AnonymizeDeviceId(srcDeviceId).c_str());
1097 }
1098 
RemoveStartingAbilityCallbackLocked(std::pair<sptr<ISystemAbilityLoadCallback>,int32_t> & itemPair)1099 void SystemAbilityManager::RemoveStartingAbilityCallbackLocked(
1100     std::pair<sptr<ISystemAbilityLoadCallback>, int32_t>& itemPair)
1101 {
1102     if (abilityCallbackDeath_ != nullptr) {
1103         itemPair.first->AsObject()->RemoveDeathRecipient(abilityCallbackDeath_);
1104     }
1105     auto iterCount = callbackCountMap_.find(itemPair.second);
1106     if (iterCount != callbackCountMap_.end()) {
1107         --iterCount->second;
1108         if (iterCount->second == 0) {
1109             callbackCountMap_.erase(iterCount);
1110         }
1111     }
1112 }
1113 
RemoveStartingAbilityCallbackForDevice(AbilityItem & abilityItem,const sptr<IRemoteObject> & remoteObject)1114 void SystemAbilityManager::RemoveStartingAbilityCallbackForDevice(AbilityItem& abilityItem,
1115     const sptr<IRemoteObject>& remoteObject)
1116 {
1117     auto& callbacks = abilityItem.callbackMap;
1118     auto iter = callbacks.begin();
1119     while (iter != callbacks.end()) {
1120         CallbackList& callbackList = iter->second;
1121         RemoveStartingAbilityCallback(callbackList, remoteObject);
1122         if (callbackList.empty()) {
1123             callbacks.erase(iter++);
1124         } else {
1125             ++iter;
1126         }
1127     }
1128 }
1129 
RemoveStartingAbilityCallback(CallbackList & callbackList,const sptr<IRemoteObject> & remoteObject)1130 void SystemAbilityManager::RemoveStartingAbilityCallback(CallbackList& callbackList,
1131     const sptr<IRemoteObject>& remoteObject)
1132 {
1133     auto iterCallback = callbackList.begin();
1134     while (iterCallback != callbackList.end()) {
1135         auto& callbackPair = *iterCallback;
1136         if (callbackPair.first->AsObject() == remoteObject) {
1137             RemoveStartingAbilityCallbackLocked(callbackPair);
1138             iterCallback = callbackList.erase(iterCallback);
1139             break;
1140         } else {
1141             ++iterCallback;
1142         }
1143     }
1144 }
1145 
OnAbilityCallbackDied(const sptr<IRemoteObject> & remoteObject)1146 void SystemAbilityManager::OnAbilityCallbackDied(const sptr<IRemoteObject>& remoteObject)
1147 {
1148     HILOGI("OnAbilityCallbackDied received remoteObject died message!");
1149     if (remoteObject == nullptr) {
1150         return;
1151     }
1152     lock_guard<recursive_mutex> autoLock(onDemandLock_);
1153     auto iter = startingAbilityMap_.begin();
1154     while (iter != startingAbilityMap_.end()) {
1155         AbilityItem& abilityItem = iter->second;
1156         RemoveStartingAbilityCallbackForDevice(abilityItem, remoteObject);
1157         if (abilityItem.callbackMap.empty()) {
1158             startingAbilityMap_.erase(iter++);
1159         } else {
1160             ++iter;
1161         }
1162     }
1163 }
1164 
OnRemoteCallbackDied(const sptr<IRemoteObject> & remoteObject)1165 void SystemAbilityManager::OnRemoteCallbackDied(const sptr<IRemoteObject>& remoteObject)
1166 {
1167     HILOGI("OnRemoteCallbackDied received remoteObject died message!");
1168     if (remoteObject == nullptr) {
1169         return;
1170     }
1171     lock_guard<mutex> autoLock(loadRemoteLock_);
1172     auto iter = remoteCallbacks_.begin();
1173     while (iter != remoteCallbacks_.end()) {
1174         auto& callbacks = iter->second;
1175         RemoveRemoteCallbackLocked(callbacks, remoteObject);
1176         if (callbacks.empty()) {
1177             remoteCallbacks_.erase(iter++);
1178         } else {
1179             ++iter;
1180         }
1181     }
1182 }
1183 
RemoveRemoteCallbackLocked(std::list<sptr<ISystemAbilityLoadCallback>> & callbacks,const sptr<IRemoteObject> & remoteObject)1184 void SystemAbilityManager::RemoveRemoteCallbackLocked(std::list<sptr<ISystemAbilityLoadCallback>>& callbacks,
1185     const sptr<IRemoteObject>& remoteObject)
1186 {
1187     for (const auto& callback : callbacks) {
1188         if (callback->AsObject() == remoteObject) {
1189             if (remoteCallbackDeath_ != nullptr) {
1190                 callback->AsObject()->RemoveDeathRecipient(remoteCallbackDeath_);
1191             }
1192             callbacks.remove(callback);
1193             break;
1194         }
1195     }
1196 }
1197 
TransformDeviceId(const std::string & deviceId,int32_t type,bool isPrivate)1198 std::string SystemAbilityManager::TransformDeviceId(const std::string& deviceId, int32_t type, bool isPrivate)
1199 {
1200     return isPrivate ? std::string() : deviceId;
1201 }
1202 
GetLocalNodeId()1203 std::string SystemAbilityManager::GetLocalNodeId()
1204 {
1205     return std::string();
1206 }
1207 
UpdateSaFreMap(int32_t uid,int32_t saId)1208 void SystemAbilityManager::UpdateSaFreMap(int32_t uid, int32_t saId)
1209 {
1210     if (uid < 0) {
1211         HILOGW("UpdateSaFreMap return, uid not valid!");
1212         return;
1213     }
1214 
1215     uint64_t key = GenerateFreKey(uid, saId);
1216     lock_guard<mutex> autoLock(saFrequencyLock_);
1217     auto& count = saFrequencyMap_[key];
1218     if (count < MAX_SA_FREQUENCY_COUNT) {
1219         count++;
1220     }
1221 }
1222 
GenerateFreKey(int32_t uid,int32_t saId) const1223 uint64_t SystemAbilityManager::GenerateFreKey(int32_t uid, int32_t saId) const
1224 {
1225     uint32_t uSaid = static_cast<uint32_t>(saId);
1226     uint64_t key = static_cast<uint64_t>(uid);
1227     return (key << SHFIT_BIT) | uSaid;
1228 }
1229 
ReportGetSAPeriodically()1230 void SystemAbilityManager::ReportGetSAPeriodically()
1231 {
1232     HILOGI("ReportGetSAPeriodically start!");
1233     lock_guard<mutex> autoLock(saFrequencyLock_);
1234     for (const auto& [key, count] : saFrequencyMap_) {
1235         uint32_t saId = static_cast<uint32_t>(key);
1236         uint32_t uid = key >> SHFIT_BIT;
1237         ReportGetSAFrequency(uid, saId, count);
1238     }
1239     saFrequencyMap_.clear();
1240 }
1241 } // namespace OHOS
1242