• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ability_window_configuration.h"
17 #include "app_running_record.h"
18 #include "app_mgr_service_inner.h"
19 #include "event_report.h"
20 #include "exit_resident_process_manager.h"
21 #include "freeze_util.h"
22 #include "hitrace_meter.h"
23 #include "hilog_tag_wrapper.h"
24 #include "ui_extension_utils.h"
25 #include "app_mgr_service_const.h"
26 #include "app_mgr_service_dump_error_code.h"
27 #include "window_visibility_info.h"
28 #include "cache_process_manager.h"
29 
30 namespace OHOS {
31 namespace AppExecFwk {
32 using AbilityRuntime::FreezeUtil;
33 namespace {
34 constexpr int64_t NANOSECONDS = 1000000000;  // NANOSECONDS mean 10^9 nano second
35 constexpr int64_t MICROSECONDS = 1000000;    // MICROSECONDS mean 10^6 millias second
36 constexpr int32_t MAX_RESTART_COUNT = 3;
37 constexpr int32_t RESTART_INTERVAL_TIME = 120000;
38 constexpr const char* LAUNCHER_NAME = "com.ohos.sceneboard";
39 }
40 
41 int64_t AppRunningRecord::appEventId_ = 0;
42 
RenderRecord(pid_t hostPid,const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,int32_t crashFd,const std::shared_ptr<AppRunningRecord> & host)43 RenderRecord::RenderRecord(pid_t hostPid, const std::string &renderParam,
44                            int32_t ipcFd, int32_t sharedFd, int32_t crashFd,
45                            const std::shared_ptr<AppRunningRecord> &host)
46     : hostPid_(hostPid), renderParam_(renderParam), ipcFd_(ipcFd),
47       sharedFd_(sharedFd), crashFd_(crashFd), host_(host) {}
48 
~RenderRecord()49 RenderRecord::~RenderRecord()
50 {
51     close(sharedFd_);
52     close(ipcFd_);
53     close(crashFd_);
54 }
55 
CreateRenderRecord(pid_t hostPid,const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,int32_t crashFd,const std::shared_ptr<AppRunningRecord> & host)56 std::shared_ptr<RenderRecord> RenderRecord::CreateRenderRecord(
57     pid_t hostPid, const std::string &renderParam, int32_t ipcFd,
58     int32_t sharedFd, int32_t crashFd,
59     const std::shared_ptr<AppRunningRecord> &host)
60 {
61     if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0 ||
62         crashFd <= 0 || !host) {
63         return nullptr;
64     }
65 
66     auto renderRecord = std::make_shared<RenderRecord>(
67         hostPid, renderParam, ipcFd, sharedFd, crashFd, host);
68     renderRecord->SetHostUid(host->GetUid());
69     renderRecord->SetHostBundleName(host->GetBundleName());
70     renderRecord->SetProcessName(host->GetProcessName());
71     return renderRecord;
72 }
73 
SetPid(pid_t pid)74 void RenderRecord::SetPid(pid_t pid)
75 {
76     pid_ = pid;
77 }
78 
GetPid() const79 pid_t RenderRecord::GetPid() const
80 {
81     return pid_;
82 }
83 
GetHostPid() const84 pid_t RenderRecord::GetHostPid() const
85 {
86     return hostPid_;
87 }
88 
SetUid(int32_t uid)89 void RenderRecord::SetUid(int32_t uid)
90 {
91     uid_ = uid;
92 }
93 
GetUid() const94 int32_t RenderRecord::GetUid() const
95 {
96     return uid_;
97 }
98 
SetHostUid(const int32_t hostUid)99 void RenderRecord::SetHostUid(const int32_t hostUid)
100 {
101     hostUid_ = hostUid;
102 }
103 
GetHostUid() const104 int32_t RenderRecord::GetHostUid() const
105 {
106     return hostUid_;
107 }
108 
SetHostBundleName(const std::string & hostBundleName)109 void RenderRecord::SetHostBundleName(const std::string &hostBundleName)
110 {
111     hostBundleName_ = hostBundleName;
112 }
113 
GetHostBundleName() const114 std::string RenderRecord::GetHostBundleName() const
115 {
116     return hostBundleName_;
117 }
118 
SetProcessName(const std::string & hostProcessName)119 void RenderRecord::SetProcessName(const std::string &hostProcessName)
120 {
121     processName_ = hostProcessName;
122 }
123 
GetProcessName() const124 std::string RenderRecord::GetProcessName() const
125 {
126     return processName_;
127 }
128 
GetRenderParam() const129 std::string RenderRecord::GetRenderParam() const
130 {
131     return renderParam_;
132 }
133 
GetIpcFd() const134 int32_t RenderRecord::GetIpcFd() const
135 {
136     return ipcFd_;
137 }
138 
GetSharedFd() const139 int32_t RenderRecord::GetSharedFd() const
140 {
141     return sharedFd_;
142 }
143 
GetCrashFd() const144 int32_t RenderRecord::GetCrashFd() const
145 {
146     return crashFd_;
147 }
148 
GetProcessType() const149 ProcessType RenderRecord::GetProcessType() const
150 {
151     return processType_;
152 }
153 
GetHostRecord() const154 std::shared_ptr<AppRunningRecord> RenderRecord::GetHostRecord() const
155 {
156     return host_.lock();
157 }
158 
GetScheduler() const159 sptr<IRenderScheduler> RenderRecord::GetScheduler() const
160 {
161     return renderScheduler_;
162 }
163 
SetScheduler(const sptr<IRenderScheduler> & scheduler)164 void RenderRecord::SetScheduler(const sptr<IRenderScheduler> &scheduler)
165 {
166     renderScheduler_ = scheduler;
167 }
168 
SetDeathRecipient(const sptr<AppDeathRecipient> recipient)169 void RenderRecord::SetDeathRecipient(const sptr<AppDeathRecipient> recipient)
170 {
171     deathRecipient_ = recipient;
172 }
173 
RegisterDeathRecipient()174 void RenderRecord::RegisterDeathRecipient()
175 {
176     if (renderScheduler_ && deathRecipient_) {
177         auto obj = renderScheduler_->AsObject();
178         if (!obj || !obj->AddDeathRecipient(deathRecipient_)) {
179             TAG_LOGE(AAFwkTag::APPMGR, "AddDeathRecipient failed.");
180         }
181     }
182 }
183 
SetProcessType(ProcessType type)184 void RenderRecord::SetProcessType(ProcessType type)
185 {
186     processType_ = type;
187 }
188 
SetState(int32_t state)189 void RenderRecord::SetState(int32_t state)
190 {
191     state_ = state;
192 }
193 
GetState() const194 int32_t RenderRecord::GetState() const
195 {
196     return state_;
197 }
198 
Insert(const int32_t userId,const Configuration & config)199 void MultiUserConfigurationMgr::Insert(const int32_t userId, const Configuration& config)
200 {
201     std::lock_guard<std::mutex> guard(multiUserConfigurationMutex_);
202     auto it = multiUserConfiguration_.find(userId);
203     if (it != multiUserConfiguration_.end()) {
204         std::vector<std::string> diffVe;
205         it->second.CompareDifferent(diffVe, config);
206         it->second.Merge(diffVe, config);
207     } else {
208         multiUserConfiguration_[userId] = config;
209     }
210 }
211 
GetConfigurationByUserId(const int32_t userId)212 Configuration MultiUserConfigurationMgr::GetConfigurationByUserId(const int32_t userId)
213 {
214     std::lock_guard<std::mutex> guard(multiUserConfigurationMutex_);
215     auto it = multiUserConfiguration_.find(userId);
216     if (it == multiUserConfiguration_.end()) {
217         return {};
218     }
219     return it->second;
220 }
221 
AppRunningRecord(const std::shared_ptr<ApplicationInfo> & info,const int32_t recordId,const std::string & processName)222 AppRunningRecord::AppRunningRecord(
223     const std::shared_ptr<ApplicationInfo> &info, const int32_t recordId, const std::string &processName)
224     : appRecordId_(recordId), processName_(processName)
225 {
226     if (info) {
227         appInfo_ = info;
228         mainBundleName_ = info->bundleName;
229         isLauncherApp_ = info->isLauncherApp;
230         mainAppName_ = info->name;
231     }
232     priorityObject_ = std::make_shared<PriorityObject>();
233 
234     struct timespec t;
235     t.tv_sec = 0;
236     t.tv_nsec = 0;
237     clock_gettime(CLOCK_MONOTONIC, &t);
238     startTimeMillis_ = static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS);
239 }
240 
SetApplicationClient(const sptr<IAppScheduler> & thread)241 void AppRunningRecord::SetApplicationClient(const sptr<IAppScheduler> &thread)
242 {
243     if (!appLifeCycleDeal_) {
244         appLifeCycleDeal_ = std::make_shared<AppLifeCycleDeal>();
245     }
246     appLifeCycleDeal_->SetApplicationClient(thread);
247 
248     auto moduleRecordList = GetAllModuleRecord();
249     if (moduleRecordList.empty()) {
250         TAG_LOGD(AAFwkTag::APPMGR, "moduleRecordList is empty");
251         return;
252     }
253     for (const auto &moduleRecord : moduleRecordList) {
254         moduleRecord->SetApplicationClient(appLifeCycleDeal_);
255     }
256 }
257 
GetBundleName() const258 const std::string &AppRunningRecord::GetBundleName() const
259 {
260     return mainBundleName_;
261 }
262 
GetCallerPid() const263 int32_t AppRunningRecord::GetCallerPid() const
264 {
265     return callerPid_;
266 }
267 
SetCallerPid(int32_t pid)268 void AppRunningRecord::SetCallerPid(int32_t pid)
269 {
270     callerPid_ = pid;
271 }
272 
GetCallerUid() const273 int32_t AppRunningRecord::GetCallerUid() const
274 {
275     return callerUid_;
276 }
277 
SetCallerUid(int32_t uid)278 void AppRunningRecord::SetCallerUid(int32_t uid)
279 {
280     callerUid_ = uid;
281 }
282 
GetCallerTokenId() const283 int32_t AppRunningRecord::GetCallerTokenId() const
284 {
285     return callerTokenId_;
286 }
287 
SetCallerTokenId(int32_t tokenId)288 void AppRunningRecord::SetCallerTokenId(int32_t tokenId)
289 {
290     callerTokenId_ = tokenId;
291 }
292 
IsLauncherApp() const293 bool AppRunningRecord::IsLauncherApp() const
294 {
295     return isLauncherApp_;
296 }
297 
GetRecordId() const298 int32_t AppRunningRecord::GetRecordId() const
299 {
300     return appRecordId_;
301 }
302 
GetName() const303 const std::string &AppRunningRecord::GetName() const
304 {
305     return mainAppName_;
306 }
307 
GetSignCode() const308 const std::string &AppRunningRecord::GetSignCode() const
309 {
310     return signCode_;
311 }
312 
SetSignCode(const std::string & signCode)313 void AppRunningRecord::SetSignCode(const std::string &signCode)
314 {
315     signCode_ = signCode;
316 }
317 
GetJointUserId() const318 const std::string &AppRunningRecord::GetJointUserId() const
319 {
320     return jointUserId_;
321 }
322 
SetJointUserId(const std::string & jointUserId)323 void AppRunningRecord::SetJointUserId(const std::string &jointUserId)
324 {
325     jointUserId_ = jointUserId;
326 }
327 
GetProcessName() const328 const std::string &AppRunningRecord::GetProcessName() const
329 {
330     return processName_;
331 }
332 
SetSpecifiedProcessFlag(const std::string & flag)333 void AppRunningRecord::SetSpecifiedProcessFlag(const std::string &flag)
334 {
335     specifiedProcessFlag_ = flag;
336 }
337 
GetSpecifiedProcessFlag() const338 const std::string &AppRunningRecord::GetSpecifiedProcessFlag() const
339 {
340     return specifiedProcessFlag_;
341 }
342 
GetUid() const343 int32_t AppRunningRecord::GetUid() const
344 {
345     return mainUid_;
346 }
347 
SetUid(const int32_t uid)348 void AppRunningRecord::SetUid(const int32_t uid)
349 {
350     mainUid_ = uid;
351 }
352 
GetState() const353 ApplicationState AppRunningRecord::GetState() const
354 {
355     return curState_;
356 }
357 
SetState(const ApplicationState state)358 void AppRunningRecord::SetState(const ApplicationState state)
359 {
360     if (state >= ApplicationState::APP_STATE_END && state != ApplicationState::APP_STATE_CACHED) {
361         TAG_LOGE(AAFwkTag::APPMGR, "Invalid application state");
362         return;
363     }
364     if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) {
365         restartResidentProcCount_ = MAX_RESTART_COUNT;
366     }
367     curState_ = state;
368 }
369 
SetRestartTimeMillis(const int64_t restartTimeMillis)370 void AppRunningRecord::SetRestartTimeMillis(const int64_t restartTimeMillis)
371 {
372     restartTimeMillis_ = restartTimeMillis;
373 }
374 
GetAppInfoList()375 const std::list<std::shared_ptr<ApplicationInfo>> AppRunningRecord::GetAppInfoList()
376 {
377     std::list<std::shared_ptr<ApplicationInfo>> appInfoList;
378     std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
379     for (const auto &item : appInfos_) {
380         appInfoList.push_back(item.second);
381     }
382     return appInfoList;
383 }
384 
SetAppIdentifier(const std::string & appIdentifier)385 void AppRunningRecord::SetAppIdentifier(const std::string &appIdentifier)
386 {
387     appIdentifier_ = appIdentifier;
388 }
389 
GetAppIdentifier() const390 const std::string &AppRunningRecord::GetAppIdentifier() const
391 {
392     return appIdentifier_;
393 }
394 
GetAbilities()395 const std::map<const sptr<IRemoteObject>, std::shared_ptr<AbilityRunningRecord>> AppRunningRecord::GetAbilities()
396 {
397     std::map<const sptr<IRemoteObject>, std::shared_ptr<AbilityRunningRecord>> abilitysMap;
398     auto moduleRecordList = GetAllModuleRecord();
399     for (const auto &moduleRecord : moduleRecordList) {
400         auto abilities = moduleRecord->GetAbilities();
401         abilitysMap.insert(abilities.begin(), abilities.end());
402     }
403     return abilitysMap;
404 }
405 
GetApplicationClient() const406 sptr<IAppScheduler> AppRunningRecord::GetApplicationClient() const
407 {
408     return (appLifeCycleDeal_ ? appLifeCycleDeal_->GetApplicationClient() : nullptr);
409 }
410 
GetAbilityRunningRecord(const int64_t eventId) const411 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecord(const int64_t eventId) const
412 {
413     TAG_LOGD(AAFwkTag::APPMGR, "called");
414     auto moduleRecordList = GetAllModuleRecord();
415     for (const auto &moduleRecord : moduleRecordList) {
416         auto abilityRecord = moduleRecord->GetAbilityRunningRecord(eventId);
417         if (abilityRecord) {
418             return abilityRecord;
419         }
420     }
421 
422     return nullptr;
423 }
424 
RemoveModuleRecord(const std::shared_ptr<ModuleRunningRecord> & moduleRecord,bool isExtensionDebug)425 void AppRunningRecord::RemoveModuleRecord(
426     const std::shared_ptr<ModuleRunningRecord> &moduleRecord, bool isExtensionDebug)
427 {
428     TAG_LOGD(AAFwkTag::APPMGR, "called");
429 
430     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
431     for (auto &item : hapModules_) {
432         auto iter = std::find_if(item.second.begin(),
433             item.second.end(),
434             [&moduleRecord](const std::shared_ptr<ModuleRunningRecord> &record) { return moduleRecord == record; });
435         if (iter != item.second.end()) {
436             TAG_LOGD(AAFwkTag::APPMGR, "Removed a record.");
437             iter = item.second.erase(iter);
438             if (item.second.empty() && !isExtensionDebug) {
439                 {
440                     std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
441                     TAG_LOGD(AAFwkTag::APPMGR, "Removed an appInfo.");
442                     appInfos_.erase(item.first);
443                 }
444                 hapModules_.erase(item.first);
445             }
446             return;
447         }
448     }
449 }
450 
LaunchApplication(const Configuration & config)451 void AppRunningRecord::LaunchApplication(const Configuration &config)
452 {
453     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
454     if (appLifeCycleDeal_ == nullptr) {
455         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
456         return;
457     }
458     if (!appLifeCycleDeal_->GetApplicationClient()) {
459         TAG_LOGE(AAFwkTag::APPMGR, "appThread null");
460         return;
461     }
462     AppLaunchData launchData;
463     {
464         std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
465         auto moduleRecords = appInfos_.find(mainBundleName_);
466         if (moduleRecords != appInfos_.end()) {
467             launchData.SetApplicationInfo(*(moduleRecords->second));
468         }
469     }
470     ProcessInfo processInfo(processName_, GetPriorityObject()->GetPid());
471     processInfo.SetProcessType(processType_);
472     launchData.SetProcessInfo(processInfo);
473     launchData.SetRecordId(appRecordId_);
474     launchData.SetUId(mainUid_);
475     launchData.SetUserTestInfo(userTestRecord_);
476     launchData.SetAppIndex(appIndex_);
477     launchData.SetDebugApp(isDebugApp_);
478     launchData.SetPerfCmd(perfCmd_);
479     launchData.SetErrorInfoEnhance(isErrorInfoEnhance_);
480     launchData.SetMultiThread(isMultiThread_);
481     launchData.SetJITEnabled(jitEnabled_);
482     launchData.SetNativeStart(isNativeStart_);
483     launchData.SetAppRunningUniqueId(std::to_string(startTimeMillis_));
484     launchData.SetNWebPreload(isAllowedNWebPreload_);
485 
486     TAG_LOGD(AAFwkTag::APPMGR, "%{public}s called,app is %{public}s.", __func__, GetName().c_str());
487     AddAppLifecycleEvent("AppRunningRecord::LaunchApplication");
488     appLifeCycleDeal_->LaunchApplication(launchData, config);
489 }
490 
UpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)491 void AppRunningRecord::UpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
492 {
493     if (!isStageBasedModel_) {
494         TAG_LOGI(AAFwkTag::APPMGR, "Current version than supports !");
495         return;
496     }
497 
498     if (appLifeCycleDeal_ == nullptr) {
499         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
500         return;
501     }
502     appLifeCycleDeal_->UpdateApplicationInfoInstalled(appInfo);
503 }
504 
AddAbilityStage()505 void AppRunningRecord::AddAbilityStage()
506 {
507     if (!isStageBasedModel_) {
508         TAG_LOGI(AAFwkTag::APPMGR, "Current version than supports !");
509         return;
510     }
511     HapModuleInfo abilityStage;
512     if (GetTheModuleInfoNeedToUpdated(mainBundleName_, abilityStage)) {
513         SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT);
514         TAG_LOGI(AAFwkTag::APPMGR, "Current Informed module : [%{public}s] | bundle : [%{public}s]",
515             abilityStage.moduleName.c_str(), mainBundleName_.c_str());
516         if (appLifeCycleDeal_ == nullptr) {
517             TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
518             return;
519         }
520         appLifeCycleDeal_->AddAbilityStage(abilityStage);
521     }
522 }
523 
AddAbilityStageBySpecifiedAbility(const std::string & bundleName)524 bool AppRunningRecord::AddAbilityStageBySpecifiedAbility(const std::string &bundleName)
525 {
526     if (!eventHandler_) {
527         TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
528         return false;
529     }
530 
531     HapModuleInfo hapModuleInfo;
532     if (GetTheModuleInfoNeedToUpdated(bundleName, hapModuleInfo)) {
533         if (startProcessSpecifiedAbilityEventId_ == 0) {
534             TAG_LOGI(
535                 AAFwkTag::APPMGR, "START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG not exist");
536             SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG,
537                 AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT);
538         }
539         if (appLifeCycleDeal_ == nullptr) {
540             TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
541             return false;
542         }
543         appLifeCycleDeal_->AddAbilityStage(hapModuleInfo);
544         return true;
545     }
546     return false;
547 }
548 
AddAbilityStageBySpecifiedProcess(const std::string & bundleName)549 void AppRunningRecord::AddAbilityStageBySpecifiedProcess(const std::string &bundleName)
550 {
551     TAG_LOGD(AAFwkTag::APPMGR, "call.");
552     if (!eventHandler_) {
553         TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
554         return;
555     }
556 
557     HapModuleInfo hapModuleInfo;
558     if (GetTheModuleInfoNeedToUpdated(bundleName, hapModuleInfo)) {
559         SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG,
560             AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT);
561         if (appLifeCycleDeal_ == nullptr) {
562             TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
563             return;
564         }
565         appLifeCycleDeal_->AddAbilityStage(hapModuleInfo);
566     }
567 }
568 
AddAbilityStageDone()569 void AppRunningRecord::AddAbilityStageDone()
570 {
571     TAG_LOGI(AAFwkTag::APPMGR, "bundle %{public}s and eventId %{public}d", mainBundleName_.c_str(),
572         static_cast<int>(eventId_));
573 
574     if (!eventHandler_) {
575         TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
576         return;
577     }
578 
579     if (startProcessSpecifiedAbilityEventId_ != 0) {
580         eventHandler_->RemoveEvent(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
581             startProcessSpecifiedAbilityEventId_);
582         startProcessSpecifiedAbilityEventId_ = 0;
583     }
584     if (addAbilityStageInfoEventId_ != 0) {
585         eventHandler_->RemoveEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG,
586             addAbilityStageInfoEventId_);
587         addAbilityStageInfoEventId_ = 0;
588     }
589     // Should proceed to the next notification
590 
591     if (IsStartSpecifiedAbility()) {
592         ScheduleAcceptWant(moduleName_);
593         return;
594     }
595 
596     if (IsNewProcessRequest()) {
597         TAG_LOGD(AAFwkTag::APPMGR, "ScheduleNewProcessRequest.");
598         ScheduleNewProcessRequest(GetNewProcessRequestWant(), moduleName_);
599         return;
600     }
601 
602     AddAbilityStage();
603 }
604 
LaunchAbility(const std::shared_ptr<AbilityRunningRecord> & ability)605 void AppRunningRecord::LaunchAbility(const std::shared_ptr<AbilityRunningRecord> &ability)
606 {
607     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
608     if (appLifeCycleDeal_ == nullptr) {
609         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
610         return;
611     }
612     if (!ability || !ability->GetToken()) {
613         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord or abilityToken null");
614         return;
615     }
616 
617     auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
618     if (!moduleRecord) {
619         TAG_LOGE(AAFwkTag::APPMGR, "moduleRecord null");
620         return;
621     }
622 
623     moduleRecord->LaunchAbility(ability);
624 }
625 
ScheduleTerminate()626 void AppRunningRecord::ScheduleTerminate()
627 {
628     SendEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT);
629     if (appLifeCycleDeal_ == nullptr) {
630         TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
631         return;
632     }
633     bool isLastProcess = false;
634     auto serviceInner = appMgrServiceInner_.lock();
635     if (serviceInner != nullptr) {
636         isLastProcess = serviceInner->IsFinalAppProcessByBundleName(GetBundleName());
637     }
638     appLifeCycleDeal_->ScheduleTerminate(isLastProcess);
639 }
640 
LaunchPendingAbilities()641 void AppRunningRecord::LaunchPendingAbilities()
642 {
643     TAG_LOGI(AAFwkTag::APPMGR, "Launch pending abilities.");
644     AddAppLifecycleEvent("AppRunningRecord::LaunchPendingAbilities");
645     auto moduleRecordList = GetAllModuleRecord();
646     if (moduleRecordList.empty()) {
647         TAG_LOGE(AAFwkTag::APPMGR, "moduleRecordList is empty");
648         return;
649     }
650     for (const auto &moduleRecord : moduleRecordList) {
651         moduleRecord->SetApplicationClient(appLifeCycleDeal_);
652         moduleRecord->LaunchPendingAbilities();
653     }
654 }
ScheduleForegroundRunning()655 bool AppRunningRecord::ScheduleForegroundRunning()
656 {
657     SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_FOREGROUNDING);
658     if (appLifeCycleDeal_) {
659         AddAppLifecycleEvent("AppRunningRecord::ScheduleForegroundRunning");
660         return appLifeCycleDeal_->ScheduleForegroundRunning();
661     }
662     return false;
663 }
664 
ScheduleBackgroundRunning()665 void AppRunningRecord::ScheduleBackgroundRunning()
666 {
667     SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_BACKGROUNDING);
668     int32_t recordId = GetRecordId();
669     auto serviceInner = appMgrServiceInner_;
670     auto appbackgroundtask = [recordId, serviceInner]() {
671         auto serviceInnerObj = serviceInner.lock();
672         if (serviceInnerObj == nullptr) {
673             TAG_LOGW(AAFwkTag::APPMGR, "APPManager is invalid");
674             return;
675         }
676         TAG_LOGE(AAFwkTag::APPMGR, "APPManager move to background timeout");
677         serviceInnerObj->ApplicationBackgrounded(recordId);
678     };
679     auto taskName = std::string("appbackground_") + std::to_string(recordId);
680     if (taskHandler_) {
681         taskHandler_->CancelTask(taskName);
682     }
683     PostTask(taskName, AMSEventHandler::BACKGROUND_APPLICATION_TIMEOUT, appbackgroundtask);
684     if (appLifeCycleDeal_) {
685         AddAppLifecycleEvent("AppRunningRecord::ScheduleBackgroundRunning");
686         appLifeCycleDeal_->ScheduleBackgroundRunning();
687     }
688     isAbilityForegrounding_.store(false);
689 }
690 
ScheduleProcessSecurityExit()691 void AppRunningRecord::ScheduleProcessSecurityExit()
692 {
693     if (appLifeCycleDeal_) {
694         auto appRecord = shared_from_this();
695         DelayedSingleton<CacheProcessManager>::GetInstance()->PrepareActivateCache(appRecord);
696         appLifeCycleDeal_->ScheduleProcessSecurityExit();
697     }
698 }
699 
ScheduleTrimMemory()700 void AppRunningRecord::ScheduleTrimMemory()
701 {
702     if (appLifeCycleDeal_ && priorityObject_) {
703         appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel());
704     }
705 }
706 
ScheduleMemoryLevel(int32_t level)707 void AppRunningRecord::ScheduleMemoryLevel(int32_t level)
708 {
709     if (appLifeCycleDeal_) {
710         appLifeCycleDeal_->ScheduleMemoryLevel(level);
711     }
712 }
713 
ScheduleHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)714 void AppRunningRecord::ScheduleHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
715 {
716     if (appLifeCycleDeal_) {
717         appLifeCycleDeal_->ScheduleHeapMemory(pid, mallocInfo);
718     }
719 }
720 
ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)721 void AppRunningRecord::ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
722 {
723     if (appLifeCycleDeal_) {
724         appLifeCycleDeal_->ScheduleJsHeapMemory(info);
725     }
726 }
727 
LowMemoryWarning()728 void AppRunningRecord::LowMemoryWarning()
729 {
730     if (appLifeCycleDeal_) {
731         appLifeCycleDeal_->LowMemoryWarning();
732     }
733 }
734 
AddModules(const std::shared_ptr<ApplicationInfo> & appInfo,const std::vector<HapModuleInfo> & moduleInfos)735 void AppRunningRecord::AddModules(
736     const std::shared_ptr<ApplicationInfo> &appInfo, const std::vector<HapModuleInfo> &moduleInfos)
737 {
738     TAG_LOGD(AAFwkTag::APPMGR, "Add modules");
739 
740     if (moduleInfos.empty()) {
741         TAG_LOGI(AAFwkTag::APPMGR, "moduleInfos is empty.");
742         return;
743     }
744 
745     for (auto &iter : moduleInfos) {
746         AddModule(appInfo, nullptr, nullptr, iter, nullptr, 0);
747     }
748 }
749 
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)750 void AppRunningRecord::AddModule(std::shared_ptr<ApplicationInfo> appInfo,
751     std::shared_ptr<AbilityInfo> abilityInfo, sptr<IRemoteObject> token,
752     const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, int32_t abilityRecordId)
753 {
754     TAG_LOGD(AAFwkTag::APPMGR, "called");
755 
756     if (!appInfo) {
757         TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
758         return;
759     }
760 
761     std::shared_ptr<ModuleRunningRecord> moduleRecord;
762 
763     auto initModuleRecord = [=](const std::shared_ptr<ModuleRunningRecord> &moduleRecord) {
764         moduleRecord->Init(hapModuleInfo);
765         moduleRecord->SetAppMgrServiceInner(appMgrServiceInner_);
766         moduleRecord->SetApplicationClient(appLifeCycleDeal_);
767     };
768 
769     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
770     const auto &iter = hapModules_.find(appInfo->bundleName);
771     if (iter != hapModules_.end()) {
772         moduleRecord = GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
773         if (!moduleRecord) {
774             moduleRecord = std::make_shared<ModuleRunningRecord>(appInfo, eventHandler_);
775             iter->second.push_back(moduleRecord);
776             initModuleRecord(moduleRecord);
777         }
778     } else {
779         moduleRecord = std::make_shared<ModuleRunningRecord>(appInfo, eventHandler_);
780         std::vector<std::shared_ptr<ModuleRunningRecord>> moduleList;
781         moduleList.push_back(moduleRecord);
782         hapModules_.emplace(appInfo->bundleName, moduleList);
783         {
784             std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
785             appInfos_.emplace(appInfo->bundleName, appInfo);
786         }
787         initModuleRecord(moduleRecord);
788     }
789 
790     if (!abilityInfo || !token) {
791         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo or token null");
792         return;
793     }
794     moduleRecord->AddAbility(token, abilityInfo, want, abilityRecordId);
795 
796     return;
797 }
798 
GetModuleRecordByModuleName(const std::string bundleName,const std::string & moduleName)799 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRecordByModuleName(
800     const std::string bundleName, const std::string &moduleName)
801 {
802     TAG_LOGD(AAFwkTag::APPMGR, "called");
803     auto moduleRecords = hapModules_.find(bundleName);
804     if (moduleRecords != hapModules_.end()) {
805         for (auto &iter : moduleRecords->second) {
806             if (iter->GetModuleName() == moduleName) {
807                 return iter;
808             }
809         }
810     }
811 
812     return nullptr;
813 }
814 
StateChangedNotifyObserver(const std::shared_ptr<AbilityRunningRecord> & ability,int32_t state,bool isAbility,bool isFromWindowFocusChanged)815 void AppRunningRecord::StateChangedNotifyObserver(const std::shared_ptr<AbilityRunningRecord> &ability,
816     int32_t state, bool isAbility, bool isFromWindowFocusChanged)
817 {
818     if (ability == nullptr) {
819         TAG_LOGE(AAFwkTag::APPMGR, "null ability");
820         return;
821     }
822     auto abilityInfo = ability->GetAbilityInfo();
823     if (abilityInfo == nullptr) {
824         TAG_LOGE(AAFwkTag::APPMGR, "null abilityInfo");
825         return;
826     }
827     AbilityStateData abilityStateData;
828     abilityStateData.bundleName = abilityInfo->applicationInfo.bundleName;
829     abilityStateData.moduleName = abilityInfo->moduleName;
830     abilityStateData.abilityName = ability->GetName();
831     abilityStateData.pid = GetPriorityObject()->GetPid();
832     abilityStateData.abilityState = state;
833     abilityStateData.uid = abilityInfo->applicationInfo.uid;
834     abilityStateData.token = ability->GetToken();
835     abilityStateData.abilityType = static_cast<int32_t>(abilityInfo->type);
836     abilityStateData.isFocused = ability->GetFocusFlag();
837     abilityStateData.abilityRecordId = ability->GetAbilityRecordId();
838     auto applicationInfo = GetApplicationInfo();
839     if (applicationInfo && (static_cast<int32_t>(applicationInfo->multiAppMode.multiAppModeType) ==
840             static_cast<int32_t>(MultiAppModeType::APP_CLONE))) {
841             abilityStateData.appCloneIndex = appIndex_;
842     }
843     if (ability->GetWant() != nullptr) {
844         abilityStateData.callerAbilityName = ability->GetWant()->GetStringParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
845         abilityStateData.callerBundleName = ability->GetWant()->GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
846     }
847     if (applicationInfo && applicationInfo->bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
848         abilityStateData.isAtomicService = true;
849     }
850     TAG_LOGI(AAFwkTag::APPMGR, "The ability(bundle:%{public}s, ability:%{public}s) state will change.",
851         abilityStateData.bundleName.c_str(), abilityStateData.abilityName.c_str());
852     if (isAbility && abilityInfo->type == AbilityType::EXTENSION &&
853         abilityInfo->extensionAbilityType != ExtensionAbilityType::UI) {
854         TAG_LOGD(AAFwkTag::APPMGR, "extensionType:%{public}d, not notify", abilityInfo->extensionAbilityType);
855         return;
856     }
857     auto serviceInner = appMgrServiceInner_.lock();
858     if (serviceInner) {
859         serviceInner->StateChangedNotifyObserver(abilityStateData, isAbility, isFromWindowFocusChanged);
860     }
861 }
862 
GetModuleRunningRecordByToken(const sptr<IRemoteObject> & token) const863 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRunningRecordByToken(
864     const sptr<IRemoteObject> &token) const
865 {
866     if (!token) {
867         return nullptr;
868     }
869 
870     auto moduleRecordList = GetAllModuleRecord();
871     for (const auto &moduleRecord : moduleRecordList) {
872         if (moduleRecord && moduleRecord->GetAbilityRunningRecordByToken(token)) {
873             return moduleRecord;
874         }
875     }
876 
877     return nullptr;
878 }
879 
GetModuleRunningRecordByTerminateLists(const sptr<IRemoteObject> & token) const880 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRunningRecordByTerminateLists(
881     const sptr<IRemoteObject> &token) const
882 {
883     if (!token) {
884         TAG_LOGE(AAFwkTag::APPMGR, "token null");
885         return nullptr;
886     }
887 
888     auto moduleRecordList = GetAllModuleRecord();
889     for (const auto &moduleRecord : moduleRecordList) {
890         if (moduleRecord && moduleRecord->GetAbilityByTerminateLists(token)) {
891             return moduleRecord;
892         }
893     }
894 
895     return nullptr;
896 }
897 
GetAbilityRunningRecordByToken(const sptr<IRemoteObject> & token) const898 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecordByToken(
899     const sptr<IRemoteObject> &token) const
900 {
901     auto moduleRecord = GetModuleRunningRecordByToken(token);
902     if (!moduleRecord) {
903         return nullptr;
904     }
905     return moduleRecord->GetAbilityRunningRecordByToken(token);
906 }
907 
GetAbilityByTerminateLists(const sptr<IRemoteObject> & token) const908 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityByTerminateLists(
909     const sptr<IRemoteObject> &token) const
910 {
911     auto moduleRecord = GetModuleRunningRecordByTerminateLists(token);
912     if (!moduleRecord) {
913         return nullptr;
914     }
915     return moduleRecord->GetAbilityByTerminateLists(token);
916 }
917 
UpdateAbilityFocusState(const sptr<IRemoteObject> & token,bool isFocus)918 bool AppRunningRecord::UpdateAbilityFocusState(const sptr<IRemoteObject> &token, bool isFocus)
919 {
920     TAG_LOGD(AAFwkTag::APPMGR, "focus state is :%{public}d", isFocus);
921     auto abilityRecord = GetAbilityRunningRecordByToken(token);
922     if (!abilityRecord) {
923         TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record");
924         return false;
925     }
926 
927     bool lastFocusState = abilityRecord->GetFocusFlag();
928     if (lastFocusState == isFocus) {
929         TAG_LOGE(AAFwkTag::APPMGR, "focus state not change, no need update");
930         return false;
931     }
932 
933     if (isFocus) {
934         return AbilityFocused(abilityRecord);
935     } else {
936         return AbilityUnfocused(abilityRecord);
937     }
938 }
939 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)940 void AppRunningRecord::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
941 {
942     TAG_LOGD(AAFwkTag::APPMGR, "state is :%{public}d", static_cast<int32_t>(state));
943     auto abilityRecord = GetAbilityRunningRecordByToken(token);
944     if (!abilityRecord) {
945         TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record");
946         return;
947     }
948     if (state == AbilityState::ABILITY_STATE_CREATE) {
949         StateChangedNotifyObserver(
950             abilityRecord, static_cast<int32_t>(AbilityState::ABILITY_STATE_CREATE), true, false);
951         return;
952     }
953     if (state == abilityRecord->GetState()) {
954         TAG_LOGE(AAFwkTag::APPMGR, "current state is already, no need update");
955         return;
956     }
957 
958     if (state == AbilityState::ABILITY_STATE_FOREGROUND) {
959         AbilityForeground(abilityRecord);
960     } else if (state == AbilityState::ABILITY_STATE_BACKGROUND) {
961         AbilityBackground(abilityRecord);
962     } else {
963         TAG_LOGW(AAFwkTag::APPMGR, "wrong state");
964     }
965 }
966 
AbilityForeground(const std::shared_ptr<AbilityRunningRecord> & ability)967 void AppRunningRecord::AbilityForeground(const std::shared_ptr<AbilityRunningRecord> &ability)
968 {
969     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
970     if (!ability) {
971         TAG_LOGE(AAFwkTag::APPMGR, "ability null");
972         return;
973     }
974     AbilityState curAbilityState = ability->GetState();
975     if (curAbilityState != AbilityState::ABILITY_STATE_READY &&
976         curAbilityState != AbilityState::ABILITY_STATE_BACKGROUND) {
977         TAG_LOGE(AAFwkTag::APPMGR, "ability state(%{public}d) error", static_cast<int32_t>(curAbilityState));
978         return;
979     }
980     TAG_LOGI(AAFwkTag::APPMGR, "appState: %{public}d, pState: %{public}d, bundle: %{public}s, ability: %{public}s",
981         curState_, pendingState_, mainBundleName_.c_str(), ability->GetName().c_str());
982     // We need schedule application to foregrounded when current application state is ready or background running.
983     if (curState_ == ApplicationState::APP_STATE_FOREGROUND
984         && pendingState_ != ApplicationPendingState::BACKGROUNDING) {
985         // Just change ability to foreground if current application state is foreground or focus.
986         auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
987         if (moduleRecord == nullptr) {
988             TAG_LOGE(AAFwkTag::APPMGR, "moduleRecord null");
989             return;
990         }
991 
992         moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
993         StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND), true, false);
994         auto serviceInner = appMgrServiceInner_.lock();
995         if (serviceInner) {
996             serviceInner->OnAppStateChanged(shared_from_this(), curState_, false, false);
997         }
998         return;
999     }
1000     if (curState_ == ApplicationState::APP_STATE_READY || curState_ == ApplicationState::APP_STATE_BACKGROUND
1001         || curState_ == ApplicationState::APP_STATE_FOREGROUND) {
1002         auto pendingState = pendingState_;
1003         SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING);
1004         if (pendingState == ApplicationPendingState::READY && !ScheduleForegroundRunning()) {
1005             FreezeUtil::LifecycleFlow flow{ ability->GetToken(), FreezeUtil::TimeoutState::FOREGROUND };
1006             FreezeUtil::GetInstance().AppendLifecycleEvent(flow, "AppRunningRecord::AbilityForeground ipc fail");
1007         }
1008         foregroundingAbilityTokens_.insert(ability->GetToken());
1009         TAG_LOGD(AAFwkTag::APPMGR, "foregroundingAbility size: %{public}d",
1010             static_cast<int32_t>(foregroundingAbilityTokens_.size()));
1011         if (curState_ == ApplicationState::APP_STATE_BACKGROUND) {
1012             SendAppStartupTypeEvent(ability, AppStartType::HOT);
1013         }
1014     } else {
1015         TAG_LOGW(AAFwkTag::APPMGR, "wrong application state");
1016     }
1017 }
1018 
AbilityBackground(const std::shared_ptr<AbilityRunningRecord> & ability)1019 void AppRunningRecord::AbilityBackground(const std::shared_ptr<AbilityRunningRecord> &ability)
1020 {
1021     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1022     if (!ability) {
1023         TAG_LOGE(AAFwkTag::APPMGR, "ability null");
1024         return;
1025     }
1026     TAG_LOGD(AAFwkTag::APPMGR, "ability is %{public}s", mainBundleName_.c_str());
1027     if (ability->GetState() != AbilityState::ABILITY_STATE_FOREGROUND &&
1028         ability->GetState() != AbilityState::ABILITY_STATE_READY) {
1029         TAG_LOGE(AAFwkTag::APPMGR, "ability state is not foreground or focus");
1030         return;
1031     }
1032 
1033     // First change ability to background.
1034     auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
1035     if (moduleRecord == nullptr) {
1036         TAG_LOGE(AAFwkTag::APPMGR, "moduleRecord null");
1037         return;
1038     }
1039     moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BACKGROUND);
1040     StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_BACKGROUND), true, false);
1041     if (curState_ == ApplicationState::APP_STATE_FOREGROUND || curState_ == ApplicationState::APP_STATE_CACHED) {
1042         int32_t foregroundSize = 0;
1043         auto abilitiesMap = GetAbilities();
1044         for (const auto &item : abilitiesMap) {
1045             const auto &abilityRecord = item.second;
1046             if (abilityRecord && abilityRecord->GetState() == AbilityState::ABILITY_STATE_FOREGROUND &&
1047                 abilityRecord->GetAbilityInfo() &&
1048                 (abilityRecord->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE
1049                 || AAFwk::UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo()->extensionAbilityType))) {
1050                 foregroundSize++;
1051                 break;
1052             }
1053         }
1054 
1055         // Then schedule application background when all ability is not foreground.
1056         if (foregroundSize == 0 && mainBundleName_ != LAUNCHER_NAME && windowIds_.empty()) {
1057             auto pendingState = pendingState_;
1058             SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING);
1059             if (pendingState == ApplicationPendingState::READY) {
1060                 ScheduleBackgroundRunning();
1061             }
1062         }
1063     } else {
1064         TAG_LOGW(AAFwkTag::APPMGR, "wrong application state");
1065     }
1066 }
1067 
AbilityFocused(const std::shared_ptr<AbilityRunningRecord> & ability)1068 bool AppRunningRecord::AbilityFocused(const std::shared_ptr<AbilityRunningRecord> &ability)
1069 {
1070     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1071     if (!ability) {
1072         TAG_LOGE(AAFwkTag::APPMGR, "ability null");
1073         return false;
1074     }
1075     ability->UpdateFocusState(true);
1076 
1077     // update ability state
1078     int32_t abilityState = static_cast<int32_t>(ability->GetState());
1079     bool isAbility = true;
1080     if (ability->GetAbilityInfo() != nullptr && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) {
1081         isAbility = false;
1082     }
1083     StateChangedNotifyObserver(ability, abilityState, isAbility, true);
1084 
1085     if (isFocused_) {
1086         // process state is already focused, no need update process state.
1087         return false;
1088     }
1089 
1090     // update process focus state to true.
1091     isFocused_ = true;
1092     return true;
1093 }
1094 
AbilityUnfocused(const std::shared_ptr<AbilityRunningRecord> & ability)1095 bool AppRunningRecord::AbilityUnfocused(const std::shared_ptr<AbilityRunningRecord> &ability)
1096 {
1097     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1098     if (!ability) {
1099         TAG_LOGE(AAFwkTag::APPMGR, "ability null");
1100         return false;
1101     }
1102     ability->UpdateFocusState(false);
1103 
1104     // update ability state to unfocused.
1105     int32_t abilityState = static_cast<int32_t>(ability->GetState());
1106     bool isAbility = true;
1107     if (ability->GetAbilityInfo() != nullptr && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) {
1108         isAbility = false;
1109     }
1110     StateChangedNotifyObserver(ability, abilityState, isAbility, true);
1111 
1112     if (!isFocused_) {
1113         return false; // invalid process focus state, already unfocused, process state not change.
1114     }
1115 
1116     bool changeProcessToUnfocused = true;
1117     auto abilitysMap = GetAbilities();
1118     for (const auto &item : abilitysMap) {
1119         const auto &abilityRecord = item.second;
1120         if (abilityRecord && abilityRecord->GetFocusFlag()) {
1121             changeProcessToUnfocused = false;
1122             break;
1123         }
1124     }
1125 
1126     if (changeProcessToUnfocused) {
1127         isFocused_ = false; // process focus state : from focus to unfocus.
1128     }
1129     return changeProcessToUnfocused;
1130 }
1131 
PopForegroundingAbilityTokens()1132 void AppRunningRecord::PopForegroundingAbilityTokens()
1133 {
1134     TAG_LOGI(AAFwkTag::APPMGR, "fg ability size: %{public}d",
1135         static_cast<int32_t>(foregroundingAbilityTokens_.size()));
1136     for (auto iter = foregroundingAbilityTokens_.begin(); iter != foregroundingAbilityTokens_.end();) {
1137         auto ability = GetAbilityRunningRecordByToken(*iter);
1138         auto moduleRecord = GetModuleRunningRecordByToken(*iter);
1139         if (moduleRecord != nullptr) {
1140             moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
1141             StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND),
1142                 true, false);
1143         } else {
1144             TAG_LOGW(AAFwkTag::APPMGR, "can not find module record");
1145         }
1146         // The token should be removed even though the module record didn't exist.
1147         iter = foregroundingAbilityTokens_.erase(iter);
1148     }
1149 }
1150 
TerminateAbility(const sptr<IRemoteObject> & token,const bool isForce,bool isTimeout)1151 void AppRunningRecord::TerminateAbility(const sptr<IRemoteObject> &token, const bool isForce, bool isTimeout)
1152 {
1153     TAG_LOGD(AAFwkTag::APPMGR, "isForce: %{public}d", static_cast<int>(isForce));
1154 
1155     auto moduleRecord = GetModuleRunningRecordByToken(token);
1156     if (!moduleRecord) {
1157         TAG_LOGE(AAFwkTag::APPMGR, "can not find module record");
1158         return;
1159     }
1160 
1161     auto abilityRecord = GetAbilityRunningRecordByToken(token);
1162     if (abilityRecord) {
1163         TAG_LOGI(AAFwkTag::APPMGR, "TerminateAbility:%{public}s", abilityRecord->GetName().c_str());
1164     }
1165     if (!isTimeout) {
1166         StateChangedNotifyObserver(
1167             abilityRecord, static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true, false);
1168     }
1169     moduleRecord->TerminateAbility(shared_from_this(), token, isForce);
1170 }
1171 
AbilityTerminated(const sptr<IRemoteObject> & token)1172 void AppRunningRecord::AbilityTerminated(const sptr<IRemoteObject> &token)
1173 {
1174     TAG_LOGD(AAFwkTag::APPMGR, "called");
1175     auto moduleRecord = GetModuleRunningRecordByTerminateLists(token);
1176     if (!moduleRecord) {
1177         TAG_LOGE(AAFwkTag::APPMGR, "AbilityTerminated error, can not find module record");
1178         return;
1179     }
1180 
1181     bool isExtensionDebug = false;
1182     auto abilityRecord = moduleRecord->GetAbilityByTerminateLists(token);
1183     if (abilityRecord != nullptr && abilityRecord->GetAbilityInfo() != nullptr) {
1184         isExtensionDebug = (abilityRecord->GetAbilityInfo()->type == AppExecFwk::AbilityType::EXTENSION) &&
1185                            (isAttachDebug_ || isDebugApp_);
1186     }
1187     TAG_LOGD(AAFwkTag::APPMGR, "Extension debug is [%{public}s]", isExtensionDebug ? "true" : "false");
1188 
1189     moduleRecord->AbilityTerminated(token);
1190 
1191     auto appRecord = shared_from_this();
1192     auto cacheProcMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
1193     bool needCache = false;
1194     if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) {
1195         cacheProcMgr->CheckAndCacheProcess(appRecord);
1196         TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s should cache, not remove module and terminate app.",
1197             appRecord->GetBundleName().c_str());
1198         needCache = true;
1199     }
1200     if (moduleRecord->GetAbilities().empty() && (!IsKeepAliveApp()
1201         || AAFwk::UIExtensionUtils::IsUIExtension(GetExtensionType())
1202         || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent()) && !needCache) {
1203         RemoveModuleRecord(moduleRecord, isExtensionDebug);
1204     }
1205 
1206     auto moduleRecordList = GetAllModuleRecord();
1207     if (moduleRecordList.empty() && (!IsKeepAliveApp()
1208         || AAFwk::UIExtensionUtils::IsUIExtension(GetExtensionType())
1209         || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent()) && !isExtensionDebug
1210         && !needCache) {
1211         ScheduleTerminate();
1212     }
1213 }
1214 
GetAllModuleRecord() const1215 std::list<std::shared_ptr<ModuleRunningRecord>> AppRunningRecord::GetAllModuleRecord() const
1216 {
1217     std::list<std::shared_ptr<ModuleRunningRecord>> moduleRecordList;
1218     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1219     for (const auto &item : hapModules_) {
1220         for (const auto &list : item.second) {
1221             moduleRecordList.push_back(list);
1222         }
1223     }
1224     return moduleRecordList;
1225 }
1226 
RemoveAppDeathRecipient() const1227 void AppRunningRecord::RemoveAppDeathRecipient() const
1228 {
1229     if (appLifeCycleDeal_ == nullptr) {
1230         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1231         return;
1232     }
1233     if (!appLifeCycleDeal_->GetApplicationClient()) {
1234         TAG_LOGE(AAFwkTag::APPMGR, "appThread null");
1235         return;
1236     }
1237     auto object = appLifeCycleDeal_->GetApplicationClient()->AsObject();
1238     if (object) {
1239         if (!object->RemoveDeathRecipient(appDeathRecipient_)) {
1240             TAG_LOGD(AAFwkTag::APPMGR, "Failed to remove deathRecipient.");
1241         }
1242     }
1243 }
1244 
SetAppMgrServiceInner(const std::weak_ptr<AppMgrServiceInner> & inner)1245 void AppRunningRecord::SetAppMgrServiceInner(const std::weak_ptr<AppMgrServiceInner> &inner)
1246 {
1247     appMgrServiceInner_ = inner;
1248 
1249     auto moduleRecordList = GetAllModuleRecord();
1250     if (moduleRecordList.empty()) {
1251         TAG_LOGE(AAFwkTag::APPMGR, "moduleRecordList is empty");
1252         return;
1253     }
1254 
1255     for (const auto &moduleRecord : moduleRecordList) {
1256         moduleRecord->SetAppMgrServiceInner(appMgrServiceInner_);
1257     }
1258 }
1259 
SetAppDeathRecipient(const sptr<AppDeathRecipient> & appDeathRecipient)1260 void AppRunningRecord::SetAppDeathRecipient(const sptr<AppDeathRecipient> &appDeathRecipient)
1261 {
1262     appDeathRecipient_ = appDeathRecipient;
1263 }
1264 
GetPriorityObject()1265 std::shared_ptr<PriorityObject> AppRunningRecord::GetPriorityObject()
1266 {
1267     return priorityObject_;
1268 }
1269 
SendEventForSpecifiedAbility(uint32_t msg,int64_t timeOut)1270 void AppRunningRecord::SendEventForSpecifiedAbility(uint32_t msg, int64_t timeOut)
1271 {
1272     SendEvent(msg, timeOut);
1273 }
1274 
SendAppStartupTypeEvent(const std::shared_ptr<AbilityRunningRecord> & ability,const AppStartType startType)1275 void AppRunningRecord::SendAppStartupTypeEvent(const std::shared_ptr<AbilityRunningRecord> &ability,
1276     const AppStartType startType)
1277 {
1278     if (!ability) {
1279         TAG_LOGE(AAFwkTag::APPMGR, "AbilityRunningRecord null");
1280         return;
1281     }
1282     AAFwk::EventInfo eventInfo;
1283     auto applicationInfo = GetApplicationInfo();
1284     if (!applicationInfo) {
1285         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo null, can not get app information");
1286     } else {
1287         eventInfo.bundleName = applicationInfo->name;
1288         eventInfo.versionName = applicationInfo->versionName;
1289         eventInfo.versionCode = applicationInfo->versionCode;
1290     }
1291 
1292     auto abilityInfo = ability->GetAbilityInfo();
1293     if (!abilityInfo) {
1294         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo null, can not get ability information");
1295     } else {
1296         eventInfo.abilityName = abilityInfo->name;
1297     }
1298     if (GetPriorityObject() == nullptr) {
1299         TAG_LOGE(AAFwkTag::APPMGR, "appRecord's priorityObject null");
1300     } else {
1301         eventInfo.pid = GetPriorityObject()->GetPid();
1302     }
1303     eventInfo.startType = static_cast<int32_t>(startType);
1304     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_STARTUP_TYPE, HiSysEventType::BEHAVIOR, eventInfo);
1305 }
1306 
SendEvent(uint32_t msg,int64_t timeOut)1307 void AppRunningRecord::SendEvent(uint32_t msg, int64_t timeOut)
1308 {
1309     if (!eventHandler_) {
1310         TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1311         return;
1312     }
1313 
1314     if (isDebugApp_ || isNativeDebug_ || isAttachDebug_) {
1315         TAG_LOGI(AAFwkTag::APPMGR, "Is debug mode, no need to handle time out.");
1316         return;
1317     }
1318 
1319     appEventId_++;
1320     eventId_ = appEventId_;
1321     if (msg == AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG) {
1322         startProcessSpecifiedAbilityEventId_ = eventId_;
1323     }
1324     if (msg == AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG) {
1325         addAbilityStageInfoEventId_ = eventId_;
1326     }
1327 
1328     TAG_LOGI(AAFwkTag::APPMGR, "eventId %{public}d", static_cast<int>(eventId_));
1329     eventHandler_->SendEvent(AAFwk::EventWrap(msg, eventId_), timeOut, false);
1330     SendClearTask(msg, timeOut);
1331 }
1332 
SendClearTask(uint32_t msg,int64_t timeOut)1333 void AppRunningRecord::SendClearTask(uint32_t msg, int64_t timeOut)
1334 {
1335     if (!taskHandler_) {
1336         TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
1337         return;
1338     }
1339     int64_t* eventId = nullptr;
1340     if (msg == AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG) {
1341         eventId = &startProcessSpecifiedAbilityEventId_;
1342     } else if (msg == AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG) {
1343         eventId = &addAbilityStageInfoEventId_;
1344     } else {
1345         TAG_LOGD(AAFwkTag::APPMGR, "Other msg: %{public}d", msg);
1346         return;
1347     }
1348     taskHandler_->SubmitTask([wthis = weak_from_this(), eventId]() {
1349         auto pthis = wthis.lock();
1350         if (pthis) {
1351             *eventId = 0;
1352         }
1353         }, timeOut);
1354 }
1355 
PostTask(std::string msg,int64_t timeOut,const Closure & task)1356 void AppRunningRecord::PostTask(std::string msg, int64_t timeOut, const Closure &task)
1357 {
1358     if (!taskHandler_) {
1359         TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
1360         return;
1361     }
1362     taskHandler_->SubmitTask(task, msg, timeOut);
1363 }
1364 
GetEventId() const1365 int64_t AppRunningRecord::GetEventId() const
1366 {
1367     return eventId_;
1368 }
1369 
SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)1370 void AppRunningRecord::SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)
1371 {
1372     taskHandler_ = taskHandler;
1373 }
1374 
SetEventHandler(const std::shared_ptr<AMSEventHandler> & handler)1375 void AppRunningRecord::SetEventHandler(const std::shared_ptr<AMSEventHandler> &handler)
1376 {
1377     eventHandler_ = handler;
1378 }
1379 
IsLastAbilityRecord(const sptr<IRemoteObject> & token)1380 bool AppRunningRecord::IsLastAbilityRecord(const sptr<IRemoteObject> &token)
1381 {
1382     auto moduleRecord = GetModuleRunningRecordByToken(token);
1383     if (!moduleRecord) {
1384         TAG_LOGE(AAFwkTag::APPMGR, "can not find module record");
1385         return false;
1386     }
1387 
1388     auto moduleRecordList = GetAllModuleRecord();
1389     if (moduleRecordList.size() == 1) {
1390         return moduleRecord->IsLastAbilityRecord(token);
1391     }
1392 
1393     return false;
1394 }
1395 
ExtensionAbilityRecordExists()1396 bool AppRunningRecord::ExtensionAbilityRecordExists()
1397 {
1398     auto moduleRecordList = GetAllModuleRecord();
1399     for (auto moduleRecord : moduleRecordList) {
1400         if (moduleRecord && moduleRecord->ExtensionAbilityRecordExists()) {
1401             return true;
1402         }
1403     }
1404     TAG_LOGD(AAFwkTag::APPMGR, "can not find extension record");
1405     return false;
1406 }
1407 
IsLastPageAbilityRecord(const sptr<IRemoteObject> & token)1408 bool AppRunningRecord::IsLastPageAbilityRecord(const sptr<IRemoteObject> &token)
1409 {
1410     auto moduleRecord = GetModuleRunningRecordByToken(token);
1411     if (!moduleRecord) {
1412         TAG_LOGE(AAFwkTag::APPMGR, "can not find module record");
1413         return false;
1414     }
1415 
1416     int32_t pageAbilitySize = 0;
1417     auto moduleRecordList = GetAllModuleRecord();
1418     for (auto moduleRecord : moduleRecordList) {
1419         if (moduleRecord) {
1420             pageAbilitySize += moduleRecord->GetPageAbilitySize();
1421         }
1422         if (pageAbilitySize > 1) {
1423             return false;
1424         }
1425     }
1426 
1427     return pageAbilitySize == 1;
1428 }
1429 
SetTerminating()1430 void AppRunningRecord::SetTerminating()
1431 {
1432     isTerminating = true;
1433     auto prioObject = GetPriorityObject();
1434     if (prioObject) {
1435         FreezeUtil::GetInstance().DeleteAppLifecycleEvent(prioObject->GetPid());
1436     }
1437 }
1438 
IsTerminating()1439 bool AppRunningRecord::IsTerminating()
1440 {
1441     return isTerminating;
1442 }
1443 
IsKeepAliveApp() const1444 bool AppRunningRecord::IsKeepAliveApp() const
1445 {
1446     if (!isMainProcess_ || !isKeepAliveBundle_ || !isKeepAliveRdb_) {
1447         return false;
1448     }
1449     auto userId = GetUid() / BASE_USER_RANGE;
1450     if (userId == 0) {
1451         return isSingleton_;
1452     }
1453     return true;
1454 }
1455 
SetKeepAliveEnableState(bool isKeepAliveEnable)1456 void AppRunningRecord::SetKeepAliveEnableState(bool isKeepAliveEnable)
1457 {
1458     isKeepAliveRdb_ = isKeepAliveEnable;
1459 }
1460 
SetKeepAliveBundle(bool isKeepAliveBundle)1461 void AppRunningRecord::SetKeepAliveBundle(bool isKeepAliveBundle)
1462 {
1463     isKeepAliveBundle_ = isKeepAliveBundle;
1464 }
1465 
IsEmptyKeepAliveApp() const1466 bool AppRunningRecord::IsEmptyKeepAliveApp() const
1467 {
1468     return isEmptyKeepAliveApp_;
1469 }
1470 
SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp)1471 void AppRunningRecord::SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp)
1472 {
1473     isEmptyKeepAliveApp_ = isEmptyKeepAliveApp;
1474 }
1475 
IsMainProcess() const1476 bool AppRunningRecord::IsMainProcess() const
1477 {
1478     return isMainProcess_;
1479 }
1480 
SetMainProcess(bool isMainProcess)1481 void AppRunningRecord::SetMainProcess(bool isMainProcess)
1482 {
1483     isMainProcess_ = isMainProcess;
1484 }
1485 
SetSingleton(bool isSingleton)1486 void AppRunningRecord::SetSingleton(bool isSingleton)
1487 {
1488     isSingleton_ = isSingleton;
1489 }
1490 
SetStageModelState(bool isStageBasedModel)1491 void AppRunningRecord::SetStageModelState(bool isStageBasedModel)
1492 {
1493     isStageBasedModel_ = isStageBasedModel;
1494 }
1495 
GetTheModuleInfoNeedToUpdated(const std::string bundleName,HapModuleInfo & info)1496 bool AppRunningRecord::GetTheModuleInfoNeedToUpdated(const std::string bundleName, HapModuleInfo &info)
1497 {
1498     bool result = false;
1499     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1500     auto moduleInfoVectorIter = hapModules_.find(bundleName);
1501     if (moduleInfoVectorIter == hapModules_.end() || moduleInfoVectorIter->second.empty()) {
1502         return result;
1503     }
1504     std::string moduleName = moduleName_;
1505     auto findCondition = [moduleName](const std::shared_ptr<ModuleRunningRecord> &record) {
1506         if (record) {
1507             return (moduleName.empty() || (moduleName == record->GetModuleName())) &&
1508                 (record->GetModuleRecordState() == ModuleRecordState::INITIALIZED_STATE);
1509         }
1510         return false;
1511     };
1512     auto moduleRecordIter =
1513         std::find_if(moduleInfoVectorIter->second.begin(), moduleInfoVectorIter->second.end(), findCondition);
1514     if (moduleRecordIter != moduleInfoVectorIter->second.end()) {
1515         (*moduleRecordIter)->GetHapModuleInfo(info);
1516         (*moduleRecordIter)->SetModuleRecordState(ModuleRecordState::RUNNING_STATE);
1517         result = true;
1518     }
1519 
1520     return result;
1521 }
1522 
SetRestartResidentProcCount(int count)1523 void AppRunningRecord::SetRestartResidentProcCount(int count)
1524 {
1525     restartResidentProcCount_ = count;
1526 }
1527 
DecRestartResidentProcCount()1528 void AppRunningRecord::DecRestartResidentProcCount()
1529 {
1530     restartResidentProcCount_--;
1531 }
1532 
GetRestartResidentProcCount() const1533 int AppRunningRecord::GetRestartResidentProcCount() const
1534 {
1535     return restartResidentProcCount_;
1536 }
1537 
CanRestartResidentProc()1538 bool AppRunningRecord::CanRestartResidentProc()
1539 {
1540     struct timespec t;
1541     t.tv_sec = 0;
1542     t.tv_nsec = 0;
1543     clock_gettime(CLOCK_MONOTONIC, &t);
1544     int64_t systemTimeMillis = static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS);
1545     if ((restartResidentProcCount_ >= 0) || ((systemTimeMillis - restartTimeMillis_) > RESTART_INTERVAL_TIME)) {
1546         return true;
1547     }
1548     return false;
1549 }
1550 
GetBundleNames(std::vector<std::string> & bundleNames)1551 void AppRunningRecord::GetBundleNames(std::vector<std::string> &bundleNames)
1552 {
1553     std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
1554     for (auto &app : appInfos_) {
1555         bundleNames.emplace_back(app.first);
1556     }
1557 }
1558 
SetUserTestInfo(const std::shared_ptr<UserTestRecord> & record)1559 void AppRunningRecord::SetUserTestInfo(const std::shared_ptr<UserTestRecord> &record)
1560 {
1561     userTestRecord_ = record;
1562 }
1563 
GetUserTestInfo()1564 std::shared_ptr<UserTestRecord> AppRunningRecord::GetUserTestInfo()
1565 {
1566     return userTestRecord_;
1567 }
1568 
SetProcessAndExtensionType(const std::shared_ptr<AbilityInfo> & abilityInfo)1569 void AppRunningRecord::SetProcessAndExtensionType(const std::shared_ptr<AbilityInfo> &abilityInfo)
1570 {
1571     if (abilityInfo == nullptr) {
1572         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo null");
1573         return;
1574     }
1575     extensionType_ = abilityInfo->extensionAbilityType;
1576     if (extensionType_ == ExtensionAbilityType::UNSPECIFIED) {
1577         //record Service Ability in FA model as Service Extension
1578         if (abilityInfo->type == AbilityType::SERVICE) {
1579             processType_ = ProcessType::EXTENSION;
1580             extensionType_ = ExtensionAbilityType::SERVICE;
1581             return;
1582         }
1583         //record Data Ability in FA model as Datashare Extension
1584         if (abilityInfo->type == AbilityType::DATA) {
1585             processType_ = ProcessType::EXTENSION;
1586             extensionType_ = ExtensionAbilityType::DATASHARE;
1587             return;
1588         }
1589         processType_ = ProcessType::NORMAL;
1590         return;
1591     }
1592     processType_ = ProcessType::EXTENSION;
1593     return;
1594 }
1595 
SetSpecifiedAbilityFlagAndWant(int requestId,const AAFwk::Want & want,const std::string & moduleName)1596 void AppRunningRecord::SetSpecifiedAbilityFlagAndWant(
1597     int requestId, const AAFwk::Want &want, const std::string &moduleName)
1598 {
1599     std::lock_guard lock(specifiedMutex_);
1600     if (specifiedRequestId_ != -1) {
1601         TAG_LOGW(AAFwkTag::APPMGR, "specifiedRequestId: %{public}d", specifiedRequestId_);
1602     }
1603     specifiedRequestId_ = requestId;
1604     specifiedWant_ = want;
1605     moduleName_ = moduleName;
1606 }
1607 
GetSpecifiedRequestId() const1608 int32_t AppRunningRecord::GetSpecifiedRequestId() const
1609 {
1610     std::lock_guard lock(specifiedMutex_);
1611     return specifiedRequestId_;
1612 }
1613 
ResetSpecifiedRequestId()1614 void AppRunningRecord::ResetSpecifiedRequestId()
1615 {
1616     std::lock_guard lock(specifiedMutex_);
1617     specifiedRequestId_ = -1;
1618 }
1619 
SetScheduleNewProcessRequestState(int32_t requestId,const AAFwk::Want & want,const std::string & moduleName)1620 void AppRunningRecord::SetScheduleNewProcessRequestState(int32_t requestId,
1621     const AAFwk::Want &want, const std::string &moduleName)
1622 {
1623     std::lock_guard lock(specifiedMutex_);
1624     if (newProcessRequestId_ != -1) {
1625         TAG_LOGW(AAFwkTag::APPMGR, "newProcessRequestId: %{public}d", newProcessRequestId_);
1626     }
1627     newProcessRequestId_ = requestId;
1628     newProcessRequestWant_ = want;
1629     moduleName_ = moduleName;
1630 }
1631 
IsNewProcessRequest() const1632 bool AppRunningRecord::IsNewProcessRequest() const
1633 {
1634     std::lock_guard lock(specifiedMutex_);
1635     return newProcessRequestId_ != -1;
1636 }
1637 
IsStartSpecifiedAbility() const1638 bool AppRunningRecord::IsStartSpecifiedAbility() const
1639 {
1640     std::lock_guard lock(specifiedMutex_);
1641     return specifiedRequestId_ != -1;
1642 }
1643 
ScheduleAcceptWant(const std::string & moduleName)1644 void AppRunningRecord::ScheduleAcceptWant(const std::string &moduleName)
1645 {
1646     SendEvent(
1647         AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG, AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT);
1648     if (appLifeCycleDeal_ == nullptr) {
1649         TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1650         return;
1651     }
1652     appLifeCycleDeal_->ScheduleAcceptWant(GetSpecifiedWant(), moduleName);
1653 }
1654 
ScheduleAcceptWantDone()1655 void AppRunningRecord::ScheduleAcceptWantDone()
1656 {
1657     TAG_LOGI(AAFwkTag::APPMGR, "Schedule accept want done. bundle %{public}s and eventId %{public}d",
1658         mainBundleName_.c_str(), static_cast<int>(eventId_));
1659 
1660     if (!eventHandler_) {
1661         TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1662         return;
1663     }
1664 
1665     eventHandler_->RemoveEvent(AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG, eventId_);
1666 }
1667 
ScheduleNewProcessRequest(const AAFwk::Want & want,const std::string & moduleName)1668 void AppRunningRecord::ScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName)
1669 {
1670     SendEvent(
1671         AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG, AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT);
1672     if (appLifeCycleDeal_ == nullptr) {
1673         TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1674         return;
1675     }
1676     appLifeCycleDeal_->ScheduleNewProcessRequest(want, moduleName);
1677 }
1678 
ScheduleNewProcessRequestDone()1679 void AppRunningRecord::ScheduleNewProcessRequestDone()
1680 {
1681     TAG_LOGI(AAFwkTag::APPMGR, "ScheduleNewProcessRequestDone. bundle %{public}s and eventId %{public}d",
1682         mainBundleName_.c_str(), static_cast<int>(eventId_));
1683 
1684     if (!eventHandler_) {
1685         TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1686         return;
1687     }
1688 
1689     eventHandler_->RemoveEvent(AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG, eventId_);
1690 }
1691 
ApplicationTerminated()1692 void AppRunningRecord::ApplicationTerminated()
1693 {
1694     TAG_LOGD(AAFwkTag::APPMGR, "Application terminated bundle %{public}s and eventId %{public}d",
1695         mainBundleName_.c_str(), static_cast<int>(eventId_));
1696 
1697     if (!eventHandler_) {
1698         TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1699         return;
1700     }
1701 
1702     eventHandler_->RemoveEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, eventId_);
1703 }
1704 
GetSpecifiedWant() const1705 AAFwk::Want AppRunningRecord::GetSpecifiedWant() const
1706 {
1707     std::lock_guard lock(specifiedMutex_);
1708     return specifiedWant_;
1709 }
1710 
GetNewProcessRequestWant() const1711 AAFwk::Want AppRunningRecord::GetNewProcessRequestWant() const
1712 {
1713     std::lock_guard lock(specifiedMutex_);
1714     return newProcessRequestWant_;
1715 }
1716 
GetNewProcessRequestId() const1717 int32_t AppRunningRecord::GetNewProcessRequestId() const
1718 {
1719     std::lock_guard lock(specifiedMutex_);
1720     return newProcessRequestId_;
1721 }
1722 
ResetNewProcessRequestId()1723 void AppRunningRecord::ResetNewProcessRequestId()
1724 {
1725     std::lock_guard lock(specifiedMutex_);
1726     newProcessRequestId_ = -1;
1727 }
1728 
UpdateConfiguration(const Configuration & config)1729 int32_t AppRunningRecord::UpdateConfiguration(const Configuration &config)
1730 {
1731     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1732     TAG_LOGD(AAFwkTag::APPMGR, "called");
1733     if (!appLifeCycleDeal_) {
1734         TAG_LOGI(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1735         return ERR_INVALID_VALUE;
1736     }
1737     return appLifeCycleDeal_->UpdateConfiguration(config);
1738 }
1739 
AddRenderRecord(const std::shared_ptr<RenderRecord> & record)1740 void AppRunningRecord::AddRenderRecord(const std::shared_ptr<RenderRecord> &record)
1741 {
1742     if (!record) {
1743         TAG_LOGD(AAFwkTag::APPMGR, "AddRenderRecord: record null");
1744         return;
1745     }
1746     {
1747         std::lock_guard renderPidSetLock(renderPidSetLock_);
1748         renderPidSet_.insert(record->GetPid());
1749     }
1750     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1751     renderRecordMap_.emplace(record->GetUid(), record);
1752 }
1753 
RemoveRenderRecord(const std::shared_ptr<RenderRecord> & record)1754 void AppRunningRecord::RemoveRenderRecord(const std::shared_ptr<RenderRecord> &record)
1755 {
1756     if (!record) {
1757         TAG_LOGD(AAFwkTag::APPMGR, "RemoveRenderRecord: record null");
1758         return;
1759     }
1760     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1761     renderRecordMap_.erase(record->GetUid());
1762 }
1763 
RemoveRenderPid(pid_t renderPid)1764 void AppRunningRecord::RemoveRenderPid(pid_t renderPid)
1765 {
1766     std::lock_guard renderPidSetLock(renderPidSetLock_);
1767     renderPidSet_.erase(renderPid);
1768 }
1769 
ConstainsRenderPid(pid_t renderPid)1770 bool AppRunningRecord::ConstainsRenderPid(pid_t renderPid)
1771 {
1772     std::lock_guard renderPidSetLock(renderPidSetLock_);
1773     return renderPidSet_.find(renderPid) != renderPidSet_.end();
1774 }
1775 
GetRenderRecordByPid(const pid_t pid)1776 std::shared_ptr<RenderRecord> AppRunningRecord::GetRenderRecordByPid(const pid_t pid)
1777 {
1778     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1779     if (renderRecordMap_.empty()) {
1780         return nullptr;
1781     }
1782     for (auto iter : renderRecordMap_) {
1783         auto renderRecord = iter.second;
1784         if (renderRecord && renderRecord->GetPid() == pid) {
1785             return renderRecord;
1786         }
1787     }
1788     return nullptr;
1789 }
1790 
GetRenderRecordMap()1791 std::map<int32_t, std::shared_ptr<RenderRecord>> AppRunningRecord::GetRenderRecordMap()
1792 {
1793     std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1794     return renderRecordMap_;
1795 }
1796 
SetStartMsg(const AppSpawnStartMsg & msg)1797 void AppRunningRecord::SetStartMsg(const AppSpawnStartMsg &msg)
1798 {
1799     startMsg_ = msg;
1800 }
1801 
GetStartMsg()1802 AppSpawnStartMsg AppRunningRecord::GetStartMsg()
1803 {
1804     return startMsg_;
1805 }
1806 
SetDebugApp(bool isDebugApp)1807 void AppRunningRecord::SetDebugApp(bool isDebugApp)
1808 {
1809     TAG_LOGD(AAFwkTag::APPMGR, "value is %{public}d", isDebugApp);
1810     isDebugApp_ = isDebugApp;
1811 }
1812 
IsDebugApp()1813 bool AppRunningRecord::IsDebugApp()
1814 {
1815     return isDebugApp_;
1816 }
1817 
SetNativeDebug(bool isNativeDebug)1818 void AppRunningRecord::SetNativeDebug(bool isNativeDebug)
1819 {
1820     TAG_LOGD(AAFwkTag::APPMGR, "SetNativeDebug, value is %{public}d", isNativeDebug);
1821     isNativeDebug_ = isNativeDebug;
1822 }
1823 
SetPerfCmd(const std::string & perfCmd)1824 void AppRunningRecord::SetPerfCmd(const std::string &perfCmd)
1825 {
1826     perfCmd_ = perfCmd;
1827 }
1828 
SetErrorInfoEnhance(bool errorInfoEnhance)1829 void AppRunningRecord::SetErrorInfoEnhance(bool errorInfoEnhance)
1830 {
1831     isErrorInfoEnhance_ = errorInfoEnhance;
1832 }
1833 
SetMultiThread(bool multiThread)1834 void AppRunningRecord::SetMultiThread(bool multiThread)
1835 {
1836     isMultiThread_ = multiThread;
1837 }
1838 
SetAppIndex(const int32_t appIndex)1839 void AppRunningRecord::SetAppIndex(const int32_t appIndex)
1840 {
1841     appIndex_ = appIndex;
1842 }
1843 
GetSplitModeAndFloatingMode(bool & isSplitScreenMode,bool & isFloatingWindowMode)1844 void AppRunningRecord::GetSplitModeAndFloatingMode(bool &isSplitScreenMode, bool &isFloatingWindowMode)
1845 {
1846     auto abilitiesMap = GetAbilities();
1847     isSplitScreenMode = false;
1848     isFloatingWindowMode = false;
1849     for (const auto &item : abilitiesMap) {
1850         const auto &abilityRecord = item.second;
1851         if (abilityRecord == nullptr) {
1852             continue;
1853         }
1854         const auto &abilityWant = abilityRecord->GetWant();
1855         if (abilityWant != nullptr) {
1856             int windowMode = abilityWant->GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1);
1857             if (windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING) {
1858                 isFloatingWindowMode = true;
1859             }
1860             if (windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY ||
1861                 windowMode == AAFwk::AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY) {
1862                 isSplitScreenMode = true;
1863             }
1864         }
1865         if (isFloatingWindowMode && isSplitScreenMode) {
1866             break;
1867         }
1868     }
1869 }
1870 
GetAppIndex() const1871 int32_t AppRunningRecord::GetAppIndex() const
1872 {
1873     return appIndex_;
1874 }
1875 
SetSecurityFlag(bool securityFlag)1876 void AppRunningRecord::SetSecurityFlag(bool securityFlag)
1877 {
1878     securityFlag_ = securityFlag;
1879 }
1880 
GetSecurityFlag() const1881 bool AppRunningRecord::GetSecurityFlag() const
1882 {
1883     return securityFlag_;
1884 }
1885 
SetKilling()1886 void AppRunningRecord::SetKilling()
1887 {
1888     isKilling_ = true;
1889 }
1890 
IsKilling() const1891 bool AppRunningRecord::IsKilling() const
1892 {
1893     return isKilling_;
1894 }
1895 
NeedUpdateConfigurationBackground()1896 bool AppRunningRecord::NeedUpdateConfigurationBackground()
1897 {
1898     bool needUpdate = false;
1899     auto abilitiesMap = GetAbilities();
1900     for (const auto &item : abilitiesMap) {
1901         const auto &abilityRecord = item.second;
1902         if (!abilityRecord || !abilityRecord->GetAbilityInfo()) {
1903             continue;
1904         }
1905         if (abilityRecord->GetAbilityInfo()->type != AppExecFwk::AbilityType::PAGE &&
1906             !(AAFwk::UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo()->extensionAbilityType))) {
1907             needUpdate = true;
1908             break;
1909         }
1910     }
1911     return needUpdate;
1912 }
1913 
RemoveTerminateAbilityTimeoutTask(const sptr<IRemoteObject> & token) const1914 void AppRunningRecord::RemoveTerminateAbilityTimeoutTask(const sptr<IRemoteObject>& token) const
1915 {
1916     auto moduleRecord = GetModuleRunningRecordByToken(token);
1917     if (!moduleRecord) {
1918         TAG_LOGE(AAFwkTag::APPMGR, "can not find module record");
1919         return;
1920     }
1921     (void)moduleRecord->RemoveTerminateAbilityTimeoutTask(token);
1922 }
1923 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)1924 int32_t AppRunningRecord::NotifyLoadRepairPatch(const std::string &bundleName, const sptr<IQuickFixCallback> &callback,
1925     const int32_t recordId)
1926 {
1927     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1928     TAG_LOGD(AAFwkTag::APPMGR, "called");
1929     if (!appLifeCycleDeal_) {
1930         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1931         return ERR_INVALID_VALUE;
1932     }
1933     return appLifeCycleDeal_->NotifyLoadRepairPatch(bundleName, callback, recordId);
1934 }
1935 
NotifyHotReloadPage(const sptr<IQuickFixCallback> & callback,const int32_t recordId)1936 int32_t AppRunningRecord::NotifyHotReloadPage(const sptr<IQuickFixCallback> &callback, const int32_t recordId)
1937 {
1938     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1939     TAG_LOGD(AAFwkTag::APPMGR, "called");
1940     if (!appLifeCycleDeal_) {
1941         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1942         return ERR_INVALID_VALUE;
1943     }
1944     return appLifeCycleDeal_->NotifyHotReloadPage(callback, recordId);
1945 }
1946 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback,const int32_t recordId)1947 int32_t AppRunningRecord::NotifyUnLoadRepairPatch(const std::string &bundleName,
1948     const sptr<IQuickFixCallback> &callback, const int32_t recordId)
1949 {
1950     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1951     TAG_LOGD(AAFwkTag::APPMGR, "called");
1952     if (!appLifeCycleDeal_) {
1953         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1954         return ERR_INVALID_VALUE;
1955     }
1956     return appLifeCycleDeal_->NotifyUnLoadRepairPatch(bundleName, callback, recordId);
1957 }
1958 
NotifyAppFault(const FaultData & faultData)1959 int32_t AppRunningRecord::NotifyAppFault(const FaultData &faultData)
1960 {
1961     TAG_LOGD(AAFwkTag::APPMGR, "called");
1962     if (!appLifeCycleDeal_) {
1963         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1964         return ERR_INVALID_VALUE;
1965     }
1966     return appLifeCycleDeal_->NotifyAppFault(faultData);
1967 }
1968 
IsAbilitytiesBackground()1969 bool AppRunningRecord::IsAbilitytiesBackground()
1970 {
1971     std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1972     for (const auto &iter : hapModules_) {
1973         for (const auto &moduleRecord : iter.second) {
1974             if (moduleRecord == nullptr) {
1975                 TAG_LOGE(AAFwkTag::APPMGR, "Module record null");
1976                 continue;
1977             }
1978             if (!moduleRecord->IsAbilitiesBackgrounded()) {
1979                 return false;
1980             }
1981         }
1982     }
1983     return true;
1984 }
1985 
OnWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)1986 void AppRunningRecord::OnWindowVisibilityChanged(
1987     const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
1988 {
1989     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1990     TAG_LOGD(AAFwkTag::APPMGR, "called");
1991     AddAppLifecycleEvent("AppRunningRecord::OnWindowVisibilityChanged");
1992     if (windowVisibilityInfos.empty()) {
1993         TAG_LOGW(AAFwkTag::APPMGR, "Window visibility info is empty.");
1994         return;
1995     }
1996 
1997     for (const auto &info : windowVisibilityInfos) {
1998         if (info == nullptr) {
1999             TAG_LOGE(AAFwkTag::APPMGR, "Window visibility info null");
2000             continue;
2001         }
2002         if (info->pid_ != GetPriorityObject()->GetPid()) {
2003             continue;
2004         }
2005         auto iter = windowIds_.find(info->windowId_);
2006         if (iter != windowIds_.end() &&
2007             info->visibilityState_ == OHOS::Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_TOTALLY_OCCUSION) {
2008             windowIds_.erase(iter);
2009             continue;
2010         }
2011         if (iter == windowIds_.end() &&
2012             info->visibilityState_ < OHOS::Rosen::WindowVisibilityState::WINDOW_VISIBILITY_STATE_TOTALLY_OCCUSION) {
2013             windowIds_.emplace(info->windowId_);
2014         }
2015     }
2016 
2017     TAG_LOGI(AAFwkTag::APPMGR, "window id empty: %{public}d, pState: %{public}d, cState: %{public}d",
2018         windowIds_.empty(), pendingState_, curState_);
2019     if (pendingState_ == ApplicationPendingState::READY) {
2020         if (!windowIds_.empty() && curState_ != ApplicationState::APP_STATE_FOREGROUND) {
2021             SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING);
2022             ScheduleForegroundRunning();
2023         }
2024         if (windowIds_.empty() && IsAbilitytiesBackground() && curState_ == ApplicationState::APP_STATE_FOREGROUND) {
2025             SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING);
2026             ScheduleBackgroundRunning();
2027         }
2028     } else {
2029         TAG_LOGI(AAFwkTag::APPMGR, "pending state is not READY.");
2030         if (!windowIds_.empty()) {
2031             SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING);
2032         }
2033         if (windowIds_.empty() && IsAbilitytiesBackground() && foregroundingAbilityTokens_.empty()) {
2034             SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING);
2035         }
2036     }
2037 }
2038 
IsContinuousTask()2039 bool AppRunningRecord::IsContinuousTask()
2040 {
2041     return isContinuousTask_;
2042 }
2043 
SetContinuousTaskAppState(bool isContinuousTask)2044 void AppRunningRecord::SetContinuousTaskAppState(bool isContinuousTask)
2045 {
2046     isContinuousTask_ = isContinuousTask;
2047 }
2048 
GetFocusFlag() const2049 bool AppRunningRecord::GetFocusFlag() const
2050 {
2051     return isFocused_;
2052 }
2053 
GetAppStartTime() const2054 int64_t AppRunningRecord::GetAppStartTime() const
2055 {
2056     return startTimeMillis_;
2057 }
2058 
SetRequestProcCode(int32_t requestProcCode)2059 void AppRunningRecord::SetRequestProcCode(int32_t requestProcCode)
2060 {
2061     requestProcCode_ = requestProcCode;
2062 }
2063 
GetRequestProcCode() const2064 int32_t AppRunningRecord::GetRequestProcCode() const
2065 {
2066     return requestProcCode_;
2067 }
2068 
SetProcessChangeReason(ProcessChangeReason reason)2069 void AppRunningRecord::SetProcessChangeReason(ProcessChangeReason reason)
2070 {
2071     processChangeReason_ = reason;
2072 }
2073 
GetProcessChangeReason() const2074 ProcessChangeReason AppRunningRecord::GetProcessChangeReason() const
2075 {
2076     return processChangeReason_;
2077 }
2078 
GetExtensionType() const2079 ExtensionAbilityType AppRunningRecord::GetExtensionType() const
2080 {
2081     return extensionType_;
2082 }
2083 
GetProcessType() const2084 ProcessType AppRunningRecord::GetProcessType() const
2085 {
2086     return processType_;
2087 }
2088 
GetChildAppRecordMap() const2089 std::map<pid_t, std::weak_ptr<AppRunningRecord>> AppRunningRecord::GetChildAppRecordMap() const
2090 {
2091     return childAppRecordMap_;
2092 }
2093 
AddChildAppRecord(pid_t pid,std::shared_ptr<AppRunningRecord> appRecord)2094 void AppRunningRecord::AddChildAppRecord(pid_t pid, std::shared_ptr<AppRunningRecord> appRecord)
2095 {
2096     childAppRecordMap_[pid] = appRecord;
2097 }
2098 
RemoveChildAppRecord(pid_t pid)2099 void AppRunningRecord::RemoveChildAppRecord(pid_t pid)
2100 {
2101     childAppRecordMap_.erase(pid);
2102 }
2103 
ClearChildAppRecordMap()2104 void AppRunningRecord::ClearChildAppRecordMap()
2105 {
2106     childAppRecordMap_.clear();
2107 }
2108 
SetParentAppRecord(std::shared_ptr<AppRunningRecord> appRecord)2109 void AppRunningRecord::SetParentAppRecord(std::shared_ptr<AppRunningRecord> appRecord)
2110 {
2111     parentAppRecord_ = appRecord;
2112 }
2113 
GetParentAppRecord()2114 std::shared_ptr<AppRunningRecord> AppRunningRecord::GetParentAppRecord()
2115 {
2116     return parentAppRecord_.lock();
2117 }
2118 
ChangeAppGcState(const int32_t state)2119 int32_t AppRunningRecord::ChangeAppGcState(const int32_t state)
2120 {
2121     TAG_LOGD(AAFwkTag::APPMGR, "called");
2122     if (appLifeCycleDeal_ == nullptr) {
2123         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
2124         return ERR_INVALID_VALUE;
2125     }
2126     return appLifeCycleDeal_->ChangeAppGcState(state);
2127 }
2128 
SetAttachDebug(const bool & isAttachDebug)2129 void AppRunningRecord::SetAttachDebug(const bool &isAttachDebug)
2130 {
2131     TAG_LOGD(AAFwkTag::APPMGR, "called");
2132     isAttachDebug_ = isAttachDebug;
2133 
2134     if (appLifeCycleDeal_ == nullptr) {
2135         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
2136         return;
2137     }
2138     isAttachDebug_ ? appLifeCycleDeal_->AttachAppDebug() : appLifeCycleDeal_->DetachAppDebug();
2139 }
2140 
isAttachDebug() const2141 bool AppRunningRecord::isAttachDebug() const
2142 {
2143     return isAttachDebug_;
2144 }
2145 
SetApplicationPendingState(ApplicationPendingState pendingState)2146 void AppRunningRecord::SetApplicationPendingState(ApplicationPendingState pendingState)
2147 {
2148     pendingState_ = pendingState;
2149 }
2150 
GetApplicationPendingState() const2151 ApplicationPendingState AppRunningRecord::GetApplicationPendingState() const
2152 {
2153     return pendingState_;
2154 }
2155 
SetApplicationScheduleState(ApplicationScheduleState scheduleState)2156 void AppRunningRecord::SetApplicationScheduleState(ApplicationScheduleState scheduleState)
2157 {
2158     scheduleState_ = scheduleState;
2159 }
2160 
GetApplicationScheduleState() const2161 ApplicationScheduleState AppRunningRecord::GetApplicationScheduleState() const
2162 {
2163     return scheduleState_;
2164 }
2165 
AddChildProcessRecord(pid_t pid,const std::shared_ptr<ChildProcessRecord> record)2166 void AppRunningRecord::AddChildProcessRecord(pid_t pid, const std::shared_ptr<ChildProcessRecord> record)
2167 {
2168     if (!record) {
2169         TAG_LOGE(AAFwkTag::APPMGR, "record null.");
2170         return;
2171     }
2172     if (pid <= 0) {
2173         TAG_LOGE(AAFwkTag::APPMGR, "pid <= 0.");
2174         return;
2175     }
2176     std::lock_guard lock(childProcessRecordMapLock_);
2177     childProcessRecordMap_.emplace(pid, record);
2178 }
2179 
RemoveChildProcessRecord(const std::shared_ptr<ChildProcessRecord> record)2180 void AppRunningRecord::RemoveChildProcessRecord(const std::shared_ptr<ChildProcessRecord> record)
2181 {
2182     TAG_LOGI(AAFwkTag::APPMGR, "pid: %{public}d", record->GetPid());
2183     if (!record) {
2184         TAG_LOGE(AAFwkTag::APPMGR, "record null.");
2185         return;
2186     }
2187     auto pid = record->GetPid();
2188     if (pid <= 0) {
2189         TAG_LOGE(AAFwkTag::APPMGR, "record.pid <= 0.");
2190         return;
2191     }
2192     std::lock_guard lock(childProcessRecordMapLock_);
2193     childProcessRecordMap_.erase(pid);
2194 }
2195 
GetChildProcessRecordByPid(const pid_t pid)2196 std::shared_ptr<ChildProcessRecord> AppRunningRecord::GetChildProcessRecordByPid(const pid_t pid)
2197 {
2198     std::lock_guard lock(childProcessRecordMapLock_);
2199     auto iter = childProcessRecordMap_.find(pid);
2200     if (iter == childProcessRecordMap_.end()) {
2201         return nullptr;
2202     }
2203     return iter->second;
2204 }
2205 
GetChildProcessRecordMap()2206 std::map<int32_t, std::shared_ptr<ChildProcessRecord>> AppRunningRecord::GetChildProcessRecordMap()
2207 {
2208     std::lock_guard lock(childProcessRecordMapLock_);
2209     return childProcessRecordMap_;
2210 }
2211 
GetChildProcessCount()2212 int32_t AppRunningRecord::GetChildProcessCount()
2213 {
2214     std::lock_guard lock(childProcessRecordMapLock_);
2215     return childProcessRecordMap_.size();
2216 }
2217 
SetJITEnabled(const bool jitEnabled)2218 void AppRunningRecord::SetJITEnabled(const bool jitEnabled)
2219 {
2220     jitEnabled_ = jitEnabled;
2221 }
2222 
IsJITEnabled() const2223 bool AppRunningRecord::IsJITEnabled() const
2224 {
2225     return jitEnabled_;
2226 }
2227 
SetPreloadState(PreloadState state)2228 void AppRunningRecord::SetPreloadState(PreloadState state)
2229 {
2230     preloadState_ = state;
2231 }
2232 
IsPreloading() const2233 bool AppRunningRecord::IsPreloading() const
2234 {
2235     return preloadState_ == PreloadState::PRELOADING;
2236 }
2237 
IsPreloaded() const2238 bool AppRunningRecord::IsPreloaded() const
2239 {
2240     return preloadState_ == PreloadState::PRELOADED;
2241 }
2242 
GetAssignTokenId() const2243 int32_t AppRunningRecord::GetAssignTokenId() const
2244 {
2245     return assignTokenId_;
2246 }
2247 
SetAssignTokenId(int32_t assignTokenId)2248 void AppRunningRecord::SetAssignTokenId(int32_t assignTokenId)
2249 {
2250     assignTokenId_ = assignTokenId;
2251 }
2252 
SetRestartAppFlag(bool isRestartApp)2253 void AppRunningRecord::SetRestartAppFlag(bool isRestartApp)
2254 {
2255     isRestartApp_ = isRestartApp;
2256 }
2257 
GetRestartAppFlag() const2258 bool AppRunningRecord::GetRestartAppFlag() const
2259 {
2260     return isRestartApp_;
2261 }
2262 
SetAssertionPauseFlag(bool flag)2263 void AppRunningRecord::SetAssertionPauseFlag(bool flag)
2264 {
2265     isAssertPause_ = flag;
2266 }
2267 
IsAssertionPause() const2268 bool AppRunningRecord::IsAssertionPause() const
2269 {
2270     return isAssertPause_;
2271 }
2272 
IsDebugging() const2273 bool AppRunningRecord::IsDebugging() const
2274 {
2275     return isDebugApp_ || isAssertPause_;
2276 }
2277 
SetNativeStart(bool isNativeStart)2278 void AppRunningRecord::SetNativeStart(bool isNativeStart)
2279 {
2280     isNativeStart_ = isNativeStart;
2281 }
2282 
isNativeStart() const2283 bool AppRunningRecord::isNativeStart() const
2284 {
2285     return isNativeStart_;
2286 }
2287 
SetExitReason(int32_t reason)2288 void AppRunningRecord::SetExitReason(int32_t reason)
2289 {
2290     exitReason_ = reason;
2291 }
2292 
GetExitReason() const2293 int32_t AppRunningRecord::GetExitReason() const
2294 {
2295     return exitReason_;
2296 }
2297 
SetExitMsg(const std::string & exitMsg)2298 void AppRunningRecord::SetExitMsg(const std::string &exitMsg)
2299 {
2300     exitMsg_ = exitMsg;
2301 }
2302 
GetExitMsg() const2303 std::string AppRunningRecord::GetExitMsg() const
2304 {
2305     return exitMsg_;
2306 }
2307 
DumpIpcStart(std::string & result)2308 int AppRunningRecord::DumpIpcStart(std::string& result)
2309 {
2310     TAG_LOGD(AAFwkTag::APPMGR, "called");
2311     if (appLifeCycleDeal_ == nullptr) {
2312         result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
2313             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2314             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2315         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
2316         return DumpErrorCode::ERR_INTERNAL_ERROR;
2317     }
2318     return appLifeCycleDeal_->DumpIpcStart(result);
2319 }
2320 
DumpIpcStop(std::string & result)2321 int AppRunningRecord::DumpIpcStop(std::string& result)
2322 {
2323     TAG_LOGD(AAFwkTag::APPMGR, "called");
2324     if (appLifeCycleDeal_ == nullptr) {
2325         result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
2326             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2327             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2328         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
2329         return DumpErrorCode::ERR_INTERNAL_ERROR;
2330     }
2331     return appLifeCycleDeal_->DumpIpcStop(result);
2332 }
2333 
DumpIpcStat(std::string & result)2334 int AppRunningRecord::DumpIpcStat(std::string& result)
2335 {
2336     TAG_LOGD(AAFwkTag::APPMGR, "called");
2337     if (appLifeCycleDeal_ == nullptr) {
2338         result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
2339             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2340             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2341         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
2342         return DumpErrorCode::ERR_INTERNAL_ERROR;
2343     }
2344     return appLifeCycleDeal_->DumpIpcStat(result);
2345 }
2346 
DumpFfrt(std::string & result)2347 int AppRunningRecord::DumpFfrt(std::string& result)
2348 {
2349     TAG_LOGD(AAFwkTag::APPMGR, "called");
2350     if (appLifeCycleDeal_ == nullptr) {
2351         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
2352             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
2353         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
2354         return DumpErrorCode::ERR_INTERNAL_ERROR;
2355     }
2356     return appLifeCycleDeal_->DumpFfrt(result);
2357 }
2358 
SetSupportedProcessCache(bool isSupport)2359 bool AppRunningRecord::SetSupportedProcessCache(bool isSupport)
2360 {
2361     TAG_LOGI(AAFwkTag::APPMGR, "Called");
2362     procCacheSupportState_ = isSupport ? SupportProcessCacheState::SUPPORT : SupportProcessCacheState::NOT_SUPPORT;
2363     return true;
2364 }
2365 
SetEnableProcessCache(bool enable)2366 bool AppRunningRecord::SetEnableProcessCache(bool enable)
2367 {
2368     TAG_LOGI(AAFwkTag::APPMGR, "call");
2369     enableProcessCache_ = enable;
2370     return true;
2371 }
2372 
GetEnableProcessCache()2373 bool AppRunningRecord::GetEnableProcessCache()
2374 {
2375     return enableProcessCache_;
2376 }
2377 
GetSupportProcessCacheState()2378 SupportProcessCacheState AppRunningRecord::GetSupportProcessCacheState()
2379 {
2380     return procCacheSupportState_;
2381 }
2382 
ScheduleCacheProcess()2383 void AppRunningRecord::ScheduleCacheProcess()
2384 {
2385     if (appLifeCycleDeal_ == nullptr) {
2386         TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
2387         return;
2388     }
2389     appLifeCycleDeal_->ScheduleCacheProcess();
2390 }
2391 
CancelTask(std::string msg)2392 bool AppRunningRecord::CancelTask(std::string msg)
2393 {
2394     if (!taskHandler_) {
2395         TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
2396         return false;
2397     }
2398     return taskHandler_->CancelTask(msg);
2399 }
2400 
SetBrowserHost(sptr<IRemoteObject> browser)2401 void AppRunningRecord::SetBrowserHost(sptr<IRemoteObject> browser)
2402 {
2403     browserHost_ = browser;
2404 }
2405 
GetBrowserHost()2406 sptr<IRemoteObject> AppRunningRecord::GetBrowserHost()
2407 {
2408     return browserHost_;
2409 }
2410 
SetIsGPU(bool gpu)2411 void AppRunningRecord::SetIsGPU(bool gpu)
2412 {
2413     if (gpu) {
2414         isGPU_ = gpu;
2415     }
2416 }
2417 
GetIsGPU()2418 bool AppRunningRecord::GetIsGPU()
2419 {
2420     return isGPU_;
2421 }
2422 
SetGPUPid(pid_t gpuPid)2423 void AppRunningRecord::SetGPUPid(pid_t gpuPid)
2424 {
2425     gpuPid_ = gpuPid;
2426 }
2427 
GetGPUPid()2428 pid_t AppRunningRecord::GetGPUPid()
2429 {
2430     return gpuPid_;
2431 }
2432 
SetAttachedToStatusBar(bool isAttached)2433 void AppRunningRecord::SetAttachedToStatusBar(bool isAttached)
2434 {
2435     isAttachedToStatusBar = isAttached;
2436 }
2437 
IsAttachedToStatusBar()2438 bool AppRunningRecord::IsAttachedToStatusBar()
2439 {
2440     return isAttachedToStatusBar;
2441 }
2442 
SetProcessCacheBlocked(bool isBlocked)2443 void AppRunningRecord::SetProcessCacheBlocked(bool isBlocked)
2444 {
2445     processCacheBlocked = isBlocked;
2446 }
2447 
GetProcessCacheBlocked()2448 bool AppRunningRecord::GetProcessCacheBlocked()
2449 {
2450     return processCacheBlocked;
2451 }
2452 
IsAllAbilityReadyToCleanedByUserRequest()2453 bool AppRunningRecord::IsAllAbilityReadyToCleanedByUserRequest()
2454 {
2455     std::lock_guard<ffrt::mutex> lock(hapModulesLock_);
2456     for (const auto &iter : hapModules_) {
2457         for (const auto &moduleRecord : iter.second) {
2458             if (moduleRecord == nullptr) {
2459                 TAG_LOGE(AAFwkTag::APPMGR, "Module record null");
2460                 continue;
2461             }
2462             if (!moduleRecord->IsAllAbilityReadyToCleanedByUserRequest()) {
2463                 return false;
2464             }
2465         }
2466     }
2467     return true;
2468 }
2469 
SetUserRequestCleaning()2470 void AppRunningRecord::SetUserRequestCleaning()
2471 {
2472     isUserRequestCleaning_ = true;
2473 }
2474 
IsUserRequestCleaning() const2475 bool AppRunningRecord::IsUserRequestCleaning() const
2476 {
2477     return isUserRequestCleaning_;
2478 }
2479 
IsProcessAttached() const2480 bool AppRunningRecord::IsProcessAttached() const
2481 {
2482     if (appLifeCycleDeal_ == nullptr) {
2483         return false;
2484     }
2485     return appLifeCycleDeal_->GetApplicationClient() != nullptr;
2486 }
2487 
SetUIAbilityLaunched(bool hasLaunched)2488 void AppRunningRecord::SetUIAbilityLaunched(bool hasLaunched)
2489 {
2490     hasUIAbilityLaunched_ = hasLaunched;
2491 }
2492 
HasUIAbilityLaunched()2493 bool AppRunningRecord::HasUIAbilityLaunched()
2494 {
2495     return hasUIAbilityLaunched_;
2496 }
2497 
SetProcessCaching(bool isCaching)2498 void AppRunningRecord::SetProcessCaching(bool isCaching)
2499 {
2500     isCaching_ = isCaching;
2501 }
2502 
IsCaching()2503 bool AppRunningRecord::IsCaching()
2504 {
2505     return isCaching_;
2506 }
2507 
AddAppLifecycleEvent(const std::string & msg)2508 void AppRunningRecord::AddAppLifecycleEvent(const std::string &msg)
2509 {
2510     auto prioObject = GetPriorityObject();
2511     if (prioObject && prioObject->GetPid() != 0) {
2512         FreezeUtil::GetInstance().AddAppLifecycleEvent(prioObject->GetPid(), msg);
2513     }
2514 }
2515 
SetNWebPreload(const bool isAllowedNWebPreload)2516 void AppRunningRecord::SetNWebPreload(const bool isAllowedNWebPreload)
2517 {
2518     isAllowedNWebPreload_ = isAllowedNWebPreload;
2519 }
2520 }  // namespace AppExecFwk
2521 }  // namespace OHOS
2522