1 /*
2 * Copyright (c) 2021-2024 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 "app_running_manager.h"
17
18 #include "app_mgr_service_inner.h"
19 #include "datetime_ex.h"
20 #include "iremote_object.h"
21
22 #include "appexecfwk_errors.h"
23 #include "app_utils.h"
24 #include "common_event_support.h"
25 #include "exit_resident_process_manager.h"
26 #include "freeze_util.h"
27 #include "hilog_tag_wrapper.h"
28 #include "hitrace_meter.h"
29 #include "os_account_manager_wrapper.h"
30 #include "perf_profile.h"
31 #include "parameters.h"
32 #include "quick_fix_callback_with_record.h"
33 #include <cstddef>
34 #include "scene_board_judgement.h"
35 #include "app_mgr_service_const.h"
36 #include "app_mgr_service_dump_error_code.h"
37 #include "cache_process_manager.h"
38 #include "res_sched_util.h"
39 #include "ui_extension_utils.h"
40 #include "window_visibility_info.h"
41 namespace OHOS {
42 namespace AppExecFwk {
43 namespace {
44 constexpr int32_t QUICKFIX_UID = 5524;
45 const std::string SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant";
46 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
47 }
48 using EventFwk::CommonEventSupport;
49
AppRunningManager()50 AppRunningManager::AppRunningManager()
51 : configuration_(std::make_shared<Configuration>())
52 {}
~AppRunningManager()53 AppRunningManager::~AppRunningManager()
54 {}
55
initConfig(const Configuration & config)56 void AppRunningManager::initConfig(const Configuration &config)
57 {
58 std::vector<std::string> changeKeyV;
59 configuration_->CompareDifferent(changeKeyV, config);
60 if (!changeKeyV.empty()) {
61 configuration_->Merge(changeKeyV, config);
62 }
63 }
64
CreateAppRunningRecord(const std::shared_ptr<ApplicationInfo> & appInfo,const std::string & processName,const BundleInfo & bundleInfo)65 std::shared_ptr<AppRunningRecord> AppRunningManager::CreateAppRunningRecord(
66 const std::shared_ptr<ApplicationInfo> &appInfo, const std::string &processName, const BundleInfo &bundleInfo)
67 {
68 if (!appInfo) {
69 TAG_LOGE(AAFwkTag::APPMGR, "param error");
70 return nullptr;
71 }
72
73 if (processName.empty()) {
74 TAG_LOGE(AAFwkTag::APPMGR, "processName error");
75 return nullptr;
76 }
77
78 auto recordId = AppRecordId::Create();
79 auto appRecord = std::make_shared<AppRunningRecord>(appInfo, recordId, processName);
80
81 std::regex rule("[a-zA-Z.]+[-_#]{1}");
82 std::string signCode;
83 bool isStageBasedModel = false;
84 ClipStringContent(rule, bundleInfo.appId, signCode);
85 if (!bundleInfo.hapModuleInfos.empty()) {
86 isStageBasedModel = bundleInfo.hapModuleInfos.back().isStageBasedModel;
87 }
88 TAG_LOGD(AAFwkTag::APPMGR,
89 "Create AppRunningRecord, processName: %{public}s, StageBasedModel:%{public}d, recordId: %{public}d",
90 processName.c_str(), isStageBasedModel, recordId);
91
92 appRecord->SetStageModelState(isStageBasedModel);
93 appRecord->SetSingleton(bundleInfo.singleton);
94 appRecord->SetKeepAliveBundle(bundleInfo.isKeepAlive);
95 appRecord->SetSignCode(signCode);
96 appRecord->SetJointUserId(bundleInfo.jointUserId);
97 appRecord->SetAppIdentifier(bundleInfo.signatureInfo.appIdentifier);
98 {
99 std::lock_guard guard(runningRecordMapMutex_);
100 appRunningRecordMap_.emplace(recordId, appRecord);
101 }
102 {
103 std::lock_guard guard(updateConfigurationDelayedLock_);
104 updateConfigurationDelayedMap_.emplace(recordId, false);
105 }
106 return appRecord;
107 }
108
CheckAppRunningRecordIsExist(const std::string & appName,const std::string & processName,const int uid,const BundleInfo & bundleInfo,const std::string & specifiedProcessFlag)109 std::shared_ptr<AppRunningRecord> AppRunningManager::CheckAppRunningRecordIsExist(const std::string &appName,
110 const std::string &processName, const int uid, const BundleInfo &bundleInfo,
111 const std::string &specifiedProcessFlag)
112 {
113 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
114 TAG_LOGD(AAFwkTag::APPMGR,
115 "appName: %{public}s, processName: %{public}s, uid: %{public}d, specifiedProcessFlag: %{public}s",
116 appName.c_str(), processName.c_str(), uid, specifiedProcessFlag.c_str());
117 std::regex rule("[a-zA-Z.]+[-_#]{1}");
118 std::string signCode;
119 auto jointUserId = bundleInfo.jointUserId;
120 TAG_LOGD(AAFwkTag::APPMGR, "jointUserId : %{public}s", jointUserId.c_str());
121 ClipStringContent(rule, bundleInfo.appId, signCode);
122
123 auto FindSameProcess = [signCode, specifiedProcessFlag, processName, jointUserId](const auto &pair) {
124 return (pair.second != nullptr) &&
125 (specifiedProcessFlag.empty() ||
126 pair.second->GetSpecifiedProcessFlag() == specifiedProcessFlag) &&
127 (pair.second->GetSignCode() == signCode) &&
128 (pair.second->GetProcessName() == processName) &&
129 (pair.second->GetJointUserId() == jointUserId) &&
130 !(pair.second->IsTerminating()) &&
131 !(pair.second->IsKilling()) && !(pair.second->GetRestartAppFlag());
132 };
133
134 auto appRunningMap = GetAppRunningRecordMap();
135 if (!jointUserId.empty()) {
136 auto iter = std::find_if(appRunningMap.begin(), appRunningMap.end(), FindSameProcess);
137 return ((iter == appRunningMap.end()) ? nullptr : iter->second);
138 }
139 for (const auto &item : appRunningMap) {
140 const auto &appRecord = item.second;
141 if (appRecord && appRecord->GetProcessName() == processName &&
142 (specifiedProcessFlag.empty() ||
143 appRecord->GetSpecifiedProcessFlag() == specifiedProcessFlag) &&
144 !(appRecord->IsTerminating()) && !(appRecord->IsKilling()) && !(appRecord->GetRestartAppFlag()) &&
145 !(appRecord->IsUserRequestCleaning())) {
146 auto appInfoList = appRecord->GetAppInfoList();
147 TAG_LOGD(AAFwkTag::APPMGR,
148 "appInfoList: %{public}zu, processName: %{public}s, specifiedProcessFlag: %{public}s",
149 appInfoList.size(), appRecord->GetProcessName().c_str(), specifiedProcessFlag.c_str());
150 auto isExist = [&appName, &uid](const std::shared_ptr<ApplicationInfo> &appInfo) {
151 TAG_LOGD(AAFwkTag::APPMGR, "appInfo->name: %{public}s", appInfo->name.c_str());
152 return appInfo->name == appName && appInfo->uid == uid;
153 };
154 auto appInfoIter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
155 if (appInfoIter != appInfoList.end()) {
156 DelayedSingleton<CacheProcessManager>::GetInstance()->ReuseCachedProcess(appRecord);
157 return appRecord;
158 }
159 }
160 }
161 return nullptr;
162 }
163
164 #ifdef APP_NO_RESPONSE_DIALOG
CheckAppRunningRecordIsExist(const std::string & bundleName,const std::string & ablityName)165 bool AppRunningManager::CheckAppRunningRecordIsExist(const std::string &bundleName, const std::string &ablityName)
166 {
167 std::lock_guard guard(runningRecordMapMutex_);
168 if (appRunningRecordMap_.empty()) {
169 return false;
170 }
171 for (const auto &item : appRunningRecordMap_) {
172 const auto &appRecord = item.second;
173 if (!appRecord) {
174 continue;
175 }
176 if (appRecord->GetBundleName() != bundleName) {
177 continue;
178 }
179 const auto &abilityRunningRecordMap = appRecord->GetAbilities();
180 for (const auto &abilityItem : abilityRunningRecordMap) {
181 const auto &abilityRunning = abilityItem.second;
182 if (abilityRunning && abilityRunning->GetName() == ablityName) {
183 return true;
184 }
185 }
186 }
187 return false;
188 }
189 #endif
190
CheckAppRunningRecordIsExistByBundleName(const std::string & bundleName)191 bool AppRunningManager::CheckAppRunningRecordIsExistByBundleName(const std::string &bundleName)
192 {
193 std::lock_guard guard(runningRecordMapMutex_);
194 if (appRunningRecordMap_.empty()) {
195 return false;
196 }
197 for (const auto &item : appRunningRecordMap_) {
198 const auto &appRecord = item.second;
199 if (appRecord && appRecord->GetBundleName() == bundleName && !(appRecord->GetRestartAppFlag())) {
200 return true;
201 }
202 }
203 return false;
204 }
205
CheckAppRunningRecordIsExistByUid(int32_t uid)206 bool AppRunningManager::CheckAppRunningRecordIsExistByUid(int32_t uid)
207 {
208 std::lock_guard guard(runningRecordMapMutex_);
209 if (appRunningRecordMap_.empty()) {
210 return false;
211 }
212 for (const auto &item : appRunningRecordMap_) {
213 const auto &appRecord = item.second;
214 if (appRecord && appRecord->GetUid() == uid && !(appRecord->GetRestartAppFlag())) {
215 return true;
216 }
217 }
218 return false;
219 }
220
CheckAppCloneRunningRecordIsExistByBundleName(const std::string & bundleName,int32_t appCloneIndex,bool & isRunning)221 int32_t AppRunningManager::CheckAppCloneRunningRecordIsExistByBundleName(const std::string &bundleName,
222 int32_t appCloneIndex, bool &isRunning)
223 {
224 std::lock_guard guard(runningRecordMapMutex_);
225 for (const auto &item : appRunningRecordMap_) {
226 const auto &appRecord = item.second;
227 if (appRecord && appRecord->GetBundleName() == bundleName && !(appRecord->GetRestartAppFlag()) &&
228 appRecord->GetAppIndex() == appCloneIndex) {
229 isRunning = true;
230 break;
231 }
232 }
233 return ERR_OK;
234 }
235
GetAllAppRunningRecordCountByBundleName(const std::string & bundleName)236 int32_t AppRunningManager::GetAllAppRunningRecordCountByBundleName(const std::string &bundleName)
237 {
238 int32_t count = 0;
239 std::lock_guard guard(runningRecordMapMutex_);
240 for (const auto &item : appRunningRecordMap_) {
241 const auto &appRecord = item.second;
242 if (appRecord && appRecord->GetBundleName() == bundleName) {
243 count++;
244 }
245 }
246
247 return count;
248 }
249
GetAppRunningRecordByPid(const pid_t pid)250 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByPid(const pid_t pid)
251 {
252 std::lock_guard guard(runningRecordMapMutex_);
253 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
254 return pair.second->GetPriorityObject()->GetPid() == pid;
255 });
256 return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second);
257 }
258
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken)259 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByAbilityToken(
260 const sptr<IRemoteObject> &abilityToken)
261 {
262 std::lock_guard guard(runningRecordMapMutex_);
263 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
264 for (const auto &item : appRunningRecordMap_) {
265 const auto &appRecord = item.second;
266 if (appRecord && appRecord->GetAbilityRunningRecordByToken(abilityToken)) {
267 return appRecord;
268 }
269 }
270 return nullptr;
271 }
272
ProcessExitByBundleName(const std::string & bundleName,std::list<pid_t> & pids)273 bool AppRunningManager::ProcessExitByBundleName(const std::string &bundleName, std::list<pid_t> &pids)
274 {
275 auto appRunningMap = GetAppRunningRecordMap();
276 for (const auto &item : appRunningMap) {
277 const auto &appRecord = item.second;
278 // condition [!appRecord->IsKeepAliveApp()] Is to not kill the resident process.
279 // Before using this method, consider whether you need.
280 if (appRecord && (!appRecord->IsKeepAliveApp() ||
281 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent())) {
282 pid_t pid = appRecord->GetPriorityObject()->GetPid();
283 auto appInfoList = appRecord->GetAppInfoList();
284 auto isExist = [&bundleName](const std::shared_ptr<ApplicationInfo> &appInfo) {
285 return appInfo->bundleName == bundleName;
286 };
287 auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
288 if (iter != appInfoList.end() && pid > 0) {
289 pids.push_back(pid);
290 appRecord->ScheduleProcessSecurityExit();
291 }
292 }
293 }
294
295 return !pids.empty();
296 }
297
GetPidsByUserId(int32_t userId,std::list<pid_t> & pids)298 bool AppRunningManager::GetPidsByUserId(int32_t userId, std::list<pid_t> &pids)
299 {
300 auto appRunningMap = GetAppRunningRecordMap();
301 for (const auto &item : appRunningMap) {
302 const auto &appRecord = item.second;
303 if (appRecord) {
304 int32_t id = -1;
305 if ((DelayedSingleton<OsAccountManagerWrapper>::GetInstance()->
306 GetOsAccountLocalIdFromUid(appRecord->GetUid(), id) == 0) && (id == userId)) {
307 pid_t pid = appRecord->GetPriorityObject()->GetPid();
308 if (pid > 0) {
309 pids.push_back(pid);
310 appRecord->ScheduleProcessSecurityExit();
311 }
312 }
313 }
314 }
315
316 return (!pids.empty());
317 }
318
ProcessUpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)319 int32_t AppRunningManager::ProcessUpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
320 {
321 auto appRunningMap = GetAppRunningRecordMap();
322 int32_t result = ERR_OK;
323 for (const auto &item : appRunningMap) {
324 const auto &appRecord = item.second;
325 if (!appRecord) {
326 continue;
327 }
328 auto appInfoList = appRecord->GetAppInfoList();
329 for (auto iter : appInfoList) {
330 if (iter->bundleName == appInfo.bundleName && iter->uid == appInfo.uid) {
331 appRecord->UpdateApplicationInfoInstalled(appInfo);
332 break;
333 }
334 }
335 }
336 return result;
337 }
338
ProcessExitByBundleNameAndUid(const std::string & bundleName,const int uid,std::list<pid_t> & pids)339 bool AppRunningManager::ProcessExitByBundleNameAndUid(
340 const std::string &bundleName, const int uid, std::list<pid_t> &pids)
341 {
342 auto appRunningMap = GetAppRunningRecordMap();
343 for (const auto &item : appRunningMap) {
344 const auto &appRecord = item.second;
345 if (appRecord) {
346 auto appInfoList = appRecord->GetAppInfoList();
347 auto isExist = [&bundleName, &uid](const std::shared_ptr<ApplicationInfo> &appInfo) {
348 return appInfo->bundleName == bundleName && appInfo->uid == uid;
349 };
350 auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
351 pid_t pid = appRecord->GetPriorityObject()->GetPid();
352 if (iter != appInfoList.end() && pid > 0) {
353 pids.push_back(pid);
354
355 appRecord->SetKilling();
356 appRecord->ScheduleProcessSecurityExit();
357 }
358 }
359 }
360
361 return (pids.empty() ? false : true);
362 }
363
GetPidsByBundleNameUserIdAndAppIndex(const std::string & bundleName,const int userId,const int appIndex,std::list<pid_t> & pids)364 bool AppRunningManager::GetPidsByBundleNameUserIdAndAppIndex(const std::string &bundleName,
365 const int userId, const int appIndex, std::list<pid_t> &pids)
366 {
367 auto appRunningMap = GetAppRunningRecordMap();
368 for (const auto &item : appRunningMap) {
369 const auto &appRecord = item.second;
370 if (appRecord == nullptr) {
371 continue;
372 }
373 auto appInfoList = appRecord->GetAppInfoList();
374 auto isExist = [&bundleName, &userId, &appIndex](const std::shared_ptr<ApplicationInfo> &appInfo) {
375 return appInfo->bundleName == bundleName && appInfo->uid / BASE_USER_RANGE == userId &&
376 appInfo->appIndex == appIndex;
377 };
378 auto iter = std::find_if(appInfoList.begin(), appInfoList.end(), isExist);
379 pid_t pid = appRecord->GetPriorityObject()->GetPid();
380 if (iter == appInfoList.end() || pid <= 0) {
381 continue;
382 }
383 pids.push_back(pid);
384 appRecord->SetKilling();
385 }
386
387 return (!pids.empty());
388 }
389
OnRemoteDied(const wptr<IRemoteObject> & remote,std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)390 std::shared_ptr<AppRunningRecord> AppRunningManager::OnRemoteDied(const wptr<IRemoteObject> &remote,
391 std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)
392 {
393 TAG_LOGD(AAFwkTag::APPMGR, "called");
394 if (remote == nullptr) {
395 TAG_LOGE(AAFwkTag::APPMGR, "null remote");
396 return nullptr;
397 }
398 sptr<IRemoteObject> object = remote.promote();
399 if (!object) {
400 TAG_LOGE(AAFwkTag::APPMGR, "null object");
401 return nullptr;
402 }
403
404 std::shared_ptr<AppRunningRecord> appRecord = nullptr;
405 {
406 std::lock_guard guard(runningRecordMapMutex_);
407 const auto &iter =
408 std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&object](const auto &pair) {
409 if (pair.second && pair.second->GetApplicationClient() != nullptr) {
410 return pair.second->GetApplicationClient()->AsObject() == object;
411 }
412 return false;
413 });
414 if (iter == appRunningRecordMap_.end()) {
415 TAG_LOGE(AAFwkTag::APPMGR, "remote not in map");
416 return nullptr;
417 }
418 appRecord = iter->second;
419 appRunningRecordMap_.erase(iter);
420 }
421 if (appRecord != nullptr) {
422 {
423 std::lock_guard guard(updateConfigurationDelayedLock_);
424 updateConfigurationDelayedMap_.erase(appRecord->GetRecordId());
425 }
426 appRecord->RemoveAppDeathRecipient();
427 appRecord->SetApplicationClient(nullptr);
428 TAG_LOGI(AAFwkTag::APPMGR, "pname: %{public}s", appRecord->GetProcessName().c_str());
429 auto priorityObject = appRecord->GetPriorityObject();
430 if (priorityObject != nullptr) {
431 TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d", priorityObject->GetPid());
432 if (appMgrServiceInner != nullptr) {
433 appMgrServiceInner->KillProcessByPid(priorityObject->GetPid(), "OnRemoteDied");
434 }
435 AbilityRuntime::FreezeUtil::GetInstance().DeleteAppLifecycleEvent(priorityObject->GetPid());
436 }
437 }
438 if (appRecord != nullptr && appRecord->GetPriorityObject() != nullptr) {
439 RemoveUIExtensionLauncherItem(appRecord->GetPriorityObject()->GetPid());
440 }
441
442 return appRecord;
443 }
444
GetAppRunningRecordMap()445 std::map<const int32_t, const std::shared_ptr<AppRunningRecord>> AppRunningManager::GetAppRunningRecordMap()
446 {
447 std::lock_guard guard(runningRecordMapMutex_);
448 return appRunningRecordMap_;
449 }
450
RemoveAppRunningRecordById(const int32_t recordId)451 void AppRunningManager::RemoveAppRunningRecordById(const int32_t recordId)
452 {
453 std::shared_ptr<AppRunningRecord> appRecord = nullptr;
454 {
455 std::lock_guard guard(runningRecordMapMutex_);
456 auto it = appRunningRecordMap_.find(recordId);
457 if (it != appRunningRecordMap_.end()) {
458 appRecord = it->second;
459 appRunningRecordMap_.erase(it);
460 }
461 }
462 {
463 std::lock_guard guard(updateConfigurationDelayedLock_);
464 updateConfigurationDelayedMap_.erase(recordId);
465 }
466
467 if (appRecord != nullptr && appRecord->GetPriorityObject() != nullptr) {
468 RemoveUIExtensionLauncherItem(appRecord->GetPriorityObject()->GetPid());
469 AbilityRuntime::FreezeUtil::GetInstance().DeleteAppLifecycleEvent(appRecord->GetPriorityObject()->GetPid());
470 }
471 }
472
ClearAppRunningRecordMap()473 void AppRunningManager::ClearAppRunningRecordMap()
474 {
475 std::lock_guard guard(runningRecordMapMutex_);
476 appRunningRecordMap_.clear();
477 }
478
HandleTerminateTimeOut(int64_t eventId)479 void AppRunningManager::HandleTerminateTimeOut(int64_t eventId)
480 {
481 TAG_LOGD(AAFwkTag::APPMGR, "called");
482 auto abilityRecord = GetAbilityRunningRecord(eventId);
483 if (!abilityRecord) {
484 TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord is nullptr.");
485 return;
486 }
487 auto abilityToken = abilityRecord->GetToken();
488 auto appRecord = GetTerminatingAppRunningRecord(abilityToken);
489 if (!appRecord) {
490 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
491 return;
492 }
493 appRecord->AbilityTerminated(abilityToken);
494 }
495
GetTerminatingAppRunningRecord(const sptr<IRemoteObject> & abilityToken)496 std::shared_ptr<AppRunningRecord> AppRunningManager::GetTerminatingAppRunningRecord(
497 const sptr<IRemoteObject> &abilityToken)
498 {
499 std::lock_guard guard(runningRecordMapMutex_);
500 for (const auto &item : appRunningRecordMap_) {
501 const auto &appRecord = item.second;
502 if (appRecord && appRecord->GetAbilityByTerminateLists(abilityToken)) {
503 return appRecord;
504 }
505 }
506 return nullptr;
507 }
508
GetAbilityRunningRecord(const int64_t eventId)509 std::shared_ptr<AbilityRunningRecord> AppRunningManager::GetAbilityRunningRecord(const int64_t eventId)
510 {
511 TAG_LOGD(AAFwkTag::APPMGR, "called");
512 std::lock_guard guard(runningRecordMapMutex_);
513 for (auto &item : appRunningRecordMap_) {
514 if (item.second) {
515 auto abilityRecord = item.second->GetAbilityRunningRecord(eventId);
516 if (abilityRecord) {
517 return abilityRecord;
518 }
519 }
520 }
521 return nullptr;
522 }
523
GetAppRunningRecord(const int64_t eventId)524 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecord(const int64_t eventId)
525 {
526 TAG_LOGD(AAFwkTag::APPMGR, "called");
527 std::lock_guard guard(runningRecordMapMutex_);
528 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&eventId](const auto &pair) {
529 return pair.second->GetEventId() == eventId;
530 });
531 return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second);
532 }
533
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token,std::shared_ptr<AppMgrServiceInner> serviceInner)534 void AppRunningManager::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token,
535 std::shared_ptr<AppMgrServiceInner> serviceInner)
536 {
537 TAG_LOGD(AAFwkTag::APPMGR, "called");
538 if (token == nullptr) {
539 TAG_LOGE(AAFwkTag::APPMGR, "token is nullptr.");
540 return;
541 }
542
543 auto appRecord = GetAppRunningRecordByAbilityToken(token);
544 if (!appRecord) {
545 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
546 return;
547 }
548
549 std::shared_ptr<AbilityRunningRecord> abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
550 bool isSCB = false;
551 if (abilityRecord) {
552 abilityRecord->SetTerminating();
553 isSCB = abilityRecord->IsSceneBoard();
554 if (isSCB && appRecord->GetPriorityObject() && serviceInner != nullptr) {
555 pid_t pid = appRecord->GetPriorityObject()->GetPid();
556 (void)serviceInner->KillProcessByPid(pid, "AttachTimeoutKillSCB");
557 }
558 appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(
559 AbilityState::ABILITY_STATE_TERMINATED), true, false);
560 }
561
562 if ((isSCB || appRecord->IsLastAbilityRecord(token)) && (!appRecord->IsKeepAliveApp() ||
563 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent())) {
564 appRecord->SetTerminating();
565 }
566
567 std::weak_ptr<AppRunningRecord> appRecordWptr(appRecord);
568 auto timeoutTask = [appRecordWptr, token]() {
569 auto appRecord = appRecordWptr.lock();
570 if (appRecord == nullptr) {
571 TAG_LOGW(AAFwkTag::APPMGR, "null appRecord");
572 return;
573 }
574 appRecord->TerminateAbility(token, true, true);
575 };
576 appRecord->PostTask("DELAY_KILL_ABILITY", AMSEventHandler::KILL_PROCESS_TIMEOUT, timeoutTask);
577 }
578
PrepareTerminate(const sptr<IRemoteObject> & token,bool clearMissionFlag)579 void AppRunningManager::PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag)
580 {
581 if (token == nullptr) {
582 TAG_LOGE(AAFwkTag::APPMGR, "token is nullptr.");
583 return;
584 }
585
586 auto appRecord = GetAppRunningRecordByAbilityToken(token);
587 if (!appRecord) {
588 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
589 return;
590 }
591
592 auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
593 if (abilityRecord) {
594 abilityRecord->SetTerminating();
595 }
596
597 // set app record terminating when close last page ability
598 auto isLastAbility =
599 clearMissionFlag ? appRecord->IsLastPageAbilityRecord(token) : appRecord->IsLastAbilityRecord(token);
600 if (isLastAbility && (!appRecord->IsKeepAliveApp() ||
601 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent())) {
602 auto cacheProcMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
603 if (cacheProcMgr != nullptr) {
604 cacheProcMgr->CheckAndSetProcessCacheEnable(appRecord);
605 }
606 if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) {
607 cacheProcMgr->PenddingCacheProcess(appRecord);
608 TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s supports process cache, not terminate record.",
609 appRecord->GetBundleName().c_str());
610 return;
611 }
612 TAG_LOGI(AAFwkTag::APPMGR, "The ability is the last in the app:%{public}s.", appRecord->GetName().c_str());
613 appRecord->SetTerminating();
614 }
615 }
616
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag,std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)617 void AppRunningManager::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag,
618 std::shared_ptr<AppMgrServiceInner> appMgrServiceInner)
619 {
620 auto appRecord = GetAppRunningRecordByAbilityToken(token);
621 if (!appRecord) {
622 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
623 return;
624 }
625
626 auto killProcess = [appRecord, token, inner = appMgrServiceInner]() {
627 if (appRecord == nullptr || token == nullptr || inner == nullptr) {
628 TAG_LOGE(AAFwkTag::APPMGR, "Pointer parameter error.");
629 return;
630 }
631 appRecord->RemoveTerminateAbilityTimeoutTask(token);
632 TAG_LOGD(AAFwkTag::APPMGR, "The ability is the last, kill application");
633 auto priorityObject = appRecord->GetPriorityObject();
634 if (priorityObject == nullptr) {
635 TAG_LOGE(AAFwkTag::APPMGR, "priorityObject is nullptr.");
636 return;
637 }
638 auto pid = priorityObject->GetPid();
639 if (pid < 0) {
640 TAG_LOGE(AAFwkTag::APPMGR, "Pid error.");
641 return;
642 }
643 auto result = inner->KillProcessByPid(pid, "TerminateAbility");
644 if (result < 0) {
645 TAG_LOGW(AAFwkTag::APPMGR, "Kill application directly failed, pid: %{public}d", pid);
646 }
647 inner->NotifyAppStatus(appRecord->GetBundleName(), CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
648 };
649
650 if (clearMissionFlag && appRecord->IsDebugApp()) {
651 killProcess();
652 return;
653 }
654
655 auto isLastAbility =
656 clearMissionFlag ? appRecord->IsLastPageAbilityRecord(token) : appRecord->IsLastAbilityRecord(token);
657 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
658 appRecord->TerminateAbility(token, true);
659 } else {
660 appRecord->TerminateAbility(token, false);
661 }
662 auto isLauncherApp = appRecord->GetApplicationInfo()->isLauncherApp;
663 auto isKeepAliveApp = appRecord->IsKeepAliveApp();
664 TAG_LOGI(AAFwkTag::APPMGR, "TerminateAbility:isLast:%{public}d,keepAlive:%{public}d",
665 isLastAbility, isKeepAliveApp);
666 if (isLastAbility && (!isKeepAliveApp ||
667 !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent()) && !isLauncherApp) {
668 auto cacheProcMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
669 if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) {
670 cacheProcMgr->PenddingCacheProcess(appRecord);
671 TAG_LOGI(AAFwkTag::APPMGR, "app %{public}s is not terminate app",
672 appRecord->GetBundleName().c_str());
673 if (clearMissionFlag) {
674 NotifyAppPreCache(appRecord, appMgrServiceInner);
675 }
676 return;
677 }
678 TAG_LOGI(AAFwkTag::APPMGR, "Terminate last ability in app:%{public}s.", appRecord->GetName().c_str());
679 appRecord->SetTerminating();
680 if (clearMissionFlag && appMgrServiceInner != nullptr) {
681 auto delayTime = appRecord->ExtensionAbilityRecordExists() ?
682 AMSEventHandler::DELAY_KILL_EXTENSION_PROCESS_TIMEOUT : AMSEventHandler::DELAY_KILL_PROCESS_TIMEOUT;
683 appRecord->PostTask("DELAY_KILL_PROCESS", delayTime, killProcess);
684 }
685 }
686 }
687
NotifyAppPreCache(const std::shared_ptr<AppRunningRecord> & appRecord,const std::shared_ptr<AppMgrServiceInner> & appMgrServiceInner)688 void AppRunningManager::NotifyAppPreCache(const std::shared_ptr<AppRunningRecord>& appRecord,
689 const std::shared_ptr<AppMgrServiceInner>& appMgrServiceInner)
690 {
691 if (appMgrServiceInner == nullptr || appRecord == nullptr ||
692 appRecord->GetPriorityObject() == nullptr) {
693 return;
694 }
695 int32_t pid = appRecord->GetPriorityObject()->GetPid();
696 int32_t userId = appRecord->GetUid() / BASE_USER_RANGE;
697 auto notifyAppPreCache = [pid, userId, inner = appMgrServiceInner]() {
698 if (inner == nullptr) {
699 return;
700 }
701 inner->NotifyAppPreCache(pid, userId);
702 };
703 appRecord->PostTask("NotifyAppPreCache", 0, notifyAppPreCache);
704 }
705
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)706 void AppRunningManager::GetRunningProcessInfoByToken(
707 const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
708 {
709 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
710 auto appRecord = GetAppRunningRecordByAbilityToken(token);
711 AssignRunningProcessInfoByAppRecord(appRecord, info);
712 }
713
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info)714 int32_t AppRunningManager::GetRunningProcessInfoByPid(const pid_t pid, OHOS::AppExecFwk::RunningProcessInfo &info)
715 {
716 if (pid <= 0) {
717 TAG_LOGE(AAFwkTag::APPMGR, "invalid process pid:%{public}d", pid);
718 return ERR_INVALID_OPERATION;
719 }
720 auto appRecord = GetAppRunningRecordByPid(pid);
721 return AssignRunningProcessInfoByAppRecord(appRecord, info);
722 }
723
AssignRunningProcessInfoByAppRecord(std::shared_ptr<AppRunningRecord> appRecord,AppExecFwk::RunningProcessInfo & info) const724 int32_t AppRunningManager::AssignRunningProcessInfoByAppRecord(
725 std::shared_ptr<AppRunningRecord> appRecord, AppExecFwk::RunningProcessInfo &info) const
726 {
727 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
728 if (!appRecord) {
729 TAG_LOGE(AAFwkTag::APPMGR, "null");
730 return ERR_INVALID_OPERATION;
731 }
732
733 info.processName_ = appRecord->GetProcessName();
734 info.pid_ = appRecord->GetPriorityObject()->GetPid();
735 info.uid_ = appRecord->GetUid();
736 info.bundleNames.emplace_back(appRecord->GetBundleName());
737 info.state_ = static_cast<AppExecFwk::AppProcessState>(appRecord->GetState());
738 info.isContinuousTask = appRecord->IsContinuousTask();
739 info.isKeepAlive = appRecord->IsKeepAliveApp();
740 info.isFocused = appRecord->GetFocusFlag();
741 info.isTestProcess = (appRecord->GetUserTestInfo() != nullptr);
742 info.startTimeMillis_ = appRecord->GetAppStartTime();
743 info.isAbilityForegrounding = appRecord->GetAbilityForegroundingFlag();
744 info.isTestMode = info.isTestProcess && system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
745 info.extensionType_ = appRecord->GetExtensionType();
746 info.processType_ = appRecord->GetProcessType();
747 info.isStrictMode = appRecord->IsStrictMode();
748 auto appInfo = appRecord->GetApplicationInfo();
749 if (appInfo) {
750 info.bundleType = static_cast<int32_t>(appInfo->bundleType);
751 }
752 if (appInfo && (static_cast<int32_t>(appInfo->multiAppMode.multiAppModeType) ==
753 static_cast<int32_t>(MultiAppModeType::APP_CLONE))) {
754 info.appCloneIndex = appRecord->GetAppIndex();
755 }
756 return ERR_OK;
757 }
758
SetAbilityForegroundingFlagToAppRecord(const pid_t pid)759 void AppRunningManager::SetAbilityForegroundingFlagToAppRecord(const pid_t pid)
760 {
761 auto appRecord = GetAppRunningRecordByPid(pid);
762 if (appRecord == nullptr) {
763 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
764 return;
765 }
766 appRecord->SetAbilityForegroundingFlag();
767 }
768
ClipStringContent(const std::regex & re,const std::string & source,std::string & afterCutStr)769 void AppRunningManager::ClipStringContent(const std::regex &re, const std::string &source, std::string &afterCutStr)
770 {
771 std::smatch basket;
772 if (std::regex_search(source, basket, re)) {
773 afterCutStr = basket.prefix().str() + basket.suffix().str();
774 }
775 }
776
GetForegroundApplications(std::vector<AppStateData> & list)777 void AppRunningManager::GetForegroundApplications(std::vector<AppStateData> &list)
778 {
779 std::lock_guard guard(runningRecordMapMutex_);
780 for (const auto &item : appRunningRecordMap_) {
781 const auto &appRecord = item.second;
782 if (!appRecord) {
783 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
784 return;
785 }
786 auto state = appRecord->GetState();
787 if (state == ApplicationState::APP_STATE_FOREGROUND) {
788 AppStateData appData;
789 appData.bundleName = appRecord->GetBundleName();
790 appData.uid = appRecord->GetUid();
791 appData.pid = appRecord->GetPriorityObject()->GetPid();
792 appData.state = static_cast<int32_t>(ApplicationState::APP_STATE_FOREGROUND);
793 auto appInfo = appRecord->GetApplicationInfo();
794 appData.accessTokenId = appInfo ? appInfo->accessTokenId : 0;
795 appData.extensionType = appRecord->GetExtensionType();
796 appData.isFocused = appRecord->GetFocusFlag();
797 appData.appIndex = appRecord->GetAppIndex();
798 list.push_back(appData);
799 TAG_LOGD(AAFwkTag::APPMGR, "bundleName:%{public}s", appData.bundleName.c_str());
800 }
801 }
802 }
UpdateConfiguration(const Configuration & config,const int32_t userId)803 int32_t AppRunningManager::UpdateConfiguration(const Configuration& config, const int32_t userId)
804 {
805 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
806 std::vector<std::string> changeKeyV;
807 configuration_->CompareDifferent(changeKeyV, config);
808 if (!changeKeyV.empty()) {
809 configuration_->Merge(changeKeyV, config);
810 }
811
812 auto appRunningMap = GetAppRunningRecordMap();
813 TAG_LOGD(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningMap.size());
814 int32_t result = ERR_OK;
815 for (const auto& item : appRunningMap) {
816 const auto& appRecord = item.second;
817 if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
818 TAG_LOGD(AAFwkTag::APPMGR, "app not ready, appName is %{public}s", appRecord->GetBundleName().c_str());
819 continue;
820 }
821 if (!(userId == -1 || appRecord->GetUid() / BASE_USER_RANGE == 0 ||
822 appRecord->GetUid() / BASE_USER_RANGE == userId)) {
823 continue;
824 }
825 if (appRecord && !isCollaboratorReserveType(appRecord)) {
826 TAG_LOGD(AAFwkTag::APPMGR, "Notification app [%{public}s]", appRecord->GetName().c_str());
827 std::lock_guard guard(updateConfigurationDelayedLock_);
828 if (appRecord->NeedUpdateConfigurationBackground() ||
829 appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
830 updateConfigurationDelayedMap_[appRecord->GetRecordId()] = false;
831 result = appRecord->UpdateConfiguration(config);
832 } else {
833 updateConfigurationDelayedMap_[appRecord->GetRecordId()] = true;
834 }
835 }
836 }
837 return result;
838 }
839
UpdateConfigurationByBundleName(const Configuration & config,const std::string & name)840 int32_t AppRunningManager::UpdateConfigurationByBundleName(const Configuration &config, const std::string &name)
841 {
842 auto appRunningMap = GetAppRunningRecordMap();
843 int32_t result = ERR_OK;
844 for (const auto &item : appRunningMap) {
845 const auto &appRecord = item.second;
846 if (appRecord && appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
847 TAG_LOGD(AAFwkTag::APPMGR, "app not ready, appName is %{public}s", appRecord->GetBundleName().c_str());
848 continue;
849 }
850 if (appRecord && !isCollaboratorReserveType(appRecord) && appRecord->GetBundleName() == name) {
851 TAG_LOGD(AAFwkTag::APPMGR, "Notification app [%{public}s]", appRecord->GetName().c_str());
852 result = appRecord->UpdateConfiguration(config);
853 }
854 }
855 return result;
856 }
857
isCollaboratorReserveType(const std::shared_ptr<AppRunningRecord> & appRecord)858 bool AppRunningManager::isCollaboratorReserveType(const std::shared_ptr<AppRunningRecord> &appRecord)
859 {
860 std::string bundleName = appRecord->GetApplicationInfo()->name;
861 bool isReserveType = bundleName == SHELL_ASSISTANT_BUNDLENAME;
862 if (isReserveType) {
863 TAG_LOGI(AAFwkTag::APPMGR, "isReserveType app [%{public}s]", appRecord->GetName().c_str());
864 }
865 return isReserveType;
866 }
867
NotifyMemoryLevel(int32_t level)868 int32_t AppRunningManager::NotifyMemoryLevel(int32_t level)
869 {
870 std::unordered_set<int32_t> frozenPids;
871 AAFwk::ResSchedUtil::GetInstance().GetAllFrozenPidsFromRSS(frozenPids);
872 auto appRunningMap = GetAppRunningRecordMap();
873 for (const auto &item : appRunningMap) {
874 const auto &appRecord = item.second;
875 if (!appRecord) {
876 TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
877 continue;
878 }
879 auto priorityObject = appRecord->GetPriorityObject();
880 if (!priorityObject) {
881 TAG_LOGW(AAFwkTag::APPMGR, "priorityObject null");
882 continue;
883 }
884 auto pid = priorityObject->GetPid();
885 if (frozenPids.count(pid) == 0) {
886 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] memory level = %{public}d", pid, level);
887 appRecord->ScheduleMemoryLevel(level);
888 } else {
889 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] is frozen", pid);
890 }
891 }
892 return ERR_OK;
893 }
894
NotifyProcMemoryLevel(const std::map<pid_t,MemoryLevel> & procLevelMap)895 int32_t AppRunningManager::NotifyProcMemoryLevel(const std::map<pid_t, MemoryLevel> &procLevelMap)
896 {
897 std::unordered_set<int32_t> frozenPids;
898 AAFwk::ResSchedUtil::GetInstance().GetAllFrozenPidsFromRSS(frozenPids);
899 auto appRunningMap = GetAppRunningRecordMap();
900 for (const auto &item : appRunningMap) {
901 const auto &appRecord = item.second;
902 if (!appRecord) {
903 TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
904 continue;
905 }
906 auto priorityObject = appRecord->GetPriorityObject();
907 if (!priorityObject) {
908 TAG_LOGW(AAFwkTag::APPMGR, "priorityObject null");
909 continue;
910 }
911 auto pid = priorityObject->GetPid();
912 if (frozenPids.count(pid) == 0) {
913 auto it = procLevelMap.find(pid);
914 if (it == procLevelMap.end()) {
915 TAG_LOGW(AAFwkTag::APPMGR, "proc[pid=%{public}d] is not found in procLevelMap.", pid);
916 } else {
917 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] memory level = %{public}d", pid, it->second);
918 appRecord->ScheduleMemoryLevel(it->second);
919 }
920 } else {
921 TAG_LOGD(AAFwkTag::APPMGR, "proc[pid=%{public}d] is frozen", pid);
922 }
923 }
924 return ERR_OK;
925 }
926
DumpHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)927 int32_t AppRunningManager::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
928 {
929 std::shared_ptr<AppRunningRecord> appRecord;
930 {
931 std::lock_guard guard(runningRecordMapMutex_);
932 TAG_LOGI(AAFwkTag::APPMGR, "current app size %{public}zu", appRunningRecordMap_.size());
933 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
934 auto priorityObject = pair.second->GetPriorityObject();
935 return priorityObject && priorityObject->GetPid() == pid;
936 });
937 if (iter == appRunningRecordMap_.end()) {
938 TAG_LOGE(AAFwkTag::APPMGR, "No matching application was found.");
939 return ERR_INVALID_VALUE;
940 }
941 appRecord = iter->second;
942 if (appRecord == nullptr) {
943 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
944 return ERR_INVALID_VALUE;
945 }
946 }
947 appRecord->ScheduleHeapMemory(pid, mallocInfo);
948 return ERR_OK;
949 }
950
DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)951 int32_t AppRunningManager::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
952 {
953 int32_t pid = static_cast<int32_t>(info.pid);
954 auto appRecord = GetAppRunningRecordByPid(pid);
955 if (appRecord == nullptr) {
956 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
957 return ERR_INVALID_VALUE;
958 }
959 appRecord->ScheduleJsHeapMemory(info);
960 return ERR_OK;
961 }
962
GetAppRunningRecordByRenderPid(const pid_t pid)963 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByRenderPid(const pid_t pid)
964 {
965 std::lock_guard guard(runningRecordMapMutex_);
966 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
967 auto renderRecordMap = pair.second->GetRenderRecordMap();
968 if (renderRecordMap.empty()) {
969 return false;
970 }
971 for (auto it : renderRecordMap) {
972 auto renderRecord = it.second;
973 if (renderRecord && renderRecord->GetPid() == pid) {
974 return true;
975 }
976 }
977 return false;
978 });
979 return ((iter == appRunningRecordMap_.end()) ? nullptr : iter->second);
980 }
981
OnRemoteRenderDied(const wptr<IRemoteObject> & remote)982 std::shared_ptr<RenderRecord> AppRunningManager::OnRemoteRenderDied(const wptr<IRemoteObject> &remote)
983 {
984 if (remote == nullptr) {
985 TAG_LOGE(AAFwkTag::APPMGR, "remote is null");
986 return nullptr;
987 }
988 sptr<IRemoteObject> object = remote.promote();
989 if (!object) {
990 TAG_LOGE(AAFwkTag::APPMGR, "promote failed.");
991 return nullptr;
992 }
993
994 std::lock_guard guard(runningRecordMapMutex_);
995 std::shared_ptr<RenderRecord> renderRecord;
996 const auto &it =
997 std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(),
998 [&object, &renderRecord](const auto &pair) {
999 if (!pair.second) {
1000 return false;
1001 }
1002
1003 auto renderRecordMap = pair.second->GetRenderRecordMap();
1004 if (renderRecordMap.empty()) {
1005 return false;
1006 }
1007 for (auto iter : renderRecordMap) {
1008 if (iter.second == nullptr) {
1009 continue;
1010 }
1011 auto scheduler = iter.second->GetScheduler();
1012 if (scheduler && scheduler->AsObject() == object) {
1013 renderRecord = iter.second;
1014 return true;
1015 }
1016 }
1017 return false;
1018 });
1019 if (it != appRunningRecordMap_.end()) {
1020 auto appRecord = it->second;
1021 appRecord->RemoveRenderRecord(renderRecord);
1022 TAG_LOGI(AAFwkTag::APPMGR, "RemoveRenderRecord pid:%{public}d, uid:%{public}d.", renderRecord->GetPid(),
1023 renderRecord->GetUid());
1024 return renderRecord;
1025 }
1026 return nullptr;
1027 }
1028
GetAppRunningStateByBundleName(const std::string & bundleName)1029 bool AppRunningManager::GetAppRunningStateByBundleName(const std::string &bundleName)
1030 {
1031 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1032 TAG_LOGD(AAFwkTag::APPMGR, "called");
1033 std::lock_guard guard(runningRecordMapMutex_);
1034 for (const auto &item : appRunningRecordMap_) {
1035 const auto &appRecord = item.second;
1036 if (appRecord && appRecord->GetBundleName() == bundleName) {
1037 TAG_LOGD(AAFwkTag::APPMGR, "Process of [%{public}s] is running, processName: %{public}s.",
1038 bundleName.c_str(), appRecord->GetProcessName().c_str());
1039 if (IPCSkeleton::GetCallingUid() == QUICKFIX_UID && appRecord->GetPriorityObject() != nullptr) {
1040 TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d.", appRecord->GetPriorityObject()->GetPid());
1041 }
1042 return true;
1043 }
1044 }
1045 return false;
1046 }
1047
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1048 int32_t AppRunningManager::NotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
1049 {
1050 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1051 TAG_LOGD(AAFwkTag::APPMGR, "called");
1052 int32_t result = ERR_OK;
1053 bool loadSucceed = false;
1054 auto callbackByRecord = sptr<QuickFixCallbackWithRecord>::MakeSptr(callback);
1055 if (callbackByRecord == nullptr) {
1056 TAG_LOGE(AAFwkTag::APPMGR, "Failed to create callback record.");
1057 return ERR_INVALID_VALUE;
1058 }
1059
1060 auto appRunningMap = GetAppRunningRecordMap();
1061 for (const auto &item : appRunningMap) {
1062 const auto &appRecord = item.second;
1063 if (appRecord && appRecord->GetBundleName() == bundleName) {
1064 auto recordId = appRecord->GetRecordId();
1065 TAG_LOGD(AAFwkTag::APPMGR, "Notify application [%{public}s] load patch, record id %{public}d.",
1066 appRecord->GetProcessName().c_str(), recordId);
1067 callbackByRecord->AddRecordId(recordId);
1068 result = appRecord->NotifyLoadRepairPatch(bundleName, callbackByRecord, recordId);
1069 if (result == ERR_OK) {
1070 loadSucceed = true;
1071 } else {
1072 callbackByRecord->RemoveRecordId(recordId);
1073 }
1074 }
1075 }
1076 return loadSucceed == true ? ERR_OK : result;
1077 }
1078
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1079 int32_t AppRunningManager::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
1080 {
1081 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1082 TAG_LOGD(AAFwkTag::APPMGR, "called");
1083 int32_t result = ERR_OK;
1084 bool reloadPageSucceed = false;
1085 auto callbackByRecord = sptr<QuickFixCallbackWithRecord>::MakeSptr(callback);
1086 if (callbackByRecord == nullptr) {
1087 TAG_LOGE(AAFwkTag::APPMGR, "Failed to create callback record.");
1088 return ERR_INVALID_VALUE;
1089 }
1090
1091 auto appRunningMap = GetAppRunningRecordMap();
1092 for (const auto &item : appRunningMap) {
1093 const auto &appRecord = item.second;
1094 if (appRecord && appRecord->GetBundleName() == bundleName) {
1095 auto recordId = appRecord->GetRecordId();
1096 TAG_LOGD(AAFwkTag::APPMGR, "Notify application [%{public}s] reload page, record id %{public}d.",
1097 appRecord->GetProcessName().c_str(), recordId);
1098 callbackByRecord->AddRecordId(recordId);
1099 result = appRecord->NotifyHotReloadPage(callbackByRecord, recordId);
1100 if (result == ERR_OK) {
1101 reloadPageSucceed = true;
1102 } else {
1103 callbackByRecord->RemoveRecordId(recordId);
1104 }
1105 }
1106 }
1107 return reloadPageSucceed == true ? ERR_OK : result;
1108 }
1109
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)1110 int32_t AppRunningManager::NotifyUnLoadRepairPatch(const std::string &bundleName,
1111 const sptr<IQuickFixCallback> &callback)
1112 {
1113 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1114 TAG_LOGD(AAFwkTag::APPMGR, "called");
1115 int32_t result = ERR_OK;
1116 bool unLoadSucceed = false;
1117 auto callbackByRecord = sptr<QuickFixCallbackWithRecord>::MakeSptr(callback);
1118 if (callbackByRecord == nullptr) {
1119 TAG_LOGE(AAFwkTag::APPMGR, "Failed to create callback record.");
1120 return ERR_INVALID_VALUE;
1121 }
1122
1123 auto appRunningMap = GetAppRunningRecordMap();
1124 for (const auto &item : appRunningMap) {
1125 const auto &appRecord = item.second;
1126 if (appRecord && appRecord->GetBundleName() == bundleName) {
1127 auto recordId = appRecord->GetRecordId();
1128 TAG_LOGD(AAFwkTag::APPMGR, "Notify application [%{public}s] unload patch, record id %{public}d.",
1129 appRecord->GetProcessName().c_str(), recordId);
1130 callbackByRecord->AddRecordId(recordId);
1131 result = appRecord->NotifyUnLoadRepairPatch(bundleName, callbackByRecord, recordId);
1132 if (result == ERR_OK) {
1133 unLoadSucceed = true;
1134 } else {
1135 callbackByRecord->RemoveRecordId(recordId);
1136 }
1137 }
1138 }
1139 return unLoadSucceed == true ? ERR_OK : result;
1140 }
1141
IsApplicationFirstForeground(const AppRunningRecord & foregroundingRecord)1142 bool AppRunningManager::IsApplicationFirstForeground(const AppRunningRecord &foregroundingRecord)
1143 {
1144 TAG_LOGD(AAFwkTag::APPMGR, "called");
1145 if (AAFwk::UIExtensionUtils::IsUIExtension(foregroundingRecord.GetExtensionType())
1146 || AAFwk::UIExtensionUtils::IsWindowExtension(foregroundingRecord.GetExtensionType())) {
1147 return false;
1148 }
1149
1150 std::lock_guard guard(runningRecordMapMutex_);
1151 for (const auto &item : appRunningRecordMap_) {
1152 const auto &appRecord = item.second;
1153 if (appRecord == nullptr || appRecord->GetBundleName() != foregroundingRecord.GetBundleName()
1154 || AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
1155 || AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
1156 || appRecord->GetAppIndex() != foregroundingRecord.GetAppIndex()) {
1157 continue;
1158 }
1159 auto state = appRecord->GetState();
1160 if (state == ApplicationState::APP_STATE_FOREGROUND &&
1161 appRecord->GetRecordId() != foregroundingRecord.GetRecordId()) {
1162 return false;
1163 }
1164 }
1165 return true;
1166 }
1167
IsApplicationBackground(const AppRunningRecord & backgroundingRecord)1168 bool AppRunningManager::IsApplicationBackground(const AppRunningRecord &backgroundingRecord)
1169 {
1170 TAG_LOGD(AAFwkTag::APPMGR, "called");
1171 std::lock_guard guard(runningRecordMapMutex_);
1172 for (const auto &item : appRunningRecordMap_) {
1173 const auto &appRecord = item.second;
1174 if (appRecord == nullptr) {
1175 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1176 return false;
1177 }
1178 if (AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
1179 || AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
1180 || appRecord->GetAppIndex() != backgroundingRecord.GetAppIndex()) {
1181 continue;
1182 }
1183 auto state = appRecord->GetState();
1184 if (appRecord && appRecord->GetBundleName() == backgroundingRecord.GetBundleName() &&
1185 state == ApplicationState::APP_STATE_FOREGROUND) {
1186 return false;
1187 }
1188 }
1189 return true;
1190 }
1191
OnWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)1192 void AppRunningManager::OnWindowVisibilityChanged(
1193 const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
1194 {
1195 TAG_LOGD(AAFwkTag::APPMGR, "called");
1196 std::set<int32_t> pids;
1197 for (const auto &info : windowVisibilityInfos) {
1198 if (info == nullptr) {
1199 TAG_LOGE(AAFwkTag::APPMGR, "Window visibility info is nullptr.");
1200 continue;
1201 }
1202 if (pids.find(info->pid_) != pids.end()) {
1203 continue;
1204 }
1205 auto appRecord = GetAppRunningRecordByPid(info->pid_);
1206 if (appRecord == nullptr) {
1207 TAG_LOGE(AAFwkTag::APPMGR, "App running record is nullptr.");
1208 return;
1209 }
1210 TAG_LOGD(AAFwkTag::APPMGR, "The visibility of %{public}s was changed.", appRecord->GetBundleName().c_str());
1211 appRecord->OnWindowVisibilityChanged(windowVisibilityInfos);
1212 pids.emplace(info->pid_);
1213 }
1214 }
1215
IsApplicationFirstFocused(const AppRunningRecord & focusedRecord)1216 bool AppRunningManager::IsApplicationFirstFocused(const AppRunningRecord &focusedRecord)
1217 {
1218 TAG_LOGD(AAFwkTag::APPMGR, "called");
1219 std::lock_guard guard(runningRecordMapMutex_);
1220 for (const auto &item : appRunningRecordMap_) {
1221 const auto &appRecord = item.second;
1222 if (appRecord == nullptr || appRecord->GetBundleName() != focusedRecord.GetBundleName()) {
1223 continue;
1224 }
1225 if (appRecord->GetFocusFlag() && appRecord->GetRecordId() != focusedRecord.GetRecordId()) {
1226 return false;
1227 }
1228 }
1229 return true;
1230 }
1231
IsApplicationUnfocused(const std::string & bundleName)1232 bool AppRunningManager::IsApplicationUnfocused(const std::string &bundleName)
1233 {
1234 TAG_LOGD(AAFwkTag::APPMGR, "check is application unfocused.");
1235 std::lock_guard guard(runningRecordMapMutex_);
1236 for (const auto &item : appRunningRecordMap_) {
1237 const auto &appRecord = item.second;
1238 if (appRecord && appRecord->GetBundleName() == bundleName && appRecord->GetFocusFlag()) {
1239 return false;
1240 }
1241 }
1242 return true;
1243 }
1244
SetAttachAppDebug(const std::string & bundleName,const bool & isAttachDebug)1245 void AppRunningManager::SetAttachAppDebug(const std::string &bundleName, const bool &isAttachDebug)
1246 {
1247 TAG_LOGD(AAFwkTag::APPMGR, "called");
1248 auto appRunningMap = GetAppRunningRecordMap();
1249 for (const auto &item : appRunningMap) {
1250 const auto &appRecord = item.second;
1251 if (appRecord == nullptr) {
1252 continue;
1253 }
1254 if (appRecord->GetBundleName() == bundleName) {
1255 TAG_LOGD(AAFwkTag::APPMGR, "The application: %{public}s will be set debug mode.", bundleName.c_str());
1256 appRecord->SetAttachDebug(isAttachDebug);
1257 }
1258 }
1259 }
1260
GetAppDebugInfosByBundleName(const std::string & bundleName,const bool & isDetachDebug)1261 std::vector<AppDebugInfo> AppRunningManager::GetAppDebugInfosByBundleName(
1262 const std::string &bundleName, const bool &isDetachDebug)
1263 {
1264 TAG_LOGD(AAFwkTag::APPMGR, "called");
1265 std::lock_guard guard(runningRecordMapMutex_);
1266 std::vector<AppDebugInfo> debugInfos;
1267 for (const auto &item : appRunningRecordMap_) {
1268 const auto &appRecord = item.second;
1269 if (appRecord == nullptr || appRecord->GetBundleName() != bundleName ||
1270 (isDetachDebug && (appRecord->IsDebugApp() || appRecord->IsAssertionPause()))) {
1271 continue;
1272 }
1273
1274 AppDebugInfo debugInfo;
1275 debugInfo.bundleName = bundleName;
1276 auto priorityObject = appRecord->GetPriorityObject();
1277 if (priorityObject) {
1278 debugInfo.pid = priorityObject->GetPid();
1279 }
1280 debugInfo.uid = appRecord->GetUid();
1281 debugInfo.isDebugStart = (appRecord->IsDebugApp() || appRecord->IsAssertionPause());
1282 debugInfos.emplace_back(debugInfo);
1283 }
1284 return debugInfos;
1285 }
1286
GetAbilityTokensByBundleName(const std::string & bundleName,std::vector<sptr<IRemoteObject>> & abilityTokens)1287 void AppRunningManager::GetAbilityTokensByBundleName(
1288 const std::string &bundleName, std::vector<sptr<IRemoteObject>> &abilityTokens)
1289 {
1290 TAG_LOGD(AAFwkTag::APPMGR, "called");
1291 std::lock_guard guard(runningRecordMapMutex_);
1292 for (const auto &item : appRunningRecordMap_) {
1293 const auto &appRecord = item.second;
1294 if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) {
1295 continue;
1296 }
1297
1298 for (const auto &token : appRecord->GetAbilities()) {
1299 abilityTokens.emplace_back(token.first);
1300 }
1301 }
1302 }
1303
GetAppRunningRecordByChildProcessPid(const pid_t pid)1304 std::shared_ptr<AppRunningRecord> AppRunningManager::GetAppRunningRecordByChildProcessPid(const pid_t pid)
1305 {
1306 std::lock_guard guard(runningRecordMapMutex_);
1307 auto iter = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(), [&pid](const auto &pair) {
1308 auto childProcessRecordMap = pair.second->GetChildProcessRecordMap();
1309 return childProcessRecordMap.find(pid) != childProcessRecordMap.end();
1310 });
1311 if (iter != appRunningRecordMap_.end()) {
1312 return iter->second;
1313 }
1314 return nullptr;
1315 }
1316
IsChildProcessReachLimit(uint32_t accessTokenId)1317 bool AppRunningManager::IsChildProcessReachLimit(uint32_t accessTokenId)
1318 {
1319 TAG_LOGD(AAFwkTag::APPMGR, "called.");
1320 int32_t childCount = 0;
1321 std::lock_guard guard(runningRecordMapMutex_);
1322 for (auto &pair : appRunningRecordMap_) {
1323 auto appRecord = pair.second;
1324 if (!appRecord || !appRecord->GetApplicationInfo() ||
1325 accessTokenId != appRecord->GetApplicationInfo()->accessTokenId) {
1326 continue;
1327 }
1328 childCount += appRecord->GetChildProcessCount();
1329 }
1330 return childCount >= AAFwk::AppUtils::GetInstance().MaxChildProcess();
1331 }
1332
OnChildProcessRemoteDied(const wptr<IRemoteObject> & remote)1333 std::shared_ptr<ChildProcessRecord> AppRunningManager::OnChildProcessRemoteDied(const wptr<IRemoteObject> &remote)
1334 {
1335 TAG_LOGE(AAFwkTag::APPMGR, "On child process remote died.");
1336 if (remote == nullptr) {
1337 TAG_LOGE(AAFwkTag::APPMGR, "remote is null");
1338 return nullptr;
1339 }
1340 sptr<IRemoteObject> object = remote.promote();
1341 if (!object) {
1342 TAG_LOGE(AAFwkTag::APPMGR, "promote failed.");
1343 return nullptr;
1344 }
1345
1346 std::lock_guard guard(runningRecordMapMutex_);
1347 std::shared_ptr<ChildProcessRecord> childRecord;
1348 const auto &it = std::find_if(appRunningRecordMap_.begin(), appRunningRecordMap_.end(),
1349 [&object, &childRecord](const auto &pair) {
1350 auto appRecord = pair.second;
1351 if (!appRecord) {
1352 return false;
1353 }
1354 auto childRecordMap = appRecord->GetChildProcessRecordMap();
1355 if (childRecordMap.empty()) {
1356 return false;
1357 }
1358 for (auto iter : childRecordMap) {
1359 if (iter.second == nullptr) {
1360 continue;
1361 }
1362 auto scheduler = iter.second->GetScheduler();
1363 if (scheduler && scheduler->AsObject() == object) {
1364 childRecord = iter.second;
1365 return true;
1366 }
1367 }
1368 return false;
1369 });
1370 if (it != appRunningRecordMap_.end()) {
1371 auto appRecord = it->second;
1372 appRecord->RemoveChildProcessRecord(childRecord);
1373 TAG_LOGI(AAFwkTag::APPMGR, "RemoveChildProcessRecord pid:%{public}d, uid:%{public}d.", childRecord->GetPid(),
1374 childRecord->GetUid());
1375 return childRecord;
1376 }
1377 return nullptr;
1378 }
1379
SignRestartAppFlag(int32_t uid)1380 int32_t AppRunningManager::SignRestartAppFlag(int32_t uid)
1381 {
1382 TAG_LOGD(AAFwkTag::APPMGR, "called");
1383 std::lock_guard guard(runningRecordMapMutex_);
1384 for (const auto &item : appRunningRecordMap_) {
1385 const auto &appRecord = item.second;
1386 if (appRecord == nullptr || appRecord->GetUid() != uid) {
1387 continue;
1388 }
1389 TAG_LOGD(AAFwkTag::APPMGR, "sign");
1390 appRecord->SetRestartAppFlag(true);
1391 return ERR_OK;
1392 }
1393 TAG_LOGE(AAFwkTag::APPMGR, "Not find apprecord.");
1394 return ERR_INVALID_VALUE;
1395 }
1396
GetAppRunningUniqueIdByPid(pid_t pid,std::string & appRunningUniqueId)1397 int32_t AppRunningManager::GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId)
1398 {
1399 TAG_LOGD(AAFwkTag::APPMGR, "called");
1400 auto appRecord = GetAppRunningRecordByPid(pid);
1401 if (appRecord == nullptr) {
1402 TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1403 return ERR_INVALID_VALUE;
1404 }
1405 appRunningUniqueId = std::to_string(appRecord->GetAppStartTime());
1406 TAG_LOGD(AAFwkTag::APPMGR, "appRunningUniqueId = %{public}s.", appRunningUniqueId.c_str());
1407 return ERR_OK;
1408 }
1409
GetAllUIExtensionRootHostPid(pid_t pid,std::vector<pid_t> & hostPids)1410 int32_t AppRunningManager::GetAllUIExtensionRootHostPid(pid_t pid, std::vector<pid_t> &hostPids)
1411 {
1412 TAG_LOGD(AAFwkTag::APPMGR, "called");
1413 std::lock_guard guard(uiExtensionMapLock_);
1414 for (auto &item: uiExtensionLauncherMap_) {
1415 auto temp = item.second.second;
1416 if (temp == pid) {
1417 hostPids.emplace_back(item.second.first);
1418 }
1419 }
1420 std::string hostPidStr = std::accumulate(hostPids.begin(), hostPids.end(), std::string(),
1421 [](const std::string& a, pid_t b) {
1422 return a + std::to_string(b) + " ";
1423 });
1424 TAG_LOGD(AAFwkTag::APPMGR, "pid: %{public}s, hostPid: %{public}s.", std::to_string(pid).c_str(),
1425 hostPidStr.c_str());
1426 return ERR_OK;
1427 }
1428
GetAllUIExtensionProviderPid(pid_t hostPid,std::vector<pid_t> & providerPids)1429 int32_t AppRunningManager::GetAllUIExtensionProviderPid(pid_t hostPid, std::vector<pid_t> &providerPids)
1430 {
1431 std::lock_guard guard(uiExtensionMapLock_);
1432 for (auto &item: uiExtensionLauncherMap_) {
1433 auto temp = item.second.first;
1434 if (temp == hostPid) {
1435 providerPids.emplace_back(item.second.second);
1436 }
1437 }
1438
1439 return ERR_OK;
1440 }
1441
AddUIExtensionLauncherItem(int32_t uiExtensionAbilityId,pid_t hostPid,pid_t providerPid)1442 int32_t AppRunningManager::AddUIExtensionLauncherItem(int32_t uiExtensionAbilityId, pid_t hostPid, pid_t providerPid)
1443 {
1444 std::lock_guard guard(uiExtensionMapLock_);
1445 uiExtensionLauncherMap_.emplace(uiExtensionAbilityId, std::pair<pid_t, pid_t>(hostPid, providerPid));
1446 return ERR_OK;
1447 }
1448
RemoveUIExtensionLauncherItem(pid_t pid)1449 int32_t AppRunningManager::RemoveUIExtensionLauncherItem(pid_t pid)
1450 {
1451 std::lock_guard guard(uiExtensionMapLock_);
1452 for (auto it = uiExtensionLauncherMap_.begin(); it != uiExtensionLauncherMap_.end();) {
1453 if (it->second.first == pid || it->second.second == pid) {
1454 it = uiExtensionLauncherMap_.erase(it);
1455 continue;
1456 }
1457 it++;
1458 }
1459
1460 return ERR_OK;
1461 }
1462
RemoveUIExtensionLauncherItemById(int32_t uiExtensionAbilityId)1463 int32_t AppRunningManager::RemoveUIExtensionLauncherItemById(int32_t uiExtensionAbilityId)
1464 {
1465 std::lock_guard guard(uiExtensionMapLock_);
1466 for (auto it = uiExtensionLauncherMap_.begin(); it != uiExtensionLauncherMap_.end();) {
1467 if (it->first == uiExtensionAbilityId) {
1468 it = uiExtensionLauncherMap_.erase(it);
1469 continue;
1470 }
1471 it++;
1472 }
1473
1474 return ERR_OK;
1475 }
1476
DumpIpcAllStart(std::string & result)1477 int AppRunningManager::DumpIpcAllStart(std::string& result)
1478 {
1479 TAG_LOGD(AAFwkTag::APPMGR, "called");
1480 int errCode = DumpErrorCode::ERR_OK;
1481 for (const auto &item : GetAppRunningRecordMap()) {
1482 const auto &appRecord = item.second;
1483 TAG_LOGD(AAFwkTag::APPMGR, "AppRunningManager::DumpIpcAllStart::pid:%{public}d",
1484 appRecord->GetPriorityObject()->GetPid());
1485 std::string currentResult;
1486 errCode = appRecord->DumpIpcStart(currentResult);
1487 result += currentResult + "\n";
1488 if (errCode != DumpErrorCode::ERR_OK) {
1489 return errCode;
1490 }
1491 }
1492 return errCode;
1493 }
1494
DumpIpcAllStop(std::string & result)1495 int AppRunningManager::DumpIpcAllStop(std::string& result)
1496 {
1497 TAG_LOGD(AAFwkTag::APPMGR, "called");
1498 int errCode = DumpErrorCode::ERR_OK;
1499 for (const auto &item : GetAppRunningRecordMap()) {
1500 const auto &appRecord = item.second;
1501 TAG_LOGD(AAFwkTag::APPMGR, "AppRunningManager::DumpIpcAllStop::pid:%{public}d",
1502 appRecord->GetPriorityObject()->GetPid());
1503 std::string currentResult;
1504 errCode = appRecord->DumpIpcStop(currentResult);
1505 result += currentResult + "\n";
1506 if (errCode != DumpErrorCode::ERR_OK) {
1507 return errCode;
1508 }
1509 }
1510 return errCode;
1511 }
1512
DumpIpcAllStat(std::string & result)1513 int AppRunningManager::DumpIpcAllStat(std::string& result)
1514 {
1515 TAG_LOGD(AAFwkTag::APPMGR, "called");
1516 int errCode = DumpErrorCode::ERR_OK;
1517 for (const auto &item : GetAppRunningRecordMap()) {
1518 const auto &appRecord = item.second;
1519 TAG_LOGD(AAFwkTag::APPMGR, "AppRunningManager::DumpIpcAllStat::pid:%{public}d",
1520 appRecord->GetPriorityObject()->GetPid());
1521 std::string currentResult;
1522 errCode = appRecord->DumpIpcStat(currentResult);
1523 result += currentResult + "\n";
1524 if (errCode != DumpErrorCode::ERR_OK) {
1525 return errCode;
1526 }
1527 }
1528 return errCode;
1529 }
1530
DumpIpcStart(const int32_t pid,std::string & result)1531 int AppRunningManager::DumpIpcStart(const int32_t pid, std::string& result)
1532 {
1533 TAG_LOGD(AAFwkTag::APPMGR, "called");
1534 const auto& appRecord = GetAppRunningRecordByPid(pid);
1535 if (!appRecord) {
1536 result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
1537 .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
1538 .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
1539 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1540 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1541 }
1542 return appRecord->DumpIpcStart(result);
1543 }
1544
DumpIpcStop(const int32_t pid,std::string & result)1545 int AppRunningManager::DumpIpcStop(const int32_t pid, std::string& result)
1546 {
1547 TAG_LOGD(AAFwkTag::APPMGR, "called");
1548 const auto& appRecord = GetAppRunningRecordByPid(pid);
1549 if (!appRecord) {
1550 result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
1551 .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
1552 .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
1553 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1554 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1555 }
1556 return appRecord->DumpIpcStop(result);
1557 }
1558
DumpIpcStat(const int32_t pid,std::string & result)1559 int AppRunningManager::DumpIpcStat(const int32_t pid, std::string& result)
1560 {
1561 TAG_LOGD(AAFwkTag::APPMGR, "called");
1562 const auto& appRecord = GetAppRunningRecordByPid(pid);
1563 if (!appRecord) {
1564 result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
1565 .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
1566 .append(MSG_DUMP_FAIL_REASON_INVALILD_PID, strlen(MSG_DUMP_FAIL_REASON_INVALILD_PID));
1567 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1568 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1569 }
1570 return appRecord->DumpIpcStat(result);
1571 }
1572
DumpFfrt(const std::vector<int32_t> & pids,std::string & result)1573 int AppRunningManager::DumpFfrt(const std::vector<int32_t>& pids, std::string& result)
1574 {
1575 TAG_LOGD(AAFwkTag::APPMGR, "called");
1576 int errCode = DumpErrorCode::ERR_OK;
1577 size_t count = 0;
1578 for (const auto& pid : pids) {
1579 TAG_LOGD(AAFwkTag::APPMGR, "DumpFfrt current pid:%{public}d", pid);
1580 const auto& appRecord = GetAppRunningRecordByPid(pid);
1581 if (!appRecord) {
1582 TAG_LOGE(AAFwkTag::APPMGR, "pid %{public}d does not exist", pid);
1583 ++count;
1584 continue;
1585 }
1586 std::string currentResult;
1587 errCode = appRecord->DumpFfrt(currentResult);
1588 if (errCode != DumpErrorCode::ERR_OK) {
1589 continue;
1590 }
1591 result += currentResult + "\n";
1592 }
1593 if (count == pids.size()) {
1594 TAG_LOGE(AAFwkTag::APPMGR, "no valid pid");
1595 return DumpErrorCode::ERR_INVALID_PID_ERROR;
1596 }
1597 if (result.empty()) {
1598 TAG_LOGE(AAFwkTag::APPMGR, "no ffrt usage is found");
1599 return DumpErrorCode::ERR_INTERNAL_ERROR;
1600 }
1601 return DumpErrorCode::ERR_OK;
1602 }
1603
HandleUserRequestClean(const sptr<IRemoteObject> & abilityToken,pid_t & pid,int32_t & uid)1604 bool AppRunningManager::HandleUserRequestClean(const sptr<IRemoteObject> &abilityToken, pid_t &pid, int32_t &uid)
1605 {
1606 if (abilityToken == nullptr) {
1607 TAG_LOGE(AAFwkTag::APPMGR, "abilityToken is nullptr");
1608 return false;
1609 }
1610
1611 auto appRecord = GetAppRunningRecordByAbilityToken(abilityToken);
1612 if (!appRecord) {
1613 TAG_LOGE(AAFwkTag::APPMGR, "failed to get appRecord.");
1614 return false;
1615 }
1616 if (appRecord->GetSupportProcessCacheState() == SupportProcessCacheState::SUPPORT) {
1617 TAG_LOGI(AAFwkTag::APPMGR, "support porcess cache should not force clean");
1618 return false;
1619 }
1620 auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(abilityToken);
1621 if (!abilityRecord) {
1622 TAG_LOGE(AAFwkTag::APPMGR, "failed to get abilityRecord.");
1623 return false;
1624 }
1625 abilityRecord->SetUserRequestCleaningStatus();
1626
1627 bool canKill = appRecord->IsAllAbilityReadyToCleanedByUserRequest();
1628 if (!canKill || appRecord->IsKeepAliveApp()) {
1629 return false;
1630 }
1631
1632 appRecord->SetUserRequestCleaning();
1633 if (appRecord->GetPriorityObject()) {
1634 pid = appRecord->GetPriorityObject()->GetPid();
1635 }
1636 uid = appRecord->GetUid();
1637 return true;
1638 }
1639
IsAppProcessesAllCached(const std::string & bundleName,int32_t uid,const std::set<std::shared_ptr<AppRunningRecord>> & cachedSet)1640 bool AppRunningManager::IsAppProcessesAllCached(const std::string &bundleName, int32_t uid,
1641 const std::set<std::shared_ptr<AppRunningRecord>> &cachedSet)
1642 {
1643 if (cachedSet.size() == 0) {
1644 TAG_LOGI(AAFwkTag::APPMGR, "empty cache set.");
1645 return false;
1646 }
1647 std::lock_guard guard(runningRecordMapMutex_);
1648 for (const auto &item : appRunningRecordMap_) {
1649 auto &itemRecord = item.second;
1650 if (itemRecord == nullptr) {
1651 continue;
1652 }
1653 if (itemRecord->GetBundleName() == bundleName && itemRecord->GetUid() == uid) {
1654 auto supportCache =
1655 DelayedSingleton<CacheProcessManager>::GetInstance()->IsAppSupportProcessCache(itemRecord);
1656 // need wait for unsupported processes
1657 if ((cachedSet.find(itemRecord) == cachedSet.end() && supportCache) || !supportCache) {
1658 return false;
1659 }
1660 }
1661 }
1662 return true;
1663 }
1664
UpdateConfigurationDelayed(const std::shared_ptr<AppRunningRecord> & appRecord)1665 int32_t AppRunningManager::UpdateConfigurationDelayed(const std::shared_ptr<AppRunningRecord>& appRecord)
1666 {
1667 std::lock_guard guard(updateConfigurationDelayedLock_);
1668 int32_t result = ERR_OK;
1669 auto it = updateConfigurationDelayedMap_.find(appRecord->GetRecordId());
1670 if (it != updateConfigurationDelayedMap_.end() && it->second) {
1671 int32_t userId = appRecord->GetUid() / BASE_USER_RANGE;
1672 if (userId != 0) {
1673 auto config = multiUserConfigurationMgr_->GetConfigurationByUserId(userId);
1674 std::vector<std::string> diffVe;
1675 configuration_->CompareDifferent(diffVe, config);
1676 configuration_->Merge(diffVe, config);
1677 }
1678 result = appRecord->UpdateConfiguration(*configuration_);
1679 it->second = false;
1680 }
1681 return result;
1682 }
1683
SetMultiUserConfigurationMgr(const std::shared_ptr<MultiUserConfigurationMgr> & multiUserConfigurationMgr)1684 void AppRunningManager::SetMultiUserConfigurationMgr(
1685 const std::shared_ptr<MultiUserConfigurationMgr>& multiUserConfigurationMgr)
1686 {
1687 multiUserConfigurationMgr_ = multiUserConfigurationMgr;
1688 }
1689 } // namespace AppExecFwk
1690 } // namespace OHOS
1691