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