• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 <thread>
20 #include <unistd.h>
21 
22 #include "ability_death_recipient.h"
23 #include "accesstoken_kit.h"
24 #include "datetime_ex.h"
25 #include "directory_ex.h"
26 #include "errors.h"
27 #include "file_ex.h"
28 #include "hisysevent_adapter.h"
29 #include "hitrace_meter.h"
30 #include "if_local_ability_manager.h"
31 #include "ipc_skeleton.h"
32 #include "local_ability_manager_proxy.h"
33 #include "memory_guard.h"
34 #include "parse_util.h"
35 #include "parameter.h"
36 #include "parameters.h"
37 #include "sam_log.h"
38 #include "service_control.h"
39 #include "string_ex.h"
40 #include "system_ability_manager_dumper.h"
41 #include "tools.h"
42 
43 #ifdef SUPPORT_DEVICE_MANAGER
44 #include "device_manager.h"
45 using namespace OHOS::DistributedHardware;
46 #endif
47 
48 using namespace std;
49 
50 namespace OHOS {
51 namespace {
52 const string START_SAID = "said";
53 const string EVENT_TYPE = "eventId";
54 const string EVENT_NAME = "name";
55 const string EVENT_VALUE = "value";
56 const string EVENT_EXTRA_DATA_ID = "extraDataId";
57 const string PKG_NAME = "Samgr_Networking";
58 const string PREFIX = "/system/profile/";
59 const string LOCAL_DEVICE = "local";
60 const string ONDEMAND_PARAM = "persist.samgr.perf.ondemand";
61 const string DYNAMIC_CACHE_PARAM = "persist.samgr.cache.sa";
62 const string RESOURCE_SCHEDULE_PROCESS_NAME = "resource_schedule_service";
63 constexpr const char* ONDEMAND_PERF_PARAM = "persist.samgr.perf.ondemand";
64 constexpr const char* ONDEMAND_WORKER = "OndemandLoader";
65 
66 constexpr uint32_t REPORT_GET_SA_INTERVAL = 24 * 60 * 60 * 1000; // ms and is one day
67 constexpr int32_t MAX_NAME_SIZE = 200;
68 constexpr int32_t SPLIT_NAME_VECTOR_SIZE = 2;
69 constexpr int32_t UID_ROOT = 0;
70 constexpr int32_t UID_SYSTEM = 1000;
71 constexpr int32_t MAX_SUBSCRIBE_COUNT = 256;
72 constexpr int32_t MAX_SA_FREQUENCY_COUNT = INT32_MAX - 1000000;
73 constexpr int32_t SHFIT_BIT = 32;
74 constexpr int32_t DEVICE_INFO_SERVICE_SA = 3902;
75 constexpr int32_t HIDUMPER_SERVICE_SA = 1212;
76 constexpr int32_t MEDIA_ANALYSIS_SERVICE_SA = 10120;
77 constexpr int64_t ONDEMAND_PERF_DELAY_TIME = 60 * 1000; // ms
78 constexpr int64_t CHECK_LOADED_DELAY_TIME = 4 * 1000; // ms
79 constexpr int32_t SOFTBUS_SERVER_SA_ID = 4700;
80 }
81 
82 std::mutex SystemAbilityManager::instanceLock;
83 sptr<SystemAbilityManager> SystemAbilityManager::instance;
84 
SystemAbilityManager()85 SystemAbilityManager::SystemAbilityManager()
86 {
87     dBinderService_ = DBinderService::GetInstance();
88 }
89 
~SystemAbilityManager()90 SystemAbilityManager::~SystemAbilityManager()
91 {
92     if (reportEventTimer_ != nullptr) {
93         reportEventTimer_->Shutdown();
94     }
95 }
96 
Init()97 void SystemAbilityManager::Init()
98 {
99     abilityDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityDeathRecipient());
100     systemProcessDeath_ = sptr<IRemoteObject::DeathRecipient>(new SystemProcessDeathRecipient());
101     abilityStatusDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityStatusDeathRecipient());
102     abilityCallbackDeath_ = sptr<IRemoteObject::DeathRecipient>(new AbilityCallbackDeathRecipient());
103     remoteCallbackDeath_ = sptr<IRemoteObject::DeathRecipient>(new RemoteCallbackDeathRecipient());
104 
105     rpcCallbackImp_ = make_shared<RpcCallbackImp>();
106     if (workHandler_ == nullptr) {
107         workHandler_ = make_shared<FFRTHandler>("workHandler");
108     }
109     collectManager_ = sptr<DeviceStatusCollectManager>(new DeviceStatusCollectManager());
110     abilityStateScheduler_ = std::make_shared<SystemAbilityStateScheduler>();
111     InitSaProfile();
112     reportEventTimer_ = std::make_unique<Utils::Timer>("DfxReporter");
113     OndemandLoadForPerf();
114     SetKey(DYNAMIC_CACHE_PARAM);
115 }
116 
CleanFfrt()117 void SystemAbilityManager::CleanFfrt()
118 {
119     if (workHandler_ != nullptr) {
120         workHandler_->CleanFfrt();
121     }
122     if (collectManager_ != nullptr) {
123         collectManager_->CleanFfrt();
124     }
125     if (abilityStateScheduler_ != nullptr) {
126         abilityStateScheduler_->CleanFfrt();
127     }
128 }
129 
SetFfrt()130 void SystemAbilityManager::SetFfrt()
131 {
132     if (workHandler_ != nullptr) {
133         workHandler_->SetFfrt("workHandler");
134     }
135     if (collectManager_ != nullptr) {
136         collectManager_->SetFfrt();
137     }
138     if (abilityStateScheduler_ != nullptr) {
139         abilityStateScheduler_->SetFfrt();
140     }
141 }
142 
Dump(int32_t fd,const std::vector<std::u16string> & args)143 int32_t SystemAbilityManager::Dump(int32_t fd, const std::vector<std::u16string>& args)
144 {
145     std::vector<std::string> argsWithStr8;
146     for (const auto& arg : args) {
147         argsWithStr8.emplace_back(Str16ToStr8(arg));
148     }
149     std::string result;
150     SystemAbilityManagerDumper::Dump(abilityStateScheduler_, argsWithStr8, result);
151     if (!SaveStringToFd(fd, result)) {
152         HILOGE("save to fd failed");
153         return ERR_INVALID_VALUE;
154     }
155     return ERR_OK;
156 }
157 
AddSamgrToAbilityMap()158 void SystemAbilityManager::AddSamgrToAbilityMap()
159 {
160     unique_lock<shared_mutex> writeLock(abilityMapLock_);
161     int32_t systemAbilityId = 0;
162     SAInfo saInfo;
163     saInfo.remoteObj = this;
164     saInfo.isDistributed = false;
165     saInfo.capability = u"";
166     abilityMap_[systemAbilityId] = std::move(saInfo);
167     HILOGD("samgr inserted");
168 }
169 
GetDBinder() const170 const sptr<DBinderService> SystemAbilityManager::GetDBinder() const
171 {
172     return dBinderService_;
173 }
174 
StartDfxTimer()175 void SystemAbilityManager::StartDfxTimer()
176 {
177     reportEventTimer_->Setup();
178     uint32_t timerId = reportEventTimer_->Register(std::bind(&SystemAbilityManager::ReportGetSAPeriodically, this),
179         REPORT_GET_SA_INTERVAL);
180     HILOGI("StartDfxTimer timerId : %{public}u!", timerId);
181 }
182 
GetInstance()183 sptr<SystemAbilityManager> SystemAbilityManager::GetInstance()
184 {
185     std::lock_guard<std::mutex> autoLock(instanceLock);
186     if (instance == nullptr) {
187         instance = new SystemAbilityManager;
188     }
189     return instance;
190 }
191 
InitSaProfile()192 void SystemAbilityManager::InitSaProfile()
193 {
194     int64_t begin = GetTickCount();
195     std::vector<std::string> fileNames;
196     GetDirFiles(PREFIX, fileNames);
197     auto parser = std::make_shared<ParseUtil>();
198     for (const auto& file : fileNames) {
199         if (file.empty() || file.find(".json") == std::string::npos ||
200             file.find("_trust.json") != std::string::npos) {
201             continue;
202         }
203         parser->ParseSaProfiles(file);
204     }
205     std::list<SaProfile> saInfos = parser->GetAllSaProfiles();
206     if (abilityStateScheduler_ != nullptr) {
207         abilityStateScheduler_->Init(saInfos);
208     }
209     if (collectManager_ != nullptr) {
210         collectManager_->Init(saInfos);
211     }
212     lock_guard<mutex> autoLock(saProfileMapLock_);
213     onDemandSaIdsSet_.insert(DEVICE_INFO_SERVICE_SA);
214     onDemandSaIdsSet_.insert(HIDUMPER_SERVICE_SA);
215     onDemandSaIdsSet_.insert(MEDIA_ANALYSIS_SERVICE_SA);
216     for (const auto& saInfo : saInfos) {
217         saProfileMap_[saInfo.saId] = saInfo;
218         if (!saInfo.runOnCreate) {
219             HILOGI("[InitSaProfile] saId %{public}d", saInfo.saId);
220             onDemandSaIdsSet_.insert(saInfo.saId);
221         }
222     }
223     HILOGI("[PerformanceTest] InitSaProfile spend %{public}" PRId64 " ms", GetTickCount() - begin);
224 }
225 
OndemandLoadForPerf()226 void SystemAbilityManager::OndemandLoadForPerf()
227 {
228     if (workHandler_ == nullptr) {
229         HILOGE("LoadForPerf workHandler_ not init!");
230         return;
231     }
232     auto callback = [this] () {
233         OndemandLoad();
234     };
235     workHandler_->PostTask(callback, ONDEMAND_PERF_DELAY_TIME);
236 }
237 
OndemandLoad()238 void SystemAbilityManager::OndemandLoad()
239 {
240     auto bootEventCallback = [](const char *key, const char *value, void *context) {
241         int64_t begin = GetTickCount();
242         SystemAbilityManager::GetInstance()->DoLoadForPerf();
243         HILOGI("[PerformanceTest] DoLoadForPerf spend %{public}" PRId64 " ms", GetTickCount() - begin);
244     };
245 
246     int ret = WatchParameter(ONDEMAND_PERF_PARAM, bootEventCallback, nullptr);
247     HILOGD("OndemandLoad ret %{public}d", ret);
248 }
249 
GetAllOndemandSa()250 std::list<int32_t> SystemAbilityManager::GetAllOndemandSa()
251 {
252     std::list<int32_t> ondemandSaids;
253     {
254         lock_guard<mutex> autoLock(saProfileMapLock_);
255         for (const auto& [said, value] : saProfileMap_) {
256             shared_lock<shared_mutex> readLock(abilityMapLock_);
257             auto iter = abilityMap_.find(said);
258             if (iter == abilityMap_.end()) {
259                 ondemandSaids.emplace_back(said);
260             }
261         }
262     }
263     return ondemandSaids;
264 }
265 
DoLoadForPerf()266 void SystemAbilityManager::DoLoadForPerf()
267 {
268     bool value = system::GetBoolParameter(ONDEMAND_PARAM, false);
269     if (value) {
270         std::list<int32_t> saids = GetAllOndemandSa();
271         HILOGD("DoLoadForPerf ondemand size : %{public}zu.", saids.size());
272         sptr<ISystemAbilityLoadCallback> callback(new SystemAbilityLoadCallbackStub());
273         for (auto said : saids) {
274             LoadSystemAbility(said, callback);
275         }
276     }
277 }
278 
GetSaProfile(int32_t saId,SaProfile & saProfile)279 bool SystemAbilityManager::GetSaProfile(int32_t saId, SaProfile& saProfile)
280 {
281     lock_guard<mutex> autoLock(saProfileMapLock_);
282     auto iter = saProfileMap_.find(saId);
283     if (iter == saProfileMap_.end()) {
284         return false;
285     } else {
286         saProfile = iter->second;
287     }
288     return true;
289 }
290 
CheckCallerProcess(SaProfile & saProfile)291 bool SystemAbilityManager::CheckCallerProcess(SaProfile& saProfile)
292 {
293     if (!CheckCallerProcess(Str16ToStr8(saProfile.process))) {
294         HILOGE("cannot operate SA: %{public}d by process: %{public}s",
295             saProfile.saId, Str16ToStr8(saProfile.process).c_str());
296         return false;
297     }
298     return true;
299 }
300 
CheckCallerProcess(const std::string & callProcess)301 bool SystemAbilityManager::CheckCallerProcess(const std::string& callProcess)
302 {
303     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
304     Security::AccessToken::NativeTokenInfo nativeTokenInfo;
305     int32_t tokenInfoResult = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
306     if (tokenInfoResult != ERR_OK) {
307         HILOGE("get token info failed");
308         return false;
309     }
310 
311     if (nativeTokenInfo.processName != callProcess) {
312         HILOGE("cannot operate by process: %{public}s", nativeTokenInfo.processName.c_str());
313         return false;
314     }
315     return true;
316 }
317 
CheckAllowUpdate(OnDemandPolicyType type,SaProfile & saProfile)318 bool SystemAbilityManager::CheckAllowUpdate(OnDemandPolicyType type, SaProfile& saProfile)
319 {
320     if (type == OnDemandPolicyType::START_POLICY && saProfile.startOnDemand.allowUpdate) {
321         return true;
322     } else if (type == OnDemandPolicyType::STOP_POLICY && saProfile.stopOnDemand.allowUpdate) {
323         return true;
324     }
325     return false;
326 }
327 
ConvertToOnDemandEvent(const SystemAbilityOnDemandEvent & from,OnDemandEvent & to)328 void SystemAbilityManager::ConvertToOnDemandEvent(const SystemAbilityOnDemandEvent& from, OnDemandEvent& to)
329 {
330     to.eventId = static_cast<int32_t>(from.eventId);
331     to.name = from.name;
332     to.value = from.value;
333     to.persistence = from.persistence;
334     for (auto& item : from.conditions) {
335         OnDemandCondition condition;
336         condition.eventId = static_cast<int32_t>(item.eventId);
337         condition.name = item.name;
338         condition.value = item.value;
339         to.conditions.push_back(condition);
340     }
341     to.enableOnce = from.enableOnce;
342 }
343 
ConvertToSystemAbilityOnDemandEvent(const OnDemandEvent & from,SystemAbilityOnDemandEvent & to)344 void SystemAbilityManager::ConvertToSystemAbilityOnDemandEvent(const OnDemandEvent& from,
345     SystemAbilityOnDemandEvent& to)
346 {
347     to.eventId = static_cast<OnDemandEventId>(from.eventId);
348     to.name = from.name;
349     to.value = from.value;
350     to.persistence = from.persistence;
351     for (auto& item : from.conditions) {
352         SystemAbilityOnDemandCondition condition;
353         condition.eventId = static_cast<OnDemandEventId>(item.eventId);
354         condition.name = item.name;
355         condition.value = item.value;
356         to.conditions.push_back(condition);
357     }
358     to.enableOnce = from.enableOnce;
359 }
360 
GetOnDemandPolicy(int32_t systemAbilityId,OnDemandPolicyType type,std::vector<SystemAbilityOnDemandEvent> & abilityOnDemandEvents)361 int32_t SystemAbilityManager::GetOnDemandPolicy(int32_t systemAbilityId, OnDemandPolicyType type,
362     std::vector<SystemAbilityOnDemandEvent>& abilityOnDemandEvents)
363 {
364     SaProfile saProfile;
365     if (!GetSaProfile(systemAbilityId, saProfile)) {
366         HILOGE("GetOnDemandPolicy invalid SA:%{public}d", systemAbilityId);
367         return ERR_INVALID_VALUE;
368     }
369     if (!CheckCallerProcess(saProfile)) {
370         HILOGE("GetOnDemandPolicy invalid caller SA:%{public}d", systemAbilityId);
371         return ERR_INVALID_VALUE;
372     }
373     if (!CheckAllowUpdate(type, saProfile)) {
374         HILOGE("GetOnDemandPolicy not allow get SA:%{public}d", systemAbilityId);
375         return ERR_PERMISSION_DENIED;
376     }
377 
378     if (collectManager_ == nullptr) {
379         HILOGE("GetOnDemandPolicy collectManager is nullptr");
380         return ERR_INVALID_VALUE;
381     }
382     std::vector<OnDemandEvent> onDemandEvents;
383     int32_t result = ERR_INVALID_VALUE;
384     result = collectManager_->GetOnDemandEvents(systemAbilityId, type, onDemandEvents);
385     if (result != ERR_OK) {
386         HILOGE("GetOnDemandPolicy add collect event failed");
387         return result;
388     }
389     for (auto& item : onDemandEvents) {
390         SystemAbilityOnDemandEvent eventOuter;
391         ConvertToSystemAbilityOnDemandEvent(item, eventOuter);
392         abilityOnDemandEvents.push_back(eventOuter);
393     }
394     HILOGI("GetOnDemandPolicy policy size : %{public}zu.", abilityOnDemandEvents.size());
395     return ERR_OK;
396 }
397 
UpdateOnDemandPolicy(int32_t systemAbilityId,OnDemandPolicyType type,const std::vector<SystemAbilityOnDemandEvent> & abilityOnDemandEvents)398 int32_t SystemAbilityManager::UpdateOnDemandPolicy(int32_t systemAbilityId, OnDemandPolicyType type,
399     const std::vector<SystemAbilityOnDemandEvent>& abilityOnDemandEvents)
400 {
401     SaProfile saProfile;
402     if (!GetSaProfile(systemAbilityId, saProfile)) {
403         HILOGE("UpdateOnDemandPolicy invalid SA:%{public}d", systemAbilityId);
404         return ERR_INVALID_VALUE;
405     }
406     if (!CheckCallerProcess(saProfile)) {
407         HILOGE("UpdateOnDemandPolicy invalid caller SA:%{public}d", systemAbilityId);
408         return ERR_INVALID_VALUE;
409     }
410     if (!CheckAllowUpdate(type, saProfile)) {
411         HILOGE("UpdateOnDemandPolicy not allow get SA:%{public}d", systemAbilityId);
412         return ERR_PERMISSION_DENIED;
413     }
414 
415     if (collectManager_ == nullptr) {
416         HILOGE("UpdateOnDemandPolicy collectManager is nullptr");
417         return ERR_INVALID_VALUE;
418     }
419     std::vector<OnDemandEvent> onDemandEvents;
420     for (auto& item : abilityOnDemandEvents) {
421         OnDemandEvent event;
422         ConvertToOnDemandEvent(item, event);
423         onDemandEvents.push_back(event);
424     }
425     int32_t result = ERR_INVALID_VALUE;
426     result = collectManager_->UpdateOnDemandEvents(systemAbilityId, type, onDemandEvents);
427     if (result != ERR_OK) {
428         HILOGE("UpdateOnDemandPolicy add collect event failed");
429         return result;
430     }
431     HILOGI("UpdateOnDemandPolicy policy size : %{public}zu.", onDemandEvents.size());
432     return ERR_OK;
433 }
434 
ProcessOnDemandEvent(const OnDemandEvent & event,const std::list<SaControlInfo> & saControlList)435 void SystemAbilityManager::ProcessOnDemandEvent(const OnDemandEvent& event,
436     const std::list<SaControlInfo>& saControlList)
437 {
438     HILOGI("SystemAbilityManager::ProcessEvent eventId:%{public}d name:%{public}s value:%{public}s",
439         event.eventId, event.name.c_str(), event.value.c_str());
440     sptr<ISystemAbilityLoadCallback> callback(new SystemAbilityLoadCallbackStub());
441     if (abilityStateScheduler_ == nullptr) {
442         HILOGE("abilityStateScheduler is nullptr");
443         return;
444     }
445     for (auto& saControl : saControlList) {
446         int32_t result = ERR_INVALID_VALUE;
447         if (saControl.ondemandId == START_ON_DEMAND) {
448             result = CheckStartEnableOnce(event, saControl, callback);
449         } else if (saControl.ondemandId == STOP_ON_DEMAND) {
450             result = CheckStopEnableOnce(event, saControl);
451         } else {
452             HILOGE("ondemandId error");
453         }
454         if (result != ERR_OK) {
455             HILOGE("process ondemand event failed, ondemandId:%{public}d, SA:%{public}d",
456                 saControl.ondemandId, saControl.saId);
457         }
458     }
459 }
460 
CheckStartEnableOnce(const OnDemandEvent & event,const SaControlInfo & saControl,sptr<ISystemAbilityLoadCallback> callback)461 int32_t SystemAbilityManager::CheckStartEnableOnce(const OnDemandEvent& event,
462     const SaControlInfo& saControl, sptr<ISystemAbilityLoadCallback> callback)
463 {
464     int32_t result = ERR_INVALID_VALUE;
465     if (saControl.enableOnce) {
466         lock_guard<mutex> autoLock(startEnableOnceLock_);
467         auto iter = startEnableOnceMap_.find(saControl.saId);
468         if (iter != startEnableOnceMap_.end() && IsSameEvent(event, startEnableOnceMap_[saControl.saId])) {
469             HILOGI("ondemand canceled for enable-once, ondemandId:%{public}d, SA:%{public}d",
470                 saControl.ondemandId, saControl.saId);
471             return result;
472         }
473         startEnableOnceMap_[saControl.saId].emplace_back(event);
474         HILOGI("startEnableOnceMap_ add SA:%{public}d, eventId:%{public}d",
475             saControl.saId, event.eventId);
476     }
477     auto callingPid = IPCSkeleton::GetCallingPid();
478     LoadRequestInfo loadRequestInfo = {saControl.saId, LOCAL_DEVICE, callback, callingPid, event};
479     result = abilityStateScheduler_->HandleLoadAbilityEvent(loadRequestInfo);
480     if (saControl.enableOnce && result != ERR_OK) {
481         lock_guard<mutex> autoLock(startEnableOnceLock_);
482         auto& events = startEnableOnceMap_[saControl.saId];
483         events.remove(event);
484         if (events.empty()) {
485             startEnableOnceMap_.erase(saControl.saId);
486         }
487         HILOGI("startEnableOnceMap_remove SA:%{public}d, eventId:%{public}d",
488             saControl.saId, event.eventId);
489     }
490     return result;
491 }
492 
CheckStopEnableOnce(const OnDemandEvent & event,const SaControlInfo & saControl)493 int32_t SystemAbilityManager::CheckStopEnableOnce(const OnDemandEvent& event,
494     const SaControlInfo& saControl)
495 {
496     int32_t result = ERR_INVALID_VALUE;
497     if (saControl.enableOnce) {
498         lock_guard<mutex> autoLock(stopEnableOnceLock_);
499         auto iter = stopEnableOnceMap_.find(saControl.saId);
500         if (iter != stopEnableOnceMap_.end() && IsSameEvent(event, stopEnableOnceMap_[saControl.saId])) {
501             HILOGI("ondemand canceled for enable-once, ondemandId:%{public}d, SA:%{public}d",
502                 saControl.ondemandId, saControl.saId);
503             return result;
504         }
505         stopEnableOnceMap_[saControl.saId].emplace_back(event);
506         HILOGI("stopEnableOnceMap_ add SA:%{public}d, eventId:%{public}d",
507             saControl.saId, event.eventId);
508     }
509     auto callingPid = IPCSkeleton::GetCallingPid();
510     UnloadRequestInfo unloadRequestInfo = {saControl.saId, event, callingPid};
511     result = abilityStateScheduler_->HandleUnloadAbilityEvent(unloadRequestInfo);
512     if (saControl.enableOnce && result != ERR_OK) {
513         lock_guard<mutex> autoLock(stopEnableOnceLock_);
514         auto& events = stopEnableOnceMap_[saControl.saId];
515         events.remove(event);
516         if (events.empty()) {
517             stopEnableOnceMap_.erase(saControl.saId);
518         }
519         HILOGI("stopEnableOnceMap_ remove SA:%{public}d, eventId:%{public}d",
520             saControl.saId, event.eventId);
521     }
522     return result;
523 }
524 
IsSameEvent(const OnDemandEvent & event,std::list<OnDemandEvent> & enableOnceList)525 bool SystemAbilityManager::IsSameEvent(const OnDemandEvent& event, std::list<OnDemandEvent>& enableOnceList)
526 {
527     for (auto iter = enableOnceList.begin(); iter != enableOnceList.end(); iter++) {
528         if (event.eventId == iter->eventId && event.name == iter->name && event.value == iter->value) {
529             HILOGI("event already exits in enable-once list");
530             return true;
531         }
532     }
533     return false;
534 }
535 
GetSystemAbility(int32_t systemAbilityId)536 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId)
537 {
538     return CheckSystemAbility(systemAbilityId);
539 }
540 
GetSystemAbility(int32_t systemAbilityId,const std::string & deviceId)541 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
542 {
543     return CheckSystemAbility(systemAbilityId, deviceId);
544 }
545 
GetSystemAbilityFromRemote(int32_t systemAbilityId)546 sptr<IRemoteObject> SystemAbilityManager::GetSystemAbilityFromRemote(int32_t systemAbilityId)
547 {
548     HILOGD("%{public}s called, systemAbilityId = %{public}d", __func__, systemAbilityId);
549     if (!CheckInputSysAbilityId(systemAbilityId)) {
550         HILOGW("GetSystemAbilityFromRemote invalid!");
551         return nullptr;
552     }
553 
554     shared_lock<shared_mutex> readLock(abilityMapLock_);
555     auto iter = abilityMap_.find(systemAbilityId);
556     if (iter == abilityMap_.end()) {
557         HILOGI("GetSystemAbilityFromRemote not found SA %{public}d.", systemAbilityId);
558         return nullptr;
559     }
560     if (!(iter->second.isDistributed)) {
561         HILOGW("GetSystemAbilityFromRemote SA:%{public}d not distributed", systemAbilityId);
562         return nullptr;
563     }
564     HILOGI("GetSystemAbilityFromRemote found SA:%{public}d.", systemAbilityId);
565     return iter->second.remoteObj;
566 }
567 
CheckSystemAbility(int32_t systemAbilityId)568 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId)
569 {
570     HILOGD("%{public}s called, SA:%{public}d", __func__, systemAbilityId);
571 
572     if (!CheckInputSysAbilityId(systemAbilityId)) {
573         HILOGW("CheckSystemAbility CheckSystemAbility invalid!");
574         return nullptr;
575     }
576     int32_t count = UpdateSaFreMap(IPCSkeleton::GetCallingUid(), systemAbilityId);
577     shared_lock<shared_mutex> readLock(abilityMapLock_);
578     auto iter = abilityMap_.find(systemAbilityId);
579     if (iter != abilityMap_.end()) {
580         HILOGD("found SA:%{public}d,callpid:%{public}d", systemAbilityId, IPCSkeleton::GetCallingPid());
581         return iter->second.remoteObj;
582     }
583     HILOGI("NOT found SA:%{public}d,callpid:%{public}d,count:%{public}d",
584         systemAbilityId, IPCSkeleton::GetCallingPid(), count);
585     return nullptr;
586 }
587 
CheckDistributedPermission()588 bool SystemAbilityManager::CheckDistributedPermission()
589 {
590     auto callingUid = IPCSkeleton::GetCallingUid();
591     if (callingUid != UID_ROOT && callingUid != UID_SYSTEM) {
592         return false;
593     }
594     return true;
595 }
596 
CheckSystemAbility(int32_t systemAbilityId,const std::string & deviceId)597 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId,
598     const std::string& deviceId)
599 {
600     return DoMakeRemoteBinder(systemAbilityId, IPCSkeleton::GetCallingPid(), IPCSkeleton::GetCallingUid(), deviceId);
601 }
602 
FindSystemAbilityNotify(int32_t systemAbilityId,int32_t code)603 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, int32_t code)
604 {
605     return FindSystemAbilityNotify(systemAbilityId, "", code);
606 }
607 
NotifySystemAbilityChanged(int32_t systemAbilityId,const std::string & deviceId,int32_t code,const sptr<ISystemAbilityStatusChange> & listener)608 void SystemAbilityManager::NotifySystemAbilityChanged(int32_t systemAbilityId, const std::string& deviceId,
609     int32_t code, const sptr<ISystemAbilityStatusChange>& listener)
610 {
611     HILOGD("NotifySystemAbilityChanged, SA:%{public}d", systemAbilityId);
612     if (listener == nullptr) {
613         HILOGE("%{public}s listener null pointer!", __func__);
614         return;
615     }
616 
617     switch (code) {
618         case static_cast<uint32_t>(SamgrInterfaceCode::ADD_SYSTEM_ABILITY_TRANSACTION): {
619             listener->OnAddSystemAbility(systemAbilityId, deviceId);
620             break;
621         }
622         case static_cast<uint32_t>(SamgrInterfaceCode::REMOVE_SYSTEM_ABILITY_TRANSACTION): {
623             listener->OnRemoveSystemAbility(systemAbilityId, deviceId);
624             break;
625         }
626         default:
627             break;
628     }
629 }
630 
FindSystemAbilityNotify(int32_t systemAbilityId,const std::string & deviceId,int32_t code)631 int32_t SystemAbilityManager::FindSystemAbilityNotify(int32_t systemAbilityId, const std::string& deviceId,
632     int32_t code)
633 {
634     HILOGI("%{public}s called:SA:%{public}d, code=%{public}d, listenSize:%{public}zu",
635         __func__, systemAbilityId, code, listenerMap_.size());
636     lock_guard<mutex> autoLock(listenerMapLock_);
637     auto iter = listenerMap_.find(systemAbilityId);
638     if (iter != listenerMap_.end()) {
639         auto& listeners = iter->second;
640         for (const auto& item : listeners) {
641             NotifySystemAbilityChanged(systemAbilityId, deviceId, code, item.first);
642         }
643     }
644 
645     return ERR_OK;
646 }
647 
IsNameInValid(const std::u16string & name)648 bool SystemAbilityManager::IsNameInValid(const std::u16string& name)
649 {
650     HILOGD("%{public}s called:name = %{public}s", __func__, Str16ToStr8(name).c_str());
651     bool ret = false;
652     if (name.empty() || name.size() > MAX_NAME_SIZE || DeleteBlank(name).empty()) {
653         ret = true;
654     }
655 
656     return ret;
657 }
658 
StartOnDemandAbility(const std::u16string & procName,int32_t systemAbilityId)659 void SystemAbilityManager::StartOnDemandAbility(const std::u16string& procName, int32_t systemAbilityId)
660 {
661     lock_guard<mutex> autoLock(onDemandLock_);
662     StartOnDemandAbilityLocked(procName, systemAbilityId);
663 }
664 
StartOnDemandAbilityLocked(const std::u16string & procName,int32_t systemAbilityId)665 void SystemAbilityManager::StartOnDemandAbilityLocked(const std::u16string& procName, int32_t systemAbilityId)
666 {
667     auto iter = startingAbilityMap_.find(systemAbilityId);
668     if (iter == startingAbilityMap_.end()) {
669         return;
670     }
671     auto& abilityItem = iter->second;
672     StartOnDemandAbilityInner(procName, systemAbilityId, abilityItem);
673 }
674 
StartOnDemandAbilityInner(const std::u16string & procName,int32_t systemAbilityId,AbilityItem & abilityItem)675 int32_t SystemAbilityManager::StartOnDemandAbilityInner(const std::u16string& procName, int32_t systemAbilityId,
676     AbilityItem& abilityItem)
677 {
678     if (abilityItem.state != AbilityState::INIT) {
679         return ERR_INVALID_VALUE;
680     }
681     sptr<ILocalAbilityManager> procObject =
682         iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
683     if (procObject == nullptr) {
684         HILOGI("get process:%{public}s fail", Str16ToStr8(procName).c_str());
685         return ERR_INVALID_VALUE;
686     }
687     auto event = abilityItem.event;
688     auto eventStr = EventToStr(event);
689     procObject->StartAbility(systemAbilityId, eventStr);
690     abilityItem.state = AbilityState::STARTING;
691     return ERR_OK;
692 }
693 
StopOnDemandAbility(const std::u16string & procName,int32_t systemAbilityId,const OnDemandEvent & event)694 bool SystemAbilityManager::StopOnDemandAbility(const std::u16string& procName,
695     int32_t systemAbilityId, const OnDemandEvent& event)
696 {
697     lock_guard<mutex> autoLock(onDemandLock_);
698     return StopOnDemandAbilityInner(procName, systemAbilityId, event);
699 }
700 
StopOnDemandAbilityInner(const std::u16string & procName,int32_t systemAbilityId,const OnDemandEvent & event)701 bool SystemAbilityManager::StopOnDemandAbilityInner(const std::u16string& procName,
702     int32_t systemAbilityId, const OnDemandEvent& event)
703 {
704     sptr<ILocalAbilityManager> procObject =
705         iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
706     if (procObject == nullptr) {
707         HILOGI("get process:%{public}s fail", Str16ToStr8(procName).c_str());
708         return false;
709     }
710     auto eventStr = EventToStr(event);
711     return procObject->StopAbility(systemAbilityId, eventStr);
712 }
713 
AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,const std::u16string & procName)714 int32_t SystemAbilityManager::AddOnDemandSystemAbilityInfo(int32_t systemAbilityId,
715     const std::u16string& procName)
716 {
717     HILOGD("%{public}s called", __func__);
718     if (!CheckInputSysAbilityId(systemAbilityId) || IsNameInValid(procName)) {
719         HILOGW("AddOnDemandSystemAbilityInfo systemAbilityId or procName invalid.");
720         return ERR_INVALID_VALUE;
721     }
722 
723     lock_guard<mutex> autoLock(onDemandLock_);
724     auto onDemandSaSize = onDemandAbilityMap_.size();
725     if (onDemandSaSize >= MAX_SERVICES) {
726         HILOGE("map size error, (Has been greater than %{public}zu)",
727             onDemandAbilityMap_.size());
728         return ERR_INVALID_VALUE;
729     }
730     {
731         lock_guard<mutex> autoLock(systemProcessMapLock_);
732         if (systemProcessMap_.count(procName) == 0) {
733             HILOGW("AddOnDemandSystemAbilityInfo procName:%{public}s not exist.", Str16ToStr8(procName).c_str());
734             return ERR_INVALID_VALUE;
735         }
736     }
737     onDemandAbilityMap_[systemAbilityId] = procName;
738     HILOGI("insert onDemand SA:%{public}d. size:%{public}zu", systemAbilityId,
739         onDemandAbilityMap_.size());
740     if (startingAbilityMap_.count(systemAbilityId) != 0) {
741         if (workHandler_ != nullptr) {
742             auto pendingTask = [procName, systemAbilityId, this] () {
743                 StartOnDemandAbility(procName, systemAbilityId);
744             };
745             bool ret = workHandler_->PostTask(pendingTask);
746             if (!ret) {
747                 HILOGW("AddOnDemandSystemAbilityInfo PostTask failed!");
748             }
749         }
750     }
751     return ERR_OK;
752 }
753 
StartOnDemandAbility(int32_t systemAbilityId,bool & isExist)754 int32_t SystemAbilityManager::StartOnDemandAbility(int32_t systemAbilityId, bool& isExist)
755 {
756     lock_guard<mutex> onDemandAbilityLock(onDemandLock_);
757     return StartOnDemandAbilityLocked(systemAbilityId, isExist);
758 }
759 
StartOnDemandAbilityLocked(int32_t systemAbilityId,bool & isExist)760 int32_t SystemAbilityManager::StartOnDemandAbilityLocked(int32_t systemAbilityId, bool& isExist)
761 {
762     auto iter = onDemandAbilityMap_.find(systemAbilityId);
763     if (iter == onDemandAbilityMap_.end()) {
764         isExist = false;
765         return ERR_INVALID_VALUE;
766     }
767     HILOGI("found onDemand SA:%{public}d.", systemAbilityId);
768     isExist = true;
769     AbilityItem& abilityItem = startingAbilityMap_[systemAbilityId];
770     return StartOnDemandAbilityInner(iter->second, systemAbilityId, abilityItem);
771 }
772 
CheckSystemAbility(int32_t systemAbilityId,bool & isExist)773 sptr<IRemoteObject> SystemAbilityManager::CheckSystemAbility(int32_t systemAbilityId, bool& isExist)
774 {
775     if (!CheckInputSysAbilityId(systemAbilityId)) {
776         return nullptr;
777     }
778     if (abilityStateScheduler_ == nullptr) {
779         HILOGE("abilityStateScheduler is nullptr");
780         return nullptr;
781     }
782     if (abilityStateScheduler_->IsSystemAbilityUnloading(systemAbilityId)) {
783         HILOGW("SA:%{public}d is unloading", systemAbilityId);
784         return nullptr;
785     }
786     sptr<IRemoteObject> abilityProxy = CheckSystemAbility(systemAbilityId);
787     if (abilityProxy == nullptr) {
788         abilityStateScheduler_->HandleLoadAbilityEvent(systemAbilityId, isExist);
789         return nullptr;
790     }
791     isExist = true;
792     return abilityProxy;
793 }
794 
DoLoadOnDemandAbility(int32_t systemAbilityId,bool & isExist)795 bool SystemAbilityManager::DoLoadOnDemandAbility(int32_t systemAbilityId, bool& isExist)
796 {
797     lock_guard<mutex> autoLock(onDemandLock_);
798     sptr<IRemoteObject> abilityProxy = CheckSystemAbility(systemAbilityId);
799     if (abilityProxy != nullptr) {
800         isExist = true;
801         return true;
802     }
803     auto iter = startingAbilityMap_.find(systemAbilityId);
804     if (iter != startingAbilityMap_.end() && iter->second.state == AbilityState::STARTING) {
805         isExist = true;
806         return true;
807     }
808     auto onDemandIter = onDemandAbilityMap_.find(systemAbilityId);
809     if (onDemandIter == onDemandAbilityMap_.end()) {
810         isExist = false;
811         return false;
812     }
813     auto& abilityItem = startingAbilityMap_[systemAbilityId];
814     abilityItem.event = {INTERFACE_CALL, "get", ""};
815     return StartOnDemandAbilityLocked(systemAbilityId, isExist) == ERR_OK;
816 }
817 
RemoveSystemAbility(int32_t systemAbilityId)818 int32_t SystemAbilityManager::RemoveSystemAbility(int32_t systemAbilityId)
819 {
820     if (!CheckInputSysAbilityId(systemAbilityId)) {
821         HILOGW("RemoveSystemAbility SA:%{public}d", systemAbilityId);
822         return ERR_INVALID_VALUE;
823     }
824     {
825         unique_lock<shared_mutex> writeLock(abilityMapLock_);
826         auto itSystemAbility = abilityMap_.find(systemAbilityId);
827         if (itSystemAbility == abilityMap_.end()) {
828             HILOGI("SystemAbilityManager::RemoveSystemAbility not found!");
829             return ERR_INVALID_VALUE;
830         }
831         sptr<IRemoteObject> ability = itSystemAbility->second.remoteObj;
832         if (ability != nullptr && abilityDeath_ != nullptr) {
833             ability->RemoveDeathRecipient(abilityDeath_);
834         }
835         (void)abilityMap_.erase(itSystemAbility);
836         HILOGI("%{public}s called, SA:%{public}d, size:%{public}zu", __func__, systemAbilityId,
837             abilityMap_.size());
838     }
839     if (abilityStateScheduler_ == nullptr) {
840         HILOGE("abilityStateScheduler is nullptr");
841         return ERR_INVALID_VALUE;
842     }
843     SystemAbilityInvalidateCache(systemAbilityId);
844     abilityStateScheduler_->SendAbilityStateEvent(systemAbilityId, AbilityStateEvent::ABILITY_UNLOAD_SUCCESS_EVENT);
845     SendSystemAbilityRemovedMsg(systemAbilityId);
846     return ERR_OK;
847 }
848 
RemoveSystemAbility(const sptr<IRemoteObject> & ability)849 int32_t SystemAbilityManager::RemoveSystemAbility(const sptr<IRemoteObject>& ability)
850 {
851     HILOGD("%{public}s called, (ability)", __func__);
852     if (ability == nullptr) {
853         HILOGW("ability is nullptr ");
854         return ERR_INVALID_VALUE;
855     }
856 
857     int32_t saId = 0;
858     {
859         unique_lock<shared_mutex> writeLock(abilityMapLock_);
860         for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); ++iter) {
861             if (iter->second.remoteObj == ability) {
862                 saId = iter->first;
863                 SystemAbilityInvalidateCache(saId);
864                 (void)abilityMap_.erase(iter);
865                 if (abilityDeath_ != nullptr) {
866                     ability->RemoveDeathRecipient(abilityDeath_);
867                 }
868                 HILOGI("%{public}s called, SA:%{public}d removed, size:%{public}zu", __func__, saId,
869                     abilityMap_.size());
870                 break;
871             }
872         }
873     }
874 
875     if (saId != 0) {
876         if (abilityStateScheduler_ == nullptr) {
877             HILOGE("abilityStateScheduler is nullptr");
878             return ERR_INVALID_VALUE;
879         }
880         abilityStateScheduler_->HandleAbilityDiedEvent(saId);
881         SendSystemAbilityRemovedMsg(saId);
882     }
883     return ERR_OK;
884 }
885 
RemoveDiedSystemAbility(int32_t systemAbilityId)886 int32_t SystemAbilityManager::RemoveDiedSystemAbility(int32_t systemAbilityId)
887 {
888     {
889         unique_lock<shared_mutex> writeLock(abilityMapLock_);
890         auto itSystemAbility = abilityMap_.find(systemAbilityId);
891         if (itSystemAbility == abilityMap_.end()) {
892             return ERR_OK;
893         }
894         sptr<IRemoteObject> ability = itSystemAbility->second.remoteObj;
895         if (ability != nullptr && abilityDeath_ != nullptr) {
896             ability->RemoveDeathRecipient(abilityDeath_);
897         }
898         (void)abilityMap_.erase(itSystemAbility);
899         HILOGI("%{public}s called, SA:%{public}d removed, size:%{public}zu", __func__, systemAbilityId,
900             abilityMap_.size());
901     }
902     SendSystemAbilityRemovedMsg(systemAbilityId);
903     return ERR_OK;
904 }
905 
ListSystemAbilities(uint32_t dumpFlags)906 vector<u16string> SystemAbilityManager::ListSystemAbilities(uint32_t dumpFlags)
907 {
908     vector<u16string> list;
909     shared_lock<shared_mutex> readLock(abilityMapLock_);
910     for (auto iter = abilityMap_.begin(); iter != abilityMap_.end(); iter++) {
911         list.emplace_back(Str8ToStr16(to_string(iter->first)));
912     }
913     return list;
914 }
915 
SubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)916 int32_t SystemAbilityManager::SubscribeSystemAbility(int32_t systemAbilityId,
917     const sptr<ISystemAbilityStatusChange>& listener)
918 {
919     if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
920         HILOGW("SubscribeSystemAbility systemAbilityId or listener invalid!");
921         return ERR_INVALID_VALUE;
922     }
923 
924     auto callingPid = IPCSkeleton::GetCallingPid();
925     {
926         lock_guard<mutex> autoLock(listenerMapLock_);
927         auto& listeners = listenerMap_[systemAbilityId];
928         for (const auto& itemListener : listeners) {
929             if (listener->AsObject() == itemListener.first->AsObject()) {
930                 HILOGI("already exist listener object SA:%{public}d", systemAbilityId);
931                 return ERR_OK;
932             }
933         }
934         auto& count = subscribeCountMap_[callingPid];
935         if (count >= MAX_SUBSCRIBE_COUNT) {
936             HILOGE("SubscribeSystemAbility pid:%{public}d overflow max subscribe count!", callingPid);
937             return ERR_PERMISSION_DENIED;
938         }
939         ++count;
940         if (abilityStatusDeath_ != nullptr) {
941             bool ret = listener->AsObject()->AddDeathRecipient(abilityStatusDeath_);
942             listeners.emplace_back(listener, callingPid);
943             HILOGI("SubscribeSystemAbility SA:%{public}d AddDeathRecipient %{public}s, count:%{public}d, "
944                 "callpid:%{public}d", systemAbilityId, ret ? "succeed" : "failed", count, callingPid);
945         }
946         HILOGI("SubscribeSystemAbility SA:%{public}d, size=%{public}zu, count:%{public}d, callpid:%{public}d",
947             systemAbilityId, listeners.size(), count, callingPid);
948     }
949     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
950     if (targetObject != nullptr) {
951         HILOGI("NotifySystemAbilityChanged add SA:%{public}d, count:%{public}d, callpid:%{public}d",
952             systemAbilityId, subscribeCountMap_[callingPid], callingPid);
953         NotifySystemAbilityChanged(systemAbilityId, "",
954             static_cast<uint32_t>(SamgrInterfaceCode::ADD_SYSTEM_ABILITY_TRANSACTION), listener);
955     }
956     return ERR_OK;
957 }
958 
UnSubscribeSystemAbilityLocked(std::list<std::pair<sptr<ISystemAbilityStatusChange>,int32_t>> & listenerList,const sptr<IRemoteObject> & listener)959 void SystemAbilityManager::UnSubscribeSystemAbilityLocked(
960     std::list<std::pair<sptr<ISystemAbilityStatusChange>, int32_t>>& listenerList,
961     const sptr<IRemoteObject>& listener)
962 {
963     auto iter = listenerList.begin();
964     while (iter != listenerList.end()) {
965         auto& item = *iter;
966         if (item.first->AsObject() != listener) {
967             ++iter;
968             continue;
969         }
970 
971         if (abilityStatusDeath_ != nullptr) {
972             listener->RemoveDeathRecipient(abilityStatusDeath_);
973         }
974         auto iterPair = subscribeCountMap_.find(item.second);
975         if (iterPair != subscribeCountMap_.end()) {
976             --iterPair->second;
977             if (iterPair->second == 0) {
978                 subscribeCountMap_.erase(iterPair);
979             }
980         }
981         HILOGI("Remove SA Status listener added by callingPid:%{public}d, szie:%{public}zu",
982             item.second, listenerList.size());
983         iter = listenerList.erase(iter);
984         break;
985     }
986 }
987 
UnSubscribeSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityStatusChange> & listener)988 int32_t SystemAbilityManager::UnSubscribeSystemAbility(int32_t systemAbilityId,
989     const sptr<ISystemAbilityStatusChange>& listener)
990 {
991     if (!CheckInputSysAbilityId(systemAbilityId) || listener == nullptr) {
992         HILOGW("UnSubscribeSystemAbility systemAbilityId or listener invalid!");
993         return ERR_INVALID_VALUE;
994     }
995 
996     lock_guard<mutex> autoLock(listenerMapLock_);
997     auto& listeners = listenerMap_[systemAbilityId];
998     UnSubscribeSystemAbilityLocked(listeners, listener->AsObject());
999     HILOGI("UnSubscribeSystemAbility SA:%{public}d, size:%{public}zu", systemAbilityId,
1000         listeners.size());
1001     return ERR_OK;
1002 }
1003 
UnSubscribeSystemAbility(const sptr<IRemoteObject> & remoteObject)1004 void SystemAbilityManager::UnSubscribeSystemAbility(const sptr<IRemoteObject>& remoteObject)
1005 {
1006     lock_guard<mutex> autoLock(listenerMapLock_);
1007     HILOGD("UnSubscribeSystemAbility remote object dead! size:%{public}zu", listenerMap_.size());
1008     for (auto& item : listenerMap_) {
1009         auto& listeners = item.second;
1010         UnSubscribeSystemAbilityLocked(listeners, remoteObject);
1011     }
1012 }
1013 
SetDeviceName(const u16string & name)1014 void SystemAbilityManager::SetDeviceName(const u16string &name)
1015 {
1016     deviceName_ = name;
1017 }
1018 
GetDeviceName() const1019 const u16string& SystemAbilityManager::GetDeviceName() const
1020 {
1021     return deviceName_;
1022 }
1023 
NotifyRemoteSaDied(const std::u16string & name)1024 void SystemAbilityManager::NotifyRemoteSaDied(const std::u16string& name)
1025 {
1026     std::u16string saName;
1027     std::string deviceId;
1028     ParseRemoteSaName(name, deviceId, saName);
1029     if (dBinderService_ != nullptr) {
1030         std::string nodeId = TransformDeviceId(deviceId, NODE_ID, false);
1031         dBinderService_->NoticeServiceDie(saName, nodeId);
1032         HILOGI("NotifyRemoteSaDied, serviceName is %{public}s, deviceId is %{public}s",
1033             Str16ToStr8(saName).c_str(), AnonymizeDeviceId(nodeId).c_str());
1034     }
1035 }
1036 
NotifyRemoteDeviceOffline(const std::string & deviceId)1037 void SystemAbilityManager::NotifyRemoteDeviceOffline(const std::string& deviceId)
1038 {
1039     if (dBinderService_ != nullptr) {
1040         dBinderService_->NoticeDeviceDie(deviceId);
1041         HILOGI("NotifyRemoteDeviceOffline, deviceId is %{public}s", AnonymizeDeviceId(deviceId).c_str());
1042     }
1043 }
1044 
ParseRemoteSaName(const std::u16string & name,std::string & deviceId,std::u16string & saName)1045 void SystemAbilityManager::ParseRemoteSaName(const std::u16string& name, std::string& deviceId, std::u16string& saName)
1046 {
1047     vector<string> strVector;
1048     SplitStr(Str16ToStr8(name), "_", strVector);
1049     if (strVector.size() == SPLIT_NAME_VECTOR_SIZE) {
1050         deviceId = strVector[0];
1051         saName = Str8ToStr16(strVector[1]);
1052     }
1053 }
1054 
AddSystemAbility(int32_t systemAbilityId,const sptr<IRemoteObject> & ability,const SAExtraProp & extraProp)1055 int32_t SystemAbilityManager::AddSystemAbility(int32_t systemAbilityId, const sptr<IRemoteObject>& ability,
1056     const SAExtraProp& extraProp)
1057 {
1058     if (!CheckInputSysAbilityId(systemAbilityId) || ability == nullptr) {
1059         HILOGE("AddSystemAbilityExtra input params is invalid.");
1060         return ERR_INVALID_VALUE;
1061     }
1062     {
1063         unique_lock<shared_mutex> writeLock(abilityMapLock_);
1064         auto saSize = abilityMap_.size();
1065         if (saSize >= MAX_SERVICES) {
1066             HILOGE("map size error, (Has been greater than %zu)", saSize);
1067             return ERR_INVALID_VALUE;
1068         }
1069         SAInfo saInfo;
1070         saInfo.remoteObj = ability;
1071         saInfo.isDistributed = extraProp.isDistributed;
1072         saInfo.capability = extraProp.capability;
1073         saInfo.permission = Str16ToStr8(extraProp.permission);
1074         if (abilityMap_.count(systemAbilityId) > 0) {
1075             auto callingPid = IPCSkeleton::GetCallingPid();
1076             auto callingUid = IPCSkeleton::GetCallingUid();
1077             HILOGW("systemAbility: %{public}d is being covered, callingPid is %{public}d, callingUid is %{public}d",
1078                 systemAbilityId, callingPid, callingUid);
1079         }
1080         abilityMap_[systemAbilityId] = std::move(saInfo);
1081         HILOGI("insert %{public}d. size : %{public}zu", systemAbilityId, abilityMap_.size());
1082     }
1083     RemoveCheckLoadedMsg(systemAbilityId);
1084     if (abilityDeath_ != nullptr) {
1085         ability->AddDeathRecipient(abilityDeath_);
1086     }
1087 
1088     u16string strName = Str8ToStr16(to_string(systemAbilityId));
1089     if (extraProp.isDistributed && dBinderService_ != nullptr) {
1090         dBinderService_->RegisterRemoteProxy(strName, systemAbilityId);
1091         HILOGI("AddSystemAbility RegisterRemoteProxy, SA:%{public}d", systemAbilityId);
1092     }
1093     if (systemAbilityId == SOFTBUS_SERVER_SA_ID) {
1094         if (dBinderService_ != nullptr && rpcCallbackImp_ != nullptr) {
1095             bool ret = dBinderService_->StartDBinderService(rpcCallbackImp_);
1096             HILOGI("start result is %{public}s", ret ? "succeed" : "fail");
1097         }
1098     }
1099     if (abilityStateScheduler_ == nullptr) {
1100         HILOGE("abilityStateScheduler is nullptr");
1101         return ERR_INVALID_VALUE;
1102     }
1103     SystemAbilityInvalidateCache(systemAbilityId);
1104     abilityStateScheduler_->SendAbilityStateEvent(systemAbilityId, AbilityStateEvent::ABILITY_LOAD_SUCCESS_EVENT);
1105     SendSystemAbilityAddedMsg(systemAbilityId, ability);
1106     return ERR_OK;
1107 }
1108 
SystemAbilityInvalidateCache(int32_t systemAbilityId)1109 void SystemAbilityManager::SystemAbilityInvalidateCache(int32_t systemAbilityId)
1110 {
1111     auto pos = onDemandSaIdsSet_.find(systemAbilityId);
1112     if (pos != onDemandSaIdsSet_.end()) {
1113         HILOGD("SystemAbilityInvalidateCache SA:%{public}d.", systemAbilityId);
1114         return;
1115     }
1116     auto invalidateCacheTask = [this] () {
1117         InvalidateCache();
1118     };
1119     ffrt::submit(invalidateCacheTask);
1120 }
1121 
AddSystemProcess(const u16string & procName,const sptr<IRemoteObject> & procObject)1122 int32_t SystemAbilityManager::AddSystemProcess(const u16string& procName,
1123     const sptr<IRemoteObject>& procObject)
1124 {
1125     if (procName.empty() || procObject == nullptr) {
1126         HILOGE("AddSystemProcess empty name or null object!");
1127         return ERR_INVALID_VALUE;
1128     }
1129     {
1130         lock_guard<mutex> autoLock(systemProcessMapLock_);
1131         size_t procNum = systemProcessMap_.size();
1132         if (procNum >= MAX_SERVICES) {
1133             HILOGE("AddSystemProcess map size reach MAX_SERVICES already");
1134             return ERR_INVALID_VALUE;
1135         }
1136         systemProcessMap_[procName] = procObject;
1137         HILOGI("AddSystemProcess insert %{public}s. size : %{public}zu", Str16ToStr8(procName).c_str(),
1138             systemProcessMap_.size());
1139     }
1140     if (systemProcessDeath_ != nullptr) {
1141         bool ret = procObject->AddDeathRecipient(systemProcessDeath_);
1142         HILOGW("AddSystemProcess %{public}s, size:%{public}zu, AddDeathRecipient %{public}s!",
1143             Str16ToStr8(procName).c_str(), systemProcessMap_.size(), ret ? "succeed" : "failed");
1144     }
1145     {
1146         lock_guard<mutex> autoLock(startingProcessMapLock_);
1147         auto iterStarting = startingProcessMap_.find(procName);
1148         if (iterStarting != startingProcessMap_.end()) {
1149             int64_t end = GetTickCount();
1150             HILOGI("[PerformanceTest] AddSystemProcess start process:%{public}s spend %{public}" PRId64 " ms",
1151                 Str16ToStr8(procName).c_str(), (end - iterStarting->second));
1152             startingProcessMap_.erase(iterStarting);
1153         }
1154     }
1155     if (abilityStateScheduler_ == nullptr) {
1156         HILOGE("abilityStateScheduler is nullptr");
1157         return ERR_INVALID_VALUE;
1158     }
1159     auto callingPid = IPCSkeleton::GetCallingPid();
1160     auto callingUid = IPCSkeleton::GetCallingUid();
1161     ProcessInfo processInfo = {procName, callingPid, callingUid};
1162     abilityStateScheduler_->SendProcessStateEvent(processInfo, ProcessStateEvent::PROCESS_STARTED_EVENT);
1163     return ERR_OK;
1164 }
1165 
RemoveSystemProcess(const sptr<IRemoteObject> & procObject)1166 int32_t SystemAbilityManager::RemoveSystemProcess(const sptr<IRemoteObject>& procObject)
1167 {
1168     if (procObject == nullptr) {
1169         HILOGW("RemoveSystemProcess null object!");
1170         return ERR_INVALID_VALUE;
1171     }
1172 
1173     int32_t result = ERR_INVALID_VALUE;
1174     std::u16string processName;
1175     if (systemProcessDeath_ != nullptr) {
1176         procObject->RemoveDeathRecipient(systemProcessDeath_);
1177     }
1178     {
1179         lock_guard<mutex> autoLock(systemProcessMapLock_);
1180         for (const auto& [procName, object] : systemProcessMap_) {
1181             if (object != procObject) {
1182                 continue;
1183             }
1184             std::string name = Str16ToStr8(procName);
1185             processName = procName;
1186             (void)systemProcessMap_.erase(procName);
1187             HILOGI("RemoveSystemProcess process:%{public}s dead, size : %{public}zu", name.c_str(),
1188                 systemProcessMap_.size());
1189             result = ERR_OK;
1190             break;
1191         }
1192     }
1193     if (result == ERR_OK) {
1194         if (abilityStateScheduler_ == nullptr) {
1195             HILOGE("abilityStateScheduler is nullptr");
1196             return ERR_INVALID_VALUE;
1197         }
1198         ProcessInfo processInfo = {processName};
1199         abilityStateScheduler_->SendProcessStateEvent(processInfo, ProcessStateEvent::PROCESS_STOPPED_EVENT);
1200     } else {
1201         HILOGW("RemoveSystemProcess called and not found process.");
1202     }
1203     return result;
1204 }
1205 
GetSystemProcess(const u16string & procName)1206 sptr<IRemoteObject> SystemAbilityManager::GetSystemProcess(const u16string& procName)
1207 {
1208     if (procName.empty()) {
1209         HILOGE("GetSystemProcess empty name!");
1210         return nullptr;
1211     }
1212 
1213     lock_guard<mutex> autoLock(systemProcessMapLock_);
1214     auto iter = systemProcessMap_.find(procName);
1215     if (iter != systemProcessMap_.end()) {
1216         HILOGD("process:%{public}s found", Str16ToStr8(procName).c_str());
1217         return iter->second;
1218     }
1219     HILOGE("process:%{public}s not exist", Str16ToStr8(procName).c_str());
1220     return nullptr;
1221 }
1222 
GetSystemProcessInfo(int32_t systemAbilityId,SystemProcessInfo & systemProcessInfo)1223 int32_t SystemAbilityManager::GetSystemProcessInfo(int32_t systemAbilityId, SystemProcessInfo& systemProcessInfo)
1224 {
1225     if (abilityStateScheduler_ == nullptr) {
1226         HILOGE("abilityStateScheduler is nullptr");
1227         return ERR_INVALID_VALUE;
1228     }
1229     return abilityStateScheduler_->GetSystemProcessInfo(systemAbilityId, systemProcessInfo);
1230 }
1231 
GetRunningSystemProcess(std::list<SystemProcessInfo> & systemProcessInfos)1232 int32_t SystemAbilityManager::GetRunningSystemProcess(std::list<SystemProcessInfo>& systemProcessInfos)
1233 {
1234     if (abilityStateScheduler_ == nullptr) {
1235         HILOGE("abilityStateScheduler is nullptr");
1236         return ERR_INVALID_VALUE;
1237     }
1238     return abilityStateScheduler_->GetRunningSystemProcess(systemProcessInfos);
1239 }
1240 
SubscribeSystemProcess(const sptr<ISystemProcessStatusChange> & listener)1241 int32_t SystemAbilityManager::SubscribeSystemProcess(const sptr<ISystemProcessStatusChange>& listener)
1242 {
1243     if (abilityStateScheduler_ == nullptr) {
1244         HILOGE("abilityStateScheduler is nullptr");
1245         return ERR_INVALID_VALUE;
1246     }
1247     return abilityStateScheduler_->SubscribeSystemProcess(listener);
1248 }
1249 
UnSubscribeSystemProcess(const sptr<ISystemProcessStatusChange> & listener)1250 int32_t SystemAbilityManager::UnSubscribeSystemProcess(const sptr<ISystemProcessStatusChange>& listener)
1251 {
1252     if (abilityStateScheduler_ == nullptr) {
1253         HILOGE("abilityStateScheduler is nullptr");
1254         return ERR_INVALID_VALUE;
1255     }
1256     return abilityStateScheduler_->UnSubscribeSystemProcess(listener);
1257 }
1258 
GetOnDemandReasonExtraData(int64_t extraDataId,MessageParcel & extraDataParcel)1259 int32_t SystemAbilityManager::GetOnDemandReasonExtraData(int64_t extraDataId, MessageParcel& extraDataParcel)
1260 {
1261     if (collectManager_ == nullptr) {
1262         HILOGE("collectManager is nullptr");
1263         return ERR_INVALID_VALUE;
1264     }
1265     OnDemandReasonExtraData extraData;
1266     if (collectManager_->GetOnDemandReasonExtraData(extraDataId, extraData) != ERR_OK) {
1267         HILOGE("get extra data failed");
1268         return ERR_INVALID_VALUE;
1269     }
1270     if (!extraDataParcel.WriteParcelable(&extraData)) {
1271         HILOGE("write extra data failed");
1272         return ERR_INVALID_VALUE;
1273     }
1274     return ERR_OK;
1275 }
1276 
SendSystemAbilityAddedMsg(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)1277 void SystemAbilityManager::SendSystemAbilityAddedMsg(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
1278 {
1279     if (workHandler_ == nullptr) {
1280         HILOGE("SendSystemAbilityAddedMsg work handler not initialized!");
1281         return;
1282     }
1283     auto notifyAddedTask = [systemAbilityId, remoteObject, this]() {
1284         FindSystemAbilityNotify(systemAbilityId,
1285             static_cast<uint32_t>(SamgrInterfaceCode::ADD_SYSTEM_ABILITY_TRANSACTION));
1286         HILOGI("SendSystemAbilityAddedMsg notify SA:%{public}d", systemAbilityId);
1287         NotifySystemAbilityLoaded(systemAbilityId, remoteObject);
1288     };
1289     bool ret = workHandler_->PostTask(notifyAddedTask);
1290     if (!ret) {
1291         HILOGW("SendSystemAbilityAddedMsg PostTask failed!");
1292     }
1293 }
1294 
SendSystemAbilityRemovedMsg(int32_t systemAbilityId)1295 void SystemAbilityManager::SendSystemAbilityRemovedMsg(int32_t systemAbilityId)
1296 {
1297     if (workHandler_ == nullptr) {
1298         HILOGE("SendSystemAbilityRemovedMsg work handler not initialized!");
1299         return;
1300     }
1301     auto notifyRemovedTask = [systemAbilityId, this]() {
1302         FindSystemAbilityNotify(systemAbilityId,
1303             static_cast<uint32_t>(SamgrInterfaceCode::REMOVE_SYSTEM_ABILITY_TRANSACTION));
1304     };
1305     bool ret = workHandler_->PostTask(notifyRemovedTask);
1306     if (!ret) {
1307         HILOGW("SendSystemAbilityRemovedMsg PostTask failed!");
1308     }
1309 }
1310 
SendCheckLoadedMsg(int32_t systemAbilityId,const std::u16string & name,const std::string & srcDeviceId,const sptr<ISystemAbilityLoadCallback> & callback)1311 void SystemAbilityManager::SendCheckLoadedMsg(int32_t systemAbilityId, const std::u16string& name,
1312     const std::string& srcDeviceId, const sptr<ISystemAbilityLoadCallback>& callback)
1313 {
1314     if (workHandler_ == nullptr) {
1315         HILOGE("SendCheckLoadedMsg work handler not initialized!");
1316         return;
1317     }
1318 
1319     auto delayTask = [systemAbilityId, name, srcDeviceId, callback, this]() {
1320         if (workHandler_ != nullptr) {
1321             HILOGD("SendCheckLoadedMsg deltask SA:%{public}d", systemAbilityId);
1322             workHandler_->DelTask(ToString(systemAbilityId));
1323         } else {
1324             HILOGE("SendCheckLoadedMsg workHandler_ is null");
1325         }
1326         if (CheckSystemAbility(systemAbilityId) != nullptr) {
1327             HILOGI("SendCheckLoadedMsg SA:%{public}d loaded.", systemAbilityId);
1328             return;
1329         }
1330         HILOGI("SendCheckLoadedMsg handle for SA:%{public}d.", systemAbilityId);
1331         CleanCallbackForLoadFailed(systemAbilityId, name, srcDeviceId, callback);
1332         if (abilityStateScheduler_ == nullptr) {
1333             HILOGE("abilityStateScheduler is nullptr");
1334             return;
1335         }
1336         HILOGI("SendCheckLoadedMsg SA:%{public}d, load timeout.", systemAbilityId);
1337         ReportSamgrSaLoadFail(systemAbilityId, "time out");
1338         abilityStateScheduler_->SendAbilityStateEvent(systemAbilityId, AbilityStateEvent::ABILITY_LOAD_FAILED_EVENT);
1339         (void)GetSystemProcess(name);
1340     };
1341     bool ret = workHandler_->PostTask(delayTask, ToString(systemAbilityId), CHECK_LOADED_DELAY_TIME);
1342     if (!ret) {
1343         HILOGI("SendCheckLoadedMsg PostTask SA:%{public}d! failed", systemAbilityId);
1344     }
1345 }
1346 
CleanCallbackForLoadFailed(int32_t systemAbilityId,const std::u16string & name,const std::string & srcDeviceId,const sptr<ISystemAbilityLoadCallback> & callback)1347 void SystemAbilityManager::CleanCallbackForLoadFailed(int32_t systemAbilityId, const std::u16string& name,
1348     const std::string& srcDeviceId, const sptr<ISystemAbilityLoadCallback>& callback)
1349 {
1350     {
1351         lock_guard<mutex> autoLock(startingProcessMapLock_);
1352         auto iterStarting = startingProcessMap_.find(name);
1353         if (iterStarting != startingProcessMap_.end()) {
1354             HILOGI("CleanCallback clean process:%{public}s", Str16ToStr8(name).c_str());
1355             startingProcessMap_.erase(iterStarting);
1356         }
1357     }
1358     lock_guard<mutex> autoLock(onDemandLock_);
1359     auto iter = startingAbilityMap_.find(systemAbilityId);
1360     if (iter == startingAbilityMap_.end()) {
1361         HILOGI("CleanCallback SA:%{public}d not in startingAbilityMap.", systemAbilityId);
1362         return;
1363     }
1364     auto& abilityItem = iter->second;
1365     for (auto& callbackItem : abilityItem.callbackMap[srcDeviceId]) {
1366         if (callback->AsObject() == callbackItem.first->AsObject()) {
1367             NotifySystemAbilityLoadFail(systemAbilityId, callbackItem.first);
1368             RemoveStartingAbilityCallbackLocked(callbackItem);
1369             abilityItem.callbackMap[srcDeviceId].remove(callbackItem);
1370             break;
1371         }
1372     }
1373     if (abilityItem.callbackMap[srcDeviceId].empty()) {
1374         HILOGI("CleanCallback startingAbilityMap remove SA:%{public}d. with deviceId", systemAbilityId);
1375         abilityItem.callbackMap.erase(srcDeviceId);
1376     }
1377 
1378     if (abilityItem.callbackMap.empty()) {
1379         HILOGI("CleanCallback startingAbilityMap remove SA:%{public}d.", systemAbilityId);
1380         startingAbilityMap_.erase(iter);
1381     }
1382 }
1383 
RemoveCheckLoadedMsg(int32_t systemAbilityId)1384 void SystemAbilityManager::RemoveCheckLoadedMsg(int32_t systemAbilityId)
1385 {
1386     if (workHandler_ == nullptr) {
1387         HILOGE("RemoveCheckLoadedMsg work handler not initialized!");
1388         return;
1389     }
1390     workHandler_->RemoveTask(ToString(systemAbilityId));
1391 }
1392 
SendLoadedSystemAbilityMsg(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject,const sptr<ISystemAbilityLoadCallback> & callback)1393 void SystemAbilityManager::SendLoadedSystemAbilityMsg(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject,
1394     const sptr<ISystemAbilityLoadCallback>& callback)
1395 {
1396     if (workHandler_ == nullptr) {
1397         HILOGE("SendLoadedSystemAbilityMsg work handler not initialized!");
1398         return;
1399     }
1400     auto notifyLoadedTask = [systemAbilityId, remoteObject, callback, this]() {
1401         HILOGI("SendLoadedSystemAbilityMsg notify SA:%{public}d", systemAbilityId);
1402         NotifySystemAbilityLoaded(systemAbilityId, remoteObject, callback);
1403     };
1404     bool ret = workHandler_->PostTask(notifyLoadedTask);
1405     if (!ret) {
1406         HILOGW("SendLoadedSystemAbilityMsg PostTask failed!");
1407     }
1408 }
1409 
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject,const sptr<ISystemAbilityLoadCallback> & callback)1410 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject,
1411     const sptr<ISystemAbilityLoadCallback>& callback)
1412 {
1413     if (callback == nullptr) {
1414         HILOGE("NotifySystemAbilityLoaded callback null!");
1415         return;
1416     }
1417     HILOGD("NotifySystemAbilityLoaded SA:%{public}d, saSize:%{public}zu, processSize:%{public}zu, "
1418         "startingSASize:%{public}zu", systemAbilityId, abilityMap_.size(), systemProcessMap_.size(),
1419         startingAbilityMap_.size());
1420     callback->OnLoadSystemAbilitySuccess(systemAbilityId, remoteObject);
1421 }
1422 
NotifySystemAbilityLoaded(int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)1423 void SystemAbilityManager::NotifySystemAbilityLoaded(int32_t systemAbilityId, const sptr<IRemoteObject>& remoteObject)
1424 {
1425     lock_guard<mutex> autoLock(onDemandLock_);
1426     auto iter = startingAbilityMap_.find(systemAbilityId);
1427     if (iter == startingAbilityMap_.end()) {
1428         return;
1429     }
1430     auto& abilityItem = iter->second;
1431     for (auto& [deviceId, callbackList] : abilityItem.callbackMap) {
1432         for (auto& callbackItem : callbackList) {
1433             HILOGI("notify SA:%{public}d, saSize:%{public}zu, processSize:%{public}zu, callbacksize:%{public}d",
1434                 systemAbilityId, abilityMap_.size(), systemProcessMap_.size(), callbackItem.second);
1435             NotifySystemAbilityLoaded(systemAbilityId, remoteObject, callbackItem.first);
1436             RemoveStartingAbilityCallbackLocked(callbackItem);
1437         }
1438     }
1439     startingAbilityMap_.erase(iter);
1440 }
1441 
NotifySystemAbilityLoadFail(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)1442 void SystemAbilityManager::NotifySystemAbilityLoadFail(int32_t systemAbilityId,
1443     const sptr<ISystemAbilityLoadCallback>& callback)
1444 {
1445     if (callback == nullptr) {
1446         HILOGE("NotifySystemAbilityLoadFail callback null!");
1447         return;
1448     }
1449     HILOGI("NotifySystemAbilityLoadFailed SA:%{public}d", systemAbilityId);
1450     callback->OnLoadSystemAbilityFail(systemAbilityId);
1451 }
1452 
StartDynamicSystemProcess(const std::u16string & name,int32_t systemAbilityId,const OnDemandEvent & event)1453 int32_t SystemAbilityManager::StartDynamicSystemProcess(const std::u16string& name,
1454     int32_t systemAbilityId, const OnDemandEvent& event)
1455 {
1456     std::string eventStr = std::to_string(systemAbilityId) + "#" + std::to_string(event.eventId) + "#"
1457         + event.name + "#" + event.value + "#" + std::to_string(event.extraDataId) + "#";
1458     auto extraArgv = eventStr.c_str();
1459     if (abilityStateScheduler_ && abilityStateScheduler_->IsSystemProcessNeverStartedLocked(name)) {
1460         // Waiting for the init subsystem to perceive process death
1461         ServiceWaitForStatus(Str16ToStr8(name).c_str(), ServiceStatus::SERVICE_STOPPED, 1);
1462     }
1463     auto result = ServiceControlWithExtra(Str16ToStr8(name).c_str(), ServiceAction::START, &extraArgv, 1);
1464     HILOGI("StartDynamicSystemProcess call ServiceControlWithExtra process:%{public}s, SA:%{public}d, "
1465         "result:%{public}d!", Str16ToStr8(name).c_str(), systemAbilityId, result);
1466     return (result == 0) ? ERR_OK : ERR_INVALID_VALUE;
1467 }
1468 
StartingSystemProcessLocked(const std::u16string & procName,int32_t systemAbilityId,const OnDemandEvent & event)1469 int32_t SystemAbilityManager::StartingSystemProcessLocked(const std::u16string& procName,
1470     int32_t systemAbilityId, const OnDemandEvent& event)
1471 {
1472     bool isProcessStarted = false;
1473     {
1474         lock_guard<mutex> autoLock(systemProcessMapLock_);
1475         isProcessStarted = (systemProcessMap_.count(procName) != 0);
1476     }
1477     if (isProcessStarted) {
1478         bool isExist = false;
1479         StartOnDemandAbilityLocked(systemAbilityId, isExist);
1480         if (!isExist) {
1481             HILOGE("not found onDemand SA:%{public}d.", systemAbilityId);
1482         }
1483         return ERR_OK;
1484     }
1485     // call init start process
1486     {
1487         lock_guard<mutex> autoLock(startingProcessMapLock_);
1488         if (startingProcessMap_.count(procName) != 0) {
1489             HILOGI("StartingSystemProcess process:%{public}s already starting!", Str16ToStr8(procName).c_str());
1490             return ERR_OK;
1491         } else {
1492             int64_t begin = GetTickCount();
1493             startingProcessMap_.emplace(procName, begin);
1494         }
1495     }
1496     int32_t result = StartDynamicSystemProcess(procName, systemAbilityId, event);
1497     if (result != ERR_OK) {
1498         lock_guard<mutex> autoLock(startingProcessMapLock_);
1499         auto iterStarting = startingProcessMap_.find(procName);
1500         if (iterStarting != startingProcessMap_.end()) {
1501             startingProcessMap_.erase(iterStarting);
1502         }
1503     }
1504     return result;
1505 }
1506 
StartingSystemProcess(const std::u16string & procName,int32_t systemAbilityId,const OnDemandEvent & event)1507 int32_t SystemAbilityManager::StartingSystemProcess(const std::u16string& procName,
1508     int32_t systemAbilityId, const OnDemandEvent& event)
1509 {
1510     bool isProcessStarted = false;
1511     {
1512         lock_guard<mutex> autoLock(systemProcessMapLock_);
1513         isProcessStarted = (systemProcessMap_.count(procName) != 0);
1514     }
1515     if (isProcessStarted) {
1516         bool isExist = false;
1517         StartOnDemandAbility(systemAbilityId, isExist);
1518         if (!isExist) {
1519             HILOGE("not found onDemand SA:%{public}d.", systemAbilityId);
1520         }
1521         return ERR_OK;
1522     }
1523     // call init start process
1524     {
1525         lock_guard<mutex> autoLock(startingProcessMapLock_);
1526         if (startingProcessMap_.count(procName) != 0) {
1527             HILOGI("StartingSystemProcess process:%{public}s already starting!", Str16ToStr8(procName).c_str());
1528             return ERR_OK;
1529         } else {
1530             int64_t begin = GetTickCount();
1531             startingProcessMap_.emplace(procName, begin);
1532         }
1533     }
1534     int32_t result = StartDynamicSystemProcess(procName, systemAbilityId, event);
1535     if (result != ERR_OK) {
1536         lock_guard<mutex> autoLock(startingProcessMapLock_);
1537         auto iterStarting = startingProcessMap_.find(procName);
1538         if (iterStarting != startingProcessMap_.end()) {
1539             startingProcessMap_.erase(iterStarting);
1540         }
1541     }
1542     return result;
1543 }
1544 
DoLoadSystemAbility(int32_t systemAbilityId,const std::u16string & procName,const sptr<ISystemAbilityLoadCallback> & callback,int32_t callingPid,const OnDemandEvent & event)1545 int32_t SystemAbilityManager::DoLoadSystemAbility(int32_t systemAbilityId, const std::u16string& procName,
1546     const sptr<ISystemAbilityLoadCallback>& callback, int32_t callingPid, const OnDemandEvent& event)
1547 {
1548     int32_t result = ERR_INVALID_VALUE;
1549     {
1550         lock_guard<mutex> autoLock(onDemandLock_);
1551         sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
1552         if (targetObject != nullptr) {
1553             HILOGI("DoLoadSystemAbility notify SA:%{public}d callpid:%{public}d!", systemAbilityId, callingPid);
1554             NotifySystemAbilityLoaded(systemAbilityId, targetObject, callback);
1555             return ERR_OK;
1556         }
1557         auto& abilityItem = startingAbilityMap_[systemAbilityId];
1558         for (const auto& itemCallback : abilityItem.callbackMap[LOCAL_DEVICE]) {
1559             if (callback->AsObject() == itemCallback.first->AsObject()) {
1560                 HILOGI("LoadSystemAbility already existed callback object systemAbilityId:%{public}d", systemAbilityId);
1561                 return ERR_OK;
1562             }
1563         }
1564         auto& count = callbackCountMap_[callingPid];
1565         if (count >= MAX_SUBSCRIBE_COUNT) {
1566             HILOGE("LoadSystemAbility pid:%{public}d overflow max callback count!", callingPid);
1567             return ERR_PERMISSION_DENIED;
1568         }
1569         ++count;
1570         abilityItem.callbackMap[LOCAL_DEVICE].emplace_back(callback, callingPid);
1571         abilityItem.event = event;
1572         if (abilityCallbackDeath_ != nullptr) {
1573             bool ret = callback->AsObject()->AddDeathRecipient(abilityCallbackDeath_);
1574             HILOGI("LoadSystemAbility SA:%{public}d AddDeathRecipient %{public}s, count:%{public}d, callpid:%{public}d",
1575                 systemAbilityId, ret ? "succeed" : "failed", count, callingPid);
1576         }
1577         ReportSamgrSaLoad(systemAbilityId, event.eventId);
1578         HILOGI("LoadSystemAbility systemAbilityId:%{public}d size : %{public}zu, count:%{public}d",
1579             systemAbilityId, abilityItem.callbackMap[LOCAL_DEVICE].size(), count);
1580     }
1581     result = StartingSystemProcess(procName, systemAbilityId, event);
1582     SendCheckLoadedMsg(systemAbilityId, procName, LOCAL_DEVICE, callback);
1583     return result;
1584 }
1585 
DoLoadSystemAbilityFromRpc(const std::string & srcDeviceId,int32_t systemAbilityId,const std::u16string & procName,const sptr<ISystemAbilityLoadCallback> & callback,const OnDemandEvent & event)1586 int32_t SystemAbilityManager::DoLoadSystemAbilityFromRpc(const std::string& srcDeviceId, int32_t systemAbilityId,
1587     const std::u16string& procName, const sptr<ISystemAbilityLoadCallback>& callback, const OnDemandEvent& event)
1588 {
1589     {
1590         lock_guard<mutex> autoLock(onDemandLock_);
1591         sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
1592         if (targetObject != nullptr) {
1593             SendLoadedSystemAbilityMsg(systemAbilityId, targetObject, callback);
1594             return ERR_OK;
1595         }
1596         auto& abilityItem = startingAbilityMap_[systemAbilityId];
1597         abilityItem.callbackMap[srcDeviceId].emplace_back(callback, 0);
1598         StartingSystemProcessLocked(procName, systemAbilityId, event);
1599     }
1600     SendCheckLoadedMsg(systemAbilityId, procName, srcDeviceId, callback);
1601     return ERR_OK;
1602 }
1603 
LoadSystemAbility(int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)1604 int32_t SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId,
1605     const sptr<ISystemAbilityLoadCallback>& callback)
1606 {
1607     if (!CheckInputSysAbilityId(systemAbilityId) || callback == nullptr) {
1608         HILOGW("LoadSystemAbility systemAbilityId or callback invalid!");
1609         return ERR_INVALID_VALUE;
1610     }
1611     SaProfile saProfile;
1612     bool ret = GetSaProfile(systemAbilityId, saProfile);
1613     if (!ret) {
1614         HILOGE("LoadSystemAbility SA:%{public}d not supported!", systemAbilityId);
1615         return ERR_INVALID_VALUE;
1616     }
1617     auto callingPid = IPCSkeleton::GetCallingPid();
1618     OnDemandEvent onDemandEvent = {INTERFACE_CALL, "load"};
1619     LoadRequestInfo loadRequestInfo = {systemAbilityId, LOCAL_DEVICE, callback, callingPid, onDemandEvent};
1620     return abilityStateScheduler_->HandleLoadAbilityEvent(loadRequestInfo);
1621 }
1622 
LoadSystemAbilityFromRpc(const std::string & srcDeviceId,int32_t systemAbilityId,const sptr<ISystemAbilityLoadCallback> & callback)1623 bool SystemAbilityManager::LoadSystemAbilityFromRpc(const std::string& srcDeviceId, int32_t systemAbilityId,
1624     const sptr<ISystemAbilityLoadCallback>& callback)
1625 {
1626     if (!CheckInputSysAbilityId(systemAbilityId) || callback == nullptr) {
1627         HILOGW("LoadSystemAbility said or callback invalid!");
1628         return false;
1629     }
1630     SaProfile saProfile;
1631     bool ret = GetSaProfile(systemAbilityId, saProfile);
1632     if (!ret) {
1633         HILOGE("LoadSystemAbilityFromRpc SA:%{public}d not supported!", systemAbilityId);
1634         return false;
1635     }
1636 
1637     if (!saProfile.distributed) {
1638         HILOGE("LoadSystemAbilityFromRpc SA:%{public}d not distributed!", systemAbilityId);
1639         return false;
1640     }
1641     OnDemandEvent onDemandEvent = {INTERFACE_CALL, "loadFromRpc"};
1642     LoadRequestInfo loadRequestInfo = {systemAbilityId, srcDeviceId, callback, -1, onDemandEvent};
1643     if (abilityStateScheduler_ == nullptr) {
1644         HILOGE("abilityStateScheduler is nullptr");
1645         return false;
1646     }
1647     return abilityStateScheduler_->HandleLoadAbilityEvent(loadRequestInfo) == ERR_OK;
1648 }
1649 
UnloadSystemAbility(int32_t systemAbilityId)1650 int32_t SystemAbilityManager::UnloadSystemAbility(int32_t systemAbilityId)
1651 {
1652     SaProfile saProfile;
1653     bool ret = GetSaProfile(systemAbilityId, saProfile);
1654     if (!ret) {
1655         HILOGE("UnloadSystemAbility SA:%{public}d not supported!", systemAbilityId);
1656         return ERR_INVALID_VALUE;
1657     }
1658     if (!CheckCallerProcess(saProfile)) {
1659         HILOGE("UnloadSystemAbility invalid caller process, SA:%{public}d", systemAbilityId);
1660         return ERR_INVALID_VALUE;
1661     }
1662     if (abilityStateScheduler_ == nullptr) {
1663         HILOGE("abilityStateScheduler is nullptr");
1664         return ERR_INVALID_VALUE;
1665     }
1666     OnDemandEvent onDemandEvent = {INTERFACE_CALL, "unload"};
1667     auto callingPid = IPCSkeleton::GetCallingPid();
1668     UnloadRequestInfo unloadRequestInfo = {systemAbilityId, onDemandEvent, callingPid};
1669     return abilityStateScheduler_->HandleUnloadAbilityEvent(unloadRequestInfo);
1670 }
1671 
CheckSaIsImmediatelyRecycle(int32_t systemAbilityId)1672 bool SystemAbilityManager::CheckSaIsImmediatelyRecycle(int32_t systemAbilityId)
1673 {
1674     SaProfile saProfile;
1675     bool ret = GetSaProfile(systemAbilityId, saProfile);
1676     if (!ret) {
1677         HILOGE("UnloadSystemAbility SA:%{public}d not supported!", systemAbilityId);
1678         return ERR_INVALID_VALUE;
1679     }
1680     return saProfile.recycleStrategy == IMMEDIATELY;
1681 }
1682 
CancelUnloadSystemAbility(int32_t systemAbilityId)1683 int32_t SystemAbilityManager::CancelUnloadSystemAbility(int32_t systemAbilityId)
1684 {
1685     if (!CheckInputSysAbilityId(systemAbilityId)) {
1686         HILOGW("CancelUnloadSystemAbility systemAbilityId or callback invalid!");
1687         return ERR_INVALID_VALUE;
1688     }
1689     SaProfile saProfile;
1690     bool ret = GetSaProfile(systemAbilityId, saProfile);
1691     if (!ret) {
1692         HILOGE("CancelUnloadSystemAbility SA:%{public}d not supported!", systemAbilityId);
1693         return ERR_INVALID_VALUE;
1694     }
1695     if (!CheckCallerProcess(saProfile)) {
1696         HILOGE("CancelUnloadSystemAbility invalid caller process, SA:%{public}d", systemAbilityId);
1697         return ERR_INVALID_VALUE;
1698     }
1699     if (abilityStateScheduler_ == nullptr) {
1700         HILOGE("abilityStateScheduler is nullptr");
1701         return ERR_INVALID_VALUE;
1702     }
1703     return abilityStateScheduler_->HandleCancelUnloadAbilityEvent(systemAbilityId);
1704 }
1705 
DoUnloadSystemAbility(int32_t systemAbilityId,const std::u16string & procName,const OnDemandEvent & event)1706 int32_t SystemAbilityManager::DoUnloadSystemAbility(int32_t systemAbilityId,
1707     const std::u16string& procName, const OnDemandEvent& event)
1708 {
1709     lock_guard<mutex> autoLock(onDemandLock_);
1710     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
1711     if (targetObject == nullptr) {
1712         return ERR_OK;
1713     }
1714     bool result = StopOnDemandAbilityInner(procName, systemAbilityId, event);
1715     if (!result) {
1716         HILOGE("unload system ability failed, SA:%{public}d", systemAbilityId);
1717         return ERR_INVALID_VALUE;
1718     }
1719     ReportSamgrSaUnload(systemAbilityId, event.eventId);
1720     return ERR_OK;
1721 }
1722 
UnloadAllIdleSystemAbility()1723 int32_t SystemAbilityManager::UnloadAllIdleSystemAbility()
1724 {
1725     if (!CheckCallerProcess("memmgrservice")) {
1726         HILOGE("UnloadAllIdleSystemAbility invalid caller process, only support for memmgrservice");
1727         return ERR_PERMISSION_DENIED;
1728     }
1729     if (abilityStateScheduler_ == nullptr) {
1730         HILOGE("abilityStateScheduler is nullptr");
1731         return ERR_INVALID_VALUE;
1732     }
1733     return abilityStateScheduler_->UnloadAllIdleSystemAbility();
1734 }
1735 
IdleSystemAbility(int32_t systemAbilityId,const std::u16string & procName,const nlohmann::json & idleReason,int32_t & delayTime)1736 bool SystemAbilityManager::IdleSystemAbility(int32_t systemAbilityId, const std::u16string& procName,
1737     const nlohmann::json& idleReason, int32_t& delayTime)
1738 {
1739     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
1740     if (targetObject == nullptr) {
1741         HILOGE("IdleSystemAbility SA:%{public}d not loaded", systemAbilityId);
1742         return false;
1743     }
1744     sptr<ILocalAbilityManager> procObject =
1745         iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
1746     if (procObject == nullptr) {
1747         HILOGE("get process:%{public}s fail", Str16ToStr8(procName).c_str());
1748         return false;
1749     }
1750     return procObject->IdleAbility(systemAbilityId, idleReason, delayTime);
1751 }
1752 
ActiveSystemAbility(int32_t systemAbilityId,const std::u16string & procName,const nlohmann::json & activeReason)1753 bool SystemAbilityManager::ActiveSystemAbility(int32_t systemAbilityId, const std::u16string& procName,
1754     const nlohmann::json& activeReason)
1755 {
1756     sptr<IRemoteObject> targetObject = CheckSystemAbility(systemAbilityId);
1757     if (targetObject == nullptr) {
1758         HILOGE("ActiveSystemAbility SA:%{public}d not loaded", systemAbilityId);
1759         return false;
1760     }
1761     sptr<ILocalAbilityManager> procObject =
1762         iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
1763     if (procObject == nullptr) {
1764         HILOGE("get process:%{public}s fail", Str16ToStr8(procName).c_str());
1765         return false;
1766     }
1767     return procObject->ActiveAbility(systemAbilityId, activeReason);
1768 }
1769 
LoadSystemAbility(int32_t systemAbilityId,const std::string & deviceId,const sptr<ISystemAbilityLoadCallback> & callback)1770 int32_t SystemAbilityManager::LoadSystemAbility(int32_t systemAbilityId, const std::string& deviceId,
1771     const sptr<ISystemAbilityLoadCallback>& callback)
1772 {
1773     std::string key = ToString(systemAbilityId) + "_" + deviceId;
1774     {
1775         lock_guard<mutex> autoLock(loadRemoteLock_);
1776         auto& callbacks = remoteCallbacks_[key];
1777         auto iter = std::find_if(callbacks.begin(), callbacks.end(), [callback](auto itemCallback) {
1778             return callback->AsObject() == itemCallback->AsObject();
1779         });
1780         if (iter != callbacks.end()) {
1781             HILOGI("LoadSystemAbility already existed callback object SA:%{public}d", systemAbilityId);
1782             return ERR_OK;
1783         }
1784         if (remoteCallbackDeath_ != nullptr) {
1785             bool ret = callback->AsObject()->AddDeathRecipient(remoteCallbackDeath_);
1786             HILOGI("LoadSystemAbility SA:%{public}d AddDeathRecipient %{public}s",
1787                 systemAbilityId, ret ? "succeed" : "failed");
1788         }
1789         callbacks.emplace_back(callback);
1790     }
1791     auto callingPid = IPCSkeleton::GetCallingPid();
1792     auto callingUid = IPCSkeleton::GetCallingUid();
1793     auto task = std::bind(&SystemAbilityManager::DoLoadRemoteSystemAbility, this,
1794         systemAbilityId, callingPid, callingUid, deviceId, callback);
1795     std::thread thread(task);
1796     thread.detach();
1797     return ERR_OK;
1798 }
1799 
DoLoadRemoteSystemAbility(int32_t systemAbilityId,int32_t callingPid,int32_t callingUid,const std::string & deviceId,const sptr<ISystemAbilityLoadCallback> & callback)1800 void SystemAbilityManager::DoLoadRemoteSystemAbility(int32_t systemAbilityId, int32_t callingPid,
1801     int32_t callingUid, const std::string& deviceId, const sptr<ISystemAbilityLoadCallback>& callback)
1802 {
1803     Samgr::MemoryGuard cacheGuard;
1804     pthread_setname_np(pthread_self(), ONDEMAND_WORKER);
1805     sptr<DBinderServiceStub> remoteBinder = DoMakeRemoteBinder(systemAbilityId, callingPid, callingUid, deviceId);
1806 
1807     if (callback == nullptr) {
1808         HILOGI("DoLoadRemoteSystemAbility callback is null, SA:%{public}d", systemAbilityId);
1809         return;
1810     }
1811     callback->OnLoadSACompleteForRemote(deviceId, systemAbilityId, remoteBinder);
1812     std::string key = ToString(systemAbilityId) + "_" + deviceId;
1813     {
1814         lock_guard<mutex> autoLock(loadRemoteLock_);
1815         if (remoteCallbackDeath_ != nullptr) {
1816             callback->AsObject()->RemoveDeathRecipient(remoteCallbackDeath_);
1817         }
1818         auto& callbacks = remoteCallbacks_[key];
1819         callbacks.remove(callback);
1820         if (callbacks.empty()) {
1821             remoteCallbacks_.erase(key);
1822         }
1823     }
1824 }
1825 
1826 #ifdef SUPPORT_DEVICE_MANAGER
DeviceIdToNetworkId(std::string & networkId)1827 void SystemAbilityManager::DeviceIdToNetworkId(std::string& networkId)
1828 {
1829     std::vector<DmDeviceInfo> devList;
1830     if (DeviceManager::GetInstance().GetTrustedDeviceList(PKG_NAME, "", devList) == ERR_OK) {
1831         for (const DmDeviceInfo& devInfo : devList) {
1832             if (networkId == devInfo.deviceId) {
1833                 networkId = devInfo.networkId;
1834                 break;
1835             }
1836         }
1837     }
1838 }
1839 #endif
1840 
DoMakeRemoteBinder(int32_t systemAbilityId,int32_t callingPid,int32_t callingUid,const std::string & deviceId)1841 sptr<DBinderServiceStub> SystemAbilityManager::DoMakeRemoteBinder(int32_t systemAbilityId, int32_t callingPid,
1842     int32_t callingUid, const std::string& deviceId)
1843 {
1844     HILOGI("MakeRemoteBinder begin, SA:%{public}d", systemAbilityId);
1845     std::string networkId = deviceId;
1846 #ifdef SUPPORT_DEVICE_MANAGER
1847     DeviceIdToNetworkId(networkId);
1848 #endif
1849     sptr<DBinderServiceStub> remoteBinder = nullptr;
1850     if (dBinderService_ != nullptr) {
1851         string strName = to_string(systemAbilityId);
1852         remoteBinder = dBinderService_->MakeRemoteBinder(Str8ToStr16(strName),
1853             networkId, systemAbilityId, callingPid, callingUid);
1854     }
1855     HILOGI("MakeRemoteBinder end, result %{public}s, SA:%{public}d, networkId : %{public}s",
1856         remoteBinder == nullptr ? " failed" : "succeed", systemAbilityId, AnonymizeDeviceId(networkId).c_str());
1857     return remoteBinder;
1858 }
1859 
NotifyRpcLoadCompleted(const std::string & srcDeviceId,int32_t systemAbilityId,const sptr<IRemoteObject> & remoteObject)1860 void SystemAbilityManager::NotifyRpcLoadCompleted(const std::string& srcDeviceId, int32_t systemAbilityId,
1861     const sptr<IRemoteObject>& remoteObject)
1862 {
1863     if (workHandler_ == nullptr) {
1864         HILOGE("NotifyRpcLoadCompleted work handler not initialized!");
1865         return;
1866     }
1867     auto notifyTask = [srcDeviceId, systemAbilityId, remoteObject, this]() {
1868         if (dBinderService_ != nullptr) {
1869             dBinderService_->LoadSystemAbilityComplete(srcDeviceId, systemAbilityId, remoteObject);
1870             return;
1871         }
1872         HILOGW("NotifyRpcLoadCompleted failed, SA:%{public}d, deviceId : %{public}s",
1873             systemAbilityId, AnonymizeDeviceId(srcDeviceId).c_str());
1874     };
1875     bool ret = workHandler_->PostTask(notifyTask);
1876     if (!ret) {
1877         HILOGW("NotifyRpcLoadCompleted PostTask failed!");
1878     }
1879 }
1880 
RemoveStartingAbilityCallbackLocked(std::pair<sptr<ISystemAbilityLoadCallback>,int32_t> & itemPair)1881 void SystemAbilityManager::RemoveStartingAbilityCallbackLocked(
1882     std::pair<sptr<ISystemAbilityLoadCallback>, int32_t>& itemPair)
1883 {
1884     if (abilityCallbackDeath_ != nullptr) {
1885         itemPair.first->AsObject()->RemoveDeathRecipient(abilityCallbackDeath_);
1886     }
1887     auto iterCount = callbackCountMap_.find(itemPair.second);
1888     if (iterCount != callbackCountMap_.end()) {
1889         --iterCount->second;
1890         if (iterCount->second == 0) {
1891             callbackCountMap_.erase(iterCount);
1892         }
1893     }
1894 }
1895 
RemoveStartingAbilityCallbackForDevice(AbilityItem & abilityItem,const sptr<IRemoteObject> & remoteObject)1896 void SystemAbilityManager::RemoveStartingAbilityCallbackForDevice(AbilityItem& abilityItem,
1897     const sptr<IRemoteObject>& remoteObject)
1898 {
1899     auto& callbacks = abilityItem.callbackMap;
1900     auto iter = callbacks.begin();
1901     while (iter != callbacks.end()) {
1902         CallbackList& callbackList = iter->second;
1903         RemoveStartingAbilityCallback(callbackList, remoteObject);
1904         if (callbackList.empty()) {
1905             callbacks.erase(iter++);
1906         } else {
1907             ++iter;
1908         }
1909     }
1910 }
1911 
RemoveStartingAbilityCallback(CallbackList & callbackList,const sptr<IRemoteObject> & remoteObject)1912 void SystemAbilityManager::RemoveStartingAbilityCallback(CallbackList& callbackList,
1913     const sptr<IRemoteObject>& remoteObject)
1914 {
1915     auto iterCallback = callbackList.begin();
1916     while (iterCallback != callbackList.end()) {
1917         auto& callbackPair = *iterCallback;
1918         if (callbackPair.first->AsObject() == remoteObject) {
1919             RemoveStartingAbilityCallbackLocked(callbackPair);
1920             iterCallback = callbackList.erase(iterCallback);
1921             break;
1922         } else {
1923             ++iterCallback;
1924         }
1925     }
1926 }
1927 
OnAbilityCallbackDied(const sptr<IRemoteObject> & remoteObject)1928 void SystemAbilityManager::OnAbilityCallbackDied(const sptr<IRemoteObject>& remoteObject)
1929 {
1930     HILOGI("OnAbilityCallbackDied received remoteObject died message!");
1931     if (remoteObject == nullptr) {
1932         return;
1933     }
1934     lock_guard<mutex> autoLock(onDemandLock_);
1935     auto iter = startingAbilityMap_.begin();
1936     while (iter != startingAbilityMap_.end()) {
1937         AbilityItem& abilityItem = iter->second;
1938         RemoveStartingAbilityCallbackForDevice(abilityItem, remoteObject);
1939         if (abilityItem.callbackMap.empty()) {
1940             startingAbilityMap_.erase(iter++);
1941         } else {
1942             ++iter;
1943         }
1944     }
1945 }
1946 
OnRemoteCallbackDied(const sptr<IRemoteObject> & remoteObject)1947 void SystemAbilityManager::OnRemoteCallbackDied(const sptr<IRemoteObject>& remoteObject)
1948 {
1949     HILOGI("OnRemoteCallbackDied received remoteObject died message!");
1950     if (remoteObject == nullptr) {
1951         return;
1952     }
1953     lock_guard<mutex> autoLock(loadRemoteLock_);
1954     auto iter = remoteCallbacks_.begin();
1955     while (iter != remoteCallbacks_.end()) {
1956         auto& callbacks = iter->second;
1957         RemoveRemoteCallbackLocked(callbacks, remoteObject);
1958         if (callbacks.empty()) {
1959             remoteCallbacks_.erase(iter++);
1960         } else {
1961             ++iter;
1962         }
1963     }
1964 }
1965 
RemoveRemoteCallbackLocked(std::list<sptr<ISystemAbilityLoadCallback>> & callbacks,const sptr<IRemoteObject> & remoteObject)1966 void SystemAbilityManager::RemoveRemoteCallbackLocked(std::list<sptr<ISystemAbilityLoadCallback>>& callbacks,
1967     const sptr<IRemoteObject>& remoteObject)
1968 {
1969     for (const auto& callback : callbacks) {
1970         if (callback->AsObject() == remoteObject) {
1971             if (remoteCallbackDeath_ != nullptr) {
1972                 callback->AsObject()->RemoveDeathRecipient(remoteCallbackDeath_);
1973             }
1974             callbacks.remove(callback);
1975             break;
1976         }
1977     }
1978 }
1979 
TransformDeviceId(const std::string & deviceId,int32_t type,bool isPrivate)1980 std::string SystemAbilityManager::TransformDeviceId(const std::string& deviceId, int32_t type, bool isPrivate)
1981 {
1982     return isPrivate ? std::string() : deviceId;
1983 }
1984 
GetLocalNodeId()1985 std::string SystemAbilityManager::GetLocalNodeId()
1986 {
1987     return std::string();
1988 }
1989 
EventToStr(const OnDemandEvent & event)1990 std::string SystemAbilityManager::EventToStr(const OnDemandEvent& event)
1991 {
1992     nlohmann::json eventJson;
1993     eventJson[EVENT_TYPE] = event.eventId;
1994     eventJson[EVENT_NAME] = event.name;
1995     eventJson[EVENT_VALUE] = event.value;
1996     eventJson[EVENT_EXTRA_DATA_ID] = event.extraDataId;
1997     std::string eventStr = eventJson.dump();
1998     return eventStr;
1999 }
2000 
UpdateSaFreMap(int32_t uid,int32_t saId)2001 int32_t SystemAbilityManager::UpdateSaFreMap(int32_t uid, int32_t saId)
2002 {
2003     if (uid < 0) {
2004         HILOGW("UpdateSaFreMap return, uid not valid!");
2005         return -1;
2006     }
2007 
2008     uint64_t key = GenerateFreKey(uid, saId);
2009     lock_guard<mutex> autoLock(saFrequencyLock_);
2010     auto& count = saFrequencyMap_[key];
2011     if (count < MAX_SA_FREQUENCY_COUNT) {
2012         count++;
2013     }
2014     return count;
2015 }
2016 
GenerateFreKey(int32_t uid,int32_t saId) const2017 uint64_t SystemAbilityManager::GenerateFreKey(int32_t uid, int32_t saId) const
2018 {
2019     uint32_t uSaid = static_cast<uint32_t>(saId);
2020     uint64_t key = static_cast<uint64_t>(uid);
2021     return (key << SHFIT_BIT) | uSaid;
2022 }
2023 
ReportGetSAPeriodically()2024 void SystemAbilityManager::ReportGetSAPeriodically()
2025 {
2026     HILOGI("ReportGetSAPeriodically start!");
2027     lock_guard<mutex> autoLock(saFrequencyLock_);
2028     for (const auto& [key, count] : saFrequencyMap_) {
2029         uint32_t saId = static_cast<uint32_t>(key);
2030         uint32_t uid = key >> SHFIT_BIT;
2031         ReportGetSAFrequency(uid, saId, count);
2032     }
2033     saFrequencyMap_.clear();
2034 }
2035 
GetOnDemandSystemAbilityIds(std::vector<int32_t> & systemAbilityIds)2036 int32_t SystemAbilityManager::GetOnDemandSystemAbilityIds(std::vector<int32_t>& systemAbilityIds)
2037 {
2038     HILOGD("GetOnDemandSystemAbilityIds start!");
2039     if (onDemandSaIdsSet_.empty()) {
2040         HILOGD("GetOnDemandSystemAbilityIds error!");
2041         return ERR_INVALID_VALUE;
2042     }
2043     for (int32_t onDemandSaId : onDemandSaIdsSet_) {
2044         systemAbilityIds.emplace_back(onDemandSaId);
2045     }
2046     return ERR_OK;
2047 }
2048 
SendStrategy(int32_t type,std::vector<int32_t> & systemAbilityIds,int32_t level,std::string & action)2049 int32_t SystemAbilityManager::SendStrategy(int32_t type, std::vector<int32_t>& systemAbilityIds,
2050     int32_t level, std::string& action)
2051 {
2052     HILOGD("SendStrategy begin");
2053     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
2054     Security::AccessToken::NativeTokenInfo nativeTokenInfo;
2055     int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
2056     if (result != ERR_OK || nativeTokenInfo.processName != RESOURCE_SCHEDULE_PROCESS_NAME) {
2057         HILOGW("SendStrategy reject used by %{public}s", nativeTokenInfo.processName.c_str());
2058         return ERR_PERMISSION_DENIED;
2059     }
2060 
2061     for (auto saId : systemAbilityIds) {
2062         SaProfile saProfile;
2063         if (!GetSaProfile(saId, saProfile)) {
2064             HILOGW("not found SA: %{public}d.", saId);
2065             return ERR_INVALID_VALUE;
2066         }
2067         auto procName = saProfile.process;
2068         sptr<ILocalAbilityManager> procObject =
2069             iface_cast<ILocalAbilityManager>(GetSystemProcess(procName));
2070         if (procObject == nullptr) {
2071             HILOGW("get process:%{public}s fail", Str16ToStr8(procName).c_str());
2072             return ERR_INVALID_VALUE;
2073         }
2074         bool ret = procObject->SendStrategyToSA(type, saId, level, action);
2075         HILOGI("SendStrategy %{public}d %{public}s", saId, ret ? "success" : "failed");
2076     }
2077     return ERR_OK;
2078 }
2079 } // namespace OHOS
2080