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