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