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
Insert(const int32_t userId,const Configuration & config)199 void MultiUserConfigurationMgr::Insert(const int32_t userId, const Configuration& config)
200 {
201 std::lock_guard<std::mutex> guard(multiUserConfigurationMutex_);
202 auto it = multiUserConfiguration_.find(userId);
203 if (it != multiUserConfiguration_.end()) {
204 std::vector<std::string> diffVe;
205 it->second.CompareDifferent(diffVe, config);
206 it->second.Merge(diffVe, config);
207 } else {
208 multiUserConfiguration_[userId] = config;
209 }
210 }
211
GetConfigurationByUserId(const int32_t userId)212 Configuration MultiUserConfigurationMgr::GetConfigurationByUserId(const int32_t userId)
213 {
214 std::lock_guard<std::mutex> guard(multiUserConfigurationMutex_);
215 auto it = multiUserConfiguration_.find(userId);
216 if (it == multiUserConfiguration_.end()) {
217 return {};
218 }
219 return it->second;
220 }
221
AppRunningRecord(const std::shared_ptr<ApplicationInfo> & info,const int32_t recordId,const std::string & processName)222 AppRunningRecord::AppRunningRecord(
223 const std::shared_ptr<ApplicationInfo> &info, const int32_t recordId, const std::string &processName)
224 : appRecordId_(recordId), processName_(processName)
225 {
226 if (info) {
227 appInfo_ = info;
228 mainBundleName_ = info->bundleName;
229 isLauncherApp_ = info->isLauncherApp;
230 mainAppName_ = info->name;
231 }
232 priorityObject_ = std::make_shared<PriorityObject>();
233
234 struct timespec t;
235 t.tv_sec = 0;
236 t.tv_nsec = 0;
237 clock_gettime(CLOCK_MONOTONIC, &t);
238 startTimeMillis_ = static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS);
239 }
240
SetApplicationClient(const sptr<IAppScheduler> & thread)241 void AppRunningRecord::SetApplicationClient(const sptr<IAppScheduler> &thread)
242 {
243 if (!appLifeCycleDeal_) {
244 appLifeCycleDeal_ = std::make_shared<AppLifeCycleDeal>();
245 }
246 appLifeCycleDeal_->SetApplicationClient(thread);
247
248 auto moduleRecordList = GetAllModuleRecord();
249 if (moduleRecordList.empty()) {
250 TAG_LOGD(AAFwkTag::APPMGR, "moduleRecordList is empty");
251 return;
252 }
253 for (const auto &moduleRecord : moduleRecordList) {
254 moduleRecord->SetApplicationClient(appLifeCycleDeal_);
255 }
256 }
257
GetBundleName() const258 const std::string &AppRunningRecord::GetBundleName() const
259 {
260 return mainBundleName_;
261 }
262
GetCallerPid() const263 int32_t AppRunningRecord::GetCallerPid() const
264 {
265 return callerPid_;
266 }
267
SetCallerPid(int32_t pid)268 void AppRunningRecord::SetCallerPid(int32_t pid)
269 {
270 callerPid_ = pid;
271 }
272
GetCallerUid() const273 int32_t AppRunningRecord::GetCallerUid() const
274 {
275 return callerUid_;
276 }
277
SetCallerUid(int32_t uid)278 void AppRunningRecord::SetCallerUid(int32_t uid)
279 {
280 callerUid_ = uid;
281 }
282
GetCallerTokenId() const283 int32_t AppRunningRecord::GetCallerTokenId() const
284 {
285 return callerTokenId_;
286 }
287
SetCallerTokenId(int32_t tokenId)288 void AppRunningRecord::SetCallerTokenId(int32_t tokenId)
289 {
290 callerTokenId_ = tokenId;
291 }
292
IsLauncherApp() const293 bool AppRunningRecord::IsLauncherApp() const
294 {
295 return isLauncherApp_;
296 }
297
GetRecordId() const298 int32_t AppRunningRecord::GetRecordId() const
299 {
300 return appRecordId_;
301 }
302
GetName() const303 const std::string &AppRunningRecord::GetName() const
304 {
305 return mainAppName_;
306 }
307
GetSignCode() const308 const std::string &AppRunningRecord::GetSignCode() const
309 {
310 return signCode_;
311 }
312
SetSignCode(const std::string & signCode)313 void AppRunningRecord::SetSignCode(const std::string &signCode)
314 {
315 signCode_ = signCode;
316 }
317
GetJointUserId() const318 const std::string &AppRunningRecord::GetJointUserId() const
319 {
320 return jointUserId_;
321 }
322
SetJointUserId(const std::string & jointUserId)323 void AppRunningRecord::SetJointUserId(const std::string &jointUserId)
324 {
325 jointUserId_ = jointUserId;
326 }
327
GetProcessName() const328 const std::string &AppRunningRecord::GetProcessName() const
329 {
330 return processName_;
331 }
332
SetSpecifiedProcessFlag(const std::string & flag)333 void AppRunningRecord::SetSpecifiedProcessFlag(const std::string &flag)
334 {
335 specifiedProcessFlag_ = flag;
336 }
337
GetSpecifiedProcessFlag() const338 const std::string &AppRunningRecord::GetSpecifiedProcessFlag() const
339 {
340 return specifiedProcessFlag_;
341 }
342
GetUid() const343 int32_t AppRunningRecord::GetUid() const
344 {
345 return mainUid_;
346 }
347
SetUid(const int32_t uid)348 void AppRunningRecord::SetUid(const int32_t uid)
349 {
350 mainUid_ = uid;
351 }
352
GetUserId() const353 int32_t AppRunningRecord::GetUserId() const
354 {
355 return mainUid_ / BASE_USER_RANGE;
356 }
357
GetState() const358 ApplicationState AppRunningRecord::GetState() const
359 {
360 return curState_;
361 }
362
SetState(const ApplicationState state)363 void AppRunningRecord::SetState(const ApplicationState state)
364 {
365 if (state >= ApplicationState::APP_STATE_END && state != ApplicationState::APP_STATE_CACHED) {
366 TAG_LOGE(AAFwkTag::APPMGR, "Invalid application state");
367 return;
368 }
369 if (state == ApplicationState::APP_STATE_FOREGROUND || state == ApplicationState::APP_STATE_BACKGROUND) {
370 restartResidentProcCount_ = MAX_RESTART_COUNT;
371 }
372 curState_ = state;
373 }
374
SetRestartTimeMillis(const int64_t restartTimeMillis)375 void AppRunningRecord::SetRestartTimeMillis(const int64_t restartTimeMillis)
376 {
377 restartTimeMillis_ = restartTimeMillis;
378 }
379
GetAppInfoList()380 const std::list<std::shared_ptr<ApplicationInfo>> AppRunningRecord::GetAppInfoList()
381 {
382 std::list<std::shared_ptr<ApplicationInfo>> appInfoList;
383 std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
384 for (const auto &item : appInfos_) {
385 appInfoList.push_back(item.second);
386 }
387 return appInfoList;
388 }
389
SetAppIdentifier(const std::string & appIdentifier)390 void AppRunningRecord::SetAppIdentifier(const std::string &appIdentifier)
391 {
392 appIdentifier_ = appIdentifier;
393 }
394
GetAppIdentifier() const395 const std::string &AppRunningRecord::GetAppIdentifier() const
396 {
397 return appIdentifier_;
398 }
399
GetAbilities()400 const std::map<const sptr<IRemoteObject>, std::shared_ptr<AbilityRunningRecord>> AppRunningRecord::GetAbilities()
401 {
402 std::map<const sptr<IRemoteObject>, std::shared_ptr<AbilityRunningRecord>> abilitysMap;
403 auto moduleRecordList = GetAllModuleRecord();
404 for (const auto &moduleRecord : moduleRecordList) {
405 auto abilities = moduleRecord->GetAbilities();
406 abilitysMap.insert(abilities.begin(), abilities.end());
407 }
408 return abilitysMap;
409 }
410
GetApplicationClient() const411 sptr<IAppScheduler> AppRunningRecord::GetApplicationClient() const
412 {
413 return (appLifeCycleDeal_ ? appLifeCycleDeal_->GetApplicationClient() : nullptr);
414 }
415
GetAbilityRunningRecord(const int64_t eventId) const416 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecord(const int64_t eventId) const
417 {
418 TAG_LOGD(AAFwkTag::APPMGR, "called");
419 auto moduleRecordList = GetAllModuleRecord();
420 for (const auto &moduleRecord : moduleRecordList) {
421 auto abilityRecord = moduleRecord->GetAbilityRunningRecord(eventId);
422 if (abilityRecord) {
423 return abilityRecord;
424 }
425 }
426
427 return nullptr;
428 }
429
RemoveModuleRecord(const std::shared_ptr<ModuleRunningRecord> & moduleRecord,bool isExtensionDebug)430 void AppRunningRecord::RemoveModuleRecord(
431 const std::shared_ptr<ModuleRunningRecord> &moduleRecord, bool isExtensionDebug)
432 {
433 TAG_LOGD(AAFwkTag::APPMGR, "called");
434
435 std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
436 for (auto &item : hapModules_) {
437 auto iter = std::find_if(item.second.begin(),
438 item.second.end(),
439 [&moduleRecord](const std::shared_ptr<ModuleRunningRecord> &record) { return moduleRecord == record; });
440 if (iter != item.second.end()) {
441 TAG_LOGD(AAFwkTag::APPMGR, "Removed a record.");
442 iter = item.second.erase(iter);
443 if (item.second.empty() && !isExtensionDebug) {
444 {
445 std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
446 TAG_LOGD(AAFwkTag::APPMGR, "Removed an appInfo.");
447 appInfos_.erase(item.first);
448 }
449 hapModules_.erase(item.first);
450 }
451 return;
452 }
453 }
454 }
455
LaunchApplication(const Configuration & config)456 void AppRunningRecord::LaunchApplication(const Configuration &config)
457 {
458 HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
459 if (appLifeCycleDeal_ == nullptr) {
460 TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
461 return;
462 }
463 if (!appLifeCycleDeal_->GetApplicationClient()) {
464 TAG_LOGE(AAFwkTag::APPMGR, "appThread null");
465 return;
466 }
467 AppLaunchData launchData;
468 {
469 std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
470 auto moduleRecords = appInfos_.find(mainBundleName_);
471 if (moduleRecords != appInfos_.end()) {
472 launchData.SetApplicationInfo(*(moduleRecords->second));
473 }
474 }
475 ProcessInfo processInfo(processName_, GetPriorityObject()->GetPid());
476 processInfo.SetProcessType(processType_);
477 launchData.SetProcessInfo(processInfo);
478 launchData.SetRecordId(appRecordId_);
479 launchData.SetUId(mainUid_);
480 launchData.SetUserTestInfo(userTestRecord_);
481 launchData.SetAppIndex(appIndex_);
482 launchData.SetInstanceKey(instanceKey_);
483 launchData.SetDebugApp(isDebugApp_);
484 launchData.SetPerfCmd(perfCmd_);
485 launchData.SetErrorInfoEnhance(isErrorInfoEnhance_);
486 launchData.SetMultiThread(isMultiThread_);
487 launchData.SetJITEnabled(jitEnabled_);
488 launchData.SetNativeStart(isNativeStart_);
489 launchData.SetAppRunningUniqueId(std::to_string(startTimeMillis_));
490 launchData.SetIsNeedPreloadModule(isNeedPreloadModule_);
491 launchData.SetNWebPreload(isAllowedNWebPreload_);
492
493 TAG_LOGD(AAFwkTag::APPMGR, "%{public}s called,app is %{public}s.", __func__, GetName().c_str());
494 AddAppLifecycleEvent("AppRunningRecord::LaunchApplication");
495 appLifeCycleDeal_->LaunchApplication(launchData, config);
496 }
497
UpdateApplicationInfoInstalled(const ApplicationInfo & appInfo)498 void AppRunningRecord::UpdateApplicationInfoInstalled(const ApplicationInfo &appInfo)
499 {
500 if (!isStageBasedModel_) {
501 TAG_LOGI(AAFwkTag::APPMGR, "Current version than supports !");
502 return;
503 }
504
505 if (appLifeCycleDeal_ == nullptr) {
506 TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
507 return;
508 }
509 appLifeCycleDeal_->UpdateApplicationInfoInstalled(appInfo);
510 }
511
AddAbilityStage()512 void AppRunningRecord::AddAbilityStage()
513 {
514 if (!isStageBasedModel_) {
515 TAG_LOGI(AAFwkTag::APPMGR, "Current version than supports !");
516 return;
517 }
518 HapModuleInfo abilityStage;
519 if (GetTheModuleInfoNeedToUpdated(mainBundleName_, abilityStage)) {
520 SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG, AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT);
521 TAG_LOGI(AAFwkTag::APPMGR, "Current Informed module : [%{public}s] | bundle : [%{public}s]",
522 abilityStage.moduleName.c_str(), mainBundleName_.c_str());
523 if (appLifeCycleDeal_ == nullptr) {
524 TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
525 return;
526 }
527 appLifeCycleDeal_->AddAbilityStage(abilityStage);
528 }
529 }
530
AddAbilityStageBySpecifiedAbility(const std::string & bundleName)531 bool AppRunningRecord::AddAbilityStageBySpecifiedAbility(const std::string &bundleName)
532 {
533 if (!eventHandler_) {
534 TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
535 return false;
536 }
537
538 HapModuleInfo hapModuleInfo;
539 if (GetTheModuleInfoNeedToUpdated(bundleName, hapModuleInfo)) {
540 if (startProcessSpecifiedAbilityEventId_ == 0) {
541 TAG_LOGI(
542 AAFwkTag::APPMGR, "START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG not exist");
543 SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG,
544 AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT);
545 }
546 if (appLifeCycleDeal_ == nullptr) {
547 TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
548 return false;
549 }
550 appLifeCycleDeal_->AddAbilityStage(hapModuleInfo);
551 return true;
552 }
553 return false;
554 }
555
AddAbilityStageBySpecifiedProcess(const std::string & bundleName)556 void AppRunningRecord::AddAbilityStageBySpecifiedProcess(const std::string &bundleName)
557 {
558 TAG_LOGD(AAFwkTag::APPMGR, "call.");
559 if (!eventHandler_) {
560 TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
561 return;
562 }
563
564 HapModuleInfo hapModuleInfo;
565 if (GetTheModuleInfoNeedToUpdated(bundleName, hapModuleInfo)) {
566 SendEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG,
567 AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT);
568 if (appLifeCycleDeal_ == nullptr) {
569 TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
570 return;
571 }
572 appLifeCycleDeal_->AddAbilityStage(hapModuleInfo);
573 }
574 }
575
AddAbilityStageDone()576 void AppRunningRecord::AddAbilityStageDone()
577 {
578 TAG_LOGI(AAFwkTag::APPMGR, "bundle %{public}s and eventId %{public}d", mainBundleName_.c_str(),
579 static_cast<int>(eventId_));
580
581 if (!eventHandler_) {
582 TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
583 return;
584 }
585
586 if (startProcessSpecifiedAbilityEventId_ != 0) {
587 eventHandler_->RemoveEvent(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
588 startProcessSpecifiedAbilityEventId_);
589 startProcessSpecifiedAbilityEventId_ = 0;
590 }
591 if (addAbilityStageInfoEventId_ != 0) {
592 eventHandler_->RemoveEvent(AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG,
593 addAbilityStageInfoEventId_);
594 addAbilityStageInfoEventId_ = 0;
595 }
596 // Should proceed to the next notification
597
598 if (IsStartSpecifiedAbility()) {
599 ScheduleAcceptWant(moduleName_);
600 return;
601 }
602
603 if (IsNewProcessRequest()) {
604 TAG_LOGD(AAFwkTag::APPMGR, "ScheduleNewProcessRequest.");
605 ScheduleNewProcessRequest(GetNewProcessRequestWant(), moduleName_);
606 return;
607 }
608
609 AddAbilityStage();
610 }
611
LaunchAbility(const std::shared_ptr<AbilityRunningRecord> & ability)612 void AppRunningRecord::LaunchAbility(const std::shared_ptr<AbilityRunningRecord> &ability)
613 {
614 HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
615 if (appLifeCycleDeal_ == nullptr) {
616 TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
617 return;
618 }
619 if (!ability || !ability->GetToken()) {
620 TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord or abilityToken null");
621 return;
622 }
623
624 auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
625 if (!moduleRecord) {
626 TAG_LOGE(AAFwkTag::APPMGR, "moduleRecord null");
627 return;
628 }
629
630 moduleRecord->LaunchAbility(ability);
631 }
632
ScheduleTerminate()633 void AppRunningRecord::ScheduleTerminate()
634 {
635 SendEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT);
636 if (appLifeCycleDeal_ == nullptr) {
637 TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
638 return;
639 }
640 bool isLastProcess = false;
641 auto serviceInner = appMgrServiceInner_.lock();
642 if (serviceInner != nullptr) {
643 isLastProcess = serviceInner->IsFinalAppProcessByBundleName(GetBundleName());
644 }
645 appLifeCycleDeal_->ScheduleTerminate(isLastProcess);
646 }
647
LaunchPendingAbilities()648 void AppRunningRecord::LaunchPendingAbilities()
649 {
650 TAG_LOGI(AAFwkTag::APPMGR, "Launch pending abilities.");
651 AddAppLifecycleEvent("AppRunningRecord::LaunchPendingAbilities");
652 auto moduleRecordList = GetAllModuleRecord();
653 if (moduleRecordList.empty()) {
654 TAG_LOGE(AAFwkTag::APPMGR, "moduleRecordList is empty");
655 return;
656 }
657 for (const auto &moduleRecord : moduleRecordList) {
658 moduleRecord->SetApplicationClient(appLifeCycleDeal_);
659 moduleRecord->LaunchPendingAbilities();
660 }
661 }
ScheduleForegroundRunning()662 bool AppRunningRecord::ScheduleForegroundRunning()
663 {
664 SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_FOREGROUNDING);
665 if (appLifeCycleDeal_) {
666 AddAppLifecycleEvent("AppRunningRecord::ScheduleForegroundRunning");
667 return appLifeCycleDeal_->ScheduleForegroundRunning();
668 }
669 return false;
670 }
671
ScheduleBackgroundRunning()672 void AppRunningRecord::ScheduleBackgroundRunning()
673 {
674 SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_BACKGROUNDING);
675 int32_t recordId = GetRecordId();
676 auto serviceInner = appMgrServiceInner_;
677 auto appbackgroundtask = [recordId, serviceInner]() {
678 auto serviceInnerObj = serviceInner.lock();
679 if (serviceInnerObj == nullptr) {
680 TAG_LOGW(AAFwkTag::APPMGR, "APPManager is invalid");
681 return;
682 }
683 TAG_LOGE(AAFwkTag::APPMGR, "APPManager move to background timeout");
684 serviceInnerObj->ApplicationBackgrounded(recordId);
685 };
686 auto taskName = std::string("appbackground_") + std::to_string(recordId);
687 if (taskHandler_) {
688 taskHandler_->CancelTask(taskName);
689 }
690 PostTask(taskName, AMSEventHandler::BACKGROUND_APPLICATION_TIMEOUT, appbackgroundtask);
691 if (appLifeCycleDeal_) {
692 AddAppLifecycleEvent("AppRunningRecord::ScheduleBackgroundRunning");
693 appLifeCycleDeal_->ScheduleBackgroundRunning();
694 }
695 isAbilityForegrounding_.store(false);
696 }
697
ScheduleProcessSecurityExit()698 void AppRunningRecord::ScheduleProcessSecurityExit()
699 {
700 if (appLifeCycleDeal_) {
701 auto appRecord = shared_from_this();
702 DelayedSingleton<CacheProcessManager>::GetInstance()->PrepareActivateCache(appRecord);
703 appLifeCycleDeal_->ScheduleProcessSecurityExit();
704 }
705 }
706
ScheduleClearPageStack()707 void AppRunningRecord::ScheduleClearPageStack()
708 {
709 if (appLifeCycleDeal_) {
710 appLifeCycleDeal_->ScheduleClearPageStack();
711 }
712 }
713
ScheduleTrimMemory()714 void AppRunningRecord::ScheduleTrimMemory()
715 {
716 if (appLifeCycleDeal_ && priorityObject_) {
717 appLifeCycleDeal_->ScheduleTrimMemory(priorityObject_->GetTimeLevel());
718 }
719 }
720
ScheduleMemoryLevel(int32_t level)721 void AppRunningRecord::ScheduleMemoryLevel(int32_t level)
722 {
723 if (appLifeCycleDeal_) {
724 appLifeCycleDeal_->ScheduleMemoryLevel(level);
725 }
726 }
727
ScheduleHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)728 void AppRunningRecord::ScheduleHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
729 {
730 if (appLifeCycleDeal_) {
731 appLifeCycleDeal_->ScheduleHeapMemory(pid, mallocInfo);
732 }
733 }
734
ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)735 void AppRunningRecord::ScheduleJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
736 {
737 if (appLifeCycleDeal_) {
738 appLifeCycleDeal_->ScheduleJsHeapMemory(info);
739 }
740 }
741
LowMemoryWarning()742 void AppRunningRecord::LowMemoryWarning()
743 {
744 if (appLifeCycleDeal_) {
745 appLifeCycleDeal_->LowMemoryWarning();
746 }
747 }
748
AddModules(const std::shared_ptr<ApplicationInfo> & appInfo,const std::vector<HapModuleInfo> & moduleInfos)749 void AppRunningRecord::AddModules(
750 const std::shared_ptr<ApplicationInfo> &appInfo, const std::vector<HapModuleInfo> &moduleInfos)
751 {
752 TAG_LOGD(AAFwkTag::APPMGR, "Add modules");
753
754 if (moduleInfos.empty()) {
755 TAG_LOGI(AAFwkTag::APPMGR, "moduleInfos is empty.");
756 return;
757 }
758
759 for (auto &iter : moduleInfos) {
760 AddModule(appInfo, nullptr, nullptr, iter, nullptr, 0);
761 }
762 }
763
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)764 void AppRunningRecord::AddModule(std::shared_ptr<ApplicationInfo> appInfo,
765 std::shared_ptr<AbilityInfo> abilityInfo, sptr<IRemoteObject> token,
766 const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, int32_t abilityRecordId)
767 {
768 TAG_LOGD(AAFwkTag::APPMGR, "called");
769
770 if (!appInfo) {
771 TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
772 return;
773 }
774
775 std::shared_ptr<ModuleRunningRecord> moduleRecord;
776
777 auto initModuleRecord = [&](const std::shared_ptr<ModuleRunningRecord> &moduleRecord) {
778 moduleRecord->Init(hapModuleInfo);
779 moduleRecord->SetAppIndex(appIndex_);
780 moduleRecord->SetAppMgrServiceInner(appMgrServiceInner_);
781 moduleRecord->SetApplicationClient(appLifeCycleDeal_);
782 };
783
784 std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
785 const auto &iter = hapModules_.find(appInfo->bundleName);
786 if (iter != hapModules_.end()) {
787 moduleRecord = GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
788 if (!moduleRecord) {
789 moduleRecord = std::make_shared<ModuleRunningRecord>(appInfo, eventHandler_);
790 iter->second.push_back(moduleRecord);
791 initModuleRecord(moduleRecord);
792 }
793 } else {
794 moduleRecord = std::make_shared<ModuleRunningRecord>(appInfo, eventHandler_);
795 std::vector<std::shared_ptr<ModuleRunningRecord>> moduleList;
796 moduleList.push_back(moduleRecord);
797 hapModules_.emplace(appInfo->bundleName, moduleList);
798 {
799 std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
800 appInfos_.emplace(appInfo->bundleName, appInfo);
801 }
802 initModuleRecord(moduleRecord);
803 }
804
805 if (!abilityInfo || !token) {
806 TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo or token null");
807 return;
808 }
809 moduleRecord->AddAbility(token, abilityInfo, want, abilityRecordId);
810
811 return;
812 }
813
GetModuleRecordByModuleName(const std::string bundleName,const std::string & moduleName)814 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRecordByModuleName(
815 const std::string bundleName, const std::string &moduleName)
816 {
817 TAG_LOGD(AAFwkTag::APPMGR, "called");
818 auto moduleRecords = hapModules_.find(bundleName);
819 if (moduleRecords != hapModules_.end()) {
820 for (auto &iter : moduleRecords->second) {
821 if (iter->GetModuleName() == moduleName) {
822 return iter;
823 }
824 }
825 }
826
827 return nullptr;
828 }
829
StateChangedNotifyObserver(const std::shared_ptr<AbilityRunningRecord> & ability,int32_t state,bool isAbility,bool isFromWindowFocusChanged)830 void AppRunningRecord::StateChangedNotifyObserver(const std::shared_ptr<AbilityRunningRecord> &ability,
831 int32_t state, bool isAbility, bool isFromWindowFocusChanged)
832 {
833 if (ability == nullptr) {
834 TAG_LOGE(AAFwkTag::APPMGR, "null ability");
835 return;
836 }
837 auto abilityInfo = ability->GetAbilityInfo();
838 if (abilityInfo == nullptr) {
839 TAG_LOGE(AAFwkTag::APPMGR, "null abilityInfo");
840 return;
841 }
842 AbilityStateData abilityStateData;
843 abilityStateData.bundleName = abilityInfo->applicationInfo.bundleName;
844 abilityStateData.moduleName = abilityInfo->moduleName;
845 abilityStateData.abilityName = ability->GetName();
846 abilityStateData.pid = GetPriorityObject()->GetPid();
847 abilityStateData.abilityState = state;
848 abilityStateData.uid = abilityInfo->applicationInfo.uid;
849 abilityStateData.token = ability->GetToken();
850 abilityStateData.abilityType = static_cast<int32_t>(abilityInfo->type);
851 abilityStateData.isFocused = ability->GetFocusFlag();
852 abilityStateData.abilityRecordId = ability->GetAbilityRecordId();
853 auto applicationInfo = GetApplicationInfo();
854 if (applicationInfo && (static_cast<int32_t>(applicationInfo->multiAppMode.multiAppModeType) ==
855 static_cast<int32_t>(MultiAppModeType::APP_CLONE))) {
856 abilityStateData.appCloneIndex = appIndex_;
857 }
858 if (ability->GetWant() != nullptr) {
859 abilityStateData.callerAbilityName = ability->GetWant()->GetStringParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
860 abilityStateData.callerBundleName = ability->GetWant()->GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
861 }
862 if (applicationInfo && applicationInfo->bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
863 abilityStateData.isAtomicService = true;
864 }
865 TAG_LOGI(AAFwkTag::APPMGR, "The ability(bundle:%{public}s, ability:%{public}s) state will change.",
866 abilityStateData.bundleName.c_str(), abilityStateData.abilityName.c_str());
867 if (isAbility && abilityInfo->type == AbilityType::EXTENSION &&
868 abilityInfo->extensionAbilityType != ExtensionAbilityType::UI) {
869 TAG_LOGD(AAFwkTag::APPMGR, "extensionType:%{public}d, not notify", abilityInfo->extensionAbilityType);
870 return;
871 }
872 auto serviceInner = appMgrServiceInner_.lock();
873 if (serviceInner) {
874 serviceInner->StateChangedNotifyObserver(abilityStateData, isAbility, isFromWindowFocusChanged);
875 }
876 }
877
GetModuleRunningRecordByToken(const sptr<IRemoteObject> & token) const878 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRunningRecordByToken(
879 const sptr<IRemoteObject> &token) const
880 {
881 if (!token) {
882 return nullptr;
883 }
884
885 auto moduleRecordList = GetAllModuleRecord();
886 for (const auto &moduleRecord : moduleRecordList) {
887 if (moduleRecord && moduleRecord->GetAbilityRunningRecordByToken(token)) {
888 return moduleRecord;
889 }
890 }
891
892 return nullptr;
893 }
894
GetModuleRunningRecordByTerminateLists(const sptr<IRemoteObject> & token) const895 std::shared_ptr<ModuleRunningRecord> AppRunningRecord::GetModuleRunningRecordByTerminateLists(
896 const sptr<IRemoteObject> &token) const
897 {
898 if (!token) {
899 TAG_LOGE(AAFwkTag::APPMGR, "token null");
900 return nullptr;
901 }
902
903 auto moduleRecordList = GetAllModuleRecord();
904 for (const auto &moduleRecord : moduleRecordList) {
905 if (moduleRecord && moduleRecord->GetAbilityByTerminateLists(token)) {
906 return moduleRecord;
907 }
908 }
909
910 return nullptr;
911 }
912
GetAbilityRunningRecordByToken(const sptr<IRemoteObject> & token) const913 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityRunningRecordByToken(
914 const sptr<IRemoteObject> &token) const
915 {
916 auto moduleRecord = GetModuleRunningRecordByToken(token);
917 if (!moduleRecord) {
918 return nullptr;
919 }
920 return moduleRecord->GetAbilityRunningRecordByToken(token);
921 }
922
GetAbilityByTerminateLists(const sptr<IRemoteObject> & token) const923 std::shared_ptr<AbilityRunningRecord> AppRunningRecord::GetAbilityByTerminateLists(
924 const sptr<IRemoteObject> &token) const
925 {
926 auto moduleRecord = GetModuleRunningRecordByTerminateLists(token);
927 if (!moduleRecord) {
928 return nullptr;
929 }
930 return moduleRecord->GetAbilityByTerminateLists(token);
931 }
932
UpdateAbilityFocusState(const sptr<IRemoteObject> & token,bool isFocus)933 bool AppRunningRecord::UpdateAbilityFocusState(const sptr<IRemoteObject> &token, bool isFocus)
934 {
935 TAG_LOGD(AAFwkTag::APPMGR, "focus state is :%{public}d", isFocus);
936 auto abilityRecord = GetAbilityRunningRecordByToken(token);
937 if (!abilityRecord) {
938 TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record");
939 return false;
940 }
941
942 bool lastFocusState = abilityRecord->GetFocusFlag();
943 if (lastFocusState == isFocus) {
944 TAG_LOGE(AAFwkTag::APPMGR, "focus state not change, no need update");
945 return false;
946 }
947
948 if (isFocus) {
949 return AbilityFocused(abilityRecord);
950 } else {
951 return AbilityUnfocused(abilityRecord);
952 }
953 }
954
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)955 void AppRunningRecord::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
956 {
957 TAG_LOGD(AAFwkTag::APPMGR, "state is :%{public}d", static_cast<int32_t>(state));
958 auto abilityRecord = GetAbilityRunningRecordByToken(token);
959 if (!abilityRecord) {
960 TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record");
961 return;
962 }
963 if (state == AbilityState::ABILITY_STATE_CREATE) {
964 StateChangedNotifyObserver(
965 abilityRecord, static_cast<int32_t>(AbilityState::ABILITY_STATE_CREATE), true, false);
966 return;
967 }
968 if (state == abilityRecord->GetState()) {
969 TAG_LOGE(AAFwkTag::APPMGR, "current state is already, no need update");
970 return;
971 }
972
973 if (state == AbilityState::ABILITY_STATE_FOREGROUND) {
974 AbilityForeground(abilityRecord);
975 } else if (state == AbilityState::ABILITY_STATE_BACKGROUND) {
976 AbilityBackground(abilityRecord);
977 } else {
978 TAG_LOGW(AAFwkTag::APPMGR, "wrong state");
979 }
980 }
981
AbilityForeground(const std::shared_ptr<AbilityRunningRecord> & ability)982 void AppRunningRecord::AbilityForeground(const std::shared_ptr<AbilityRunningRecord> &ability)
983 {
984 HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
985 if (!ability) {
986 TAG_LOGE(AAFwkTag::APPMGR, "ability null");
987 return;
988 }
989 AbilityState curAbilityState = ability->GetState();
990 if (curAbilityState != AbilityState::ABILITY_STATE_READY &&
991 curAbilityState != AbilityState::ABILITY_STATE_BACKGROUND) {
992 TAG_LOGE(AAFwkTag::APPMGR, "ability state(%{public}d) error", static_cast<int32_t>(curAbilityState));
993 return;
994 }
995 TAG_LOGI(AAFwkTag::APPMGR, "appState: %{public}d, pState: %{public}d, bundle: %{public}s, ability: %{public}s",
996 curState_, pendingState_, mainBundleName_.c_str(), ability->GetName().c_str());
997 // We need schedule application to foregrounded when current application state is ready or background running.
998 if (curState_ == ApplicationState::APP_STATE_FOREGROUND
999 && pendingState_ != ApplicationPendingState::BACKGROUNDING) {
1000 // Just change ability to foreground if current application state is foreground or focus.
1001 auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
1002 if (moduleRecord == nullptr) {
1003 TAG_LOGE(AAFwkTag::APPMGR, "moduleRecord null");
1004 return;
1005 }
1006
1007 moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
1008 StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND), true, false);
1009 auto serviceInner = appMgrServiceInner_.lock();
1010 if (serviceInner) {
1011 serviceInner->OnAppStateChanged(shared_from_this(), curState_, false, false);
1012 }
1013 return;
1014 }
1015 if (curState_ == ApplicationState::APP_STATE_READY || curState_ == ApplicationState::APP_STATE_BACKGROUND
1016 || curState_ == ApplicationState::APP_STATE_FOREGROUND) {
1017 auto pendingState = pendingState_;
1018 SetApplicationPendingState(ApplicationPendingState::FOREGROUNDING);
1019 if (pendingState == ApplicationPendingState::READY && !ScheduleForegroundRunning()) {
1020 FreezeUtil::LifecycleFlow flow{ ability->GetToken(), FreezeUtil::TimeoutState::FOREGROUND };
1021 FreezeUtil::GetInstance().AppendLifecycleEvent(flow, "AppRunningRecord::AbilityForeground ipc fail");
1022 }
1023 foregroundingAbilityTokens_.insert(ability->GetToken());
1024 TAG_LOGD(AAFwkTag::APPMGR, "foregroundingAbility size: %{public}d",
1025 static_cast<int32_t>(foregroundingAbilityTokens_.size()));
1026 if (curState_ == ApplicationState::APP_STATE_BACKGROUND) {
1027 SendAppStartupTypeEvent(ability, AppStartType::HOT);
1028 }
1029 } else {
1030 TAG_LOGW(AAFwkTag::APPMGR, "wrong application state");
1031 }
1032 }
1033
AbilityBackground(const std::shared_ptr<AbilityRunningRecord> & ability)1034 void AppRunningRecord::AbilityBackground(const std::shared_ptr<AbilityRunningRecord> &ability)
1035 {
1036 HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1037 if (!ability) {
1038 TAG_LOGE(AAFwkTag::APPMGR, "ability null");
1039 return;
1040 }
1041 TAG_LOGD(AAFwkTag::APPMGR, "ability is %{public}s", mainBundleName_.c_str());
1042 if (ability->GetState() != AbilityState::ABILITY_STATE_FOREGROUND &&
1043 ability->GetState() != AbilityState::ABILITY_STATE_READY) {
1044 TAG_LOGE(AAFwkTag::APPMGR, "ability state is not foreground or focus");
1045 return;
1046 }
1047
1048 // First change ability to background.
1049 auto moduleRecord = GetModuleRunningRecordByToken(ability->GetToken());
1050 if (moduleRecord == nullptr) {
1051 TAG_LOGE(AAFwkTag::APPMGR, "moduleRecord null");
1052 return;
1053 }
1054 moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_BACKGROUND);
1055 StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_BACKGROUND), true, false);
1056 if (curState_ == ApplicationState::APP_STATE_FOREGROUND || curState_ == ApplicationState::APP_STATE_CACHED) {
1057 int32_t foregroundSize = 0;
1058 auto abilitiesMap = GetAbilities();
1059 for (const auto &item : abilitiesMap) {
1060 const auto &abilityRecord = item.second;
1061 if (abilityRecord && abilityRecord->GetState() == AbilityState::ABILITY_STATE_FOREGROUND &&
1062 abilityRecord->GetAbilityInfo() &&
1063 (abilityRecord->GetAbilityInfo()->type == AppExecFwk::AbilityType::PAGE
1064 || AAFwk::UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo()->extensionAbilityType))) {
1065 foregroundSize++;
1066 break;
1067 }
1068 }
1069
1070 // Then schedule application background when all ability is not foreground.
1071 if (foregroundSize == 0 && mainBundleName_ != LAUNCHER_NAME && windowIds_.empty()) {
1072 auto pendingState = pendingState_;
1073 SetApplicationPendingState(ApplicationPendingState::BACKGROUNDING);
1074 if (pendingState == ApplicationPendingState::READY) {
1075 ScheduleBackgroundRunning();
1076 }
1077 }
1078 } else {
1079 TAG_LOGW(AAFwkTag::APPMGR, "wrong application state");
1080 }
1081 }
1082
AbilityFocused(const std::shared_ptr<AbilityRunningRecord> & ability)1083 bool AppRunningRecord::AbilityFocused(const std::shared_ptr<AbilityRunningRecord> &ability)
1084 {
1085 HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1086 if (!ability) {
1087 TAG_LOGE(AAFwkTag::APPMGR, "ability null");
1088 return false;
1089 }
1090 ability->UpdateFocusState(true);
1091
1092 // update ability state
1093 int32_t abilityState = static_cast<int32_t>(ability->GetState());
1094 bool isAbility = true;
1095 if (ability->GetAbilityInfo() != nullptr && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) {
1096 isAbility = false;
1097 }
1098 StateChangedNotifyObserver(ability, abilityState, isAbility, true);
1099
1100 if (isFocused_) {
1101 // process state is already focused, no need update process state.
1102 return false;
1103 }
1104
1105 // update process focus state to true.
1106 isFocused_ = true;
1107 return true;
1108 }
1109
AbilityUnfocused(const std::shared_ptr<AbilityRunningRecord> & ability)1110 bool AppRunningRecord::AbilityUnfocused(const std::shared_ptr<AbilityRunningRecord> &ability)
1111 {
1112 HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1113 if (!ability) {
1114 TAG_LOGE(AAFwkTag::APPMGR, "ability null");
1115 return false;
1116 }
1117 ability->UpdateFocusState(false);
1118
1119 // update ability state to unfocused.
1120 int32_t abilityState = static_cast<int32_t>(ability->GetState());
1121 bool isAbility = true;
1122 if (ability->GetAbilityInfo() != nullptr && ability->GetAbilityInfo()->type == AbilityType::EXTENSION) {
1123 isAbility = false;
1124 }
1125 StateChangedNotifyObserver(ability, abilityState, isAbility, true);
1126
1127 if (!isFocused_) {
1128 return false; // invalid process focus state, already unfocused, process state not change.
1129 }
1130
1131 bool changeProcessToUnfocused = true;
1132 auto abilitysMap = GetAbilities();
1133 for (const auto &item : abilitysMap) {
1134 const auto &abilityRecord = item.second;
1135 if (abilityRecord && abilityRecord->GetFocusFlag()) {
1136 changeProcessToUnfocused = false;
1137 break;
1138 }
1139 }
1140
1141 if (changeProcessToUnfocused) {
1142 isFocused_ = false; // process focus state : from focus to unfocus.
1143 }
1144 return changeProcessToUnfocused;
1145 }
1146
PopForegroundingAbilityTokens()1147 void AppRunningRecord::PopForegroundingAbilityTokens()
1148 {
1149 TAG_LOGI(AAFwkTag::APPMGR, "fg ability size: %{public}d",
1150 static_cast<int32_t>(foregroundingAbilityTokens_.size()));
1151 for (auto iter = foregroundingAbilityTokens_.begin(); iter != foregroundingAbilityTokens_.end();) {
1152 auto ability = GetAbilityRunningRecordByToken(*iter);
1153 auto moduleRecord = GetModuleRunningRecordByToken(*iter);
1154 if (moduleRecord != nullptr) {
1155 moduleRecord->OnAbilityStateChanged(ability, AbilityState::ABILITY_STATE_FOREGROUND);
1156 StateChangedNotifyObserver(ability, static_cast<int32_t>(AbilityState::ABILITY_STATE_FOREGROUND),
1157 true, false);
1158 } else {
1159 TAG_LOGW(AAFwkTag::APPMGR, "can not find module record");
1160 }
1161 // The token should be removed even though the module record didn't exist.
1162 iter = foregroundingAbilityTokens_.erase(iter);
1163 }
1164 }
1165
TerminateAbility(const sptr<IRemoteObject> & token,const bool isForce)1166 void AppRunningRecord::TerminateAbility(const sptr<IRemoteObject> &token, const bool isForce)
1167 {
1168 TAG_LOGD(AAFwkTag::APPMGR, "isForce: %{public}d", static_cast<int>(isForce));
1169
1170 auto moduleRecord = GetModuleRunningRecordByToken(token);
1171 if (!moduleRecord) {
1172 TAG_LOGE(AAFwkTag::APPMGR, "can not find module record");
1173 return;
1174 }
1175
1176 auto abilityRecord = GetAbilityRunningRecordByToken(token);
1177 if (abilityRecord) {
1178 TAG_LOGI(AAFwkTag::APPMGR, "TerminateAbility:%{public}s", abilityRecord->GetName().c_str());
1179 }
1180 StateChangedNotifyObserver(
1181 abilityRecord, static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true, false);
1182 moduleRecord->TerminateAbility(shared_from_this(), token, isForce);
1183 }
1184
AbilityTerminated(const sptr<IRemoteObject> & token)1185 void AppRunningRecord::AbilityTerminated(const sptr<IRemoteObject> &token)
1186 {
1187 TAG_LOGD(AAFwkTag::APPMGR, "called");
1188 auto moduleRecord = GetModuleRunningRecordByTerminateLists(token);
1189 if (!moduleRecord) {
1190 TAG_LOGE(AAFwkTag::APPMGR, "AbilityTerminated error, can not find module record");
1191 return;
1192 }
1193
1194 bool isExtensionDebug = false;
1195 auto abilityRecord = moduleRecord->GetAbilityByTerminateLists(token);
1196 if (abilityRecord != nullptr && abilityRecord->GetAbilityInfo() != nullptr) {
1197 isExtensionDebug = (abilityRecord->GetAbilityInfo()->type == AppExecFwk::AbilityType::EXTENSION) &&
1198 (isAttachDebug_ || isDebugApp_);
1199 }
1200 TAG_LOGD(AAFwkTag::APPMGR, "Extension debug is [%{public}s]", isExtensionDebug ? "true" : "false");
1201
1202 moduleRecord->AbilityTerminated(token);
1203
1204 auto appRecord = shared_from_this();
1205 auto cacheProcMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
1206 bool needCache = false;
1207 if (cacheProcMgr != nullptr && cacheProcMgr->IsAppShouldCache(appRecord)) {
1208 cacheProcMgr->CheckAndCacheProcess(appRecord);
1209 TAG_LOGI(AAFwkTag::APPMGR, "App %{public}s should cache, not remove module and terminate app.",
1210 appRecord->GetBundleName().c_str());
1211 needCache = true;
1212 }
1213 if (moduleRecord->GetAbilities().empty() && (!IsKeepAliveApp()
1214 || AAFwk::UIExtensionUtils::IsUIExtension(GetExtensionType())
1215 || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent()) && !needCache) {
1216 RemoveModuleRecord(moduleRecord, isExtensionDebug);
1217 }
1218
1219 auto moduleRecordList = GetAllModuleRecord();
1220 if (moduleRecordList.empty() && (!IsKeepAliveApp()
1221 || AAFwk::UIExtensionUtils::IsUIExtension(GetExtensionType())
1222 || !ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent()) && !isExtensionDebug
1223 && !needCache) {
1224 ScheduleTerminate();
1225 }
1226 }
1227
GetAllModuleRecord() const1228 std::list<std::shared_ptr<ModuleRunningRecord>> AppRunningRecord::GetAllModuleRecord() const
1229 {
1230 std::list<std::shared_ptr<ModuleRunningRecord>> moduleRecordList;
1231 std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1232 for (const auto &item : hapModules_) {
1233 for (const auto &list : item.second) {
1234 moduleRecordList.push_back(list);
1235 }
1236 }
1237 return moduleRecordList;
1238 }
1239
RemoveAppDeathRecipient() const1240 void AppRunningRecord::RemoveAppDeathRecipient() const
1241 {
1242 if (appLifeCycleDeal_ == nullptr) {
1243 TAG_LOGE(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1244 return;
1245 }
1246 if (!appLifeCycleDeal_->GetApplicationClient()) {
1247 TAG_LOGE(AAFwkTag::APPMGR, "appThread null");
1248 return;
1249 }
1250 auto object = appLifeCycleDeal_->GetApplicationClient()->AsObject();
1251 if (object) {
1252 if (!object->RemoveDeathRecipient(appDeathRecipient_)) {
1253 TAG_LOGD(AAFwkTag::APPMGR, "Failed to remove deathRecipient.");
1254 }
1255 }
1256 }
1257
SetAppMgrServiceInner(const std::weak_ptr<AppMgrServiceInner> & inner)1258 void AppRunningRecord::SetAppMgrServiceInner(const std::weak_ptr<AppMgrServiceInner> &inner)
1259 {
1260 appMgrServiceInner_ = inner;
1261
1262 auto moduleRecordList = GetAllModuleRecord();
1263 if (moduleRecordList.empty()) {
1264 TAG_LOGE(AAFwkTag::APPMGR, "moduleRecordList is empty");
1265 return;
1266 }
1267
1268 for (const auto &moduleRecord : moduleRecordList) {
1269 moduleRecord->SetAppMgrServiceInner(appMgrServiceInner_);
1270 }
1271 }
1272
SetAppDeathRecipient(const sptr<AppDeathRecipient> & appDeathRecipient)1273 void AppRunningRecord::SetAppDeathRecipient(const sptr<AppDeathRecipient> &appDeathRecipient)
1274 {
1275 appDeathRecipient_ = appDeathRecipient;
1276 }
1277
GetPriorityObject()1278 std::shared_ptr<PriorityObject> AppRunningRecord::GetPriorityObject()
1279 {
1280 return priorityObject_;
1281 }
1282
SendEventForSpecifiedAbility(uint32_t msg,int64_t timeOut)1283 void AppRunningRecord::SendEventForSpecifiedAbility(uint32_t msg, int64_t timeOut)
1284 {
1285 SendEvent(msg, timeOut);
1286 }
1287
SendAppStartupTypeEvent(const std::shared_ptr<AbilityRunningRecord> & ability,const AppStartType startType)1288 void AppRunningRecord::SendAppStartupTypeEvent(const std::shared_ptr<AbilityRunningRecord> &ability,
1289 const AppStartType startType)
1290 {
1291 if (!ability) {
1292 TAG_LOGE(AAFwkTag::APPMGR, "AbilityRunningRecord null");
1293 return;
1294 }
1295 AAFwk::EventInfo eventInfo;
1296 auto applicationInfo = GetApplicationInfo();
1297 if (!applicationInfo) {
1298 TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo null, can not get app information");
1299 } else {
1300 eventInfo.bundleName = applicationInfo->name;
1301 eventInfo.versionName = applicationInfo->versionName;
1302 eventInfo.versionCode = applicationInfo->versionCode;
1303 }
1304
1305 auto abilityInfo = ability->GetAbilityInfo();
1306 if (!abilityInfo) {
1307 TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo null, can not get ability information");
1308 } else {
1309 eventInfo.abilityName = abilityInfo->name;
1310 }
1311 if (GetPriorityObject() == nullptr) {
1312 TAG_LOGE(AAFwkTag::APPMGR, "appRecord's priorityObject null");
1313 } else {
1314 eventInfo.pid = GetPriorityObject()->GetPid();
1315 }
1316 eventInfo.startType = static_cast<int32_t>(startType);
1317 AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_STARTUP_TYPE, HiSysEventType::BEHAVIOR, eventInfo);
1318 }
1319
SendEvent(uint32_t msg,int64_t timeOut)1320 void AppRunningRecord::SendEvent(uint32_t msg, int64_t timeOut)
1321 {
1322 if (!eventHandler_) {
1323 TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1324 return;
1325 }
1326
1327 if (isDebugApp_ || isNativeDebug_ || isAttachDebug_) {
1328 TAG_LOGI(AAFwkTag::APPMGR, "Is debug mode, no need to handle time out.");
1329 return;
1330 }
1331
1332 appEventId_++;
1333 eventId_ = appEventId_;
1334 if (msg == AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG) {
1335 startProcessSpecifiedAbilityEventId_ = eventId_;
1336 }
1337 if (msg == AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG) {
1338 addAbilityStageInfoEventId_ = eventId_;
1339 }
1340
1341 TAG_LOGI(AAFwkTag::APPMGR, "eventId %{public}d", static_cast<int>(eventId_));
1342 eventHandler_->SendEvent(AAFwk::EventWrap(msg, eventId_), timeOut, false);
1343 SendClearTask(msg, timeOut);
1344 }
1345
SendClearTask(uint32_t msg,int64_t timeOut)1346 void AppRunningRecord::SendClearTask(uint32_t msg, int64_t timeOut)
1347 {
1348 if (!taskHandler_) {
1349 TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
1350 return;
1351 }
1352 int64_t* eventId = nullptr;
1353 if (msg == AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG) {
1354 eventId = &startProcessSpecifiedAbilityEventId_;
1355 } else if (msg == AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG) {
1356 eventId = &addAbilityStageInfoEventId_;
1357 } else {
1358 TAG_LOGD(AAFwkTag::APPMGR, "Other msg: %{public}d", msg);
1359 return;
1360 }
1361 taskHandler_->SubmitTask([wthis = weak_from_this(), eventId]() {
1362 auto pthis = wthis.lock();
1363 if (pthis) {
1364 *eventId = 0;
1365 }
1366 }, timeOut);
1367 }
1368
PostTask(std::string msg,int64_t timeOut,const Closure & task)1369 void AppRunningRecord::PostTask(std::string msg, int64_t timeOut, const Closure &task)
1370 {
1371 if (!taskHandler_) {
1372 TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
1373 return;
1374 }
1375 taskHandler_->SubmitTask(task, msg, timeOut);
1376 }
1377
GetEventId() const1378 int64_t AppRunningRecord::GetEventId() const
1379 {
1380 return eventId_;
1381 }
1382
SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)1383 void AppRunningRecord::SetTaskHandler(std::shared_ptr<AAFwk::TaskHandlerWrap> taskHandler)
1384 {
1385 taskHandler_ = taskHandler;
1386 }
1387
SetEventHandler(const std::shared_ptr<AMSEventHandler> & handler)1388 void AppRunningRecord::SetEventHandler(const std::shared_ptr<AMSEventHandler> &handler)
1389 {
1390 eventHandler_ = handler;
1391 }
1392
IsLastAbilityRecord(const sptr<IRemoteObject> & token)1393 bool AppRunningRecord::IsLastAbilityRecord(const sptr<IRemoteObject> &token)
1394 {
1395 auto moduleRecord = GetModuleRunningRecordByToken(token);
1396 if (!moduleRecord) {
1397 TAG_LOGE(AAFwkTag::APPMGR, "can not find module record");
1398 return false;
1399 }
1400
1401 auto moduleRecordList = GetAllModuleRecord();
1402 if (moduleRecordList.size() == 1) {
1403 return moduleRecord->IsLastAbilityRecord(token);
1404 }
1405
1406 return false;
1407 }
1408
ExtensionAbilityRecordExists()1409 bool AppRunningRecord::ExtensionAbilityRecordExists()
1410 {
1411 auto moduleRecordList = GetAllModuleRecord();
1412 for (auto moduleRecord : moduleRecordList) {
1413 if (moduleRecord && moduleRecord->ExtensionAbilityRecordExists()) {
1414 return true;
1415 }
1416 }
1417 TAG_LOGD(AAFwkTag::APPMGR, "can not find extension record");
1418 return false;
1419 }
1420
IsLastPageAbilityRecord(const sptr<IRemoteObject> & token)1421 bool AppRunningRecord::IsLastPageAbilityRecord(const sptr<IRemoteObject> &token)
1422 {
1423 auto moduleRecord = GetModuleRunningRecordByToken(token);
1424 if (!moduleRecord) {
1425 TAG_LOGE(AAFwkTag::APPMGR, "can not find module record");
1426 return false;
1427 }
1428
1429 int32_t pageAbilitySize = 0;
1430 auto moduleRecordList = GetAllModuleRecord();
1431 for (auto moduleRecord : moduleRecordList) {
1432 if (moduleRecord) {
1433 pageAbilitySize += moduleRecord->GetPageAbilitySize();
1434 }
1435 if (pageAbilitySize > 1) {
1436 return false;
1437 }
1438 }
1439
1440 return pageAbilitySize == 1;
1441 }
1442
SetTerminating(std::shared_ptr<AppRunningManager> appRunningMgr)1443 void AppRunningRecord::SetTerminating(std::shared_ptr<AppRunningManager> appRunningMgr)
1444 {
1445 isTerminating = true;
1446 auto prioObject = GetPriorityObject();
1447 if (prioObject) {
1448 FreezeUtil::GetInstance().DeleteAppLifecycleEvent(prioObject->GetPid());
1449 }
1450 if (appRunningMgr == nullptr) {
1451 TAG_LOGE(AAFwkTag::APPMGR, "appRunningMgr null");
1452 return;
1453 }
1454 if (appRunningMgr->CheckAppRunningRecordIsLast(shared_from_this())) {
1455 UnSetPolicy();
1456 }
1457 }
1458
IsTerminating()1459 bool AppRunningRecord::IsTerminating()
1460 {
1461 return isTerminating;
1462 }
1463
IsKeepAliveApp() const1464 bool AppRunningRecord::IsKeepAliveApp() const
1465 {
1466 if (!isMainProcess_ || !isKeepAliveBundle_ || !isKeepAliveRdb_) {
1467 return false;
1468 }
1469 auto userId = GetUid() / BASE_USER_RANGE;
1470 if (userId == 0) {
1471 return isSingleton_;
1472 }
1473 return true;
1474 }
1475
SetKeepAliveEnableState(bool isKeepAliveEnable)1476 void AppRunningRecord::SetKeepAliveEnableState(bool isKeepAliveEnable)
1477 {
1478 isKeepAliveRdb_ = isKeepAliveEnable;
1479 }
1480
SetKeepAliveBundle(bool isKeepAliveBundle)1481 void AppRunningRecord::SetKeepAliveBundle(bool isKeepAliveBundle)
1482 {
1483 isKeepAliveBundle_ = isKeepAliveBundle;
1484 }
1485
IsEmptyKeepAliveApp() const1486 bool AppRunningRecord::IsEmptyKeepAliveApp() const
1487 {
1488 return isEmptyKeepAliveApp_;
1489 }
1490
SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp)1491 void AppRunningRecord::SetEmptyKeepAliveAppState(bool isEmptyKeepAliveApp)
1492 {
1493 isEmptyKeepAliveApp_ = isEmptyKeepAliveApp;
1494 }
1495
IsMainProcess() const1496 bool AppRunningRecord::IsMainProcess() const
1497 {
1498 return isMainProcess_;
1499 }
1500
SetMainProcess(bool isMainProcess)1501 void AppRunningRecord::SetMainProcess(bool isMainProcess)
1502 {
1503 isMainProcess_ = isMainProcess;
1504 }
1505
SetSingleton(bool isSingleton)1506 void AppRunningRecord::SetSingleton(bool isSingleton)
1507 {
1508 isSingleton_ = isSingleton;
1509 }
1510
SetStageModelState(bool isStageBasedModel)1511 void AppRunningRecord::SetStageModelState(bool isStageBasedModel)
1512 {
1513 isStageBasedModel_ = isStageBasedModel;
1514 }
1515
GetTheModuleInfoNeedToUpdated(const std::string bundleName,HapModuleInfo & info)1516 bool AppRunningRecord::GetTheModuleInfoNeedToUpdated(const std::string bundleName, HapModuleInfo &info)
1517 {
1518 bool result = false;
1519 std::lock_guard<ffrt::mutex> hapModulesLock(hapModulesLock_);
1520 auto moduleInfoVectorIter = hapModules_.find(bundleName);
1521 if (moduleInfoVectorIter == hapModules_.end() || moduleInfoVectorIter->second.empty()) {
1522 return result;
1523 }
1524 std::string moduleName = moduleName_;
1525 auto findCondition = [moduleName](const std::shared_ptr<ModuleRunningRecord> &record) {
1526 if (record) {
1527 return (moduleName.empty() || (moduleName == record->GetModuleName())) &&
1528 (record->GetModuleRecordState() == ModuleRecordState::INITIALIZED_STATE);
1529 }
1530 return false;
1531 };
1532 auto moduleRecordIter =
1533 std::find_if(moduleInfoVectorIter->second.begin(), moduleInfoVectorIter->second.end(), findCondition);
1534 if (moduleRecordIter != moduleInfoVectorIter->second.end()) {
1535 (*moduleRecordIter)->GetHapModuleInfo(info);
1536 (*moduleRecordIter)->SetModuleRecordState(ModuleRecordState::RUNNING_STATE);
1537 result = true;
1538 }
1539
1540 return result;
1541 }
1542
SetRestartResidentProcCount(int count)1543 void AppRunningRecord::SetRestartResidentProcCount(int count)
1544 {
1545 restartResidentProcCount_ = count;
1546 }
1547
DecRestartResidentProcCount()1548 void AppRunningRecord::DecRestartResidentProcCount()
1549 {
1550 restartResidentProcCount_--;
1551 }
1552
GetRestartResidentProcCount() const1553 int AppRunningRecord::GetRestartResidentProcCount() const
1554 {
1555 return restartResidentProcCount_;
1556 }
1557
CanRestartResidentProc()1558 bool AppRunningRecord::CanRestartResidentProc()
1559 {
1560 struct timespec t;
1561 t.tv_sec = 0;
1562 t.tv_nsec = 0;
1563 clock_gettime(CLOCK_MONOTONIC, &t);
1564 int64_t systemTimeMillis = static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS);
1565 if ((restartResidentProcCount_ >= 0) || ((systemTimeMillis - restartTimeMillis_) > RESTART_INTERVAL_TIME)) {
1566 return true;
1567 }
1568 return false;
1569 }
1570
GetBundleNames(std::vector<std::string> & bundleNames)1571 void AppRunningRecord::GetBundleNames(std::vector<std::string> &bundleNames)
1572 {
1573 std::lock_guard<ffrt::mutex> appInfosLock(appInfosLock_);
1574 for (auto &app : appInfos_) {
1575 bundleNames.emplace_back(app.first);
1576 }
1577 }
1578
SetUserTestInfo(const std::shared_ptr<UserTestRecord> & record)1579 void AppRunningRecord::SetUserTestInfo(const std::shared_ptr<UserTestRecord> &record)
1580 {
1581 userTestRecord_ = record;
1582 }
1583
GetUserTestInfo()1584 std::shared_ptr<UserTestRecord> AppRunningRecord::GetUserTestInfo()
1585 {
1586 return userTestRecord_;
1587 }
1588
SetProcessAndExtensionType(const std::shared_ptr<AbilityInfo> & abilityInfo)1589 void AppRunningRecord::SetProcessAndExtensionType(const std::shared_ptr<AbilityInfo> &abilityInfo)
1590 {
1591 if (abilityInfo == nullptr) {
1592 TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo null");
1593 return;
1594 }
1595 extensionType_ = abilityInfo->extensionAbilityType;
1596 if (extensionType_ == ExtensionAbilityType::UNSPECIFIED) {
1597 //record Service Ability in FA model as Service Extension
1598 if (abilityInfo->type == AbilityType::SERVICE) {
1599 processType_ = ProcessType::EXTENSION;
1600 extensionType_ = ExtensionAbilityType::SERVICE;
1601 return;
1602 }
1603 //record Data Ability in FA model as Datashare Extension
1604 if (abilityInfo->type == AbilityType::DATA) {
1605 processType_ = ProcessType::EXTENSION;
1606 extensionType_ = ExtensionAbilityType::DATASHARE;
1607 return;
1608 }
1609 processType_ = ProcessType::NORMAL;
1610 return;
1611 }
1612 processType_ = ProcessType::EXTENSION;
1613 return;
1614 }
1615
SetSpecifiedAbilityFlagAndWant(int requestId,const AAFwk::Want & want,const std::string & moduleName)1616 void AppRunningRecord::SetSpecifiedAbilityFlagAndWant(
1617 int requestId, const AAFwk::Want &want, const std::string &moduleName)
1618 {
1619 std::lock_guard lock(specifiedMutex_);
1620 if (specifiedRequestId_ != -1) {
1621 TAG_LOGW(AAFwkTag::APPMGR, "specifiedRequestId: %{public}d", specifiedRequestId_);
1622 }
1623 specifiedRequestId_ = requestId;
1624 specifiedWant_ = want;
1625 moduleName_ = moduleName;
1626 }
1627
GetSpecifiedRequestId() const1628 int32_t AppRunningRecord::GetSpecifiedRequestId() const
1629 {
1630 std::lock_guard lock(specifiedMutex_);
1631 return specifiedRequestId_;
1632 }
1633
ResetSpecifiedRequestId()1634 void AppRunningRecord::ResetSpecifiedRequestId()
1635 {
1636 std::lock_guard lock(specifiedMutex_);
1637 specifiedRequestId_ = -1;
1638 }
1639
SetScheduleNewProcessRequestState(int32_t requestId,const AAFwk::Want & want,const std::string & moduleName)1640 void AppRunningRecord::SetScheduleNewProcessRequestState(int32_t requestId,
1641 const AAFwk::Want &want, const std::string &moduleName)
1642 {
1643 std::lock_guard lock(specifiedMutex_);
1644 if (newProcessRequestId_ != -1) {
1645 TAG_LOGW(AAFwkTag::APPMGR, "newProcessRequestId: %{public}d", newProcessRequestId_);
1646 }
1647 newProcessRequestId_ = requestId;
1648 newProcessRequestWant_ = want;
1649 moduleName_ = moduleName;
1650 }
1651
IsNewProcessRequest() const1652 bool AppRunningRecord::IsNewProcessRequest() const
1653 {
1654 std::lock_guard lock(specifiedMutex_);
1655 return newProcessRequestId_ != -1;
1656 }
1657
IsStartSpecifiedAbility() const1658 bool AppRunningRecord::IsStartSpecifiedAbility() const
1659 {
1660 std::lock_guard lock(specifiedMutex_);
1661 return specifiedRequestId_ != -1;
1662 }
1663
ScheduleAcceptWant(const std::string & moduleName)1664 void AppRunningRecord::ScheduleAcceptWant(const std::string &moduleName)
1665 {
1666 SendEvent(
1667 AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG, AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT);
1668 if (appLifeCycleDeal_ == nullptr) {
1669 TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1670 return;
1671 }
1672 appLifeCycleDeal_->ScheduleAcceptWant(GetSpecifiedWant(), moduleName);
1673 }
1674
ScheduleAcceptWantDone()1675 void AppRunningRecord::ScheduleAcceptWantDone()
1676 {
1677 TAG_LOGI(AAFwkTag::APPMGR, "Schedule accept want done. bundle %{public}s and eventId %{public}d",
1678 mainBundleName_.c_str(), static_cast<int>(eventId_));
1679
1680 if (!eventHandler_) {
1681 TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1682 return;
1683 }
1684
1685 eventHandler_->RemoveEvent(AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG, eventId_);
1686 }
1687
ScheduleNewProcessRequest(const AAFwk::Want & want,const std::string & moduleName)1688 void AppRunningRecord::ScheduleNewProcessRequest(const AAFwk::Want &want, const std::string &moduleName)
1689 {
1690 SendEvent(
1691 AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG, AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT);
1692 if (appLifeCycleDeal_ == nullptr) {
1693 TAG_LOGW(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1694 return;
1695 }
1696 appLifeCycleDeal_->ScheduleNewProcessRequest(want, moduleName);
1697 }
1698
ScheduleNewProcessRequestDone()1699 void AppRunningRecord::ScheduleNewProcessRequestDone()
1700 {
1701 TAG_LOGI(AAFwkTag::APPMGR, "ScheduleNewProcessRequestDone. bundle %{public}s and eventId %{public}d",
1702 mainBundleName_.c_str(), static_cast<int>(eventId_));
1703
1704 if (!eventHandler_) {
1705 TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1706 return;
1707 }
1708
1709 eventHandler_->RemoveEvent(AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG, eventId_);
1710 }
1711
ApplicationTerminated()1712 void AppRunningRecord::ApplicationTerminated()
1713 {
1714 TAG_LOGD(AAFwkTag::APPMGR, "Application terminated bundle %{public}s and eventId %{public}d",
1715 mainBundleName_.c_str(), static_cast<int>(eventId_));
1716
1717 if (!eventHandler_) {
1718 TAG_LOGE(AAFwkTag::APPMGR, "eventHandler_ null");
1719 return;
1720 }
1721
1722 eventHandler_->RemoveEvent(AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG, eventId_);
1723 }
1724
GetSpecifiedWant() const1725 AAFwk::Want AppRunningRecord::GetSpecifiedWant() const
1726 {
1727 std::lock_guard lock(specifiedMutex_);
1728 return specifiedWant_;
1729 }
1730
GetNewProcessRequestWant() const1731 AAFwk::Want AppRunningRecord::GetNewProcessRequestWant() const
1732 {
1733 std::lock_guard lock(specifiedMutex_);
1734 return newProcessRequestWant_;
1735 }
1736
GetNewProcessRequestId() const1737 int32_t AppRunningRecord::GetNewProcessRequestId() const
1738 {
1739 std::lock_guard lock(specifiedMutex_);
1740 return newProcessRequestId_;
1741 }
1742
ResetNewProcessRequestId()1743 void AppRunningRecord::ResetNewProcessRequestId()
1744 {
1745 std::lock_guard lock(specifiedMutex_);
1746 newProcessRequestId_ = -1;
1747 }
1748
UpdateConfiguration(const Configuration & config)1749 int32_t AppRunningRecord::UpdateConfiguration(const Configuration &config)
1750 {
1751 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1752 TAG_LOGD(AAFwkTag::APPMGR, "called");
1753 if (!appLifeCycleDeal_) {
1754 TAG_LOGI(AAFwkTag::APPMGR, "appLifeCycleDeal_ null");
1755 return ERR_INVALID_VALUE;
1756 }
1757 return appLifeCycleDeal_->UpdateConfiguration(config);
1758 }
1759
AddRenderRecord(const std::shared_ptr<RenderRecord> & record)1760 void AppRunningRecord::AddRenderRecord(const std::shared_ptr<RenderRecord> &record)
1761 {
1762 if (!record) {
1763 TAG_LOGD(AAFwkTag::APPMGR, "AddRenderRecord: record null");
1764 return;
1765 }
1766 {
1767 std::lock_guard renderPidSetLock(renderPidSetLock_);
1768 renderPidSet_.insert(record->GetPid());
1769 }
1770 std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1771 renderRecordMap_.emplace(record->GetUid(), record);
1772 }
1773
RemoveRenderRecord(const std::shared_ptr<RenderRecord> & record)1774 void AppRunningRecord::RemoveRenderRecord(const std::shared_ptr<RenderRecord> &record)
1775 {
1776 if (!record) {
1777 TAG_LOGD(AAFwkTag::APPMGR, "RemoveRenderRecord: record null");
1778 return;
1779 }
1780 std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1781 renderRecordMap_.erase(record->GetUid());
1782 }
1783
RemoveRenderPid(pid_t renderPid)1784 void AppRunningRecord::RemoveRenderPid(pid_t renderPid)
1785 {
1786 std::lock_guard renderPidSetLock(renderPidSetLock_);
1787 renderPidSet_.erase(renderPid);
1788 }
1789
ConstainsRenderPid(pid_t renderPid)1790 bool AppRunningRecord::ConstainsRenderPid(pid_t renderPid)
1791 {
1792 std::lock_guard renderPidSetLock(renderPidSetLock_);
1793 return renderPidSet_.find(renderPid) != renderPidSet_.end();
1794 }
1795
GetRenderRecordByPid(const pid_t pid)1796 std::shared_ptr<RenderRecord> AppRunningRecord::GetRenderRecordByPid(const pid_t pid)
1797 {
1798 std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1799 if (renderRecordMap_.empty()) {
1800 return nullptr;
1801 }
1802 for (auto iter : renderRecordMap_) {
1803 auto renderRecord = iter.second;
1804 if (renderRecord && renderRecord->GetPid() == pid) {
1805 return renderRecord;
1806 }
1807 }
1808 return nullptr;
1809 }
1810
GetRenderRecordMap()1811 std::map<int32_t, std::shared_ptr<RenderRecord>> AppRunningRecord::GetRenderRecordMap()
1812 {
1813 std::lock_guard renderRecordMapLock(renderRecordMapLock_);
1814 return renderRecordMap_;
1815 }
1816
SetStartMsg(const AppSpawnStartMsg & msg)1817 void AppRunningRecord::SetStartMsg(const AppSpawnStartMsg &msg)
1818 {
1819 startMsg_ = msg;
1820 }
1821
GetStartMsg()1822 AppSpawnStartMsg AppRunningRecord::GetStartMsg()
1823 {
1824 return startMsg_;
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