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