• 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     UpdateSaFreMap(IPCSkeleton::GetCallingPid(), systemAbilityId);
251     if (!CheckInputSysAbilityId(systemAbilityId)) {
252         HILOGW("CheckSystemAbility CheckSystemAbility invalid!");
253         return nullptr;
254     }
255 
256     shared_lock<shared_mutex> readLock(abilityMapLock_);
257     auto iter = abilityMap_.find(systemAbilityId);
258     if (iter != abilityMap_.end()) {
259         HILOGI("found service : %{public}d.", systemAbilityId);
260         return iter->second.remoteObj;
261     }
262     HILOGW("NOT found service : %{public}d", systemAbilityId);
263     return nullptr;
264 }
265 
CheckDistributedPermission()266 bool SystemAbilityManager::CheckDistributedPermission()
267 {
268     auto callingUid = IPCSkeleton::GetCallingUid();
269     if (callingUid != UID_ROOT && callingUid != UID_SYSTEM) {
270         return false;
271     }
272     return true;
273 }
274 
CheckSystemAbility(int32_t systemAbilityId,const std::string & deviceId)275 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId,
276     const std::string& deviceId)
277 {
278     return DoMakeRemoteBinder(systemAbilityId, IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), deviceId);
279 }
280 
FindSystemAbilityNotify(int32_t systemAbilityId,int32_t code)281 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, int32_t code)
282 {
283     return FindSystemAbilityNotify(systemAbilityId, "", code);
284 }
285 
NotifySystemAbilityChanged(int32_t systemAbilityId,const std::string & deviceId,int32_t code,const sptr<ISystemAbilityStatusChange> & listener)286 void SystemAbilityManager::NotifySystemAbilityChanged(int32_t systemAbilityId, const std::string& deviceId,
287     int32_t code, const sptr<ISystemAbilityStatusChange>& listener)
288 {
289     HILOGD("NotifySystemAbilityChanged, systemAbilityId = %{public}d", systemAbilityId);
290     if (listener == nullptr) {
291         HILOGE("%s listener null pointer!", __func__);
292         return;
293     }
294 
295     switch (code) {
296         case ADD_SYSTEM_ABILITY_TRANSACTION: {
297             listener->OnAddSystemAbility(systemAbilityId, deviceId);
298             break;
299         }
300         case REMOVE_SYSTEM_ABILITY_TRANSACTION: {
301             listener->OnRemoveSystemAbility(systemAbilityId, deviceId);
302             break;
303         }
304         default:
305             break;
306     }
307 }
308 
FindSystemAbilityNotify(int32_t systemAbilityId,const std::string & deviceId,int32_t code)309 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, const std::string& deviceId,
310     int32_t code)
311 {
312     HILOGI("%{public}s called:systemAbilityId = %{public}d, code = %{public}d", __func__, systemAbilityId, code);
313     lock_guard<recursive_mutex> autoLock(listenerMapLock_);
314     auto iter = listenerMap_.find(systemAbilityId);
315     if (iter != listenerMap_.end()) {
316         auto& listeners = iter->second;
317         for (const auto& item : listeners) {
318             NotifySystemAbilityChanged(systemAbilityId, deviceId, code, item.first);
319         }
320     }
321 
322     return ERR_OK;
323 }
324 
IsNameInValid(const std::u16string & name)325 bool SystemAbilityManager::IsNameInValid(const std::u16string& name)
326 {
327     HILOGI("%{public}s called:name = %{public}s", __func__, Str16ToStr8(name).c_str());
328     bool ret = false;
329     if (name.empty() || name.size() > MAX_NAME_SIZE || DeleteBlank(name).empty()) {
330         ret = true;
331     }
332 
333     return ret;
334 }
335 
StartOnDemandAbility(const std::u16string & procName,int32_t systemAbilityId)336 void SystemAbilityManager::StartOnDemandAbility(const std::u16string& procName, int32_t systemAbilityId)
337 {
338     lock_guard<recursive_mutex> autoLock(onDemandLock_);
339     auto iter = startingAbilityMap_.find(systemAbilityId);
340     if (iter == startingAbilityMap_.end()) {
341         return;
342     }
343     auto& abilityItem = iter->second;
344     StartOnDemandAbilityInner(procName, systemAbilityId, abilityItem);
345 }
346 
StartOnDemandAbilityInner(const std::u16string & procName,int32_t systemAbilityId,AbilityItem & abilityItem)347 void SystemAbilityManager::StartOnDemandAbilityInner(const std::u16string& procName, int32_t systemAbilityId,
348     AbilityItem& abilityItem)
349 {
350     if (abilityItem.state != AbilityState::INIT) {
351         return;
352     }
353     sptr<ILocalAbilityManager> procObject =
354         iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
355     if (procObject == nullptr) {
356         HILOGI("get process:%{public}s fail", Str16ToStr8(procName).c_str());
357         return;
358     }
359     procObject->StartAbility(systemAbilityId);
360     abilityItem.state = AbilityState::STARTING;
361 }
362 
AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,const std::u16string & procName)363 int32_t SystemAbilityManager::AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,
364     const std::u16string& procName)
365 {
366     HILOGD("%{public}s called", __func__);
367     if (!CheckInputSysAbilityId(systemAbilityId) || IsNameInValid(procName)) {
368         HILOGW("AddOnDemandSystemAbilityInfo systemAbilityId or procName invalid.");
369         return ERR_INVALID_VALUE;
370     }
371 
372     lock_guard<recursive_mutex> autoLock(onDemandLock_);
373     auto onDemandSaSize = onDemandAbilityMap_.size();
374     if (onDemandSaSize >= MAX_SERVICES) {
375         HILOGE("map size error, (Has been greater than %{public}zu)",
376             onDemandAbilityMap_.size());
377         return ERR_INVALID_VALUE;
378     }
379 
380     if (systemProcessMap_.count(procName) == 0) {
381         HILOGW("AddOnDemandSystemAbilityInfo procName:%{public}s not exist.", Str16ToStr8(procName).c_str());
382         return ERR_INVALID_VALUE;
383     }
384     onDemandAbilityMap_[systemAbilityId] = procName;
385     HILOGI("insert onDemand systemAbilityId:%{public}d. size : %{public}zu", systemAbilityId,
386         onDemandAbilityMap_.size());
387     if (startingAbilityMap_.count(systemAbilityId) != 0) {
388         if (workHandler_ != nullptr) {
389             auto pendingTask = [procName, systemAbilityId, this] () {
390                 StartOnDemandAbility(procName, systemAbilityId);
391             };
392             bool ret = workHandler_->PostTask(pendingTask);
393             if (!ret) {
394                 HILOGW("AddOnDemandSystemAbilityInfo PostTask failed!");
395             }
396         }
397     }
398     return ERR_OK;
399 }
400 
StartOnDemandAbility(int32_t systemAbilityId)401 int32_t SystemAbilityManager::StartOnDemandAbility(int32_t systemAbilityId)
402 {
403     lock_guard<recursive_mutex> onDemandAbilityLock(onDemandLock_);
404     auto iter = onDemandAbilityMap_.find(systemAbilityId);
405     if (iter == onDemandAbilityMap_.end()) {
406         return ERR_INVALID_VALUE;
407     }
408     HILOGI("found onDemandAbility: %{public}d.", systemAbilityId);
409     AbilityItem& abilityItem = startingAbilityMap_[systemAbilityId];
410     StartOnDemandAbilityInner(iter->second, systemAbilityId, abilityItem);
411     return ERR_OK;
412 }
413 
CheckSystemAbility(int32_t systemAbilityId,bool & isExist)414 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId, bool& isExist)
415 {
416     if (!CheckInputSysAbilityId(systemAbilityId)) {
417         return nullptr;
418     }
419     sptr<IRemoteObject> abilityProxy = CheckSystemAbility(systemAbilityId);
420     if (abilityProxy == nullptr) {
421         lock_guard<recursive_mutex> autoLock(onDemandLock_);
422         auto iter = startingAbilityMap_.find(systemAbilityId);
423         if (iter != startingAbilityMap_.end() && iter->second.state == AbilityState::STARTING) {
424             isExist = true;
425             return nullptr;
426         }
427 
428         int32_t ret = StartOnDemandAbility(systemAbilityId);
429         if (ret == ERR_OK) {
430             isExist = true;
431             return nullptr;
432         }
433 
434         isExist = false;
435         return nullptr;
436     }
437 
438     isExist = true;
439     return abilityProxy;
440 }
441 
RemoveSystemAbility(int32_t systemAbilityId)442 int32_t SystemAbilityManager::RemoveSystemAbility(int32_t systemAbilityId)
443 {
444     if (!CheckInputSysAbilityId(systemAbilityId)) {
445         HILOGW("RemoveSystemAbility systemAbilityId:%{public}d", systemAbilityId);
446         return ERR_INVALID_VALUE;
447     }
448     {
449         unique_lock<shared_mutex> writeLock(abilityMapLock_);
450         auto itSystemAbility = abilityMap_.find(systemAbilityId);
451         if (itSystemAbility == abilityMap_.end()) {
452             HILOGI("SystemAbilityManager::RemoveSystemAbility not found!");
453             return ERR_INVALID_VALUE;
454         }
455         sptr<IRemoteObject> ability = itSystemAbility->second.remoteObj;
456         if (ability != nullptr && abilityDeath_ != nullptr) {
457             ability->RemoveDeathRecipient(abilityDeath_);
458         }
459         (void)abilityMap_.erase(itSystemAbility);
460         HILOGI("%s called, systemAbilityId : %{public}d, size : %{public}zu", __func__, systemAbilityId,
461             abilityMap_.size());
462     }
463     SendSystemAbilityRemovedMsg(systemAbilityId);
464     return ERR_OK;
465 }
466 
RemoveSystemAbility(const sptr<IRemoteObject> & ability)467 int32_t SystemAbilityManager::RemoveSystemAbility(const sptr<IRemoteObject>& ability)
468 {
469     HILOGI("%s called, (ability)", __func__);
470     if (ability == nullptr) {
471         HILOGW("ability is nullptr ");
472         return ERR_INVALID_VALUE;
473     }
474 
475     int32_t saId = 0;
476     {
477         unique_lock<shared_mutex> writeLock(abilityMapLock_);
478         for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); ++iter) {
479             if (iter->second.remoteObj == ability) {
480                 saId = iter->first;
481                 (void)abilityMap_.erase(iter);
482                 if (abilityDeath_ != nullptr) {
483                     ability->RemoveDeathRecipient(abilityDeath_);
484                 }
485                 HILOGI("%s called, systemAbilityId:%{public}d removed, size : %{public}zu", __func__, saId,
486                     abilityMap_.size());
487                 break;
488             }
489         }
490     }
491 
492     if (saId != 0) {
493         SendSystemAbilityRemovedMsg(saId);
494     }
495     return ERR_OK;
496 }
497 
ListSystemAbilities(uint32_t dumpFlags)498 vector<u16string> SystemAbilityManager::ListSystemAbilities(uint32_t dumpFlags)
499 {
500     vector<u16string> list;
501     shared_lock<shared_mutex> readLock(abilityMapLock_);
502     for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); iter++) {
503         list.emplace_back(Str8ToStr16(to_string(iter->first)));
504     }
505     return list;
506 }
507 
SubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)508 int32_t SystemAbilityManager::SubscribeSystemAbility(int32_t systemAbilityId,
509     const sptr<ISystemAbilityStatusChange>& listener)
510 {
511     if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
512         HILOGW("SubscribeSystemAbility systemAbilityId or listener invalid!");
513         return ERR_INVALID_VALUE;
514     }
515 
516     auto callingPid = IPCSkeleton::GetCallingPid();
517     {
518         lock_guard<recursive_mutex> autoLock(listenerMapLock_);
519         auto& listeners = listenerMap_[systemAbilityId];
520         for (const auto& itemListener : listeners) {
521             if (listener->AsObject() == itemListener.first->AsObject()) {
522                 HILOGI("already exist listener object systemAbilityId = %{public}d", systemAbilityId);
523                 return ERR_OK;
524             }
525         }
526         auto& count = subscribeCountMap_[callingPid];
527         if (count >= MAX_SUBSCRIBE_COUNT) {
528             HILOGE("SubscribeSystemAbility pid:%{public}d overflow max subscribe count!", callingPid);
529             return ERR_PERMISSION_DENIED;
530         }
531         ++count;
532         if (abilityStatusDeath_ != nullptr) {
533             bool ret = listener->AsObject()->AddDeathRecipient(abilityStatusDeath_);
534             listeners.emplace_back(listener, callingPid);
535             HILOGI("SubscribeSystemAbility systemAbilityId = %{public}d AddDeathRecipient %{public}s",
536                 systemAbilityId, ret ? "succeed" : "failed");
537         }
538         HILOGI("SubscribeSystemAbility systemAbilityId = %{public}d, size = %{public}zu", systemAbilityId,
539             listeners.size());
540     }
541     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
542     if (targetObject != nullptr) {
543         NotifySystemAbilityChanged(systemAbilityId, "", ADD_SYSTEM_ABILITY_TRANSACTION, listener);
544     }
545     return ERR_OK;
546 }
547 
UnSubscribeSystemAbilityLocked(std::list<std::pair<sptr<ISystemAbilityStatusChange>,int32_t>> & listenerList,const sptr<IRemoteObject> & listener)548 void SystemAbilityManager::UnSubscribeSystemAbilityLocked(
549     std::list<std::pair<sptr<ISystemAbilityStatusChange>, int32_t>>& listenerList,
550     const sptr<IRemoteObject>& listener)
551 {
552     auto iter = listenerList.begin();
553     while (iter != listenerList.end()) {
554         auto& item = *iter;
555         if (item.first->AsObject() != listener) {
556             ++iter;
557             continue;
558         }
559 
560         if (abilityStatusDeath_ != nullptr) {
561             listener->RemoveDeathRecipient(abilityStatusDeath_);
562         }
563         auto iterPair = subscribeCountMap_.find(item.second);
564         if (iterPair != subscribeCountMap_.end()) {
565             --iterPair->second;
566             if (iterPair->second == 0) {
567                 subscribeCountMap_.erase(iterPair);
568             }
569         }
570         iter = listenerList.erase(iter);
571         break;
572     }
573 }
574 
UnSubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)575 int32_t SystemAbilityManager::UnSubscribeSystemAbility(int32_t systemAbilityId,
576     const sptr<ISystemAbilityStatusChange>& listener)
577 {
578     if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
579         HILOGW("UnSubscribeSystemAbility systemAbilityId or listener invalid!");
580         return ERR_INVALID_VALUE;
581     }
582 
583     lock_guard<recursive_mutex> autoLock(listenerMapLock_);
584     auto& listeners = listenerMap_[systemAbilityId];
585     UnSubscribeSystemAbilityLocked(listeners, listener->AsObject());
586     HILOGI("UnSubscribeSystemAbility systemAbilityId = %{public}d, size = %{public}zu", systemAbilityId,
587         listeners.size());
588     return ERR_OK;
589 }
590 
UnSubscribeSystemAbility(const sptr<IRemoteObject> & remoteObject)591 void SystemAbilityManager::UnSubscribeSystemAbility(const sptr<IRemoteObject>& remoteObject)
592 {
593     lock_guard<recursive_mutex> autoLock(listenerMapLock_);
594     for (auto& item : listenerMap_) {
595         auto& listeners = item.second;
596         UnSubscribeSystemAbilityLocked(listeners, remoteObject);
597     }
598     HILOGI("UnSubscribeSystemAbility remote object dead!");
599 }
600 
SetDeviceName(const u16string & name)601 void SystemAbilityManager::SetDeviceName(const u16string &name)
602 {
603     deviceName_ = name;
604 }
605 
GetDeviceName() const606 const u16string& SystemAbilityManager::GetDeviceName() const
607 {
608     return deviceName_;
609 }
610 
NotifyRemoteSaDied(const std::u16string & name)611 void SystemAbilityManager::NotifyRemoteSaDied(const std::u16string& name)
612 {
613     std::u16string saName;
614     std::string deviceId;
615     ParseRemoteSaName(name, deviceId, saName);
616     if (dBinderService_ != nullptr) {
617         std::string nodeId = TransformDeviceId(deviceId, NODE_ID, false);
618         dBinderService_->NoticeServiceDie(saName, nodeId);
619         HILOGI("NotifyRemoteSaDied, serviceName is %s, deviceId is %s",
620             Str16ToStr8(saName).c_str(), nodeId.c_str());
621     }
622 }
623 
NotifyRemoteDeviceOffline(const std::string & deviceId)624 void SystemAbilityManager::NotifyRemoteDeviceOffline(const std::string& deviceId)
625 {
626     if (dBinderService_ != nullptr) {
627         dBinderService_->NoticeDeviceDie(deviceId);
628         HILOGI("NotifyRemoteDeviceOffline, deviceId is %s", deviceId.c_str());
629     }
630 }
631 
ParseRemoteSaName(const std::u16string & name,std::string & deviceId,std::u16string & saName)632 void SystemAbilityManager::ParseRemoteSaName(const std::u16string& name, std::string& deviceId, std::u16string& saName)
633 {
634     vector<string> strVector;
635     SplitStr(Str16ToStr8(name), "_", strVector);
636     if (strVector.size() == SPLIT_NAME_VECTOR_SIZE) {
637         deviceId = strVector[0];
638         saName = Str8ToStr16(strVector[1]);
639     }
640 }
641 
AddSystemAbility(int32_t systemAbilityId,const sptr<IRemoteObject> & ability,const SAExtraProp & extraProp)642 int32_t SystemAbilityManager::AddSystemAbility(int32_t systemAbilityId, const sptr<IRemoteObject>& ability,
643     const SAExtraProp& extraProp)
644 {
645     if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {
646         HILOGE("AddSystemAbilityExtra input params is invalid.");
647         return ERR_INVALID_VALUE;
648     }
649     {
650         unique_lock<shared_mutex> writeLock(abilityMapLock_);
651         auto saSize = abilityMap_.size();
652         if (saSize >= MAX_SERVICES) {
653             HILOGE("map size error, (Has been greater than %zu)", saSize);
654             return ERR_INVALID_VALUE;
655         }
656         SAInfo saInfo;
657         saInfo.remoteObj = ability;
658         saInfo.isDistributed = extraProp.isDistributed;
659         saInfo.capability = extraProp.capability;
660         saInfo.permission = Str16ToStr8(extraProp.permission);
661         abilityMap_[systemAbilityId] = std::move(saInfo);
662         HILOGI("insert %{public}d. size : %{public}zu", systemAbilityId, abilityMap_.size());
663     }
664     RemoveCheckLoadedMsg(systemAbilityId);
665     if (abilityDeath_ != nullptr) {
666         ability->AddDeathRecipient(abilityDeath_);
667     }
668 
669     u16string strName = Str8ToStr16(to_string(systemAbilityId));
670     if (extraProp.isDistributed && dBinderService_ != nullptr) {
671         dBinderService_->RegisterRemoteProxy(strName, systemAbilityId);
672         HILOGI("AddSystemAbility RegisterRemoteProxy, serviceId is %{public}d", systemAbilityId);
673     }
674     if (systemAbilityId == SOFTBUS_SERVER_SA_ID) {
675         if (dBinderService_ != nullptr && rpcCallbackImp_ != nullptr) {
676             bool ret = dBinderService_->StartDBinderService(rpcCallbackImp_);
677             HILOGI("start result is %{public}s", ret ? "succeed" : "fail");
678         }
679     }
680     SendSystemAbilityAddedMsg(systemAbilityId, ability);
681     return ERR_OK;
682 }
683 
AddSystemProcess(const u16string & procName,const sptr<IRemoteObject> & procObject)684 int32_t SystemAbilityManager::AddSystemProcess(const u16string& procName,
685     const sptr<IRemoteObject>& procObject)
686 {
687     if (procName.empty() || procObject == nullptr) {
688         HILOGE("AddSystemProcess empty name or null object!");
689         return ERR_INVALID_VALUE;
690     }
691 
692     lock_guard<recursive_mutex> autoLock(onDemandLock_);
693     size_t procNum = systemProcessMap_.size();
694     if (procNum >= MAX_SERVICES) {
695         HILOGE("AddSystemProcess map size reach MAX_SERVICES already");
696         return ERR_INVALID_VALUE;
697     }
698     systemProcessMap_[procName] = procObject;
699     if (systemProcessDeath_ != nullptr) {
700         bool ret = procObject->AddDeathRecipient(systemProcessDeath_);
701         HILOGW("AddSystemProcess AddDeathRecipient %{public}s!", ret ? "succeed" : "failed");
702     }
703     HILOGI("AddSystemProcess insert %{public}s. size : %{public}zu", Str16ToStr8(procName).c_str(),
704         systemProcessMap_.size());
705     auto iterStarting = startingProcessMap_.find(procName);
706     if (iterStarting != startingProcessMap_.end()) {
707         int64_t end = GetTickCount();
708         HILOGI("[PerformanceTest] AddSystemProcess start process:%{public}s spend %{public}" PRId64 " ms",
709             Str16ToStr8(procName).c_str(), (end - iterStarting->second));
710         startingProcessMap_.erase(iterStarting);
711     }
712     return ERR_OK;
713 }
714 
RemoveSystemProcess(const sptr<IRemoteObject> & procObject)715 int32_t SystemAbilityManager::RemoveSystemProcess(const sptr<IRemoteObject>& procObject)
716 {
717     if (procObject == nullptr) {
718         HILOGW("RemoveSystemProcess null object!");
719         return ERR_INVALID_VALUE;
720     }
721 
722     lock_guard<recursive_mutex> autoLock(onDemandLock_);
723     for (const auto& [procName, object] : systemProcessMap_) {
724         if (object == procObject) {
725             if (systemProcessDeath_ != nullptr) {
726                 procObject->RemoveDeathRecipient(systemProcessDeath_);
727             }
728             std::string name = Str16ToStr8(procName);
729             (void)systemProcessMap_.erase(procName);
730             HILOGI("RemoveSystemProcess process:%{public}s dead, size : %{public}zu", name.c_str(),
731                 systemProcessMap_.size());
732             return ERR_OK;
733         }
734     }
735     HILOGW("RemoveSystemProcess called and not found process.");
736     return ERR_INVALID_VALUE;
737 }
738 
GetSystemProcess(const u16string & procName)739 sptr<IRemoteObject> SystemAbilityManager::GetSystemProcess(const u16string& procName)
740 {
741     if (procName.empty()) {
742         HILOGE("GetSystemProcess empty name!");
743         return nullptr;
744     }
745 
746     lock_guard<recursive_mutex> autoLock(onDemandLock_);
747     auto iter = systemProcessMap_.find(procName);
748     if (iter != systemProcessMap_.end()) {
749         HILOGI("process:%{public}s found", Str16ToStr8(procName).c_str());
750         return iter->second;
751     }
752     HILOGE("process:%{public}s not exist", Str16ToStr8(procName).c_str());
753     return nullptr;
754 }
755 
SendSystemAbilityAddedMsg(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)756 void SystemAbilityManager::SendSystemAbilityAddedMsg(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
757 {
758     if (workHandler_ == nullptr) {
759         HILOGE("SendSystemAbilityAddedMsg work handler not initialized!");
760         return;
761     }
762     auto notifyAddedTask = [systemAbilityId, remoteObject, this]() {
763         FindSystemAbilityNotify(systemAbilityId, ADD_SYSTEM_ABILITY_TRANSACTION);
764         NotifySystemAbilityLoaded(systemAbilityId, remoteObject);
765     };
766     bool ret = workHandler_->PostTask(notifyAddedTask);
767     if (!ret) {
768         HILOGW("SendSystemAbilityAddedMsg PostTask failed!");
769     }
770 }
771 
SendSystemAbilityRemovedMsg(int32_t systemAbilityId)772 void SystemAbilityManager::SendSystemAbilityRemovedMsg(int32_t systemAbilityId)
773 {
774     if (workHandler_ == nullptr) {
775         HILOGE("SendSystemAbilityRemovedMsg work handler not initialized!");
776         return;
777     }
778     auto notifyRemovedTask = [systemAbilityId, this]() {
779         FindSystemAbilityNotify(systemAbilityId, REMOVE_SYSTEM_ABILITY_TRANSACTION);
780     };
781     bool ret = workHandler_->PostTask(notifyRemovedTask);
782     if (!ret) {
783         HILOGW("SendSystemAbilityRemovedMsg PostTask failed!");
784     }
785 }
786 
SendCheckLoadedMsg(int32_t systemAbilityId,const std::u16string & name,const std::string & srcDeviceId,const sptr<ISystemAbilityLoadCallback> & callback)787 void SystemAbilityManager::SendCheckLoadedMsg(int32_t systemAbilityId, const std::u16string& name,
788     const std::string& srcDeviceId, const sptr<ISystemAbilityLoadCallback>& callback)
789 {
790     if (workHandler_ == nullptr) {
791         HILOGE("SendCheckLoadedMsg work handler not initialized!");
792         return;
793     }
794 
795     auto delayTask = [systemAbilityId, name, srcDeviceId, callback, this]() {
796         HILOGI("SendCheckLoadedMsg handle for SA : %{public}d.", systemAbilityId);
797         if (CheckSystemAbility(systemAbilityId) != nullptr) {
798             HILOGI("SendCheckLoadedMsg SA : %{public}d loaded.", systemAbilityId);
799             return;
800         }
801         CleanCallbackForLoadFailed(systemAbilityId, name, srcDeviceId, callback);
802         (void)GetSystemProcess(name);
803     };
804     bool ret = workHandler_->PostTask(delayTask, ToString(systemAbilityId), CHECK_LOADED_DELAY_TIME);
805     HILOGI("SendCheckLoadedMsg PostTask name : %{public}d!, ret : %{public}s",
806         systemAbilityId, ret ? "success" : "failed");
807 }
808 
CleanCallbackForLoadFailed(int32_t systemAbilityId,const std::u16string & name,const std::string & srcDeviceId,const sptr<ISystemAbilityLoadCallback> & callback)809 void SystemAbilityManager::CleanCallbackForLoadFailed(int32_t systemAbilityId, const std::u16string& name,
810     const std::string& srcDeviceId, const sptr<ISystemAbilityLoadCallback>& callback)
811 {
812     lock_guard<recursive_mutex> autoLock(onDemandLock_);
813     auto iterStarting = startingProcessMap_.find(name);
814     if (iterStarting != startingProcessMap_.end()) {
815         HILOGI("CleanCallback clean process:%{public}s", Str16ToStr8(name).c_str());
816         startingProcessMap_.erase(iterStarting);
817     }
818     auto iter = startingAbilityMap_.find(systemAbilityId);
819     if (iter == startingAbilityMap_.end()) {
820         HILOGI("CleanCallback SA : %{public}d not in startingAbilityMap.", systemAbilityId);
821         return;
822     }
823     auto& abilityItem = iter->second;
824     for (auto& callbackItem : abilityItem.callbackMap[srcDeviceId]) {
825         if (callback->AsObject() == callbackItem.first->AsObject()) {
826             NotifySystemAbilityLoadFail(systemAbilityId, callbackItem.first);
827             RemoveStartingAbilityCallbackLocked(callbackItem);
828             abilityItem.callbackMap[srcDeviceId].remove(callbackItem);
829             break;
830         }
831     }
832     if (abilityItem.callbackMap[srcDeviceId].empty()) {
833         HILOGI("CleanCallback startingAbilityMap remove SA : %{public}d. with deviceId", systemAbilityId);
834         abilityItem.callbackMap.erase(srcDeviceId);
835     }
836 
837     if (abilityItem.callbackMap.empty()) {
838         HILOGI("CleanCallback startingAbilityMap remove SA : %{public}d.", systemAbilityId);
839         startingAbilityMap_.erase(iter);
840     }
841 }
842 
RemoveCheckLoadedMsg(int32_t systemAbilityId)843 void SystemAbilityManager::RemoveCheckLoadedMsg(int32_t systemAbilityId)
844 {
845     if (workHandler_ == nullptr) {
846         HILOGE("RemoveCheckLoadedMsg work handler not initialized!");
847         return;
848     }
849     workHandler_->RemoveTask(ToString(systemAbilityId));
850 }
851 
SendLoadedSystemAblityMsg(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject,const sptr<ISystemAbilityLoadCallback> & callback)852 void SystemAbilityManager::SendLoadedSystemAblityMsg(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject,
853     const sptr<ISystemAbilityLoadCallback>& callback)
854 {
855     if (workHandler_ == nullptr) {
856         HILOGE("SendLoadedSystemAblityMsg work handler not initialized!");
857         return;
858     }
859     auto notifyLoadedTask = [systemAbilityId, remoteObject, callback, this]() {
860         NotifySystemAbilityLoaded(systemAbilityId, remoteObject, callback);
861     };
862     bool ret = workHandler_->PostTask(notifyLoadedTask);
863     if (!ret) {
864         HILOGW("SendLoadedSystemAblityMsg PostTask failed!");
865     }
866 }
867 
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject,const sptr<ISystemAbilityLoadCallback> & callback)868 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject,
869     const sptr<ISystemAbilityLoadCallback>& callback)
870 {
871     if (callback == nullptr) {
872         HILOGE("NotifySystemAbilityLoaded callback null!");
873         return;
874     }
875     HILOGI("NotifySystemAbilityLoaded systemAbilityId : %{public}d", systemAbilityId);
876     callback->OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject);
877 }
878 
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)879 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
880 {
881     lock_guard<recursive_mutex> autoLock(onDemandLock_);
882     auto iter = startingAbilityMap_.find(systemAbilityId);
883     if (iter == startingAbilityMap_.end()) {
884         return;
885     }
886     auto& abilityItem = iter->second;
887     for (auto& [deviceId, callbackList] : abilityItem.callbackMap) {
888         for (auto& callbackItem : callbackList) {
889             NotifySystemAbilityLoaded(systemAbilityId, remoteObject, callbackItem.first);
890             RemoveStartingAbilityCallbackLocked(callbackItem);
891         }
892     }
893     startingAbilityMap_.erase(iter);
894 }
895 
NotifySystemAbilityLoadFail(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)896 void SystemAbilityManager::NotifySystemAbilityLoadFail(int32_t systemAbilityId,
897     const sptr<ISystemAbilityLoadCallback>& callback)
898 {
899     if (callback == nullptr) {
900         HILOGE("NotifySystemAbilityLoadFail callback null!");
901         return;
902     }
903     HILOGI("NotifySystemAbilityLoadFailed systemAbilityId : %{public}d", systemAbilityId);
904     callback->OnLoadSystemAbilityFail(systemAbilityId);
905 }
906 
StartDynamicSystemProcess(const std::u16string & name,int32_t systemAbilityId)907 int32_t SystemAbilityManager::StartDynamicSystemProcess(const std::u16string& name, int32_t systemAbilityId)
908 {
909     std::string strExtra = std::to_string(systemAbilityId);
910     auto extraArgv = strExtra.c_str();
911     auto result = ServiceControlWithExtra(Str16ToStr8(name).c_str(), START, &extraArgv, 1);
912     HILOGI("StartDynamicSystemProcess call ServiceControlWithExtra result:%{public}d!", result);
913     return (result == 0) ? ERR_OK : ERR_INVALID_VALUE;
914 }
915 
StartingSystemProcess(const std::u16string & procName,int32_t systemAbilityId)916 int32_t SystemAbilityManager::StartingSystemProcess(const std::u16string& procName, int32_t systemAbilityId)
917 {
918     lock_guard<recursive_mutex> autoLock(onDemandLock_);
919     if (startingProcessMap_.count(procName) != 0) {
920         HILOGI("StartingSystemProcess process:%{public}s already starting!", Str16ToStr8(procName).c_str());
921         return ERR_OK;
922     }
923     auto iter = systemProcessMap_.find(procName);
924     if (iter != systemProcessMap_.end()) {
925         StartOnDemandAbility(systemAbilityId);
926         return ERR_OK;
927     }
928     // call init start process
929     int64_t begin = GetTickCount();
930     int32_t result = StartDynamicSystemProcess(procName, systemAbilityId);
931     if (result == ERR_OK) {
932         startingProcessMap_.emplace(procName, begin);
933     }
934     return result;
935 }
936 
LoadSystemAbilityFromRpc(const std::string & srcDeviceId,int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)937 bool SystemAbilityManager::LoadSystemAbilityFromRpc(const std::string& srcDeviceId, int32_t systemAbilityId,
938     const sptr<ISystemAbilityLoadCallback>& callback)
939 {
940     if (!CheckInputSysAbilityId(systemAbilityId) || callback == nullptr) {
941         HILOGW("LoadSystemAbility said or callback invalid!");
942         return false;
943     }
944     SaProfile saProfile;
945     bool ret = GetSaProfile(systemAbilityId, saProfile);
946     if (!ret) {
947         HILOGE("LoadSystemAbilityFromRpc said:%{public}d not supported!", systemAbilityId);
948         return false;
949     }
950 
951     if (!saProfile.distributed) {
952         HILOGE("LoadSystemAbilityFromRpc said:%{public}d not distributed!", systemAbilityId);
953         return false;
954     }
955 
956     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
957     if (targetObject != nullptr) {
958         SendLoadedSystemAblityMsg(systemAbilityId, targetObject, callback);
959         return true;
960     }
961     {
962         lock_guard<recursive_mutex> autoLock(onDemandLock_);
963         auto& abilityItem = startingAbilityMap_[systemAbilityId];
964         abilityItem.callbackMap[srcDeviceId].emplace_back(callback, 0);
965         StartingSystemProcess(saProfile.process, systemAbilityId);
966     }
967     SendCheckLoadedMsg(systemAbilityId, saProfile.process, srcDeviceId, callback);
968     return true;
969 }
970 
LoadSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)971 int32_t SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId,
972     const sptr<ISystemAbilityLoadCallback>& callback)
973 {
974     if (!CheckInputSysAbilityId(systemAbilityId) || callback == nullptr) {
975         HILOGW("LoadSystemAbility systemAbilityId or callback invalid!");
976         return ERR_INVALID_VALUE;
977     }
978     SaProfile saProfile;
979     bool ret = GetSaProfile(systemAbilityId, saProfile);
980     if (!ret) {
981         HILOGE("LoadSystemAbility systemAbilityId:%{public}d not supported!", systemAbilityId);
982         return ERR_INVALID_VALUE;
983     }
984 
985     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
986     if (targetObject != nullptr) {
987         NotifySystemAbilityLoaded(systemAbilityId, targetObject, callback);
988         return ERR_OK;
989     }
990     int32_t result = ERR_INVALID_VALUE;
991     auto callingPid = IPCSkeleton::GetCallingPid();
992     {
993         lock_guard<recursive_mutex> autoLock(onDemandLock_);
994         auto& abilityItem = startingAbilityMap_[systemAbilityId];
995         for (const auto& itemCallback : abilityItem.callbackMap[LOCAL_DEVICE]) {
996             if (callback->AsObject() == itemCallback.first->AsObject()) {
997                 HILOGI("LoadSystemAbility already existed callback object systemAbilityId:%{public}d", systemAbilityId);
998                 return ERR_OK;
999             }
1000         }
1001         auto& count = callbackCountMap_[callingPid];
1002         if (count >= MAX_SUBSCRIBE_COUNT) {
1003             HILOGE("LoadSystemAbility pid:%{public}d overflow max callback count!", callingPid);
1004             return ERR_PERMISSION_DENIED;
1005         }
1006         ++count;
1007         abilityItem.callbackMap[LOCAL_DEVICE].emplace_back(callback, callingPid);
1008         if (abilityCallbackDeath_ != nullptr) {
1009             ret = callback->AsObject()->AddDeathRecipient(abilityCallbackDeath_);
1010             HILOGI("LoadSystemAbility systemAbilityId:%{public}d AddDeathRecipient %{public}s",
1011                 systemAbilityId, ret ? "succeed" : "failed");
1012         }
1013         result = StartingSystemProcess(saProfile.process, systemAbilityId);
1014         HILOGI("LoadSystemAbility systemAbilityId:%{public}d size : %{public}zu",
1015             systemAbilityId, abilityItem.callbackMap[LOCAL_DEVICE].size());
1016     }
1017     SendCheckLoadedMsg(systemAbilityId, saProfile.process, LOCAL_DEVICE, callback);
1018     return result;
1019 }
1020 
LoadSystemAbility(int32_t systemAbilityId,const std::string & deviceId,const sptr<ISystemAbilityLoadCallback> & callback)1021 int32_t SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId, const std::string& deviceId,
1022     const sptr<ISystemAbilityLoadCallback>& callback)
1023 {
1024     std::string key = ToString(systemAbilityId) + "_" + deviceId;
1025     {
1026         lock_guard<mutex> autoLock(loadRemoteLock_);
1027         auto& callbacks = remoteCallbacks_[key];
1028         auto iter = std::find_if(callbacks.begin(), callbacks.end(), [callback](auto itemCallback) {
1029             return callback->AsObject() == itemCallback->AsObject();
1030         });
1031         if (iter != callbacks.end()) {
1032             HILOGI("LoadSystemAbility already existed callback object systemAbilityId:%{public}d", systemAbilityId);
1033             return ERR_OK;
1034         }
1035         if (remoteCallbackDeath_ != nullptr) {
1036             bool ret = callback->AsObject()->AddDeathRecipient(remoteCallbackDeath_);
1037             HILOGI("LoadSystemAbility systemAbilityId:%{public}d AddDeathRecipient %{public}s",
1038                 systemAbilityId, ret ? "succeed" : "failed");
1039         }
1040         callbacks.emplace_back(callback);
1041     }
1042     auto callingPid = IPCSkeleton::GetCallingPid();
1043     auto callingUid = IPCSkeleton::GetCallingUid();
1044     auto task = std::bind(&SystemAbilityManager::DoLoadRemoteSystemAbility, this,
1045         systemAbilityId, callingPid, callingUid, deviceId, callback);
1046     loadPool_.AddTask(task);
1047     return ERR_OK;
1048 }
1049 
DoLoadRemoteSystemAbility(int32_t systemAbilityId,int32_t callingPid,int32_t callingUid,const std::string & deviceId,const sptr<ISystemAbilityLoadCallback> & callback)1050 void SystemAbilityManager::DoLoadRemoteSystemAbility(int32_t systemAbilityId, int32_t callingPid,
1051     int32_t callingUid, const std::string& deviceId, const sptr<ISystemAbilityLoadCallback>& callback)
1052 {
1053     sptr<DBinderServiceStub> remoteBinder = DoMakeRemoteBinder(systemAbilityId, callingPid, callingUid, deviceId);
1054 
1055     if (callback == nullptr) {
1056         HILOGI("DoLoadRemoteSystemAbility return, callback is nullptr, said : %{public}d", systemAbilityId);
1057         return;
1058     }
1059     callback->OnLoadSACompleteForRemote(deviceId, systemAbilityId, remoteBinder);
1060     std::string key = ToString(systemAbilityId) + "_" + deviceId;
1061     {
1062         lock_guard<mutex> autoLock(loadRemoteLock_);
1063         if (remoteCallbackDeath_ != nullptr) {
1064             callback->AsObject()->RemoveDeathRecipient(remoteCallbackDeath_);
1065         }
1066         auto& callbacks = remoteCallbacks_[key];
1067         callbacks.remove(callback);
1068         if (callbacks.empty()) {
1069             remoteCallbacks_.erase(key);
1070         }
1071     }
1072 }
1073 
DoMakeRemoteBinder(int32_t systemAbilityId,int32_t callingPid,int32_t callingUid,const std::string & deviceId)1074 sptr<DBinderServiceStub> SystemAbilityManager::DoMakeRemoteBinder(int32_t systemAbilityId, int32_t callingPid,
1075     int32_t callingUid, const std::string& deviceId)
1076 {
1077     HILOGI("MakeRemoteBinder begin, said : %{public}d", systemAbilityId);
1078     sptr<DBinderServiceStub> remoteBinder = nullptr;
1079     if (dBinderService_ != nullptr) {
1080         string strName = to_string(systemAbilityId);
1081         remoteBinder = dBinderService_->MakeRemoteBinder(Str8ToStr16(strName),
1082             deviceId, systemAbilityId, callingPid, callingUid);
1083     }
1084     HILOGI("MakeRemoteBinder end, result %{public}s, said : %{public}d, deviceId : %{public}s",
1085         remoteBinder == nullptr ? " failed" : "succeed", systemAbilityId, AnonymizeDeviceId(deviceId).c_str());
1086     return remoteBinder;
1087 }
1088 
NotifyRpcLoadCompleted(const std::string & srcDeviceId,int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)1089 void SystemAbilityManager::NotifyRpcLoadCompleted(const std::string& srcDeviceId, int32_t systemAbilityId,
1090     const sptr<IRemoteObject>& remoteObject)
1091 {
1092     if (dBinderService_ != nullptr) {
1093         dBinderService_->LoadSystemAbilityComplete(srcDeviceId, systemAbilityId, remoteObject);
1094         return;
1095     }
1096     HILOGW("NotifyRpcLoadCompleted failed, said: %{public}d, deviceId : %{public}s",
1097         systemAbilityId, AnonymizeDeviceId(srcDeviceId).c_str());
1098 }
1099 
RemoveStartingAbilityCallbackLocked(std::pair<sptr<ISystemAbilityLoadCallback>,int32_t> & itemPair)1100 void SystemAbilityManager::RemoveStartingAbilityCallbackLocked(
1101     std::pair<sptr<ISystemAbilityLoadCallback>, int32_t>& itemPair)
1102 {
1103     if (abilityCallbackDeath_ != nullptr) {
1104         itemPair.first->AsObject()->RemoveDeathRecipient(abilityCallbackDeath_);
1105     }
1106     auto iterCount = callbackCountMap_.find(itemPair.second);
1107     if (iterCount != callbackCountMap_.end()) {
1108         --iterCount->second;
1109         if (iterCount->second == 0) {
1110             callbackCountMap_.erase(iterCount);
1111         }
1112     }
1113 }
1114 
RemoveStartingAbilityCallbackForDevice(AbilityItem & abilityItem,const sptr<IRemoteObject> & remoteObject)1115 void SystemAbilityManager::RemoveStartingAbilityCallbackForDevice(AbilityItem& abilityItem,
1116     const sptr<IRemoteObject>& remoteObject)
1117 {
1118     auto& callbacks = abilityItem.callbackMap;
1119     auto iter = callbacks.begin();
1120     while (iter != callbacks.end()) {
1121         CallbackList& callbackList = iter->second;
1122         RemoveStartingAbilityCallback(callbackList, remoteObject);
1123         if (callbackList.empty()) {
1124             callbacks.erase(iter++);
1125         } else {
1126             ++iter;
1127         }
1128     }
1129 }
1130 
RemoveStartingAbilityCallback(CallbackList & callbackList,const sptr<IRemoteObject> & remoteObject)1131 void SystemAbilityManager::RemoveStartingAbilityCallback(CallbackList& callbackList,
1132     const sptr<IRemoteObject>& remoteObject)
1133 {
1134     auto iterCallback = callbackList.begin();
1135     while (iterCallback != callbackList.end()) {
1136         auto& callbackPair = *iterCallback;
1137         if (callbackPair.first->AsObject() == remoteObject) {
1138             RemoveStartingAbilityCallbackLocked(callbackPair);
1139             iterCallback = callbackList.erase(iterCallback);
1140             break;
1141         } else {
1142             ++iterCallback;
1143         }
1144     }
1145 }
1146 
OnAbilityCallbackDied(const sptr<IRemoteObject> & remoteObject)1147 void SystemAbilityManager::OnAbilityCallbackDied(const sptr<IRemoteObject>& remoteObject)
1148 {
1149     HILOGI("OnAbilityCallbackDied received remoteObject died message!");
1150     if (remoteObject == nullptr) {
1151         return;
1152     }
1153     lock_guard<recursive_mutex> autoLock(onDemandLock_);
1154     auto iter = startingAbilityMap_.begin();
1155     while (iter != startingAbilityMap_.end()) {
1156         AbilityItem& abilityItem = iter->second;
1157         RemoveStartingAbilityCallbackForDevice(abilityItem, remoteObject);
1158         if (abilityItem.callbackMap.empty()) {
1159             startingAbilityMap_.erase(iter++);
1160         } else {
1161             ++iter;
1162         }
1163     }
1164 }
1165 
OnRemoteCallbackDied(const sptr<IRemoteObject> & remoteObject)1166 void SystemAbilityManager::OnRemoteCallbackDied(const sptr<IRemoteObject>& remoteObject)
1167 {
1168     HILOGI("OnRemoteCallbackDied received remoteObject died message!");
1169     if (remoteObject == nullptr) {
1170         return;
1171     }
1172     lock_guard<mutex> autoLock(loadRemoteLock_);
1173     auto iter = remoteCallbacks_.begin();
1174     while (iter != remoteCallbacks_.end()) {
1175         auto& callbacks = iter->second;
1176         RemoveRemoteCallbackLocked(callbacks, remoteObject);
1177         if (callbacks.empty()) {
1178             remoteCallbacks_.erase(iter++);
1179         } else {
1180             ++iter;
1181         }
1182     }
1183 }
1184 
RemoveRemoteCallbackLocked(std::list<sptr<ISystemAbilityLoadCallback>> & callbacks,const sptr<IRemoteObject> & remoteObject)1185 void SystemAbilityManager::RemoveRemoteCallbackLocked(std::list<sptr<ISystemAbilityLoadCallback>>& callbacks,
1186     const sptr<IRemoteObject>& remoteObject)
1187 {
1188     for (const auto& callback : callbacks) {
1189         if (callback->AsObject() == remoteObject) {
1190             if (remoteCallbackDeath_ != nullptr) {
1191                 callback->AsObject()->RemoveDeathRecipient(remoteCallbackDeath_);
1192             }
1193             callbacks.remove(callback);
1194             break;
1195         }
1196     }
1197 }
1198 
TransformDeviceId(const std::string & deviceId,int32_t type,bool isPrivate)1199 std::string SystemAbilityManager::TransformDeviceId(const std::string& deviceId, int32_t type, bool isPrivate)
1200 {
1201     return isPrivate ? std::string() : deviceId;
1202 }
1203 
GetLocalNodeId()1204 std::string SystemAbilityManager::GetLocalNodeId()
1205 {
1206     return std::string();
1207 }
1208 
UpdateSaFreMap(int32_t pid,int32_t saId)1209 void SystemAbilityManager::UpdateSaFreMap(int32_t pid, int32_t saId)
1210 {
1211     if (pid <= 0) {
1212         HILOGW("UpdateSaFreMap return, pid not valid!");
1213         return;
1214     }
1215 
1216     uint64_t key = GenerateFreKey(pid, saId);
1217     lock_guard<mutex> autoLock(saFrequencyLock_);
1218     auto& count = saFrequencyMap_[key];
1219     if (count < MAX_SA_FREQUENCY_COUNT) {
1220         count++;
1221     }
1222 }
1223 
GenerateFreKey(int32_t pid,int32_t saId) const1224 uint64_t SystemAbilityManager::GenerateFreKey(int32_t pid, int32_t saId) const
1225 {
1226     uint32_t uSaid = static_cast<uint32_t>(saId);
1227     uint64_t key = static_cast<uint64_t>(pid);
1228     return (key << SHFIT_BIT) | uSaid;
1229 }
1230 
ReportGetSAPeriodically()1231 void SystemAbilityManager::ReportGetSAPeriodically()
1232 {
1233     HILOGI("ReportGetSAPeriodically start!");
1234     lock_guard<mutex> autoLock(saFrequencyLock_);
1235     for (const auto& [key, count] : saFrequencyMap_) {
1236         uint32_t saId = static_cast<uint32_t>(key);
1237         uint32_t pid = key >> SHFIT_BIT;
1238         ReportGetSAFrequency(pid, saId, count);
1239     }
1240     saFrequencyMap_.clear();
1241 }
1242 } // namespace OHOS
1243