• 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 <optional>
17 
18 #include "ability_window_configuration.h"
19 #include "app_running_record.h"
20 #include "app_utils.h"
21 #include "render_record.h"
22 #include "app_mgr_service_inner.h"
23 #include "error_msg_util.h"
24 #include "event_report.h"
25 #include "exit_resident_process_manager.h"
26 #include "freeze_util.h"
27 #include "hitrace_meter.h"
28 #include "hilog_tag_wrapper.h"
29 #include "insight_intent_execute_param.h"
30 #include "ui_extension_utils.h"
31 #include "app_mgr_service_const.h"
32 #include "app_mgr_service_dump_error_code.h"
33 #include "cache_process_manager.h"
34 #include "hisysevent.h"
35 #ifdef SUPPORT_SCREEN
36 #include "window_visibility_info.h"
37 #endif //SUPPORT_SCREEN
38 #ifdef SUPPORT_UPMS
39 #include "uri_permission_manager_client.h"
40 #endif // SUPPORT_UPMS
41 namespace OHOS {
42 using AAFwk::AppUtils;
43 namespace AppExecFwk {
44 namespace {
45 constexpr int64_t NANOSECONDS = 1000000000;  // NANOSECONDS mean 10^9 nano second
46 constexpr int64_t MICROSECONDS = 1000000;    // MICROSECONDS mean 10^6 millias second
47 constexpr int32_t MAX_RESTART_COUNT = 3;
48 constexpr int32_t RESTART_INTERVAL_TIME = 120000;
49 constexpr int32_t HALF_TIMEOUT = 2;
50 constexpr const char* LAUNCHER_NAME = "com.ohos.sceneboard";
51 constexpr const char *EVENT_KEY_VERSION_NAME = "VERSION_NAME";
52 constexpr const char *EVENT_KEY_VERSION_CODE = "VERSION_CODE";
53 constexpr const char *EVENT_KEY_BUNDLE_NAME = "BUNDLE_NAME";
54 constexpr const char *EVENT_KEY_SUPPORT_STATE = "SUPPORT_STATE";
55 constexpr uint32_t PROCESS_MODE_RUN_WITH_MAIN_PROCESS =
56     1 << static_cast<uint32_t>(AppExecFwk::ExtensionProcessMode::RUN_WITH_MAIN_PROCESS);
57 }
58 
59 int64_t AppRunningRecord::appEventId_ = 0;
60 
61 
AppRunningRecord(const std::shared_ptr<ApplicationInfo> & info,const int32_t recordId,const std::string & processName)62 AppRunningRecord::AppRunningRecord(
63     const std::shared_ptr<ApplicationInfo> &info, const int32_t recordId, const std::string &processName)
64     : appRecordId_(recordId), processName_(processName)
65 {
66     if (info) {
67         appInfo_ = info;
68         mainBundleName_ = info->bundleName;
69         isLauncherApp_ = info->isLauncherApp;
70         mainAppName_ = info->name;
71     }
72     priorityObject_ = std::make_shared<PriorityObject>();
73 
74     struct timespec t;
75     t.tv_sec = 0;
76     t.tv_nsec = 0;
77     clock_gettime(CLOCK_MONOTONIC, &t);
78     startTimeMillis_ = static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS);
79 }
80 
SetApplicationClient(const sptr<IAppScheduler> & thread)81 void AppRunningRecord::SetApplicationClient(const sptr<IAppScheduler> &thread)
82 {
83     if (!appLifeCycleDeal_) {
84         appLifeCycleDeal_ = std::make_shared<AppLifeCycleDeal>();
85     }
86     appLifeCycleDeal_->SetApplicationClient(thread);
87 
88     auto moduleRecordList = GetAllModuleRecord();
89     if (moduleRecordList.empty()) {
90         TAG_LOGD(AAFwkTag::APPMGR, "moduleRecordList is empty");
91         return;
92     }
93     for (const auto &moduleRecord : moduleRecordList) {
94         moduleRecord->SetApplicationClient(appLifeCycleDeal_);
95     }
96 }
97 
GetBundleName() const98 const std::string &AppRunningRecord::GetBundleName() const
99 {
100     return mainBundleName_;
101 }
102 
GetCallerPid() const103 int32_t AppRunningRecord::GetCallerPid() const
104 {
105     return callerPid_;
106 }
107 
SetCallerPid(int32_t pid)108 void AppRunningRecord::SetCallerPid(int32_t pid)
109 {
110     callerPid_ = pid;
111 }
112 
GetCallerUid() const113 int32_t AppRunningRecord::GetCallerUid() const
114 {
115     return callerUid_;
116 }
117 
SetCallerUid(int32_t uid)118 void AppRunningRecord::SetCallerUid(int32_t uid)
119 {
120     callerUid_ = uid;
121 }
122 
GetCallerTokenId() const123 int32_t AppRunningRecord::GetCallerTokenId() const
124 {
125     return callerTokenId_;
126 }
127 
SetCallerTokenId(int32_t tokenId)128 void AppRunningRecord::SetCallerTokenId(int32_t tokenId)
129 {
130     callerTokenId_ = tokenId;
131 }
132 
IsLauncherApp() const133 bool AppRunningRecord::IsLauncherApp() const
134 {
135     return isLauncherApp_;
136 }
137 
GetRecordId() const138 int32_t AppRunningRecord::GetRecordId() const
139 {
140     return appRecordId_;
141 }
142 
GetName() const143 const std::string &AppRunningRecord::GetName() const
144 {
145     return mainAppName_;
146 }
147 
GetSignCode() const148 const std::string &AppRunningRecord::GetSignCode() const
149 {
150     return signCode_;
151 }
152 
SetSignCode(const std::string & signCode)153 void AppRunningRecord::SetSignCode(const std::string &signCode)
154 {
155     signCode_ = signCode;
156 }
157 
GetJointUserId() const158 const std::string &AppRunningRecord::GetJointUserId() const
159 {
160     return jointUserId_;
161 }
162 
SetJointUserId(const std::string & jointUserId)163 void AppRunningRecord::SetJointUserId(const std::string &jointUserId)
164 {
165     jointUserId_ = jointUserId;
166 }
167 
GetProcessName() const168 const std::string &AppRunningRecord::GetProcessName() const
169 {
170     return processName_;
171 }
172 
GetExtensionSandBoxFlag() const173 bool AppRunningRecord::GetExtensionSandBoxFlag() const
174 {
175     return isExtensionSandBox_;
176 }
177 
SetExtensionSandBoxFlag(bool extensionSandBoxFlag)178 void AppRunningRecord::SetExtensionSandBoxFlag(bool extensionSandBoxFlag)
179 {
180     isExtensionSandBox_ = extensionSandBoxFlag;
181 }
182 
SetSpecifiedProcessFlag(const std::string & flag)183 void AppRunningRecord::SetSpecifiedProcessFlag(const std::string &flag)
184 {
185     specifiedProcessFlag_ = flag;
186 }
187 
GetSpecifiedProcessFlag() const188 const std::string &AppRunningRecord::GetSpecifiedProcessFlag() const
189 {
190     return specifiedProcessFlag_;
191 }
SetCustomProcessFlag(const std::string & flag)192 void AppRunningRecord::SetCustomProcessFlag(const std::string &flag)
193 {
194     customProcessFlag_ = flag;
195 }
196 
GetCustomProcessFlag() const197 const std::string &AppRunningRecord::GetCustomProcessFlag() const
198 {
199     return customProcessFlag_;
200 }
201 
GetUid() const202 int32_t AppRunningRecord::GetUid() const
203 {
204     return mainUid_;
205 }
206 
SetUid(const int32_t uid)207 void AppRunningRecord::SetUid(const int32_t uid)
208 {
209     mainUid_ = uid;
210 }
211 
GetUserId() const212 int32_t AppRunningRecord::GetUserId() const
213 {
214     return mainUid_ / BASE_USER_RANGE;
215 }
216 
GetState() const217 ApplicationState AppRunningRecord::GetState() const
218 {
219     return curState_;
220 }
221 
SetState(const ApplicationState state)222 void AppRunningRecord::SetState(const ApplicationState state)
223 {
224     if (state >= ApplicationState::APP_STATE_END && state != ApplicationState::APP_STATE_CACHED) {
225         TAG_LOGE(AAFwkTag::APPMGR, "Invalid application state");
226         return;
227     }
228     if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) {
229         restartResidentProcCount_ = MAX_RESTART_COUNT;
230     }
231     std::string foreTag = "ForeApp:";
232     if (state == ApplicationState::APP_STATE_FOREGROUND) {
233         StartAsyncTrace(HITRACE_TAG_APP, foreTag + mainBundleName_, 0);
234     } else if (state == ApplicationState::APP_STATE_BACKGROUND) {
235         FinishAsyncTrace(HITRACE_TAG_APP, foreTag + mainBundleName_, 0);
236     }
237     curState_ = state;
238 }
239 
SetRestartTimeMillis(const int64_t restartTimeMillis)240 void AppRunningRecord::SetRestartTimeMillis(const int64_t restartTimeMillis)
241 {
242     restartTimeMillis_ = restartTimeMillis;
243 }
244 
GetAppInfoList()245 const std::list<std::shared_ptr<ApplicationInfo>> AppRunningRecord::GetAppInfoList()
246 {
247     std::list<std::shared_ptr<ApplicationInfo>> appInfoList;
248     std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
249     for (const auto &item : appInfos_) {
250         appInfoList.push_back(item.second);
251     }
252     return appInfoList;
253 }
254 
SetAppIdentifier(const std::string & appIdentifier)255 void AppRunningRecord::SetAppIdentifier(const std::string &appIdentifier)
256 {
257     appIdentifier_ = appIdentifier;
258 }
259 
GetAppIdentifier() const260 const std::string &AppRunningRecord::GetAppIdentifier() const
261 {
262     return appIdentifier_;
263 }
264 
GetAbilities()265 const std::map<const sptr<IRemoteObject>, std::shared_ptr<AbilityRunningRecord>> AppRunningRecord::GetAbilities()
266 {
267     std::map<const sptr<IRemoteObject>, std::shared_ptr<AbilityRunningRecord>> abilitiesMap;
268     auto moduleRecordList = GetAllModuleRecord();
269     for (const auto &moduleRecord : moduleRecordList) {
270         auto abilities = moduleRecord->GetAbilities();
271         abilitiesMap.insert(abilities.begin(), abilities.end());
272     }
273     return abilitiesMap;
274 }
275 
IsAlreadyHaveAbility()276 bool AppRunningRecord::IsAlreadyHaveAbility()
277 {
278     auto moduleRecordList = GetAllModuleRecord();
279     for (const auto &moduleRecord : moduleRecordList) {
280         if (!moduleRecord) {
281             continue;
282         }
283         auto abilities = moduleRecord->GetAbilities();
284         if (!abilities.empty()) {
285             return true;
286         }
287     }
288     return false;
289 }
290 
GetApplicationClient() const291 sptr<IAppScheduler> AppRunningRecord::GetApplicationClient() const
292 {
293     return (appLifeCycleDeal_ ? appLifeCycleDeal_->GetApplicationClient() : nullptr);
294 }
295 
GetAbilityRunningRecord(const int64_t eventId) const296 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecord(const int64_t eventId) const
297 {
298     TAG_LOGD(AAFwkTag::APPMGR, "called");
299     auto moduleRecordList = GetAllModuleRecord();
300     for (const auto &moduleRecord : moduleRecordList) {
301         auto abilityRecord = moduleRecord->GetAbilityRunningRecord(eventId);
302         if (abilityRecord) {
303             return abilityRecord;
304         }
305     }
306 
307     return nullptr;
308 }
309 
RemoveModuleRecord(const std::shared_ptr<ModuleRunningRecord> & moduleRecord,bool isExtensionDebug)310 void AppRunningRecord::RemoveModuleRecord(
311     const std::shared_ptr<ModuleRunningRecord> &moduleRecord, bool isExtensionDebug)
312 {
313     TAG_LOGD(AAFwkTag::APPMGR, "called");
314 
315     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
316     for (auto &item : hapModules_) {
317         auto iter = std::find_if(item.second.begin(),
318             item.second.end(),
319             [&moduleRecord](const std::shared_ptr<ModuleRunningRecord> &record) { return moduleRecord == record; });
320         if (iter != item.second.end()) {
321             TAG_LOGD(AAFwkTag::APPMGR, "Removed a record.");
322             iter = item.second.erase(iter);
323             if (item.second.empty() && !isExtensionDebug) {
324                 {
325                     std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
326                     TAG_LOGD(AAFwkTag::APPMGR, "Removed an appInfo.");
327                     appInfos_.erase(item.first);
328                 }
329                 hapModules_.erase(item.first);
330             }
331             return;
332         }
333     }
334 }
335 
LaunchApplication(const Configuration & config)336 void AppRunningRecord::LaunchApplication(const Configuration &config)
337 {
338     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
339     if (appLifeCycleDeal_ == nullptr) {
340         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
341         return;
342     }
343     auto scheduler = appLifeCycleDeal_->GetApplicationClient();
344     if (!scheduler) {
345         TAG_LOGE(AAFwkTag::APPMGR, "null appThread");
346         AddAppLifecycleEvent("AppRunningRecord::LaunchApplication; null scheduler");
347         return;
348     }
349     AppLaunchData launchData;
350     {
351         std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
352         auto moduleRecords = appInfos_.find(mainBundleName_);
353         if (moduleRecords != appInfos_.end()) {
354             launchData.SetApplicationInfo(*(moduleRecords->second));
355         }
356     }
357     ProcessInfo processInfo(processName_, GetPid());
358     processInfo.SetProcessType(processType_);
359     launchData.SetProcessInfo(processInfo);
360     launchData.SetRecordId(appRecordId_);
361     launchData.SetUId(mainUid_);
362     launchData.SetUserTestInfo(userTestRecord_);
363     launchData.SetAppIndex(appIndex_);
364     launchData.SetInstanceKey(instanceKey_);
365     launchData.SetDebugApp(isDebugApp_);
366     launchData.SetPerfCmd(perfCmd_);
367     launchData.SetErrorInfoEnhance(isErrorInfoEnhance_);
368     launchData.SetMultiThread(isMultiThread_);
369     launchData.SetJITEnabled(jitEnabled_);
370     launchData.SetNativeStart(isNativeStart_);
371     launchData.SetAppRunningUniqueId(std::to_string(startTimeMillis_));
372     launchData.SetIsNeedPreloadModule(isNeedPreloadModule_);
373     launchData.SetAppPreloadMode(preloadMode_);
374     launchData.SetNWebPreload(isAllowedNWebPreload_);
375     launchData.SetPreloadModuleName(preloadModuleName_);
376     launchData.SetDebugFromLocal(isDebugFromLocal_);
377     launchData.SetStartupTaskData(startupTaskData_);
378 
379     TAG_LOGD(AAFwkTag::APPMGR, "%{public}s called,app is %{public}s.", __func__, GetName().c_str());
380     AddAppLifecycleEvent("AppRunningRecord::LaunchApplication");
381     AbilityRuntime::ErrorMsgGuard errorMsgGuard(GetPid(), reinterpret_cast<uintptr_t>(scheduler.GetRefPtr()),
382         "LaunchApplication");
383     appLifeCycleDeal_->LaunchApplication(launchData, config);
384 }
385 
UpdateApplicationInfoInstalled(const ApplicationInfo & appInfo,const std::string & moduleName)386 void AppRunningRecord::UpdateApplicationInfoInstalled(const ApplicationInfo &appInfo, const std::string &moduleName)
387 {
388     if (!isStageBasedModel_) {
389         TAG_LOGI(AAFwkTag::APPMGR, "Current version than supports");
390         return;
391     }
392 
393     if (appLifeCycleDeal_ == nullptr) {
394         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
395         return;
396     }
397     appLifeCycleDeal_->UpdateApplicationInfoInstalled(appInfo, moduleName);
398 }
399 
AddAbilityStage()400 void AppRunningRecord::AddAbilityStage()
401 {
402     if (!isStageBasedModel_) {
403         TAG_LOGI(AAFwkTag::APPMGR, "Current version than supports");
404         return;
405     }
406     HapModuleInfo abilityStage;
407     if (GetTheModuleInfoNeedToUpdated(mainBundleName_, abilityStage)) {
408         auto timeout = GetAddStageTimeout() * AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
409         SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_HALF_TIMEOUT_MSG, timeout / HALF_TIMEOUT);
410         SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, timeout);
411         TAG_LOGI(AAFwkTag::APPMGR, "Current module : [%{public}s] | bundle : [%{public}s]",
412             abilityStage.moduleName.c_str(), mainBundleName_.c_str());
413         if (appLifeCycleDeal_ == nullptr) {
414             TAG_LOGW(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
415             return;
416         }
417         appLifeCycleDeal_->AddAbilityStage(abilityStage);
418     }
419 }
420 
AddAbilityStageBySpecifiedAbility(const std::string & bundleName)421 bool AppRunningRecord::AddAbilityStageBySpecifiedAbility(const std::string &bundleName)
422 {
423     if (!eventHandler_) {
424         TAG_LOGE(AAFwkTag::APPMGR, "null eventHandler_");
425         return false;
426     }
427 
428     HapModuleInfo hapModuleInfo;
429     if (GetTheModuleInfoNeedToUpdated(bundleName, hapModuleInfo)) {
430         if (!AppEventUtil::GetInstance().HasEvent(shared_from_this(),
431             AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG)) {
432             TAG_LOGI(
433                 AAFwkTag::APPMGR, "ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG not exist");
434             auto timeout = GetAddStageTimeout() * AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
435             SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_HALF_TIMEOUT_MSG, timeout / HALF_TIMEOUT);
436             SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, timeout);
437         }
438         if (appLifeCycleDeal_ == nullptr) {
439             TAG_LOGW(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
440             return false;
441         }
442         appLifeCycleDeal_->AddAbilityStage(hapModuleInfo);
443         return true;
444     }
445     return false;
446 }
447 
AddAbilityStageBySpecifiedProcess(const std::string & bundleName)448 void AppRunningRecord::AddAbilityStageBySpecifiedProcess(const std::string &bundleName)
449 {
450     TAG_LOGD(AAFwkTag::APPMGR, "call.");
451     if (!eventHandler_) {
452         TAG_LOGE(AAFwkTag::APPMGR, "null eventHandler_");
453         return;
454     }
455 
456     HapModuleInfo hapModuleInfo;
457     if (GetTheModuleInfoNeedToUpdated(bundleName, hapModuleInfo)) {
458         auto timeout = GetAddStageTimeout() * AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
459         SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_HALF_TIMEOUT_MSG, timeout / HALF_TIMEOUT);
460         SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, timeout);
461         if (appLifeCycleDeal_ == nullptr) {
462             TAG_LOGW(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
463             return;
464         }
465         appLifeCycleDeal_->AddAbilityStage(hapModuleInfo);
466     }
467 }
468 
AddAbilityStageDone()469 void AppRunningRecord::AddAbilityStageDone()
470 {
471     TAG_LOGI(AAFwkTag::APPMGR, "bundle %{public}s", mainBundleName_.c_str());
472     RemoveEvent(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG);
473     RemoveEvent(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG);
474     RemoveEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG);
475     RemoveEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_HALF_TIMEOUT_MSG);
476     SetModuleLoaded(moduleName_);
477 
478     // Should proceed to the next notification
479     if (IsStartSpecifiedAbility()) {
480         ScheduleAcceptWant(moduleName_);
481         return;
482     }
483 
484     if (IsNewProcessRequest()) {
485         TAG_LOGD(AAFwkTag::APPMGR, "ScheduleNewProcessRequest.");
486         ScheduleNewProcessRequest(GetNewProcessRequestWant(), moduleName_);
487         return;
488     }
489 
490     AddAbilityStage();
491 }
492 
SetModuleLoaded(const std::string & moduleName) const493 void AppRunningRecord::SetModuleLoaded(const std::string &moduleName) const
494 {
495     auto moduleRecordList = GetAllModuleRecord();
496     for (const auto &item : moduleRecordList) {
497         if (item && item->GetModuleName() == moduleName) {
498             item->SetLoaded();
499             break;
500         }
501     }
502 }
503 
LaunchAbility(const std::shared_ptr<AbilityRunningRecord> & ability)504 void AppRunningRecord::LaunchAbility(const std::shared_ptr<AbilityRunningRecord> &ability)
505 {
506     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
507     if (appLifeCycleDeal_ == nullptr) {
508         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
509         return;
510     }
511     if (!ability || !ability->GetToken()) {
512         TAG_LOGE(AAFwkTag::APPMGR, "null abilityRecord or abilityToken");
513         return;
514     }
515 
516     auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
517     if (!moduleRecord) {
518         TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
519         return;
520     }
521 
522     moduleRecord->LaunchAbility(ability);
523 }
524 
ScheduleTerminate()525 void AppRunningRecord::ScheduleTerminate()
526 {
527     auto timeout = AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT * AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
528     SendEvent(AMSEventHandler::TERMINATE_APPLICATION_HALF_TIMEOUT_MSG, timeout / HALF_TIMEOUT);
529     SendEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, timeout);
530     if (appLifeCycleDeal_ == nullptr) {
531         TAG_LOGW(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
532         return;
533     }
534     bool isLastProcess = false;
535     auto serviceInner = appMgrServiceInner_.lock();
536     if (serviceInner != nullptr) {
537         isLastProcess = serviceInner->IsFinalAppProcessByBundleName(GetBundleName());
538     }
539     appLifeCycleDeal_->ScheduleTerminate(isLastProcess);
540 }
541 
LaunchPendingAbilities()542 void AppRunningRecord::LaunchPendingAbilities()
543 {
544     TAG_LOGI(AAFwkTag::APPMGR, "Launch pending abilities.");
545     AddAppLifecycleEvent("AppRunningRecord::LaunchPendingAbilities");
546     auto moduleRecordList = GetAllModuleRecord();
547     if (moduleRecordList.empty()) {
548         TAG_LOGE(AAFwkTag::APPMGR, "empty moduleRecordList");
549         return;
550     }
551     for (const auto &moduleRecord : moduleRecordList) {
552         moduleRecord->SetApplicationClient(appLifeCycleDeal_);
553         moduleRecord->LaunchPendingAbilities();
554     }
555 }
556 
ScheduleForegroundRunning()557 bool AppRunningRecord::ScheduleForegroundRunning()
558 {
559     SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_FOREGROUNDING);
560     if (appLifeCycleDeal_) {
561         AddAppLifecycleEvent("AppRunningRecord::ScheduleForegroundRunning");
562         auto scheduler = appLifeCycleDeal_->GetApplicationClient();
563         if (!scheduler) {
564             AddAppLifecycleEvent("AppRunningRecord::ScheduleForegroundRunning; null scheduler");
565             return false;
566         }
567         AbilityRuntime::ErrorMsgGuard errorMsgGuard(GetPid(), reinterpret_cast<uintptr_t>(scheduler.GetRefPtr()),
568             "ScheduleForegroundRunning");
569         return appLifeCycleDeal_->ScheduleForegroundRunning();
570     }
571     return false;
572 }
573 
ScheduleBackgroundRunning()574 void AppRunningRecord::ScheduleBackgroundRunning()
575 {
576     SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_BACKGROUNDING);
577     int32_t recordId = GetRecordId();
578     auto serviceInner = appMgrServiceInner_;
579     auto appbackgroundtask = [recordId, serviceInner]() {
580         auto serviceInnerObj = serviceInner.lock();
581         if (serviceInnerObj == nullptr) {
582             TAG_LOGW(AAFwkTag::APPMGR, "APPManager is invalid");
583             return;
584         }
585         TAG_LOGE(AAFwkTag::APPMGR, "APPManager move timeout");
586         serviceInnerObj->ApplicationBackgrounded(recordId);
587     };
588     auto taskName = std::string("appbackground_") + std::to_string(recordId);
589     if (taskHandler_) {
590         taskHandler_->CancelTask(taskName);
591     }
592     PostTask(taskName, AMSEventHandler::BACKGROUND_APPLICATION_TIMEOUT, appbackgroundtask);
593     if (appLifeCycleDeal_) {
594         AddAppLifecycleEvent("AppRunningRecord::ScheduleBackgroundRunning");
595         appLifeCycleDeal_->ScheduleBackgroundRunning();
596     }
597     isAbilityForegrounding_.store(false);
598 }
599 
ScheduleProcessSecurityExit()600 void AppRunningRecord::ScheduleProcessSecurityExit()
601 {
602     if (appLifeCycleDeal_) {
603         auto appRecord = shared_from_this();
604         DelayedSingleton<CacheProcessManager>::GetInstance()->PrepareActivateCache(appRecord);
605         appLifeCycleDeal_->ScheduleProcessSecurityExit();
606     }
607 }
608 
ScheduleClearPageStack()609 void AppRunningRecord::ScheduleClearPageStack()
610 {
611     if (appLifeCycleDeal_) {
612         appLifeCycleDeal_->ScheduleClearPageStack();
613     }
614 }
615 
ScheduleTrimMemory()616 void AppRunningRecord::ScheduleTrimMemory()
617 {
618     if (appLifeCycleDeal_ && priorityObject_) {
619         appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel());
620     }
621 }
622 
ScheduleMemoryLevel(int32_t level)623 void AppRunningRecord::ScheduleMemoryLevel(int32_t level)
624 {
625     if (appLifeCycleDeal_) {
626         appLifeCycleDeal_->ScheduleMemoryLevel(level);
627     }
628 }
629 
ScheduleHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)630 void AppRunningRecord::ScheduleHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
631 {
632     if (appLifeCycleDeal_) {
633         appLifeCycleDeal_->ScheduleHeapMemory(pid, mallocInfo);
634     }
635 }
636 
ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)637 void AppRunningRecord::ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
638 {
639     if (appLifeCycleDeal_) {
640         appLifeCycleDeal_->ScheduleJsHeapMemory(info);
641     }
642 }
643 
ScheduleCjHeapMemory(OHOS::AppExecFwk::CjHeapDumpInfo & info)644 void AppRunningRecord::ScheduleCjHeapMemory(OHOS::AppExecFwk::CjHeapDumpInfo &info)
645 {
646     if (appLifeCycleDeal_) {
647         appLifeCycleDeal_->ScheduleCjHeapMemory(info);
648     }
649 }
650 
LowMemoryWarning()651 void AppRunningRecord::LowMemoryWarning()
652 {
653     if (appLifeCycleDeal_) {
654         appLifeCycleDeal_->LowMemoryWarning();
655     }
656 }
657 
AddModules(const std::shared_ptr<ApplicationInfo> & appInfo,const std::vector<HapModuleInfo> & moduleInfos)658 void AppRunningRecord::AddModules(
659     const std::shared_ptr<ApplicationInfo> &appInfo, const std::vector<HapModuleInfo> &moduleInfos)
660 {
661     TAG_LOGD(AAFwkTag::APPMGR, "Add modules");
662 
663     if (moduleInfos.empty()) {
664         TAG_LOGI(AAFwkTag::APPMGR, "empty moduleInfos");
665         return;
666     }
667 
668     for (auto &iter : moduleInfos) {
669         AddModule(appInfo, nullptr, nullptr, iter, nullptr, 0);
670     }
671 }
672 
AddModule(std::shared_ptr<ApplicationInfo> appInfo,std::shared_ptr<AbilityInfo> abilityInfo,sptr<IRemoteObject> token,const HapModuleInfo & hapModuleInfo,std::shared_ptr<AAFwk::Want> want,int32_t abilityRecordId)673 void AppRunningRecord::AddModule(std::shared_ptr<ApplicationInfo> appInfo,
674     std::shared_ptr<AbilityInfo> abilityInfo, sptr<IRemoteObject> token,
675     const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, int32_t abilityRecordId)
676 {
677     TAG_LOGD(AAFwkTag::APPMGR, "called");
678 
679     if (!appInfo) {
680         TAG_LOGE(AAFwkTag::APPMGR, "null appInfo");
681         return;
682     }
683 
684     std::shared_ptr<ModuleRunningRecord> moduleRecord;
685     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
686     const auto &iter = hapModules_.find(appInfo->bundleName);
687     if (iter != hapModules_.end()) {
688         moduleRecord = GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
689         if (!moduleRecord) {
690             moduleRecord = std::make_shared<ModuleRunningRecord>(appInfo, eventHandler_);
691             iter->second.push_back(moduleRecord);
692             moduleRecord->Init(hapModuleInfo, appIndex_, appMgrServiceInner_, appLifeCycleDeal_);
693         }
694     } else {
695         moduleRecord = std::make_shared<ModuleRunningRecord>(appInfo, eventHandler_);
696         std::vector<std::shared_ptr<ModuleRunningRecord>> moduleList;
697         moduleList.push_back(moduleRecord);
698         hapModules_.emplace(appInfo->bundleName, moduleList);
699         {
700             std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
701             appInfos_.emplace(appInfo->bundleName, appInfo);
702         }
703         moduleRecord->Init(hapModuleInfo, appIndex_, appMgrServiceInner_, appLifeCycleDeal_);
704     }
705 
706     if (!abilityInfo || !token) {
707         TAG_LOGE(AAFwkTag::APPMGR, "null abilityInfo or token");
708         return;
709     }
710     moduleRecord->AddAbility(token, abilityInfo, want, abilityRecordId);
711 
712     return;
713 }
714 
GetModuleRecordByModuleName(const std::string & bundleName,const std::string & moduleName)715 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRecordByModuleName(
716     const std::string &bundleName, const std::string &moduleName)
717 {
718     TAG_LOGD(AAFwkTag::APPMGR, "called");
719     auto moduleRecords = hapModules_.find(bundleName);
720     if (moduleRecords != hapModules_.end()) {
721         for (auto &iter : moduleRecords->second) {
722             if (iter->GetModuleName() == moduleName) {
723                 return iter;
724             }
725         }
726     }
727 
728     return nullptr;
729 }
730 
StateChangedNotifyObserver(const std::shared_ptr<AbilityRunningRecord> & ability,int32_t state,bool isAbility,bool isFromWindowFocusChanged)731 void AppRunningRecord::StateChangedNotifyObserver(const std::shared_ptr<AbilityRunningRecord> &ability,
732     int32_t state, bool isAbility, bool isFromWindowFocusChanged)
733 {
734     if (ability == nullptr) {
735         TAG_LOGE(AAFwkTag::APPMGR, "null ability");
736         return;
737     }
738     auto abilityInfo = ability->GetAbilityInfo();
739     if (abilityInfo == nullptr) {
740         TAG_LOGE(AAFwkTag::APPMGR, "null abilityInfo");
741         return;
742     }
743     AbilityStateData abilityStateData;
744     abilityStateData.bundleName = abilityInfo->applicationInfo.bundleName;
745     abilityStateData.moduleName = abilityInfo->moduleName;
746     abilityStateData.abilityName = ability->GetName();
747     abilityStateData.pid = GetPid();
748     abilityStateData.abilityState = state;
749     abilityStateData.uid = abilityInfo->applicationInfo.uid;
750     abilityStateData.token = ability->GetToken();
751     abilityStateData.abilityType = static_cast<int32_t>(abilityInfo->type);
752     abilityStateData.isFocused = ability->GetFocusFlag();
753     abilityStateData.abilityRecordId = ability->GetAbilityRecordId();
754     auto applicationInfo = GetApplicationInfo();
755     if (applicationInfo && (static_cast<int32_t>(applicationInfo->multiAppMode.multiAppModeType) ==
756             static_cast<int32_t>(MultiAppModeType::APP_CLONE))) {
757             abilityStateData.appCloneIndex = appIndex_;
758     }
759     if (ability->GetWant() != nullptr) {
760         abilityStateData.callerAbilityName = ability->GetWant()->GetStringParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
761         abilityStateData.callerBundleName = ability->GetWant()->GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
762         abilityStateData.callerUid = ability->GetWant()->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1);
763     }
764     if (applicationInfo && applicationInfo->bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
765         abilityStateData.isAtomicService = true;
766     }
767     bool isUIExtension = AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType);
768     if (isUIExtension) {
769         if (!isAbility) {
770             abilityStateData.extensionAbilityType = static_cast<int32_t>(abilityInfo->extensionAbilityType);
771         } else {
772             abilityStateData.isInnerNotify = true;
773         }
774     }
775     abilityStateData.processType = static_cast<int32_t>(processType_);
776     auto serviceInner = appMgrServiceInner_.lock();
777     if (serviceInner) {
778         serviceInner->StateChangedNotifyObserver(abilityStateData, isAbility, isFromWindowFocusChanged);
779     }
780 }
781 
GetModuleRunningRecordByToken(const sptr<IRemoteObject> & token) const782 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRunningRecordByToken(
783     const sptr<IRemoteObject> &token) const
784 {
785     if (!token) {
786         return nullptr;
787     }
788 
789     auto moduleRecordList = GetAllModuleRecord();
790     for (const auto &moduleRecord : moduleRecordList) {
791         if (moduleRecord && moduleRecord->GetAbilityRunningRecordByToken(token)) {
792             return moduleRecord;
793         }
794     }
795 
796     return nullptr;
797 }
798 
GetModuleRunningRecordByTerminateLists(const sptr<IRemoteObject> & token) const799 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRunningRecordByTerminateLists(
800     const sptr<IRemoteObject> &token) const
801 {
802     if (!token) {
803         TAG_LOGE(AAFwkTag::APPMGR, "null token");
804         return nullptr;
805     }
806 
807     auto moduleRecordList = GetAllModuleRecord();
808     for (const auto &moduleRecord : moduleRecordList) {
809         if (moduleRecord && moduleRecord->GetAbilityByTerminateLists(token)) {
810             return moduleRecord;
811         }
812     }
813 
814     return nullptr;
815 }
816 
GetAbilityRunningRecordByToken(const sptr<IRemoteObject> & token) const817 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecordByToken(
818     const sptr<IRemoteObject> &token) const
819 {
820     auto moduleRecord = GetModuleRunningRecordByToken(token);
821     if (!moduleRecord) {
822         return nullptr;
823     }
824     return moduleRecord->GetAbilityRunningRecordByToken(token);
825 }
826 
GetAbilityByTerminateLists(const sptr<IRemoteObject> & token) const827 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityByTerminateLists(
828     const sptr<IRemoteObject> &token) const
829 {
830     auto moduleRecord = GetModuleRunningRecordByTerminateLists(token);
831     if (!moduleRecord) {
832         return nullptr;
833     }
834     return moduleRecord->GetAbilityByTerminateLists(token);
835 }
836 
UpdateAbilityFocusState(const sptr<IRemoteObject> & token,bool isFocus)837 bool AppRunningRecord::UpdateAbilityFocusState(const sptr<IRemoteObject> &token, bool isFocus)
838 {
839     TAG_LOGD(AAFwkTag::APPMGR, "focus state is :%{public}d", isFocus);
840     auto abilityRecord = GetAbilityRunningRecordByToken(token);
841     if (!abilityRecord) {
842         TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record");
843         return false;
844     }
845 
846     bool lastFocusState = abilityRecord->GetFocusFlag();
847     if (lastFocusState == isFocus) {
848         TAG_LOGE(AAFwkTag::APPMGR, "no need update");
849         return false;
850     }
851 
852     if (isFocus) {
853         return AbilityFocused(abilityRecord);
854     } else {
855         return AbilityUnfocused(abilityRecord);
856     }
857 }
858 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)859 void AppRunningRecord::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
860 {
861     TAG_LOGD(AAFwkTag::APPMGR, "state is :%{public}d", static_cast<int32_t>(state));
862     auto abilityRecord = GetAbilityRunningRecordByToken(token);
863     if (!abilityRecord) {
864         TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record");
865         return;
866     }
867     if (state == AbilityState::ABILITY_STATE_CREATE) {
868         StateChangedNotifyObserver(
869             abilityRecord, static_cast<int32_t>(AbilityState::ABILITY_STATE_CREATE), true, false);
870         return;
871     }
872     if (state == abilityRecord->GetState()) {
873         TAG_LOGE(AAFwkTag::APPMGR, "no need update");
874         return;
875     }
876 
877     if (state == AbilityState::ABILITY_STATE_FOREGROUND) {
878         AbilityForeground(abilityRecord);
879     } else if (state == AbilityState::ABILITY_STATE_BACKGROUND) {
880         AbilityBackground(abilityRecord);
881     } else {
882         TAG_LOGW(AAFwkTag::APPMGR, "wrong state");
883     }
884 }
885 
AbilityForeground(const std::shared_ptr<AbilityRunningRecord> & ability)886 void AppRunningRecord::AbilityForeground(const std::shared_ptr<AbilityRunningRecord> &ability)
887 {
888     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
889     if (!ability) {
890         TAG_LOGE(AAFwkTag::APPMGR, "null ability");
891         return;
892     }
893 
894     AbilityState curAbilityState = ability->GetState();
895     if (curAbilityState != AbilityState::ABILITY_STATE_READY &&
896         curAbilityState != AbilityState::ABILITY_STATE_BACKGROUND) {
897         TAG_LOGE(AAFwkTag::APPMGR, "ability state(%{public}d) error", static_cast<int32_t>(curAbilityState));
898         return;
899     }
900 
901     TAG_LOGI(AAFwkTag::APPMGR, "appState: %{public}d, pState: %{public}d, bundle: %{public}s, ability: %{public}s",
902         curState_, pendingState_, mainBundleName_.c_str(), ability->GetName().c_str());
903     // We need schedule application to foregrounded when current application state is ready or background running.
904     if (curState_ == ApplicationState::APP_STATE_FOREGROUND
905         && pendingState_ != ApplicationPendingState::BACKGROUNDING) {
906         // Just change ability to foreground if current application state is foreground or focus.
907         auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
908         if (moduleRecord == nullptr) {
909             TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
910             return;
911         }
912 
913         moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
914         StateChangedNotifyObserver(
915             ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND), true, false);
916 
917         auto serviceInner = appMgrServiceInner_.lock();
918         if (serviceInner) {
919             serviceInner->OnAppStateChanged(shared_from_this(), curState_, false, false);
920         }
921         return;
922     }
923     if (curState_ == ApplicationState::APP_STATE_READY || curState_ == ApplicationState::APP_STATE_BACKGROUND
924         || curState_ == ApplicationState::APP_STATE_FOREGROUND) {
925         auto pendingState = pendingState_;
926         SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING);
927         if (pendingState == ApplicationPendingState::READY && !ScheduleForegroundRunning()) {
928             AbilityRuntime::FreezeUtil::GetInstance().AppendLifecycleEvent(ability->GetToken(),
929                 "ScheduleForegroundRunning fail");
930         }
931         foregroundingAbilityTokens_.insert(ability->GetToken());
932         TAG_LOGD(AAFwkTag::APPMGR, "foregroundingAbility size: %{public}d",
933             static_cast<int32_t>(foregroundingAbilityTokens_.size()));
934     } else {
935         TAG_LOGW(AAFwkTag::APPMGR, "wrong state");
936     }
937 }
938 
AbilityBackground(const std::shared_ptr<AbilityRunningRecord> & ability)939 void AppRunningRecord::AbilityBackground(const std::shared_ptr<AbilityRunningRecord> &ability)
940 {
941     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
942     if (!ability) {
943         TAG_LOGE(AAFwkTag::APPMGR, "null ability");
944         return;
945     }
946     TAG_LOGD(AAFwkTag::APPMGR, "ability is %{public}s", mainBundleName_.c_str());
947     if (ability->GetState() != AbilityState::ABILITY_STATE_FOREGROUND &&
948         ability->GetState() != AbilityState::ABILITY_STATE_READY) {
949         TAG_LOGE(AAFwkTag::APPMGR, "ability state is not foreground or focus");
950         return;
951     }
952 
953     // First change ability to background.
954     auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
955     if (moduleRecord == nullptr) {
956         TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
957         return;
958     }
959     moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BACKGROUND);
960     StateChangedNotifyObserver(
961         ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_BACKGROUND), true, false);
962     if (curState_ != ApplicationState::APP_STATE_FOREGROUND && curState_ != ApplicationState::APP_STATE_CACHED) {
963         TAG_LOGW(AAFwkTag::APPMGR, "wrong state");
964         return;
965     }
966     int32_t foregroundSize = 0;
967     auto abilitiesMap = GetAbilities();
968     for (const auto &item : abilitiesMap) {
969         const auto &abilityRecord = item.second;
970         if (abilityRecord && abilityRecord->GetState() == AbilityState::ABILITY_STATE_FOREGROUND &&
971             abilityRecord->GetAbilityInfo() &&
972             (abilityRecord->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE
973             || AAFwk::UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo()->extensionAbilityType))) {
974             foregroundSize++;
975             break;
976         }
977     }
978 
979     // Then schedule application background when all ability is not foreground.
980     if (foregroundSize == 0 && mainBundleName_ != LAUNCHER_NAME && IsWindowIdsEmpty()) {
981         auto pendingState = pendingState_;
982         SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING);
983         if (pendingState == ApplicationPendingState::READY) {
984             ScheduleBackgroundRunning();
985         }
986     }
987 }
988 
AbilityFocused(const std::shared_ptr<AbilityRunningRecord> & ability)989 bool AppRunningRecord::AbilityFocused(const std::shared_ptr<AbilityRunningRecord> &ability)
990 {
991     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
992     if (!ability) {
993         TAG_LOGE(AAFwkTag::APPMGR, "null ability");
994         return false;
995     }
996     ability->UpdateFocusState(true);
997 
998     // update ability state
999     int32_t abilityState = static_cast<int32_t>(ability->GetState());
1000     bool isAbility = true;
1001     if (ability->GetAbilityInfo() != nullptr && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) {
1002         isAbility = false;
1003     }
1004     StateChangedNotifyObserver(ability, abilityState, isAbility, true);
1005 
1006     if (isFocused_) {
1007         // process state is already focused, no need update process state.
1008         return false;
1009     }
1010 
1011     // update process focus state to true.
1012     isFocused_ = true;
1013     return true;
1014 }
1015 
AbilityUnfocused(const std::shared_ptr<AbilityRunningRecord> & ability)1016 bool AppRunningRecord::AbilityUnfocused(const std::shared_ptr<AbilityRunningRecord> &ability)
1017 {
1018     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1019     if (!ability) {
1020         TAG_LOGE(AAFwkTag::APPMGR, "null ability");
1021         return false;
1022     }
1023     ability->UpdateFocusState(false);
1024 
1025     // update ability state to unfocused.
1026     int32_t abilityState = static_cast<int32_t>(ability->GetState());
1027     bool isAbility = true;
1028     if (ability->GetAbilityInfo() != nullptr && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) {
1029         isAbility = false;
1030     }
1031     StateChangedNotifyObserver(ability, abilityState, isAbility, true);
1032 
1033     if (!isFocused_) {
1034         return false; // invalid process focus state, already unfocused, process state not change.
1035     }
1036 
1037     bool changeProcessToUnfocused = true;
1038     auto abilitysMap = GetAbilities();
1039     for (const auto &item : abilitysMap) {
1040         const auto &abilityRecord = item.second;
1041         if (abilityRecord && abilityRecord->GetFocusFlag()) {
1042             changeProcessToUnfocused = false;
1043             break;
1044         }
1045     }
1046 
1047     if (changeProcessToUnfocused) {
1048         isFocused_ = false; // process focus state : from focus to unfocus.
1049     }
1050     return changeProcessToUnfocused;
1051 }
1052 
PopForegroundingAbilityTokens()1053 void AppRunningRecord::PopForegroundingAbilityTokens()
1054 {
1055     TAG_LOGI(AAFwkTag::APPMGR, "ability size: %{public}d",
1056         static_cast<int32_t>(foregroundingAbilityTokens_.size()));
1057     for (auto iter = foregroundingAbilityTokens_.begin(); iter != foregroundingAbilityTokens_.end();) {
1058         auto ability = GetAbilityRunningRecordByToken(*iter);
1059         auto moduleRecord = GetModuleRunningRecordByToken(*iter);
1060         if (moduleRecord != nullptr) {
1061             moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
1062             StateChangedNotifyObserver(
1063                 ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND), true, false);
1064         } else {
1065             TAG_LOGW(AAFwkTag::APPMGR, "null moduleRecord");
1066         }
1067         // The token should be removed even though the module record didn't exist.
1068         iter = foregroundingAbilityTokens_.erase(iter);
1069     }
1070 }
1071 
TerminateAbility(const sptr<IRemoteObject> & token,const bool isForce,bool isTimeout)1072 void AppRunningRecord::TerminateAbility(const sptr<IRemoteObject> &token, const bool isForce, bool isTimeout)
1073 {
1074     TAG_LOGD(AAFwkTag::APPMGR, "isForce: %{public}d", static_cast<int>(isForce));
1075 
1076     auto moduleRecord = GetModuleRunningRecordByToken(token);
1077     if (!moduleRecord) {
1078         TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
1079         return;
1080     }
1081 
1082     auto abilityRecord = GetAbilityRunningRecordByToken(token);
1083     if (abilityRecord) {
1084         TAG_LOGI(AAFwkTag::APPMGR, "TerminateAbility:%{public}s", abilityRecord->GetName().c_str());
1085     }
1086     if (!isTimeout) {
1087         StateChangedNotifyObserver(
1088             abilityRecord, static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true, false);
1089     }
1090     moduleRecord->TerminateAbility(shared_from_this(), token, isForce);
1091 }
1092 
AbilityTerminated(const sptr<IRemoteObject> & token)1093 void AppRunningRecord::AbilityTerminated(const sptr<IRemoteObject> &token)
1094 {
1095     TAG_LOGD(AAFwkTag::APPMGR, "called");
1096     auto moduleRecord = GetModuleRunningRecordByTerminateLists(token);
1097     if (!moduleRecord) {
1098         TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
1099         return;
1100     }
1101 
1102     bool isExtensionDebug = false;
1103     auto abilityRecord = moduleRecord->GetAbilityByTerminateLists(token);
1104     if (abilityRecord != nullptr && abilityRecord->GetAbilityInfo() != nullptr) {
1105         isExtensionDebug = (abilityRecord->GetAbilityInfo()->type == AppExecFwk::AbilityType::EXTENSION) &&
1106                            (isAttachDebug_ || isDebugApp_);
1107     }
1108     TAG_LOGD(AAFwkTag::APPMGR, "Extension debug is [%{public}s]", isExtensionDebug ? "true" : "false");
1109 
1110     moduleRecord->AbilityTerminated(token);
1111 
1112     auto appRecord = shared_from_this();
1113     auto cacheProcMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
1114     bool needCache = false;
1115     if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) {
1116         cacheProcMgr->CheckAndCacheProcess(appRecord);
1117         TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s should not remove module and terminate app",
1118             appRecord->GetBundleName().c_str());
1119         needCache = true;
1120     }
1121     auto state = static_cast<int>(GetSupportProcessCacheState());
1122     auto appInfo = appRecord->GetApplicationInfo();
1123     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "CACHE_SUPPORT_STATE", HiSysEvent::EventType::BEHAVIOR,
1124         EVENT_KEY_VERSION_CODE, appInfo->versionCode, EVENT_KEY_VERSION_NAME, appInfo->versionName,
1125         EVENT_KEY_BUNDLE_NAME, appInfo->bundleName, EVENT_KEY_SUPPORT_STATE, state);
1126     if (moduleRecord->GetAbilities().empty() && (!IsKeepAliveApp()
1127         || AAFwk::UIExtensionUtils::IsUIExtension(GetExtensionType())
1128         || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficient()) && !needCache) {
1129         RemoveModuleRecord(moduleRecord, isExtensionDebug);
1130     }
1131 
1132     auto moduleRecordList = GetAllModuleRecord();
1133     if (moduleRecordList.empty() && (!IsKeepAliveApp()
1134         || AAFwk::UIExtensionUtils::IsUIExtension(GetExtensionType())
1135         || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficient()) && !isExtensionDebug
1136         && !needCache) {
1137         ScheduleTerminate();
1138     }
1139 }
1140 
GetAllModuleRecord() const1141 std::list<std::shared_ptr<ModuleRunningRecord>> AppRunningRecord::GetAllModuleRecord() const
1142 {
1143     std::list<std::shared_ptr<ModuleRunningRecord>> moduleRecordList;
1144     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1145     for (const auto &item : hapModules_) {
1146         for (const auto &list : item.second) {
1147             moduleRecordList.push_back(list);
1148         }
1149     }
1150     return moduleRecordList;
1151 }
1152 
RemoveAppDeathRecipient() const1153 void AppRunningRecord::RemoveAppDeathRecipient() const
1154 {
1155     if (appLifeCycleDeal_ == nullptr) {
1156         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1157         return;
1158     }
1159     if (!appLifeCycleDeal_->GetApplicationClient()) {
1160         TAG_LOGE(AAFwkTag::APPMGR, "null appThread");
1161         return;
1162     }
1163     auto object = appLifeCycleDeal_->GetApplicationClient()->AsObject();
1164     if (object) {
1165         if (!object->RemoveDeathRecipient(appDeathRecipient_)) {
1166             TAG_LOGD(AAFwkTag::APPMGR, "Failed to remove deathRecipient.");
1167         }
1168     }
1169 }
1170 
SetAppMgrServiceInner(const std::weak_ptr<AppMgrServiceInner> & inner)1171 void AppRunningRecord::SetAppMgrServiceInner(const std::weak_ptr<AppMgrServiceInner> &inner)
1172 {
1173     appMgrServiceInner_ = inner;
1174 
1175     auto moduleRecordList = GetAllModuleRecord();
1176     if (moduleRecordList.empty()) {
1177         TAG_LOGW(AAFwkTag::APPMGR, "empty moduleRecordList");
1178         return;
1179     }
1180 
1181     for (const auto &moduleRecord : moduleRecordList) {
1182         moduleRecord->SetAppMgrServiceInner(appMgrServiceInner_);
1183     }
1184 }
1185 
SetAppDeathRecipient(const sptr<AppDeathRecipient> & appDeathRecipient)1186 void AppRunningRecord::SetAppDeathRecipient(const sptr<AppDeathRecipient> &appDeathRecipient)
1187 {
1188     appDeathRecipient_ = appDeathRecipient;
1189 }
1190 
GetPriorityObject()1191 std::shared_ptr<PriorityObject> AppRunningRecord::GetPriorityObject()
1192 {
1193     return priorityObject_;
1194 }
1195 
SendEventForSpecifiedAbility()1196 void AppRunningRecord::SendEventForSpecifiedAbility()
1197 {
1198     auto timeOUt = AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT *
1199         AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
1200     SendEvent(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG, timeOUt / HALF_TIMEOUT);
1201     SendEvent(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG, timeOUt);
1202 }
1203 
SendAppStartupTypeEvent(const std::shared_ptr<AbilityRunningRecord> & ability,const AppStartType startType)1204 void AppRunningRecord::SendAppStartupTypeEvent(const std::shared_ptr<AbilityRunningRecord> &ability,
1205     const AppStartType startType)
1206 {
1207     if (!ability) {
1208         TAG_LOGE(AAFwkTag::APPMGR, "null ability");
1209         return;
1210     }
1211     AAFwk::EventInfo eventInfo;
1212     auto applicationInfo = GetApplicationInfo();
1213     if (!applicationInfo) {
1214         TAG_LOGE(AAFwkTag::APPMGR, "null applicationInfo");
1215     } else {
1216         eventInfo.bundleName = applicationInfo->name;
1217         eventInfo.versionName = applicationInfo->versionName;
1218         eventInfo.versionCode = applicationInfo->versionCode;
1219     }
1220 
1221     auto abilityInfo = ability->GetAbilityInfo();
1222     if (!abilityInfo) {
1223         TAG_LOGE(AAFwkTag::APPMGR, "null abilityInfo");
1224     } else {
1225         eventInfo.abilityName = abilityInfo->name;
1226     }
1227     if (GetPriorityObject() == nullptr) {
1228         TAG_LOGE(AAFwkTag::APPMGR, "null priorityObject");
1229     } else {
1230         eventInfo.pid = GetPid();
1231     }
1232     eventInfo.startType = static_cast<int32_t>(startType);
1233     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_STARTUP_TYPE, HiSysEventType::BEHAVIOR, eventInfo);
1234 }
1235 
SendEvent(uint32_t msg,int64_t timeOut)1236 void AppRunningRecord::SendEvent(uint32_t msg, int64_t timeOut)
1237 {
1238     if (!eventHandler_) {
1239         TAG_LOGE(AAFwkTag::APPMGR, "null eventHandler_");
1240         return;
1241     }
1242 
1243     if (isDebugApp_ || isNativeDebug_ || isAttachDebug_) {
1244         TAG_LOGI(AAFwkTag::APPMGR, "no need to handle time out");
1245         return;
1246     }
1247 
1248     appEventId_++;
1249     auto param = appEventId_;
1250 
1251     TAG_LOGI(AAFwkTag::APPMGR, "eventId %{public}d", static_cast<int>(param));
1252     eventHandler_->SendEvent(AAFwk::EventWrap(msg, param), timeOut, false);
1253     AppEventUtil::GetInstance().AddEvent(shared_from_this(), msg, param);
1254 }
1255 
RemoveEvent(uint32_t msg)1256 void AppRunningRecord::RemoveEvent(uint32_t msg)
1257 {
1258     if (!eventHandler_) {
1259         TAG_LOGE(AAFwkTag::APPMGR, "null eventHandler_");
1260         return;
1261     }
1262     auto eventList = AppEventUtil::GetInstance().RemoveEvent(shared_from_this(), msg);
1263     for (const auto &eventData : eventList) {
1264         eventHandler_->RemoveEvent(msg, eventData.param);
1265     }
1266 }
1267 
PostTask(std::string msg,int64_t timeOut,const Closure & task)1268 void AppRunningRecord::PostTask(std::string msg, int64_t timeOut, const Closure &task)
1269 {
1270     if (!taskHandler_) {
1271         TAG_LOGE(AAFwkTag::APPMGR, "null taskHandler_");
1272         return;
1273     }
1274     taskHandler_->SubmitTask(task, msg, timeOut);
1275 }
1276 
SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)1277 void AppRunningRecord::SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)
1278 {
1279     taskHandler_ = taskHandler;
1280 }
1281 
SetEventHandler(const std::shared_ptr<AMSEventHandler> & handler)1282 void AppRunningRecord::SetEventHandler(const std::shared_ptr<AMSEventHandler> &handler)
1283 {
1284     eventHandler_ = handler;
1285 }
1286 
IsLastAbilityRecord(const sptr<IRemoteObject> & token)1287 bool AppRunningRecord::IsLastAbilityRecord(const sptr<IRemoteObject> &token)
1288 {
1289     auto moduleRecord = GetModuleRunningRecordByToken(token);
1290     if (!moduleRecord) {
1291         TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
1292         return false;
1293     }
1294 
1295     auto moduleRecordList = GetAllModuleRecord();
1296     if (moduleRecordList.size() == 1) {
1297         return moduleRecord->IsLastAbilityRecord(token);
1298     }
1299 
1300     return false;
1301 }
1302 
ExtensionAbilityRecordExists()1303 bool AppRunningRecord::ExtensionAbilityRecordExists()
1304 {
1305     auto moduleRecordList = GetAllModuleRecord();
1306     for (auto moduleRecord : moduleRecordList) {
1307         if (moduleRecord && moduleRecord->ExtensionAbilityRecordExists()) {
1308             return true;
1309         }
1310     }
1311     TAG_LOGD(AAFwkTag::APPMGR, "can not find extension record");
1312     return false;
1313 }
1314 
IsLastPageAbilityRecord(const sptr<IRemoteObject> & token)1315 bool AppRunningRecord::IsLastPageAbilityRecord(const sptr<IRemoteObject> &token)
1316 {
1317     auto moduleRecord = GetModuleRunningRecordByToken(token);
1318     if (!moduleRecord) {
1319         TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
1320         return false;
1321     }
1322 
1323     int32_t pageAbilitySize = 0;
1324     auto moduleRecordList = GetAllModuleRecord();
1325     for (auto moduleRecord : moduleRecordList) {
1326         if (moduleRecord) {
1327             pageAbilitySize += moduleRecord->GetPageAbilitySize();
1328         }
1329         if (pageAbilitySize > 1) {
1330             return false;
1331         }
1332     }
1333 
1334     return pageAbilitySize == 1;
1335 }
1336 
SetTerminating()1337 void AppRunningRecord::SetTerminating()
1338 {
1339     isTerminating = true;
1340     auto prioObject = GetPriorityObject();
1341     if (prioObject) {
1342         AbilityRuntime::FreezeUtil::GetInstance().DeleteAppLifecycleEvent(prioObject->GetPid());
1343     }
1344 }
1345 
IsTerminating()1346 bool AppRunningRecord::IsTerminating()
1347 {
1348     return isTerminating;
1349 }
1350 
IsKeepAliveApp() const1351 bool AppRunningRecord::IsKeepAliveApp() const
1352 {
1353     if (!isMainProcess_ || !isKeepAliveBundle_ || !isKeepAliveRdb_) {
1354         return false;
1355     }
1356     auto userId = GetUid() / BASE_USER_RANGE;
1357     if (userId == 0) {
1358         return isSingleton_;
1359     }
1360     return true;
1361 }
1362 
IsKeepAliveDkv() const1363 bool AppRunningRecord::IsKeepAliveDkv() const
1364 {
1365     return isKeepAliveDkv_;
1366 }
1367 
IsKeepAliveAppService() const1368 bool AppRunningRecord::IsKeepAliveAppService() const
1369 {
1370     return isKeepAliveAppService_;
1371 }
1372 
SetKeepAliveEnableState(bool isKeepAliveEnable)1373 void AppRunningRecord::SetKeepAliveEnableState(bool isKeepAliveEnable)
1374 {
1375     isKeepAliveRdb_ = isKeepAliveEnable;
1376 }
1377 
SetKeepAliveDkv(bool isKeepAliveDkv)1378 void AppRunningRecord::SetKeepAliveDkv(bool isKeepAliveDkv)
1379 {
1380     isKeepAliveDkv_ = isKeepAliveDkv;
1381 }
1382 
SetMainElementRunning(bool isMainElementRunning)1383 void AppRunningRecord::SetMainElementRunning(bool isMainElementRunning)
1384 {
1385     isMainElementRunning_ = isMainElementRunning;
1386 }
1387 
IsMainElementRunning() const1388 bool AppRunningRecord::IsMainElementRunning() const
1389 {
1390     return isMainElementRunning_;
1391 }
1392 
SetKeepAliveAppService(bool isKeepAliveAppService)1393 void AppRunningRecord::SetKeepAliveAppService(bool isKeepAliveAppService)
1394 {
1395     isKeepAliveAppService_ = isKeepAliveAppService;
1396 }
1397 
SetKeepAliveBundle(bool isKeepAliveBundle)1398 void AppRunningRecord::SetKeepAliveBundle(bool isKeepAliveBundle)
1399 {
1400     isKeepAliveBundle_ = isKeepAliveBundle;
1401 }
1402 
IsEmptyKeepAliveApp() const1403 bool AppRunningRecord::IsEmptyKeepAliveApp() const
1404 {
1405     return isEmptyKeepAliveApp_;
1406 }
1407 
SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp)1408 void AppRunningRecord::SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp)
1409 {
1410     isEmptyKeepAliveApp_ = isEmptyKeepAliveApp;
1411 }
1412 
IsMainProcess() const1413 bool AppRunningRecord::IsMainProcess() const
1414 {
1415     return isMainProcess_;
1416 }
1417 
SetMainProcess(bool isMainProcess)1418 void AppRunningRecord::SetMainProcess(bool isMainProcess)
1419 {
1420     isMainProcess_ = isMainProcess;
1421 }
1422 
SetSingleton(bool isSingleton)1423 void AppRunningRecord::SetSingleton(bool isSingleton)
1424 {
1425     isSingleton_ = isSingleton;
1426 }
1427 
SetStageModelState(bool isStageBasedModel)1428 void AppRunningRecord::SetStageModelState(bool isStageBasedModel)
1429 {
1430     isStageBasedModel_ = isStageBasedModel;
1431 }
1432 
GetTheModuleInfoNeedToUpdated(const std::string bundleName,HapModuleInfo & info)1433 bool AppRunningRecord::GetTheModuleInfoNeedToUpdated(const std::string bundleName, HapModuleInfo &info)
1434 {
1435     bool result = false;
1436     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1437     auto moduleInfoVectorIter = hapModules_.find(bundleName);
1438     if (moduleInfoVectorIter == hapModules_.end() || moduleInfoVectorIter->second.empty()) {
1439         return result;
1440     }
1441     std::string moduleName = moduleName_;
1442     auto findCondition = [moduleName](const std::shared_ptr<ModuleRunningRecord> &record) {
1443         if (record) {
1444             return (moduleName.empty() || (moduleName == record->GetModuleName())) &&
1445                 (record->GetModuleRecordState() == ModuleRecordState::INITIALIZED_STATE);
1446         }
1447         return false;
1448     };
1449     auto moduleRecordIter =
1450         std::find_if(moduleInfoVectorIter->second.begin(), moduleInfoVectorIter->second.end(), findCondition);
1451     if (moduleRecordIter != moduleInfoVectorIter->second.end()) {
1452         (*moduleRecordIter)->GetHapModuleInfo(info);
1453         (*moduleRecordIter)->SetModuleRecordState(ModuleRecordState::RUNNING_STATE);
1454         result = true;
1455     }
1456 
1457     return result;
1458 }
1459 
SetRestartResidentProcCount(int count)1460 void AppRunningRecord::SetRestartResidentProcCount(int count)
1461 {
1462     restartResidentProcCount_ = count;
1463 }
1464 
DecRestartResidentProcCount()1465 void AppRunningRecord::DecRestartResidentProcCount()
1466 {
1467     restartResidentProcCount_--;
1468 }
1469 
GetRestartResidentProcCount() const1470 int AppRunningRecord::GetRestartResidentProcCount() const
1471 {
1472     return restartResidentProcCount_;
1473 }
1474 
CanRestartResidentProc()1475 bool AppRunningRecord::CanRestartResidentProc()
1476 {
1477     struct timespec t;
1478     t.tv_sec = 0;
1479     t.tv_nsec = 0;
1480     clock_gettime(CLOCK_MONOTONIC, &t);
1481     int64_t systemTimeMillis = static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS);
1482     if ((restartResidentProcCount_ >= 0) || ((systemTimeMillis - restartTimeMillis_) > RESTART_INTERVAL_TIME)) {
1483         return true;
1484     }
1485     return false;
1486 }
1487 
GetBundleNames(std::vector<std::string> & bundleNames)1488 void AppRunningRecord::GetBundleNames(std::vector<std::string> &bundleNames)
1489 {
1490     std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
1491     for (auto &app : appInfos_) {
1492         bundleNames.emplace_back(app.first);
1493     }
1494 }
1495 
SetUserTestInfo(const std::shared_ptr<UserTestRecord> & record)1496 void AppRunningRecord::SetUserTestInfo(const std::shared_ptr<UserTestRecord> &record)
1497 {
1498     userTestRecord_ = record;
1499 }
1500 
GetUserTestInfo()1501 std::shared_ptr<UserTestRecord> AppRunningRecord::GetUserTestInfo()
1502 {
1503     return userTestRecord_;
1504 }
1505 
SetProcessAndExtensionType(const std::shared_ptr<AbilityInfo> & abilityInfo,uint32_t extensionProcessMode)1506 void AppRunningRecord::SetProcessAndExtensionType(
1507     const std::shared_ptr<AbilityInfo> &abilityInfo, uint32_t extensionProcessMode)
1508 {
1509     if (abilityInfo == nullptr) {
1510         TAG_LOGE(AAFwkTag::APPMGR, "null abilityInfo");
1511         return;
1512     }
1513     extensionType_ = abilityInfo->extensionAbilityType;
1514     preloadModuleName_ = abilityInfo->moduleName;
1515     if (extensionType_ == ExtensionAbilityType::UNSPECIFIED) {
1516         //record Service Ability in FA model as Service Extension
1517         if (abilityInfo->type == AbilityType::SERVICE) {
1518             processType_ = ProcessType::EXTENSION;
1519             extensionType_ = ExtensionAbilityType::SERVICE;
1520             return;
1521         }
1522         //record Data Ability in FA model as Datashare Extension
1523         if (abilityInfo->type == AbilityType::DATA) {
1524             processType_ = ProcessType::EXTENSION;
1525             extensionType_ = ExtensionAbilityType::DATASHARE;
1526             return;
1527         }
1528         processType_ = ProcessType::NORMAL;
1529         return;
1530     }
1531 
1532     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType_) &&
1533          extensionProcessMode == PROCESS_MODE_RUN_WITH_MAIN_PROCESS) {
1534         processType_ = ProcessType::NORMAL;
1535     } else {
1536         processType_ = ProcessType::EXTENSION;
1537     }
1538     return;
1539 }
1540 
SetStartupTaskData(const AAFwk::Want & want)1541 void AppRunningRecord::SetStartupTaskData(const AAFwk::Want &want)
1542 {
1543     std::lock_guard<ffrt::mutex> lock(startupTaskDataLock_);
1544     startupTaskData_ = std::make_shared<StartupTaskData>();
1545     startupTaskData_->uri = want.GetUriString();
1546     startupTaskData_->action = want.GetAction();
1547     const AppExecFwk::WantParams &wantParams = want.GetParams();
1548     if (wantParams.HasParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_NAME)) {
1549         startupTaskData_->insightIntentName = wantParams.GetStringParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_NAME);
1550     }
1551     TAG_LOGD(AAFwkTag::APPMGR, "uri: %{public}s, action: %{public}s, intentName: %{public}s",
1552         startupTaskData_->uri.c_str(), startupTaskData_->action.c_str(),
1553         startupTaskData_->insightIntentName.c_str());
1554 }
1555 
SetSpecifiedAbilityFlagAndWant(int requestId,const AAFwk::Want & want,const std::string & moduleName)1556 void AppRunningRecord::SetSpecifiedAbilityFlagAndWant(
1557     int requestId, const AAFwk::Want &want, const std::string &moduleName)
1558 {
1559     std::lock_guard lock(specifiedMutex_);
1560     if (specifiedAbilityRequest_ != nullptr) {
1561         TAG_LOGW(AAFwkTag::APPMGR, "specifiedRequestId: %{public}d", specifiedAbilityRequest_->requestId);
1562     }
1563     specifiedAbilityRequest_ = std::make_shared<SpecifiedRequest>();
1564     specifiedAbilityRequest_->requestId = requestId;
1565     specifiedAbilityRequest_->want = want;
1566     moduleName_ = moduleName;
1567 }
1568 
GetSpecifiedRequestId() const1569 int32_t AppRunningRecord::GetSpecifiedRequestId() const
1570 {
1571     std::lock_guard lock(specifiedMutex_);
1572     if (specifiedAbilityRequest_ != nullptr) {
1573         return specifiedAbilityRequest_->requestId;
1574     }
1575     return -1;
1576 }
1577 
ResetSpecifiedRequest()1578 void AppRunningRecord::ResetSpecifiedRequest()
1579 {
1580     std::lock_guard lock(specifiedMutex_);
1581     specifiedAbilityRequest_.reset();
1582 }
1583 
SetScheduleNewProcessRequestState(int32_t requestId,const AAFwk::Want & want,const std::string & moduleName)1584 void AppRunningRecord::SetScheduleNewProcessRequestState(int32_t requestId,
1585     const AAFwk::Want &want, const std::string &moduleName)
1586 {
1587     std::lock_guard lock(specifiedMutex_);
1588     if (specifiedProcessRequest_ != nullptr) {
1589         TAG_LOGW(AAFwkTag::APPMGR, "newProcessRequestId: %{public}d", specifiedProcessRequest_->requestId);
1590     }
1591     specifiedProcessRequest_ = std::make_shared<SpecifiedRequest>();
1592     specifiedProcessRequest_->requestId = requestId;
1593     specifiedProcessRequest_->want = want;
1594     moduleName_ = moduleName;
1595 }
1596 
IsNewProcessRequest() const1597 bool AppRunningRecord::IsNewProcessRequest() const
1598 {
1599     std::lock_guard lock(specifiedMutex_);
1600     return specifiedProcessRequest_ != nullptr;
1601 }
1602 
IsStartSpecifiedAbility() const1603 bool AppRunningRecord::IsStartSpecifiedAbility() const
1604 {
1605     std::lock_guard lock(specifiedMutex_);
1606     return specifiedAbilityRequest_ != nullptr;
1607 }
1608 
SchedulePrepareTerminate(const std::string & moduleName)1609 void AppRunningRecord::SchedulePrepareTerminate(const std::string &moduleName)
1610 {
1611     TAG_LOGD(AAFwkTag::APPMGR, "called");
1612     if (appLifeCycleDeal_ == nullptr) {
1613         TAG_LOGW(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1614         return;
1615     }
1616     bool found = false;
1617     {
1618         std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1619         for (const auto &iter : hapModules_) {
1620             for (const auto &moduleRecord : iter.second) {
1621                 if (moduleRecord != nullptr && moduleName == moduleRecord->GetModuleName()) {
1622                     found = true;
1623                     break;
1624                 }
1625             }
1626         }
1627     }
1628     if (!found) {
1629         TAG_LOGE(AAFwkTag::APPMGR, "moduleName not exist");
1630         return;
1631     }
1632     appLifeCycleDeal_->SchedulePrepareTerminate(moduleName);
1633 }
1634 
ScheduleAcceptWant(const std::string & moduleName)1635 void AppRunningRecord::ScheduleAcceptWant(const std::string &moduleName)
1636 {
1637     auto timeOUt = AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT *
1638         AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
1639     SendEvent(AMSEventHandler::START_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG, timeOUt / HALF_TIMEOUT);
1640     SendEvent(AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG, timeOUt);
1641     if (appLifeCycleDeal_ == nullptr) {
1642         TAG_LOGW(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1643         return;
1644     }
1645     appLifeCycleDeal_->ScheduleAcceptWant(GetSpecifiedWant(), moduleName);
1646 }
1647 
ScheduleAcceptWantDone()1648 void AppRunningRecord::ScheduleAcceptWantDone()
1649 {
1650     TAG_LOGI(AAFwkTag::APPMGR, "ScheduleAcceptWantDone, bundle %{public}s", mainBundleName_.c_str());
1651     RemoveEvent(AMSEventHandler::START_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG);
1652     RemoveEvent(AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG);
1653     SetModuleLoaded(moduleName_);
1654 }
1655 
ScheduleNewProcessRequest(const AAFwk::Want & want,const std::string & moduleName)1656 void AppRunningRecord::ScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName)
1657 {
1658     auto timeOUt = AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT *
1659         AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
1660     SendEvent(AMSEventHandler::START_SPECIFIED_PROCESS_HALF_TIMEOUT_MSG, timeOUt / HALF_TIMEOUT);
1661     SendEvent(AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG, timeOUt);
1662     if (appLifeCycleDeal_ == nullptr) {
1663         TAG_LOGW(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1664         return;
1665     }
1666     appLifeCycleDeal_->ScheduleNewProcessRequest(want, moduleName);
1667 }
1668 
ScheduleNewProcessRequestDone()1669 void AppRunningRecord::ScheduleNewProcessRequestDone()
1670 {
1671     TAG_LOGI(AAFwkTag::APPMGR, "bundle %{public}s", mainBundleName_.c_str());
1672     RemoveEvent(AMSEventHandler::START_SPECIFIED_PROCESS_HALF_TIMEOUT_MSG);
1673     RemoveEvent(AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG);
1674     SetModuleLoaded(moduleName_);
1675 }
1676 
ApplicationTerminated()1677 void AppRunningRecord::ApplicationTerminated()
1678 {
1679     TAG_LOGD(AAFwkTag::APPMGR, "Application terminated bundle %{public}s", mainBundleName_.c_str());
1680 
1681     RemoveEvent(AMSEventHandler::TERMINATE_APPLICATION_HALF_TIMEOUT_MSG);
1682     RemoveEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG);
1683 }
1684 
GetSpecifiedWant() const1685 AAFwk::Want AppRunningRecord::GetSpecifiedWant() const
1686 {
1687     std::lock_guard lock(specifiedMutex_);
1688     if (specifiedAbilityRequest_ != nullptr) {
1689         return specifiedAbilityRequest_->want;
1690     }
1691     return AAFwk::Want();
1692 }
1693 
GetNewProcessRequestWant() const1694 AAFwk::Want AppRunningRecord::GetNewProcessRequestWant() const
1695 {
1696     std::lock_guard lock(specifiedMutex_);
1697     if (specifiedProcessRequest_ != nullptr) {
1698         return specifiedProcessRequest_->want;
1699     }
1700     return AAFwk::Want();
1701 }
1702 
GetNewProcessRequestId() const1703 int32_t AppRunningRecord::GetNewProcessRequestId() const
1704 {
1705     std::lock_guard lock(specifiedMutex_);
1706     if (specifiedProcessRequest_ != nullptr) {
1707         return specifiedProcessRequest_->requestId;
1708     }
1709     return -1;
1710 }
1711 
ResetNewProcessRequest()1712 void AppRunningRecord::ResetNewProcessRequest()
1713 {
1714     std::lock_guard lock(specifiedMutex_);
1715     specifiedProcessRequest_.reset();
1716 }
1717 
UpdateConfiguration(const Configuration & config)1718 int32_t AppRunningRecord::UpdateConfiguration(const Configuration &config)
1719 {
1720     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1721     TAG_LOGD(AAFwkTag::APPMGR, "called");
1722     if (!appLifeCycleDeal_) {
1723         TAG_LOGI(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1724         return ERR_INVALID_VALUE;
1725     }
1726     return appLifeCycleDeal_->UpdateConfiguration(config);
1727 }
1728 
AddRenderRecord(const std::shared_ptr<RenderRecord> & record)1729 void AppRunningRecord::AddRenderRecord(const std::shared_ptr<RenderRecord> &record)
1730 {
1731     if (!record) {
1732         TAG_LOGD(AAFwkTag::APPMGR, "AddRenderRecord: record is null");
1733         return;
1734     }
1735     {
1736         std::lock_guard renderPidSetLock(renderPidSetLock_);
1737         renderPidSet_.insert(record->GetPid());
1738     }
1739     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1740     renderRecordMap_.emplace(record->GetUid(), record);
1741 }
1742 
RemoveRenderRecord(const std::shared_ptr<RenderRecord> & record)1743 void AppRunningRecord::RemoveRenderRecord(const std::shared_ptr<RenderRecord> &record)
1744 {
1745     if (!record) {
1746         TAG_LOGD(AAFwkTag::APPMGR, "RemoveRenderRecord: record null");
1747         return;
1748     }
1749     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1750     renderRecordMap_.erase(record->GetUid());
1751 }
1752 
RemoveRenderPid(pid_t renderPid)1753 void AppRunningRecord::RemoveRenderPid(pid_t renderPid)
1754 {
1755     std::lock_guard renderPidSetLock(renderPidSetLock_);
1756     renderPidSet_.erase(renderPid);
1757 }
1758 
GetRenderProcessInfos(std::list<SimpleProcessInfo> & processInfos)1759 void AppRunningRecord::GetRenderProcessInfos(std::list<SimpleProcessInfo> &processInfos)
1760 {
1761     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1762     for (auto &item : renderRecordMap_) {
1763         auto renderRecord = item.second;
1764         if (renderRecord && renderRecord->GetPid() > 0) {
1765             auto processInfo = SimpleProcessInfo(renderRecord->GetPid(), renderRecord->GetProcessName());
1766             processInfos.emplace_back(processInfo);
1767         }
1768     }
1769 }
1770 
ConstainsRenderPid(pid_t renderPid)1771 bool AppRunningRecord::ConstainsRenderPid(pid_t renderPid)
1772 {
1773     std::lock_guard renderPidSetLock(renderPidSetLock_);
1774     return renderPidSet_.find(renderPid) != renderPidSet_.end();
1775 }
1776 
GetRenderRecordByPid(const pid_t pid)1777 std::shared_ptr<RenderRecord> AppRunningRecord::GetRenderRecordByPid(const pid_t pid)
1778 {
1779     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1780     if (renderRecordMap_.empty()) {
1781         return nullptr;
1782     }
1783     for (auto iter : renderRecordMap_) {
1784         auto renderRecord = iter.second;
1785         if (renderRecord && renderRecord->GetPid() == pid) {
1786             return renderRecord;
1787         }
1788     }
1789     return nullptr;
1790 }
1791 
GetRenderRecordMap()1792 std::map<int32_t, std::shared_ptr<RenderRecord>> AppRunningRecord::GetRenderRecordMap()
1793 {
1794     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1795     return renderRecordMap_;
1796 }
1797 
SetStartMsg(const AppSpawnStartMsg & msg)1798 void AppRunningRecord::SetStartMsg(const AppSpawnStartMsg &msg)
1799 {
1800     startMsg_ = msg;
1801 }
1802 
GetStartMsg()1803 AppSpawnStartMsg AppRunningRecord::GetStartMsg()
1804 {
1805     return startMsg_;
1806 }
1807 
IsDebug()1808 bool AppRunningRecord::IsDebug()
1809 {
1810     if (IsDebugApp() || isNativeDebug_ || !perfCmd_.empty() || IsAttachDebug() || IsAssertionPause()) {
1811         TAG_LOGI(AAFwkTag::ABILITYMGR, "debugApp, no need to handle");
1812         return true;
1813     }
1814     return false;
1815 }
1816 
SetDebugApp(bool isDebugApp)1817 void AppRunningRecord::SetDebugApp(bool isDebugApp)
1818 {
1819     TAG_LOGD(AAFwkTag::APPMGR, "value is %{public}d", isDebugApp);
1820     isDebugApp_ = isDebugApp;
1821 }
1822 
IsDebugApp()1823 bool AppRunningRecord::IsDebugApp()
1824 {
1825     return isDebugApp_;
1826 }
1827 
SetNativeDebug(bool isNativeDebug)1828 void AppRunningRecord::SetNativeDebug(bool isNativeDebug)
1829 {
1830     TAG_LOGD(AAFwkTag::APPMGR, "SetNativeDebug, value is %{public}d", isNativeDebug);
1831     isNativeDebug_ = isNativeDebug;
1832 }
1833 
SetPerfCmd(const std::string & perfCmd)1834 void AppRunningRecord::SetPerfCmd(const std::string &perfCmd)
1835 {
1836     perfCmd_ = perfCmd;
1837 }
1838 
SetErrorInfoEnhance(bool errorInfoEnhance)1839 void AppRunningRecord::SetErrorInfoEnhance(bool errorInfoEnhance)
1840 {
1841     isErrorInfoEnhance_ = errorInfoEnhance;
1842 }
1843 
SetMultiThread(bool multiThread)1844 void AppRunningRecord::SetMultiThread(bool multiThread)
1845 {
1846     isMultiThread_ = multiThread;
1847 }
1848 
SetAppIndex(const int32_t appIndex)1849 void AppRunningRecord::SetAppIndex(const int32_t appIndex)
1850 {
1851     appIndex_ = appIndex;
1852 }
1853 
SetInstanceKey(const std::string & instanceKey)1854 void AppRunningRecord::SetInstanceKey(const std::string& instanceKey)
1855 {
1856     instanceKey_ = instanceKey;
1857 }
1858 
GetSplitModeAndFloatingMode(bool & isSplitScreenMode,bool & isFloatingWindowMode)1859 void AppRunningRecord::GetSplitModeAndFloatingMode(bool &isSplitScreenMode, bool &isFloatingWindowMode)
1860 {
1861     auto abilitiesMap = GetAbilities();
1862     isSplitScreenMode = false;
1863     isFloatingWindowMode = false;
1864     for (const auto &item : abilitiesMap) {
1865         const auto &abilityRecord = item.second;
1866         if (abilityRecord == nullptr) {
1867             continue;
1868         }
1869         const auto &abilityWant = abilityRecord->GetWant();
1870         if (abilityWant != nullptr) {
1871             int windowMode = abilityWant->GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1);
1872             if (windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING) {
1873                 isFloatingWindowMode = true;
1874             }
1875             if (windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY ||
1876                 windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) {
1877                 isSplitScreenMode = true;
1878             }
1879         }
1880         if (isFloatingWindowMode && isSplitScreenMode) {
1881             break;
1882         }
1883     }
1884 }
1885 
GetAppIndex() const1886 int32_t AppRunningRecord::GetAppIndex() const
1887 {
1888     return appIndex_;
1889 }
1890 
GetInstanceKey() const1891 std::string AppRunningRecord::GetInstanceKey() const
1892 {
1893     return instanceKey_;
1894 }
1895 
SetSecurityFlag(bool securityFlag)1896 void AppRunningRecord::SetSecurityFlag(bool securityFlag)
1897 {
1898     securityFlag_ = securityFlag;
1899 }
1900 
GetSecurityFlag() const1901 bool AppRunningRecord::GetSecurityFlag() const
1902 {
1903     return securityFlag_;
1904 }
1905 
SetKilling()1906 void AppRunningRecord::SetKilling()
1907 {
1908     isKilling_.store(true);
1909 }
1910 
IsKilling() const1911 bool AppRunningRecord::IsKilling() const
1912 {
1913     return isKilling_.load();
1914 }
1915 
SetPreForeground(bool isPreForeground)1916 void AppRunningRecord::SetPreForeground(bool isPreForeground)
1917 {
1918     isPreForeground_.store(isPreForeground);
1919 }
1920 
IsPreForeground() const1921 bool AppRunningRecord::IsPreForeground() const
1922 {
1923     return isPreForeground_.load();
1924 }
1925 
NeedUpdateConfigurationBackground()1926 bool AppRunningRecord::NeedUpdateConfigurationBackground()
1927 {
1928     bool needUpdate = false;
1929     auto abilitiesMap = GetAbilities();
1930     for (const auto &item : abilitiesMap) {
1931         const auto &abilityRecord = item.second;
1932         if (!abilityRecord || !abilityRecord->GetAbilityInfo()) {
1933             continue;
1934         }
1935         if (abilityRecord->GetAbilityInfo()->type != AppExecFwk::AbilityType::PAGE &&
1936             !(AAFwk::UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo()->extensionAbilityType))) {
1937             needUpdate = true;
1938             break;
1939         }
1940     }
1941     return needUpdate;
1942 }
1943 
RemoveTerminateAbilityTimeoutTask(const sptr<IRemoteObject> & token) const1944 void AppRunningRecord::RemoveTerminateAbilityTimeoutTask(const sptr<IRemoteObject>& token) const
1945 {
1946     auto moduleRecord = GetModuleRunningRecordByToken(token);
1947     if (!moduleRecord) {
1948         TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
1949         return;
1950     }
1951     (void)moduleRecord->RemoveTerminateAbilityTimeoutTask(token);
1952 }
1953 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)1954 int32_t AppRunningRecord::NotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback,
1955     const int32_t recordId)
1956 {
1957     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1958     TAG_LOGD(AAFwkTag::APPMGR, "called");
1959     if (!appLifeCycleDeal_) {
1960         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1961         return ERR_INVALID_VALUE;
1962     }
1963     return appLifeCycleDeal_->NotifyLoadRepairPatch(bundleName, callback, recordId);
1964 }
1965 
NotifyHotReloadPage(const sptr<IQuickFixCallback> & callback,const int32_t recordId)1966 int32_t AppRunningRecord::NotifyHotReloadPage(const sptr<IQuickFixCallback> &callback, const int32_t recordId)
1967 {
1968     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1969     TAG_LOGD(AAFwkTag::APPMGR, "called");
1970     if (!appLifeCycleDeal_) {
1971         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1972         return ERR_INVALID_VALUE;
1973     }
1974     return appLifeCycleDeal_->NotifyHotReloadPage(callback, recordId);
1975 }
1976 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)1977 int32_t AppRunningRecord::NotifyUnLoadRepairPatch(const std::string &bundleName,
1978     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
1979 {
1980     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1981     TAG_LOGD(AAFwkTag::APPMGR, "called");
1982     if (!appLifeCycleDeal_) {
1983         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1984         return ERR_INVALID_VALUE;
1985     }
1986     return appLifeCycleDeal_->NotifyUnLoadRepairPatch(bundleName, callback, recordId);
1987 }
1988 
NotifyAppFault(const FaultData & faultData)1989 int32_t AppRunningRecord::NotifyAppFault(const FaultData &faultData)
1990 {
1991     TAG_LOGD(AAFwkTag::APPMGR, "called");
1992     if (!appLifeCycleDeal_) {
1993         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
1994         return ERR_INVALID_VALUE;
1995     }
1996     return appLifeCycleDeal_->NotifyAppFault(faultData);
1997 }
1998 
IsAbilitiesBackground()1999 bool AppRunningRecord::IsAbilitiesBackground()
2000 {
2001     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
2002     for (const auto &iter : hapModules_) {
2003         for (const auto &moduleRecord : iter.second) {
2004             if (moduleRecord == nullptr) {
2005                 TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
2006                 continue;
2007             }
2008             if (!moduleRecord->IsAbilitiesBackgrounded()) {
2009                 return false;
2010             }
2011         }
2012     }
2013     return true;
2014 }
2015 #ifdef SUPPORT_SCREEN
2016 
ChangeWindowVisibility(const sptr<OHOS::Rosen::WindowVisibilityInfo> & info)2017 void AppRunningRecord::ChangeWindowVisibility(const sptr<OHOS::Rosen::WindowVisibilityInfo> &info)
2018 {
2019     if (info == nullptr) {
2020         TAG_LOGE(AAFwkTag::APPMGR, "null info");
2021         return;
2022     }
2023 
2024     if (GetPriorityObject() == nullptr) {
2025         TAG_LOGE(AAFwkTag::APPMGR, "null priorityObject");
2026         return;
2027     }
2028 
2029     if (info->pid_ != GetPid()) {
2030         return;
2031     }
2032 
2033     std::lock_guard windowIdsLock(windowIdsLock_);
2034     auto iter = windowIds_.find(info->windowId_);
2035     if (iter != windowIds_.end() &&
2036         info->visibilityState_ == OHOS::Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_TOTALLY_OCCUSION) {
2037         windowIds_.erase(iter);
2038         return;
2039     }
2040     if (iter == windowIds_.end() &&
2041         info->visibilityState_ < OHOS::Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_TOTALLY_OCCUSION) {
2042         windowIds_.emplace(info->windowId_);
2043     }
2044 }
2045 
OnWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)2046 void AppRunningRecord::OnWindowVisibilityChanged(
2047     const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
2048 {
2049     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2050     TAG_LOGD(AAFwkTag::APPMGR, "called");
2051     AddAppLifecycleEvent("AppRunningRecord::OnWindowVisibilityChanged");
2052     if (windowVisibilityInfos.empty()) {
2053         TAG_LOGW(AAFwkTag::APPMGR, "empty info");
2054         return;
2055     }
2056 
2057     for (const auto &info : windowVisibilityInfos) {
2058         if (info == nullptr || info->pid_ != GetPid()) {
2059             TAG_LOGE(AAFwkTag::APPMGR, "null info or info pid is not matched");
2060             continue;
2061         }
2062         std::lock_guard windowIdsLock(windowIdsLock_);
2063         auto iter = windowIds_.find(info->windowId_);
2064         if (iter != windowIds_.end() &&
2065             info->visibilityState_ == OHOS::Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_TOTALLY_OCCUSION) {
2066             windowIds_.erase(iter);
2067             continue;
2068         }
2069         if (iter == windowIds_.end() &&
2070             info->visibilityState_ < OHOS::Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_TOTALLY_OCCUSION) {
2071             windowIds_.emplace(info->windowId_);
2072         }
2073     }
2074     OnWindowVisibilityChangedWithPendingState();
2075 }
2076 
OnWindowVisibilityChangedWithPendingState()2077 void AppRunningRecord::OnWindowVisibilityChangedWithPendingState()
2078 {
2079     TAG_LOGI(AAFwkTag::APPMGR, "wnd call, %{public}s_%{public}d, isEmpty_%{public}d, c_%{public}d -> p_%{public}d",
2080         GetBundleName().c_str(), GetPid(), IsWindowIdsEmpty(), curState_, pendingState_);
2081     if (pendingState_ == ApplicationPendingState::READY) {
2082         if (!IsWindowIdsEmpty()) {
2083             if (curState_ != ApplicationState::APP_STATE_FOREGROUND) {
2084                 SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING);
2085                 ScheduleForegroundRunning();
2086             }
2087             if (watchdogVisibilityState_ != WatchdogVisibilityState::WATCHDOG_STATE_VISIBILITY) {
2088                 watchdogVisibilityState_ = WatchdogVisibilityState::WATCHDOG_STATE_VISIBILITY;
2089                 SetWatchdogBackgroundStatusRunning(false);
2090             }
2091         } else {
2092             if (IsAbilitiesBackground() && curState_ == ApplicationState::APP_STATE_FOREGROUND) {
2093                 SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING);
2094                 ScheduleBackgroundRunning();
2095             }
2096             if (watchdogVisibilityState_ != WatchdogVisibilityState::WATCHDOG_STATE_UNVISIBILITY) {
2097                 watchdogVisibilityState_ = WatchdogVisibilityState::WATCHDOG_STATE_UNVISIBILITY;
2098                 SetWatchdogBackgroundStatusRunning(true);
2099             }
2100         }
2101     } else {
2102         if (!IsWindowIdsEmpty()) {
2103             SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING);
2104         }
2105         if (IsWindowIdsEmpty() && IsAbilitiesBackground() && foregroundingAbilityTokens_.empty()) {
2106             SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING);
2107         }
2108     }
2109 }
2110 #endif //SUPPORT_SCREEN
2111 
IsWindowIdsEmpty()2112 bool AppRunningRecord::IsWindowIdsEmpty()
2113 {
2114     std::lock_guard windowIdsLock(windowIdsLock_);
2115     return windowIds_.empty();
2116 }
2117 
IsContinuousTask()2118 bool AppRunningRecord::IsContinuousTask()
2119 {
2120     return isContinuousTask_;
2121 }
2122 
SetContinuousTaskAppState(bool isContinuousTask)2123 void AppRunningRecord::SetContinuousTaskAppState(bool isContinuousTask)
2124 {
2125     isContinuousTask_ = isContinuousTask;
2126 }
2127 
GetFocusFlag() const2128 bool AppRunningRecord::GetFocusFlag() const
2129 {
2130     return isFocused_;
2131 }
2132 
GetAppStartTime() const2133 int64_t AppRunningRecord::GetAppStartTime() const
2134 {
2135     return startTimeMillis_;
2136 }
2137 
SetRequestProcCode(int32_t requestProcCode)2138 void AppRunningRecord::SetRequestProcCode(int32_t requestProcCode)
2139 {
2140     requestProcCode_ = requestProcCode;
2141 }
2142 
GetRequestProcCode() const2143 int32_t AppRunningRecord::GetRequestProcCode() const
2144 {
2145     return requestProcCode_;
2146 }
2147 
SetProcessChangeReason(ProcessChangeReason reason)2148 void AppRunningRecord::SetProcessChangeReason(ProcessChangeReason reason)
2149 {
2150     processChangeReason_ = reason;
2151 }
2152 
GetProcessChangeReason() const2153 ProcessChangeReason AppRunningRecord::GetProcessChangeReason() const
2154 {
2155     return processChangeReason_;
2156 }
2157 
GetExtensionType() const2158 ExtensionAbilityType AppRunningRecord::GetExtensionType() const
2159 {
2160     return extensionType_;
2161 }
2162 
GetProcessType() const2163 ProcessType AppRunningRecord::GetProcessType() const
2164 {
2165     return processType_;
2166 }
2167 
GetChildAppRecordMap() const2168 std::map<pid_t, std::weak_ptr<AppRunningRecord>> AppRunningRecord::GetChildAppRecordMap() const
2169 {
2170     return childAppRecordMap_;
2171 }
2172 
AddChildAppRecord(pid_t pid,std::shared_ptr<AppRunningRecord> appRecord)2173 void AppRunningRecord::AddChildAppRecord(pid_t pid, std::shared_ptr<AppRunningRecord> appRecord)
2174 {
2175     childAppRecordMap_[pid] = appRecord;
2176 }
2177 
RemoveChildAppRecord(pid_t pid)2178 void AppRunningRecord::RemoveChildAppRecord(pid_t pid)
2179 {
2180     childAppRecordMap_.erase(pid);
2181 }
2182 
ClearChildAppRecordMap()2183 void AppRunningRecord::ClearChildAppRecordMap()
2184 {
2185     childAppRecordMap_.clear();
2186 }
2187 
SetParentAppRecord(std::shared_ptr<AppRunningRecord> appRecord)2188 void AppRunningRecord::SetParentAppRecord(std::shared_ptr<AppRunningRecord> appRecord)
2189 {
2190     parentAppRecord_ = appRecord;
2191 }
2192 
GetParentAppRecord()2193 std::shared_ptr<AppRunningRecord> AppRunningRecord::GetParentAppRecord()
2194 {
2195     return parentAppRecord_.lock();
2196 }
2197 
ChangeAppGcState(int32_t state,uint64_t tid)2198 int32_t AppRunningRecord::ChangeAppGcState(int32_t state, uint64_t tid)
2199 {
2200     TAG_LOGD(AAFwkTag::APPMGR, "called");
2201     if (appLifeCycleDeal_ == nullptr) {
2202         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
2203         return ERR_INVALID_VALUE;
2204     }
2205     return appLifeCycleDeal_->ChangeAppGcState(state, tid);
2206 }
2207 
SetAttachDebug(bool isAttachDebug,bool isDebugFromLocal)2208 void AppRunningRecord::SetAttachDebug(bool isAttachDebug, bool isDebugFromLocal)
2209 {
2210     TAG_LOGD(AAFwkTag::APPMGR, "called");
2211     isAttachDebug_ = isAttachDebug;
2212     isDebugFromLocal_ = isDebugFromLocal;
2213 
2214     if (appLifeCycleDeal_ == nullptr) {
2215         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
2216         return;
2217     }
2218     isAttachDebug_ ? appLifeCycleDeal_->AttachAppDebug(isDebugFromLocal_) : appLifeCycleDeal_->DetachAppDebug();
2219 }
2220 
IsAttachDebug() const2221 bool AppRunningRecord::IsAttachDebug() const
2222 {
2223     return isAttachDebug_;
2224 }
2225 
SetApplicationPendingState(ApplicationPendingState pendingState)2226 void AppRunningRecord::SetApplicationPendingState(ApplicationPendingState pendingState)
2227 {
2228     pendingState_ = pendingState;
2229 }
2230 
GetApplicationPendingState() const2231 ApplicationPendingState AppRunningRecord::GetApplicationPendingState() const
2232 {
2233     return pendingState_;
2234 }
2235 
SetApplicationScheduleState(ApplicationScheduleState scheduleState)2236 void AppRunningRecord::SetApplicationScheduleState(ApplicationScheduleState scheduleState)
2237 {
2238     scheduleState_ = scheduleState;
2239 }
2240 
GetApplicationScheduleState() const2241 ApplicationScheduleState AppRunningRecord::GetApplicationScheduleState() const
2242 {
2243     return scheduleState_;
2244 }
2245 
2246 #ifdef SUPPORT_CHILD_PROCESS
AddChildProcessRecord(pid_t pid,std::shared_ptr<ChildProcessRecord> record)2247 void AppRunningRecord::AddChildProcessRecord(pid_t pid, std::shared_ptr<ChildProcessRecord> record)
2248 {
2249     if (!record) {
2250         TAG_LOGE(AAFwkTag::APPMGR, "null record");
2251         return;
2252     }
2253     if (pid <= 0) {
2254         TAG_LOGE(AAFwkTag::APPMGR, "pid <= 0");
2255         return;
2256     }
2257     std::lock_guard lock(childProcessRecordMapLock_);
2258     childProcessRecordMap_.emplace(pid, record);
2259 }
2260 
RemoveChildProcessRecord(std::shared_ptr<ChildProcessRecord> record)2261 void AppRunningRecord::RemoveChildProcessRecord(std::shared_ptr<ChildProcessRecord> record)
2262 {
2263     if (!record) {
2264         TAG_LOGE(AAFwkTag::APPMGR, "null record");
2265         return;
2266     }
2267     TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d", record->GetPid());
2268     auto pid = record->GetPid();
2269     if (pid <= 0) {
2270         TAG_LOGE(AAFwkTag::APPMGR, "pid <= 0");
2271         return;
2272     }
2273     std::lock_guard lock(childProcessRecordMapLock_);
2274     childProcessRecordMap_.erase(pid);
2275 }
2276 
GetChildProcessRecordByPid(pid_t pid)2277 std::shared_ptr<ChildProcessRecord> AppRunningRecord::GetChildProcessRecordByPid(pid_t pid)
2278 {
2279     std::lock_guard lock(childProcessRecordMapLock_);
2280     auto iter = childProcessRecordMap_.find(pid);
2281     if (iter == childProcessRecordMap_.end()) {
2282         return nullptr;
2283     }
2284     return iter->second;
2285 }
2286 
GetChildProcessRecordMap()2287 std::map<int32_t, std::shared_ptr<ChildProcessRecord>> AppRunningRecord::GetChildProcessRecordMap()
2288 {
2289     std::lock_guard lock(childProcessRecordMapLock_);
2290     return childProcessRecordMap_;
2291 }
2292 
GetChildProcessCount()2293 int32_t AppRunningRecord::GetChildProcessCount()
2294 {
2295     std::lock_guard lock(childProcessRecordMapLock_);
2296     return childProcessRecordMap_.size();
2297 }
2298 
GetChildProcessInfos(std::list<SimpleProcessInfo> & processInfos)2299 void AppRunningRecord::GetChildProcessInfos(std::list<SimpleProcessInfo> &processInfos)
2300 {
2301     std::lock_guard lock(childProcessRecordMapLock_);
2302     for (auto &iter : childProcessRecordMap_) {
2303         auto childRecord = iter.second;
2304         if (childRecord && childRecord->GetPid() > 0) {
2305             auto processInfo = SimpleProcessInfo(childRecord->GetPid(), childRecord->GetProcessName());
2306             processInfos.emplace_back(processInfo);
2307         }
2308     }
2309 }
2310 #endif //SUPPORT_CHILD_PROCESS
2311 
SetJITEnabled(const bool jitEnabled)2312 void AppRunningRecord::SetJITEnabled(const bool jitEnabled)
2313 {
2314     jitEnabled_ = jitEnabled;
2315 }
2316 
IsJITEnabled() const2317 bool AppRunningRecord::IsJITEnabled() const
2318 {
2319     return jitEnabled_;
2320 }
2321 
SetPreloadMode(PreloadMode mode)2322 void AppRunningRecord::SetPreloadMode(PreloadMode mode)
2323 {
2324     preloadMode_ = mode;
2325 }
2326 
GetPreloadMode()2327 PreloadMode AppRunningRecord::GetPreloadMode()
2328 {
2329     return preloadMode_;
2330 }
2331 
SetPreloadModuleName(const std::string & preloadModuleName)2332 void AppRunningRecord::SetPreloadModuleName(const std::string& preloadModuleName)
2333 {
2334     preloadModuleName_ = preloadModuleName;
2335 }
2336 
GetPreloadModuleName() const2337 std::string AppRunningRecord::GetPreloadModuleName() const
2338 {
2339     return preloadModuleName_;
2340 }
2341 
SetPreloadState(PreloadState state)2342 void AppRunningRecord::SetPreloadState(PreloadState state)
2343 {
2344     preloadState_ = state;
2345 }
2346 
SetPreloadPhase(PreloadPhase phase)2347 void AppRunningRecord::SetPreloadPhase(PreloadPhase phase)
2348 {
2349     preloadPhase_ = phase;
2350 }
2351 
GetPreloadPhase()2352 PreloadPhase AppRunningRecord::GetPreloadPhase()
2353 {
2354     return preloadPhase_;
2355 }
2356 
IsPreloading() const2357 bool AppRunningRecord::IsPreloading() const
2358 {
2359     return preloadState_ == PreloadState::PRELOADING;
2360 }
2361 
IsPreloaded() const2362 bool AppRunningRecord::IsPreloaded() const
2363 {
2364     return preloadState_ == PreloadState::PRELOADED;
2365 }
2366 
GetAssignTokenId() const2367 int32_t AppRunningRecord::GetAssignTokenId() const
2368 {
2369     return assignTokenId_;
2370 }
2371 
SetAssignTokenId(int32_t assignTokenId)2372 void AppRunningRecord::SetAssignTokenId(int32_t assignTokenId)
2373 {
2374     assignTokenId_ = assignTokenId;
2375 }
2376 
SetRestartAppFlag(bool isRestartApp)2377 void AppRunningRecord::SetRestartAppFlag(bool isRestartApp)
2378 {
2379     isRestartApp_ = isRestartApp;
2380 }
2381 
GetRestartAppFlag() const2382 bool AppRunningRecord::GetRestartAppFlag() const
2383 {
2384     return isRestartApp_;
2385 }
2386 
SetAssertionPauseFlag(bool flag)2387 void AppRunningRecord::SetAssertionPauseFlag(bool flag)
2388 {
2389     isAssertPause_ = flag;
2390 }
2391 
IsAssertionPause() const2392 bool AppRunningRecord::IsAssertionPause() const
2393 {
2394     return isAssertPause_;
2395 }
2396 
IsDebugging() const2397 bool AppRunningRecord::IsDebugging() const
2398 {
2399     return isDebugApp_ || isAssertPause_;
2400 }
2401 
SetNativeStart(bool isNativeStart)2402 void AppRunningRecord::SetNativeStart(bool isNativeStart)
2403 {
2404     isNativeStart_ = isNativeStart;
2405 }
2406 
isNativeStart() const2407 bool AppRunningRecord::isNativeStart() const
2408 {
2409     return isNativeStart_;
2410 }
2411 
SetExitReason(int32_t reason)2412 void AppRunningRecord::SetExitReason(int32_t reason)
2413 {
2414     exitReason_ = reason;
2415 }
2416 
GetExitReason() const2417 int32_t AppRunningRecord::GetExitReason() const
2418 {
2419     return exitReason_;
2420 }
2421 
SetExitMsg(const std::string & exitMsg)2422 void AppRunningRecord::SetExitMsg(const std::string &exitMsg)
2423 {
2424     exitMsg_ = exitMsg;
2425 }
2426 
GetExitMsg() const2427 std::string AppRunningRecord::GetExitMsg() const
2428 {
2429     return exitMsg_;
2430 }
2431 
DumpIpcStart(std::string & result)2432 int AppRunningRecord::DumpIpcStart(std::string& result)
2433 {
2434     TAG_LOGD(AAFwkTag::APPMGR, "called");
2435     if (appLifeCycleDeal_ == nullptr) {
2436         result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
2437             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2438             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2439         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
2440         return DumpErrorCode::ERR_INTERNAL_ERROR;
2441     }
2442     return appLifeCycleDeal_->DumpIpcStart(result);
2443 }
2444 
DumpIpcStop(std::string & result)2445 int AppRunningRecord::DumpIpcStop(std::string& result)
2446 {
2447     TAG_LOGD(AAFwkTag::APPMGR, "called");
2448     if (appLifeCycleDeal_ == nullptr) {
2449         result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
2450             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2451             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2452         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
2453         return DumpErrorCode::ERR_INTERNAL_ERROR;
2454     }
2455     return appLifeCycleDeal_->DumpIpcStop(result);
2456 }
2457 
DumpIpcStat(std::string & result)2458 int AppRunningRecord::DumpIpcStat(std::string& result)
2459 {
2460     TAG_LOGD(AAFwkTag::APPMGR, "called");
2461     if (appLifeCycleDeal_ == nullptr) {
2462         result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
2463             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2464             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2465         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
2466         return DumpErrorCode::ERR_INTERNAL_ERROR;
2467     }
2468     return appLifeCycleDeal_->DumpIpcStat(result);
2469 }
2470 
DumpFfrt(std::string & result)2471 int AppRunningRecord::DumpFfrt(std::string& result)
2472 {
2473     TAG_LOGD(AAFwkTag::APPMGR, "called");
2474     if (appLifeCycleDeal_ == nullptr) {
2475         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2476             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2477         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
2478         return DumpErrorCode::ERR_INTERNAL_ERROR;
2479     }
2480     return appLifeCycleDeal_->DumpFfrt(result);
2481 }
2482 
SetWatchdogBackgroundStatusRunning(bool status)2483 void AppRunningRecord::SetWatchdogBackgroundStatusRunning(bool status)
2484 {
2485     if (appLifeCycleDeal_) {
2486         appLifeCycleDeal_->SetWatchdogBackgroundStatusRunning(status);
2487     }
2488 }
2489 
SetSupportedProcessCache(bool isSupport)2490 bool AppRunningRecord::SetSupportedProcessCache(bool isSupport)
2491 {
2492     TAG_LOGD(AAFwkTag::APPMGR, "call");
2493     procCacheSupportState_ = isSupport ? SupportProcessCacheState::SUPPORT : SupportProcessCacheState::NOT_SUPPORT;
2494     return true;
2495 }
2496 
SetEnableProcessCache(bool enable)2497 bool AppRunningRecord::SetEnableProcessCache(bool enable)
2498 {
2499     TAG_LOGD(AAFwkTag::APPMGR, "call");
2500     enableProcessCache_ = enable;
2501     return true;
2502 }
2503 
GetEnableProcessCache()2504 bool AppRunningRecord::GetEnableProcessCache()
2505 {
2506     return enableProcessCache_;
2507 }
2508 
GetSupportProcessCacheState()2509 SupportProcessCacheState AppRunningRecord::GetSupportProcessCacheState()
2510 {
2511     return procCacheSupportState_;
2512 }
2513 
ScheduleCacheProcess()2514 void AppRunningRecord::ScheduleCacheProcess()
2515 {
2516     if (appLifeCycleDeal_ == nullptr) {
2517         TAG_LOGE(AAFwkTag::APPMGR, "null appLifeCycleDeal_");
2518         return;
2519     }
2520     appLifeCycleDeal_->ScheduleCacheProcess();
2521 }
2522 
CancelTask(std::string msg)2523 bool AppRunningRecord::CancelTask(std::string msg)
2524 {
2525     if (!taskHandler_) {
2526         TAG_LOGE(AAFwkTag::APPMGR, "null taskHandler_");
2527         return false;
2528     }
2529     return taskHandler_->CancelTask(msg);
2530 }
2531 
SetBrowserHost(sptr<IRemoteObject> browser)2532 void AppRunningRecord::SetBrowserHost(sptr<IRemoteObject> browser)
2533 {
2534     browserHost_ = browser;
2535 }
2536 
GetBrowserHost()2537 sptr<IRemoteObject> AppRunningRecord::GetBrowserHost()
2538 {
2539     return browserHost_;
2540 }
2541 
SetHasGPU(bool gpu)2542 void AppRunningRecord::SetHasGPU(bool gpu)
2543 {
2544     if (gpu) {
2545         hasGPU_ = gpu;
2546     }
2547 }
2548 
HasGPU()2549 bool AppRunningRecord::HasGPU()
2550 {
2551     return hasGPU_;
2552 }
2553 
SetGPUPid(pid_t gpuPid)2554 void AppRunningRecord::SetGPUPid(pid_t gpuPid)
2555 {
2556     gpuPid_ = gpuPid;
2557 }
2558 
GetGPUPid()2559 pid_t AppRunningRecord::GetGPUPid()
2560 {
2561     return gpuPid_;
2562 }
2563 
GetPid()2564 pid_t AppRunningRecord::GetPid()
2565 {
2566     auto prioObj = GetPriorityObject();
2567     if (prioObj) {
2568         return prioObj->GetPid();
2569     }
2570     return 0;
2571 }
2572 
SetAttachedToStatusBar(bool isAttached)2573 void AppRunningRecord::SetAttachedToStatusBar(bool isAttached)
2574 {
2575     isAttachedToStatusBar = isAttached;
2576 }
2577 
IsAttachedToStatusBar()2578 bool AppRunningRecord::IsAttachedToStatusBar()
2579 {
2580     return isAttachedToStatusBar;
2581 }
2582 
SetProcessCacheBlocked(bool isBlocked)2583 void AppRunningRecord::SetProcessCacheBlocked(bool isBlocked)
2584 {
2585     processCacheBlocked = isBlocked;
2586 }
2587 
GetProcessCacheBlocked()2588 bool AppRunningRecord::GetProcessCacheBlocked()
2589 {
2590     return processCacheBlocked;
2591 }
2592 
IsAllAbilityReadyToCleanedByUserRequest()2593 bool AppRunningRecord::IsAllAbilityReadyToCleanedByUserRequest()
2594 {
2595     std::lock_guard<ffrt::mutex> lock(hapModulesLock_);
2596     for (const auto &iter : hapModules_) {
2597         for (const auto &moduleRecord : iter.second) {
2598             if (moduleRecord == nullptr) {
2599                 TAG_LOGE(AAFwkTag::APPMGR, "null moduleRecord");
2600                 continue;
2601             }
2602             if (!moduleRecord->IsAllAbilityReadyToCleanedByUserRequest()) {
2603                 return false;
2604             }
2605         }
2606     }
2607     return true;
2608 }
2609 
SetUserRequestCleaning()2610 void AppRunningRecord::SetUserRequestCleaning()
2611 {
2612     isUserRequestCleaning_ = true;
2613 }
2614 
IsUserRequestCleaning() const2615 bool AppRunningRecord::IsUserRequestCleaning() const
2616 {
2617     return isUserRequestCleaning_;
2618 }
2619 
IsProcessAttached() const2620 bool AppRunningRecord::IsProcessAttached() const
2621 {
2622     if (appLifeCycleDeal_ == nullptr) {
2623         return false;
2624     }
2625     return appLifeCycleDeal_->GetApplicationClient() != nullptr;
2626 }
2627 
SetUIAbilityLaunched(bool hasLaunched)2628 void AppRunningRecord::SetUIAbilityLaunched(bool hasLaunched)
2629 {
2630     hasUIAbilityLaunched_ = hasLaunched;
2631 }
2632 
HasUIAbilityLaunched()2633 bool AppRunningRecord::HasUIAbilityLaunched()
2634 {
2635     return hasUIAbilityLaunched_;
2636 }
2637 
SetProcessCaching(bool isCaching)2638 void AppRunningRecord::SetProcessCaching(bool isCaching)
2639 {
2640     isCaching_ = isCaching;
2641 }
2642 
IsCaching()2643 bool AppRunningRecord::IsCaching()
2644 {
2645     return isCaching_;
2646 }
2647 
AddAppLifecycleEvent(const std::string & msg)2648 void AppRunningRecord::AddAppLifecycleEvent(const std::string &msg)
2649 {
2650     pid_t pid = GetPid();
2651     if (pid != 0) {
2652         AbilityRuntime::FreezeUtil::GetInstance().AddAppLifecycleEvent(pid, msg);
2653     }
2654 }
2655 
SetNeedPreloadModule(bool isNeedPreloadModule)2656 void AppRunningRecord::SetNeedPreloadModule(bool isNeedPreloadModule)
2657 {
2658     isNeedPreloadModule_ = isNeedPreloadModule;
2659 }
2660 
GetNeedPreloadModule()2661 bool AppRunningRecord::GetNeedPreloadModule()
2662 {
2663     return isNeedPreloadModule_;
2664 }
2665 
SetNWebPreload(const bool isAllowedNWebPreload)2666 void AppRunningRecord::SetNWebPreload(const bool isAllowedNWebPreload)
2667 {
2668     isAllowedNWebPreload_ = isAllowedNWebPreload;
2669 }
2670 
IsNWebPreload() const2671 bool AppRunningRecord::IsNWebPreload() const
2672 {
2673     return isAllowedNWebPreload_;
2674 }
2675 
SetIsUnSetPermission(bool isUnSetPermission)2676 void AppRunningRecord::SetIsUnSetPermission(bool isUnSetPermission)
2677 {
2678     isUnSetPermission_ = isUnSetPermission;
2679 }
2680 
IsUnSetPermission()2681 bool AppRunningRecord::IsUnSetPermission()
2682 {
2683     return isUnSetPermission_;
2684 }
2685 
GetNeedLimitPrio()2686 bool AppRunningRecord::GetNeedLimitPrio()
2687 {
2688     return isNeedLimitPrio_;
2689 }
2690 
SetNeedLimitPrio(bool isNeedLimitPrio)2691 void AppRunningRecord::SetNeedLimitPrio(bool isNeedLimitPrio)
2692 {
2693     isNeedLimitPrio_ = isNeedLimitPrio;
2694 }
2695 
UnSetPolicy()2696 void AppRunningRecord::UnSetPolicy()
2697 {
2698     TAG_LOGD(AAFwkTag::APPMGR, "UnSetPolicy call");
2699     auto appInfo = GetApplicationInfo();
2700     if (appInfo == nullptr) {
2701         TAG_LOGE(AAFwkTag::APPMGR, "appInfo  null");
2702         return;
2703     }
2704     if (IsUnSetPermission()) {
2705         TAG_LOGI(AAFwkTag::APPMGR, "app is unset permission");
2706         return;
2707     }
2708     SetIsUnSetPermission(true);
2709 #ifdef SUPPORT_UPMS
2710     AAFwk::UriPermissionManagerClient::GetInstance().ClearPermissionTokenByMap(appInfo->accessTokenId);
2711 #endif // SUPPORT_UPMS
2712 }
2713 
GetAddStageTimeout() const2714 int32_t AppRunningRecord::GetAddStageTimeout() const
2715 {
2716     if (IsEmptyKeepAliveApp()) {
2717         return AMSEventHandler::ADD_ABILITY_STAGE_EMPTY_RESIDENT_TIMEOUT;
2718     }
2719     return AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT;
2720 }
2721 
SetDebugFromLocal(bool isDebugFromLocal)2722 void AppRunningRecord::SetDebugFromLocal(bool isDebugFromLocal)
2723 {
2724     isDebugFromLocal_ = isDebugFromLocal;
2725 }
2726 
IsSupportMultiProcessDeviceFeature() const2727 std::optional<bool> AppRunningRecord::IsSupportMultiProcessDeviceFeature() const
2728 {
2729     std::lock_guard<ffrt::mutex> supportLock(supportMultiProcessDeviceFeatureLock_);
2730     return supportMultiProcessDeviceFeature_;
2731 }
2732 
SetSupportMultiProcessDeviceFeature(bool support)2733 void AppRunningRecord::SetSupportMultiProcessDeviceFeature(bool support)
2734 {
2735     std::lock_guard<ffrt::mutex> supportLock(supportMultiProcessDeviceFeatureLock_);
2736     supportMultiProcessDeviceFeature_ = support;
2737 }
2738 }  // namespace AppExecFwk
2739 }  // namespace OHOS
2740