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