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