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