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