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