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_record.h"
17 
18 #include <singleton.h>
19 
20 #include "ability_manager_service.h"
21 #include "ability_resident_process_rdb.h"
22 #include "ability_scheduler_stub.h"
23 #include "app_exception_handler.h"
24 #include "app_exit_reason_data_manager.h"
25 #include "app_utils.h"
26 #include "array_wrapper.h"
27 #include "accesstoken_kit.h"
28 #include "configuration_convertor.h"
29 #include "connection_state_manager.h"
30 #include "common_event_manager.h"
31 #include "freeze_util.h"
32 #include "global_constant.h"
33 #include "hitrace_meter.h"
34 #include "image_source.h"
35 #include "multi_instance_utils.h"
36 #include "os_account_manager_wrapper.h"
37 #include "ui_service_extension_connection_constants.h"
38 #include "res_sched_util.h"
39 #include "scene_board_judgement.h"
40 #include "startup_util.h"
41 #include "system_ability_token_callback.h"
42 #include "ui_extension_utils.h"
43 #include "uri_permission_manager_client.h"
44 #include "permission_constants.h"
45 #include "process_options.h"
46 #include "uri_utils.h"
47 #include "utils/state_utils.h"
48 #ifdef SUPPORT_GRAPHICS
49 #include "image_source.h"
50 #endif
51 #ifdef SUPPORT_SCREEN
52 #include "locale_config.h"
53 #endif
54 
55 namespace OHOS {
56 using AbilityRuntime::FreezeUtil;
57 namespace AAFwk {
58 using namespace OHOS::Security;
59 using namespace OHOS::AAFwk::PermissionConstants;
60 using namespace OHOS::AbilityRuntime::GlobalConstant;
61 const std::string DEBUG_APP = "debugApp";
62 const std::string NATIVE_DEBUG = "nativeDebug";
63 const std::string PERF_CMD = "perfCmd";
64 const std::string ERROR_INFO_ENHANCE = "errorInfoEnhance";
65 const std::string MULTI_THREAD = "multiThread";
66 const std::string DMS_PROCESS_NAME = "distributedsched";
67 const std::string DMS_MISSION_ID = "dmsMissionId";
68 const std::string DMS_SRC_NETWORK_ID = "dmsSrcNetworkId";
69 const std::string ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
70 const std::u16string SYSTEM_ABILITY_TOKEN_CALLBACK = u"ohos.aafwk.ISystemAbilityTokenCallback";
71 const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen";
72 #ifdef WITH_DLP
73 const std::string DLP_BUNDLE_NAME = "com.ohos.dlpmanager";
74 #endif // WITH_DLP
75 const std::string COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
76 const std::string KEY_MISSION_ID = "ohos.anco.param.missionId";
77 const std::string NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
78 const std::string PARAMS_URI = "ability.verify.uri";
79 const std::string PARAMS_FILE_SAVING_URL_KEY = "pick_path_return";
80 const uint32_t RELEASE_STARTING_BG_TIMEOUT = 15000; // release starting window resource timeout.
81 const std::string SHELL_ASSISTANT_DIEREASON = "crash_die";
82 const std::string PARAM_MISSION_AFFINITY_KEY = "ohos.anco.param.missionAffinity";
83 const std::string DISTRIBUTED_FILES_PATH = "/data/storage/el2/distributedfiles/";
84 const std::string UIEXTENSION_ABILITY_ID = "ability.want.params.uiExtensionAbilityId";
85 const std::string UIEXTENSION_ROOT_HOST_PID = "ability.want.params.uiExtensionRootHostPid";
86 constexpr const char* PARAM_SEND_RESULT_CALLER_BUNDLENAME = "ohos.anco.param.sendResultCallderBundleName";
87 constexpr const char* PARAM_SEND_RESULT_CALLER_TOKENID = "ohos.anco.param.sendResultCallerTokenId";
88 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
89 // Developer mode param
90 constexpr const char* DEVELOPER_MODE_STATE = "const.security.developermode.state";
91 constexpr const char* APP_PROVISION_TYPE_DEBUG = "debug";
92 constexpr const char* DMS_CALLER_BUNDLE_NAME = "ohos.dms.param.sourceCallerBundleName";
93 constexpr const char* DMS_CALLER_ABILITY_NAME = "ohos.dms.param.sourceCallerAbilityName";
94 constexpr const char* DMS_CALLER_NATIVE_NAME = "ohos.dms.param.sourceCallerNativeName";
95 constexpr const char* DMS_CALLER_APP_ID = "ohos.dms.param.sourceCallerAppId";
96 constexpr const char* DMS_CALLER_APP_IDENTIFIER = "ohos.dms.param.sourceCallerAppIdentifier";
97 const int32_t SHELL_ASSISTANT_DIETYPE = 0;
98 int64_t AbilityRecord::abilityRecordId = 0;
99 const int32_t DEFAULT_USER_ID = 0;
100 const int32_t SEND_RESULT_CANCELED = -1;
101 const int VECTOR_SIZE = 2;
102 const int LOAD_TIMEOUT_ASANENABLED = 150;
103 const int TERMINATE_TIMEOUT_ASANENABLED = 150;
104 const int HALF_TIMEOUT = 2;
105 const int MAX_URI_COUNT = 500;
106 const int RESTART_SCENEBOARD_DELAY = 500;
107 constexpr int32_t DMS_UID = 5522;
108 
109 auto g_addLifecycleEventTask = [](sptr<Token> token, FreezeUtil::TimeoutState state, std::string &methodName) {
110     CHECK_POINTER_LOG(token, "token is nullptr");
111     FreezeUtil::LifecycleFlow flow = { token->AsObject(), state };
112     std::string entry = std::string("AbilityRecord::") + methodName + "; the " + methodName + " lifecycle starts.";
113     FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
114 };
115 
Token(std::weak_ptr<AbilityRecord> abilityRecord)116 Token::Token(std::weak_ptr<AbilityRecord> abilityRecord) : abilityRecord_(abilityRecord)
117 {}
118 
~Token()119 Token::~Token()
120 {}
121 
GetAbilityRecordByToken(const sptr<IRemoteObject> &token)122 std::shared_ptr<AbilityRecord> Token::GetAbilityRecordByToken(const sptr<IRemoteObject> &token)
123 {
124     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
125     if (token == nullptr) {
126         return nullptr;
127     }
128 
129     std::string descriptor = Str16ToStr8(token->GetObjectDescriptor());
130     if (descriptor != "ohos.aafwk.AbilityToken") {
131         TAG_LOGE(AAFwkTag::ABILITYMGR, "not AbilityToken, descriptor:%{public}s",
132             descriptor.c_str());
133         return nullptr;
134     }
135 
136     // Double check if token is valid
137     sptr<IAbilityToken> theToken = iface_cast<IAbilityToken>(token);
138     if (!theToken) {
139         TAG_LOGE(AAFwkTag::ABILITYMGR, "input err");
140         return nullptr;
141     }
142     std::u16string castDescriptor = theToken->GetDescriptor();
143     if (castDescriptor != u"ohos.aafwk.AbilityToken") {
144         TAG_LOGE(AAFwkTag::ABILITYMGR, "Input token iface_cast error:%{public}s.", Str16ToStr8(castDescriptor).c_str());
145         return nullptr;
146     }
147 
148     return (static_cast<Token *>(token.GetRefPtr()))->GetAbilityRecord();
149 }
150 
GetAbilityRecord() const151 std::shared_ptr<AbilityRecord> Token::GetAbilityRecord() const
152 {
153     return abilityRecord_.lock();
154 }
155 
CallerRecord(int requestCode, std::weak_ptr<AbilityRecord> caller)156 CallerRecord::CallerRecord(int requestCode, std::weak_ptr<AbilityRecord> caller)
157     : requestCode_(requestCode), caller_(caller)
158 {
159     auto callerAbilityRecord = caller.lock();
160     if  (callerAbilityRecord != nullptr) {
161         callerInfo_ = std::make_shared<CallerAbilityInfo>();
162         callerInfo_->callerBundleName = callerAbilityRecord->GetAbilityInfo().bundleName;
163         callerInfo_->callerAbilityName = callerAbilityRecord->GetAbilityInfo().name;
164         callerInfo_->callerTokenId = callerAbilityRecord->GetApplicationInfo().accessTokenId;
165         callerInfo_->callerUid =  callerAbilityRecord->GetUid();
166         callerInfo_->callerPid =  callerAbilityRecord->GetPid();
167     }
168 }
169 
Update(const OHOS::AAFwk::Want &want)170 void LaunchDebugInfo::Update(const OHOS::AAFwk::Want &want)
171 {
172     isDebugAppSet = want.HasParameter(DEBUG_APP);
173     if (isDebugAppSet) {
174         debugApp = want.GetBoolParam(DEBUG_APP, false);
175     }
176     isNativeDebugSet = want.HasParameter(NATIVE_DEBUG);
177     if (isNativeDebugSet) {
178         nativeDebug = want.GetBoolParam(NATIVE_DEBUG, false);
179     }
180     isPerfCmdSet = want.HasParameter(PERF_CMD);
181     if (isPerfCmdSet) {
182         perfCmd = want.GetStringParam(PERF_CMD);
183     }
184 }
185 
AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &abilityInfo, const AppExecFwk::ApplicationInfo &applicationInfo, int requestCode)186 AbilityRecord::AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
187     const AppExecFwk::ApplicationInfo &applicationInfo, int requestCode)
188     : want_(want), abilityInfo_(abilityInfo), requestCode_(requestCode)
189 {
190     abilityInfo_.applicationInfo = applicationInfo;
191     recordId_ = abilityRecordId++;
192     auto abilityMgr = DelayedSingleton<AbilityManagerService>::GetInstance();
193     if (abilityMgr) {
194         bool isRootLauncher = (abilityInfo_.applicationInfo.bundleName == LAUNCHER_BUNDLE_NAME);
195         restartMax_ = AmsConfigurationParameter::GetInstance().GetMaxRestartNum(isRootLauncher);
196         bool flag = abilityMgr->GetStartUpNewRuleFlag();
197         want_.SetParam(COMPONENT_STARTUP_NEW_RULES, flag);
198     }
199     restartCount_ = restartMax_;
200     isAppAutoStartup_ = want_.GetBoolParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, false);
201     if (want_.HasParameter(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON)) {
202         want_.RemoveParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON);
203     }
204     SetDebugAppByWaitingDebugFlag();
205     launchDebugInfo_.Update(want_);
206 }
207 
~AbilityRecord()208 AbilityRecord::~AbilityRecord()
209 {
210     if (token_) {
211         FreezeUtil::GetInstance().DeleteLifecycleEvent(token_->AsObject());
212     }
213     FreezeUtil::GetInstance().DeleteAppLifecycleEvent(GetPid());
214     if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
215         auto object = scheduler_->AsObject();
216         if (object != nullptr) {
217             object->RemoveDeathRecipient(schedulerDeathRecipient_);
218         }
219     }
220     want_.CloseAllFd();
221 }
222 
CreateAbilityRecord(const AbilityRequest &abilityRequest)223 std::shared_ptr<AbilityRecord> AbilityRecord::CreateAbilityRecord(const AbilityRequest &abilityRequest)
224 {
225     std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(
226         abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode);
227     CHECK_POINTER_AND_RETURN(abilityRecord, nullptr);
228     abilityRecord->SetUid(abilityRequest.uid);
229     int32_t appIndex = 0;
230     (void)AbilityRuntime::StartupUtil::GetAppIndex(abilityRequest.want, appIndex);
231     abilityRecord->SetAppIndex(appIndex);
232     abilityRecord->SetSecurityFlag(abilityRequest.want.GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false));
233     abilityRecord->SetCallerAccessTokenId(abilityRequest.callerAccessTokenId);
234     abilityRecord->sessionInfo_ = abilityRequest.sessionInfo;
235     if (abilityRequest.sessionInfo != nullptr) {
236         abilityRecord->instanceKey_ = abilityRequest.sessionInfo->instanceKey;
237     }
238     if (!abilityRecord->Init()) {
239         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed init");
240         return nullptr;
241     }
242     if (abilityRequest.startSetting != nullptr) {
243         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityRequest.startSetting...");
244         abilityRecord->SetStartSetting(abilityRequest.startSetting);
245     }
246     if (abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) {
247         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityRequest.callType is CALL_REQUEST_TYPE.");
248         abilityRecord->SetStartedByCall(true);
249     }
250     abilityRecord->collaboratorType_ = abilityRequest.collaboratorType;
251     abilityRecord->missionAffinity_ = abilityRequest.want.GetStringParam(PARAM_MISSION_AFFINITY_KEY);
252 
253     auto userId = abilityRequest.appInfo.uid / BASE_USER_RANGE;
254     if ((userId == 0 ||
255         AmsConfigurationParameter::GetInstance().InResidentWhiteList(abilityRequest.abilityInfo.bundleName)) &&
256         DelayedSingleton<ResidentProcessManager>::GetInstance()->IsResidentAbility(
257             abilityRequest.abilityInfo.bundleName, abilityRequest.abilityInfo.name, userId)) {
258         abilityRecord->keepAliveBundle_ = true;
259     }
260 
261     return abilityRecord;
262 }
263 
Init()264 bool AbilityRecord::Init()
265 {
266     lifecycleDeal_ = std::make_unique<LifecycleDeal>();
267     CHECK_POINTER_RETURN_BOOL(lifecycleDeal_);
268 
269     token_ = new (std::nothrow) Token(weak_from_this());
270     CHECK_POINTER_RETURN_BOOL(token_);
271 
272     if (abilityInfo_.applicationInfo.isLauncherApp) {
273         isLauncherAbility_ = true;
274     }
275     return true;
276 }
277 
SetUid(int32_t uid)278 void AbilityRecord::SetUid(int32_t uid)
279 {
280     uid_ = uid;
281 }
282 
GetUid()283 int32_t AbilityRecord::GetUid()
284 {
285     return uid_;
286 }
287 
GetPid()288 int32_t AbilityRecord::GetPid()
289 {
290     return pid_;
291 }
292 
LoadUIAbility()293 void AbilityRecord::LoadUIAbility()
294 {
295     SetLoading(true);
296     int loadTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * LOAD_TIMEOUT_MULTIPLE;
297     if (abilityInfo_.applicationInfo.asanEnabled || abilityInfo_.applicationInfo.tsanEnabled) {
298         loadTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * LOAD_TIMEOUT_ASANENABLED;
299     } else {
300         int coldStartTimeout =
301             AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * COLDSTART_TIMEOUT_MULTIPLE;
302         std::lock_guard guard(wantLock_);
303         loadTimeout = want_.GetBoolParam("coldStart", false) ? coldStartTimeout : loadTimeout;
304     }
305     SendEvent(AbilityManagerService::LOAD_HALF_TIMEOUT_MSG, loadTimeout / HALF_TIMEOUT);
306     SendEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, loadTimeout);
307     std::string methodName = "LoadAbility";
308     g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::LOAD, methodName);
309 }
310 
LoadAbility()311 int AbilityRecord::LoadAbility()
312 {
313     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
314     TAG_LOGI(AAFwkTag::ABILITYMGR, "LoadLifecycle: abilityName:%{public}s", abilityInfo_.name.c_str());
315     startTime_ = AbilityUtil::SystemTimeMillis();
316     CHECK_POINTER_AND_RETURN(token_, ERR_INVALID_VALUE);
317     // only for UIAbility
318     if (!IsDebug() && abilityInfo_.type != AppExecFwk::AbilityType::DATA) {
319         LoadUIAbility();
320     }
321 
322     std::string appName = abilityInfo_.applicationInfo.name;
323     if (appName.empty()) {
324         TAG_LOGE(AAFwkTag::ABILITYMGR, "app name empty");
325         return ERR_INVALID_VALUE;
326     }
327 
328     if (!CanRestartRootLauncher()) {
329         TAG_LOGE(AAFwkTag::ABILITYMGR, "root launcher restart out of max");
330         return ERR_INVALID_VALUE;
331     }
332 
333     if (isRestarting_) {
334         restartTime_ = AbilityUtil::SystemTimeMillis();
335     }
336 
337     sptr<Token> callerToken_ = nullptr;
338     if (!callerList_.empty() && callerList_.back()) {
339         auto caller = callerList_.back()->GetCaller();
340         if (caller) {
341             callerToken_ = caller->GetToken();
342         }
343     }
344 
345     std::lock_guard guard(wantLock_);
346     want_.SetParam(ABILITY_OWNER_USERID, ownerMissionUserId_);
347     auto result = DelayedSingleton<AppScheduler>::GetInstance()->LoadAbility(
348         token_, callerToken_, abilityInfo_, abilityInfo_.applicationInfo, want_, recordId_, instanceKey_);
349     want_.RemoveParam(ABILITY_OWNER_USERID);
350     SetLoadState(AbilityLoadState::LOADING);
351 
352     auto isAttachDebug = DelayedSingleton<AppScheduler>::GetInstance()->IsAttachDebug(abilityInfo_.bundleName);
353     if (isAttachDebug) {
354         SetAttachDebug(true);
355     }
356     return result;
357 }
358 
CanRestartRootLauncher()359 bool AbilityRecord::CanRestartRootLauncher()
360 {
361     if (isLauncherRoot_ && isRestarting_ && IsLauncherAbility() && (restartCount_ < 0)) {
362         TAG_LOGE(AAFwkTag::ABILITYMGR, "root launcher restart out of max");
363         return false;
364     }
365     return true;
366 }
367 
CanRestartResident()368 bool AbilityRecord::CanRestartResident()
369 {
370     auto isKeepAlive = GetKeepAlive();
371     TAG_LOGD(AAFwkTag::ABILITYMGR, "isKeepAlive: %{public}d, isRestarting: %{public}d, restartCount: %{public}d",
372         isKeepAlive, isRestarting_, restartCount_);
373     if (isKeepAlive && isRestarting_ && (restartCount_ < 0)) {
374         int restartIntervalTime = 0;
375         auto abilityMgr = DelayedSingleton<AbilityManagerService>::GetInstance();
376         if (abilityMgr) {
377             restartIntervalTime = AmsConfigurationParameter::GetInstance().GetRestartIntervalTime();
378         }
379         TAG_LOGD(AAFwkTag::ABILITYMGR, "restartTime: %{public}lld, now: %{public}lld, intervalTine:%{public}d",
380             static_cast<unsigned long long>(restartTime_),
381             static_cast<unsigned long long>(AbilityUtil::SystemTimeMillis()), restartIntervalTime);
382         if ((AbilityUtil::SystemTimeMillis() - restartTime_) < restartIntervalTime) {
383             TAG_LOGE(AAFwkTag::ABILITYMGR, "resident restart out of max");
384             return false;
385         }
386     }
387     return true;
388 }
389 
390 // only for UIAbility
ForegroundAbility(uint32_t sceneFlag)391 void AbilityRecord::ForegroundAbility(uint32_t sceneFlag)
392 {
393     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
394     isWindowStarted_ = true;
395     TAG_LOGI(AAFwkTag::ABILITYMGR, "ForegroundLifecycle: name:%{public}s", abilityInfo_.name.c_str());
396     CHECK_POINTER(lifecycleDeal_);
397 
398     // schedule active after updating AbilityState and sending timeout message to avoid ability async callback
399     // earlier than above actions
400 #ifdef SUPPORT_SCREEN
401     SetAbilityStateInner(AbilityState::FOREGROUNDING);
402 #endif // SUPPORT_SCREEN
403     lifeCycleStateInfo_.sceneFlag = sceneFlag;
404     Want want = GetWant();
405     UpdateDmsCallerInfo(want);
406     if (!lifecycleDeal_->ForegroundNew(want, lifeCycleStateInfo_, GetSessionInfo()) && token_) {
407         AppExceptionHandler::GetInstance().AbilityForegroundFailed(token_->AsObject(), "ForegroundNew");
408     }
409     lifeCycleStateInfo_.sceneFlag = 0;
410     lifeCycleStateInfo_.sceneFlagBak = 0;
411     {
412         std::lock_guard guard(wantLock_);
413         InsightIntentExecuteParam::RemoveInsightIntent(want_);
414         isLaunching_ = false;
415     }
416 }
417 
GrantUriPermissionForUIExtension()418 bool AbilityRecord::GrantUriPermissionForUIExtension()
419 {
420     TAG_LOGD(AAFwkTag::ABILITYMGR, "GrantUriPermissionForUIExtension:: called.");
421     if (UIExtensionUtils::IsUIExtension(abilityInfo_.extensionAbilityType)) {
422         std::lock_guard guard(wantLock_);
423         GrantUriPermission(want_, abilityInfo_.applicationInfo.bundleName, false, 0);
424         return true;
425     }
426     return false;
427 }
428 
ForegroundUIExtensionAbility(uint32_t sceneFlag)429 void AbilityRecord::ForegroundUIExtensionAbility(uint32_t sceneFlag)
430 {
431     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
432     TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", GetURI().c_str());
433     CHECK_POINTER(lifecycleDeal_);
434 
435     // schedule active after updating AbilityState and sending timeout message to avoid ability async callback
436     // earlier than above actions.
437 #ifdef SUPPORT_SCREEN
438     SetAbilityStateInner(AbilityState::FOREGROUNDING);
439 #endif // SUPPORT_SCREEN
440     lifeCycleStateInfo_.sceneFlag = sceneFlag;
441     lifecycleDeal_->ForegroundNew(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
442     lifeCycleStateInfo_.sceneFlag = 0;
443     lifeCycleStateInfo_.sceneFlagBak = 0;
444     {
445         std::lock_guard guard(wantLock_);
446         InsightIntentExecuteParam::RemoveInsightIntent(want_);
447         isLaunching_ = false;
448     }
449 }
450 
ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFlag)451 void AbilityRecord::ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFlag)
452 {
453     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
454     std::string element = GetElementName().GetURI();
455     TAG_LOGD(AAFwkTag::ABILITYMGR, "ability record: %{public}s", element.c_str());
456     {
457         std::lock_guard guard(wantLock_);
458         GrantUriPermission(want_, abilityInfo_.applicationInfo.bundleName, false, tokenId);
459     }
460 
461     if (IsReady()) {
462         PostForegroundTimeoutTask();
463         if (IsAbilityState(AbilityState::FOREGROUND)) {
464             TAG_LOGD(AAFwkTag::ABILITYMGR, "Activate %{public}s", element.c_str());
465             ForegroundAbility(sceneFlag);
466         } else {
467             // background to active state
468             TAG_LOGD(AAFwkTag::ABILITYMGR, "MoveToForeground, %{public}s", element.c_str());
469             lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
470             std::string bundleName = GetAbilityInfo().bundleName;
471             int32_t uid = GetUid();
472             ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, "THAW_BY_FOREGROUND_ABILITY");
473             SetAbilityStateInner(AbilityState::FOREGROUNDING);
474             DelayedSingleton<AppScheduler>::GetInstance()->MoveToForeground(token_);
475         }
476     } else {
477         TAG_LOGD(AAFwkTag::ABILITYMGR, "To load ability.");
478         lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
479         LoadAbility();
480     }
481 }
482 
PostForegroundTimeoutTask()483 void AbilityRecord::PostForegroundTimeoutTask()
484 {
485     if (IsDebug()) {
486         return;
487     }
488     int foregroundTimeout =
489         AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * FOREGROUND_TIMEOUT_MULTIPLE;
490     SendEvent(AbilityManagerService::FOREGROUND_HALF_TIMEOUT_MSG, foregroundTimeout / HALF_TIMEOUT);
491     SendEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, foregroundTimeout);
492     std::string methodName = "ForegroundAbility";
493     g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::FOREGROUND, methodName);
494     ResSchedUtil::GetInstance().ReportLoadingEventToRss(LoadingStage::FOREGROUND_BEGIN, GetPid(), GetUid(),
495         foregroundTimeout);
496 }
497 
RemoveForegroundTimeoutTask()498 void AbilityRecord::RemoveForegroundTimeoutTask()
499 {
500     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetEventHandler();
501     CHECK_POINTER(handler);
502     handler->RemoveEvent(AbilityManagerService::FOREGROUND_HALF_TIMEOUT_MSG, GetAbilityRecordId());
503     handler->RemoveEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, GetAbilityRecordId());
504     SetFreezeStrategy(FreezeStrategy::NOTIFY_FREEZE_MGR);
505 }
506 
RemoveLoadTimeoutTask()507 void AbilityRecord::RemoveLoadTimeoutTask()
508 {
509     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetEventHandler();
510     CHECK_POINTER(handler);
511     handler->RemoveEvent(AbilityManagerService::LOAD_HALF_TIMEOUT_MSG, GetAbilityRecordId());
512     handler->RemoveEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, GetAbilityRecordId());
513     SetFreezeStrategy(FreezeStrategy::NOTIFY_FREEZE_MGR);
514 }
515 
PostUIExtensionAbilityTimeoutTask(uint32_t messageId)516 void AbilityRecord::PostUIExtensionAbilityTimeoutTask(uint32_t messageId)
517 {
518     if (IsDebug()) {
519         return;
520     }
521 
522     TAG_LOGD(AAFwkTag::ABILITYMGR, "post timeout %{public}d, id %{public}d", messageId, recordId_);
523     switch (messageId) {
524         case AbilityManagerService::LOAD_TIMEOUT_MSG: {
525             uint32_t timeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() *
526                 static_cast<uint32_t>(LOAD_TIMEOUT_MULTIPLE);
527             SendEvent(AbilityManagerService::LOAD_HALF_TIMEOUT_MSG, timeout / HALF_TIMEOUT, recordId_, true);
528             SendEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, timeout, recordId_, true);
529             break;
530         }
531         case AbilityManagerService::FOREGROUND_TIMEOUT_MSG: {
532             uint32_t timeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() *
533                 static_cast<uint32_t>(FOREGROUND_TIMEOUT_MULTIPLE);
534             SendEvent(AbilityManagerService::FOREGROUND_HALF_TIMEOUT_MSG, timeout / HALF_TIMEOUT, recordId_, true);
535             SendEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, timeout, recordId_, true);
536             ResSchedUtil::GetInstance().ReportLoadingEventToRss(LoadingStage::FOREGROUND_BEGIN, GetPid(), GetUid(),
537                 timeout);
538             break;
539         }
540         default: {
541             break;
542         }
543     }
544 }
545 
GetLabel()546 std::string AbilityRecord::GetLabel()
547 {
548     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
549     std::string strLabel = abilityInfo_.applicationInfo.label;
550 
551     if (abilityInfo_.resourcePath.empty()) {
552         TAG_LOGW(AAFwkTag::ABILITYMGR, "resource path empty");
553         return strLabel;
554     }
555 
556 #ifdef SUPPORT_SCREEN
557     auto resourceMgr = CreateResourceManager();
558     if (!resourceMgr) {
559         return strLabel;
560     }
561 
562     auto result = resourceMgr->GetStringById(abilityInfo_.applicationInfo.labelId, strLabel);
563     if (result != OHOS::Global::Resource::RState::SUCCESS) {
564         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, fail", __func__);
565     }
566 
567     InitColdStartingWindowResource(resourceMgr);
568 #endif
569 
570     return strLabel;
571 }
572 
573 #ifdef SUPPORT_SCREEN
ProcessForegroundAbility(const std::shared_ptr<AbilityRecord> &callerAbility, bool needExit, uint32_t sceneFlag)574 void AbilityRecord::ProcessForegroundAbility(const std::shared_ptr<AbilityRecord> &callerAbility, bool needExit,
575     uint32_t sceneFlag)
576 {
577     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
578     std::string element = GetElementName().GetURI();
579     TAG_LOGD(AAFwkTag::ABILITYMGR, "SUPPORT_GRAPHICS: ability record: %{public}s", element.c_str());
580 
581     StartingWindowHot();
582     auto flag = !IsForeground();
583     NotifyAnimationFromTerminatingAbility(callerAbility, needExit, flag);
584     PostCancelStartingWindowHotTask();
585 
586     PostForegroundTimeoutTask();
587     if (IsAbilityState(AbilityState::FOREGROUND)) {
588         TAG_LOGD(AAFwkTag::ABILITYMGR, "Activate %{public}s", element.c_str());
589         ForegroundAbility(sceneFlag);
590     } else {
591         // background to active state
592         TAG_LOGD(AAFwkTag::ABILITYMGR, "MoveToForeground, %{public}s", element.c_str());
593         lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
594         DelayedSingleton<AppScheduler>::GetInstance()->MoveToForeground(token_);
595     }
596 }
597 
NotifyAnimationFromTerminatingAbility(const std::shared_ptr<AbilityRecord>& callerAbility, bool needExit, bool flag)598 void AbilityRecord::NotifyAnimationFromTerminatingAbility(const std::shared_ptr<AbilityRecord>& callerAbility,
599     bool needExit, bool flag)
600 {
601     auto windowHandler = GetWMSHandler();
602     if (!windowHandler) {
603         TAG_LOGW(AAFwkTag::ABILITYMGR, "get WMS failed");
604         return;
605     }
606 
607     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
608     if (callerAbility) {
609         auto callerAbilityInfo = callerAbility->GetAbilityInfo();
610         SetAbilityTransitionInfo(callerAbilityInfo, fromInfo);
611         fromInfo->abilityToken_ = callerAbility->GetToken();
612     }
613 
614     if (flag && needExit) {
615         fromInfo->reason_ = TransitionReason::BACK_TRANSITION;
616     } else if (flag && !needExit) {
617         fromInfo->reason_ = TransitionReason::BACKGROUND_TRANSITION;
618     } else {
619         fromInfo->reason_ = TransitionReason::CLOSE;
620     }
621 
622     auto toInfo = CreateAbilityTransitionInfo();
623     SetAbilityTransitionInfo(abilityInfo_, toInfo);
624     bool animaEnabled = false;
625     windowHandler->NotifyWindowTransition(fromInfo, toInfo, animaEnabled);
626 }
627 
NotifyAnimationFromTerminatingAbility() const628 void AbilityRecord::NotifyAnimationFromTerminatingAbility() const
629 {
630     auto windowHandler = GetWMSHandler();
631     if (!windowHandler) {
632         TAG_LOGW(AAFwkTag::ABILITYMGR, "get WMS failed");
633         return;
634     }
635 
636     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
637     SetAbilityTransitionInfo(fromInfo);
638     fromInfo->reason_ = TransitionReason::CLOSE;
639     bool animaEnabled = false;
640     windowHandler->NotifyWindowTransition(fromInfo, nullptr, animaEnabled);
641 }
642 
NotifyAnimationFromMinimizeAbility(bool& animaEnabled)643 void AbilityRecord::NotifyAnimationFromMinimizeAbility(bool& animaEnabled)
644 {
645     auto windowHandler = GetWMSHandler();
646     if (!windowHandler) {
647         TAG_LOGW(AAFwkTag::ABILITYMGR, "get WMS failed");
648         return;
649     }
650     TAG_LOGI(AAFwkTag::ABILITYMGR, "Notify Animation From MinimizeAbility");
651     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
652     SetAbilityTransitionInfo(fromInfo);
653     fromInfo->reason_ = TransitionReason::MINIMIZE;
654     windowHandler->NotifyWindowTransition(fromInfo, nullptr, animaEnabled);
655 }
656 
SetAbilityTransitionInfo(sptr<AbilityTransitionInfo>& info) const657 void AbilityRecord::SetAbilityTransitionInfo(sptr<AbilityTransitionInfo>& info) const
658 {
659     info->abilityToken_ = token_;
660     info->missionId_ = missionId_;
661     info->abilityName_ = abilityInfo_.name;
662     info->bundleName_ = abilityInfo_.bundleName;
663     info->windowModes_ = abilityInfo_.windowModes;
664     info->maxWindowRatio_ = abilityInfo_.maxWindowRatio;
665     info->minWindowRatio_ = abilityInfo_.minWindowRatio;
666     info->maxWindowWidth_ = abilityInfo_.maxWindowWidth;
667     info->minWindowWidth_ = abilityInfo_.minWindowWidth;
668     info->maxWindowHeight_ = abilityInfo_.maxWindowHeight;
669     info->minWindowHeight_ = abilityInfo_.minWindowHeight;
670     info->orientation_ = abilityInfo_.orientation;
671     info->apiCompatibleVersion_ = abilityInfo_.applicationInfo.apiCompatibleVersion;
672 }
673 
CreateAbilityTransitionInfo()674 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo()
675 {
676     sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
677     SetAbilityTransitionInfo(info);
678     SetStartingWindow(true);
679     return info;
680 }
681 
StartingWindowHot()682 void AbilityRecord::StartingWindowHot()
683 {
684     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
685     auto windowHandler = GetWMSHandler();
686     if (!windowHandler) {
687         TAG_LOGW(AAFwkTag::ABILITYMGR, "get WMS failed");
688         return;
689     }
690 
691     auto missionListWrap = DelayedSingleton<AbilityManagerService>::GetInstance()->GetMissionListWrap();
692     if (missionListWrap == nullptr) {
693         TAG_LOGW(AAFwkTag::ABILITYMGR, "null missionListWrap");
694         return;
695     }
696 
697     auto pixelMap = missionListWrap->GetSnapshot(missionId_);
698     if (!pixelMap) {
699         TAG_LOGW(AAFwkTag::ABILITYMGR, "get snapshot failed");
700     }
701 
702     auto info = CreateAbilityTransitionInfo();
703     TAG_LOGI(AAFwkTag::ABILITYMGR, "notify wms to start StartingWindow");
704     windowHandler->StartingWindow(info, pixelMap);
705 }
706 
ProcessForegroundAbility(bool isRecent, const AbilityRequest &abilityRequest, std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility, uint32_t sceneFlag)707 void AbilityRecord::ProcessForegroundAbility(bool isRecent, const AbilityRequest &abilityRequest,
708     std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility,
709     uint32_t sceneFlag)
710 {
711     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
712     std::string element = GetElementName().GetURI();
713     TAG_LOGD(AAFwkTag::ABILITYMGR, "SUPPORT_GRAPHICS: ability record: %{public}s", element.c_str());
714     {
715         std::lock_guard guard(wantLock_);
716         GrantUriPermission(want_, abilityInfo_.applicationInfo.bundleName, false, 0);
717     }
718 
719     if (IsReady() && !GetRestartAppFlag()) {
720         auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
721         if (!handler) {
722             TAG_LOGE(AAFwkTag::ABILITYMGR, "fail get AbilityEventHandler");
723             return;
724         }
725         auto taskName = std::to_string(missionId_) + "_hot";
726         handler->CancelTask(taskName);
727 
728         if (isWindowStarted_) {
729             StartingWindowTask(isRecent, false, abilityRequest, startOptions);
730             AnimationTask(isRecent, abilityRequest, startOptions, callerAbility);
731             PostCancelStartingWindowHotTask();
732         } else {
733             StartingWindowTask(isRecent, true, abilityRequest, startOptions);
734             AnimationTask(isRecent, abilityRequest, startOptions, callerAbility);
735             PostCancelStartingWindowColdTask();
736         }
737         PostForegroundTimeoutTask();
738         if (IsAbilityState(AbilityState::FOREGROUND)) {
739             TAG_LOGD(AAFwkTag::ABILITYMGR, "Activate %{public}s", element.c_str());
740             ForegroundAbility(sceneFlag);
741         } else {
742             // background to active state
743             TAG_LOGD(AAFwkTag::ABILITYMGR, "MoveToForeground, %{public}s", element.c_str());
744             lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
745             DelayedSingleton<AppScheduler>::GetInstance()->MoveToForeground(token_);
746         }
747     } else {
748         TAG_LOGD(AAFwkTag::ABILITYMGR, "SUPPORT_GRAPHICS: to load ability.");
749         lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
750         auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
751         auto needStartingWindow = abilityRequest.want.GetBoolParam(NEED_STARTINGWINDOW, true);
752         if (!isSaCall || needStartingWindow) {
753             StartingWindowTask(isRecent, true, abilityRequest, startOptions);
754             AnimationTask(isRecent, abilityRequest, startOptions, callerAbility);
755             PostCancelStartingWindowColdTask();
756         }
757         LoadAbility();
758     }
759 }
760 
GetWantFromMission() const761 std::shared_ptr<Want> AbilityRecord::GetWantFromMission() const
762 {
763     auto missionListWrap = DelayedSingleton<AbilityManagerService>::GetInstance()->GetMissionListWrap();
764     if (missionListWrap == nullptr) {
765         TAG_LOGW(AAFwkTag::ABILITYMGR, "null missionListWrap");
766         return nullptr;
767     }
768 
769     InnerMissionInfo innerMissionInfo;
770     int getMission = missionListWrap->GetInnerMissionInfoById(missionId_, innerMissionInfo);
771     if (getMission != ERR_OK) {
772         TAG_LOGE(
773             AAFwkTag::ABILITYMGR, "no find mission info by missionId: %{public}d", missionId_);
774         return nullptr;
775     }
776 
777     return std::make_shared<Want>(innerMissionInfo.missionInfo.want);
778 }
779 
AnimationTask(bool isRecent, const AbilityRequest &abilityRequest, const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility)780 void AbilityRecord::AnimationTask(bool isRecent, const AbilityRequest &abilityRequest,
781     const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility)
782 {
783     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
784     if (isRecent) {
785         auto want = GetWantFromMission();
786         NotifyAnimationFromRecentTask(startOptions, want);
787     } else {
788         if (!IsForeground()) {
789             NotifyAnimationFromStartingAbility(callerAbility, abilityRequest);
790         }
791     }
792 }
793 
SetShowWhenLocked(const AppExecFwk::AbilityInfo &abilityInfo, sptr<AbilityTransitionInfo> &info) const794 void AbilityRecord::SetShowWhenLocked(const AppExecFwk::AbilityInfo &abilityInfo,
795     sptr<AbilityTransitionInfo> &info) const
796 {
797     for (const auto &data : abilityInfo.metaData.customizeData) {
798         if (data.name == SHOW_ON_LOCK_SCREEN) {
799             info->isShowWhenLocked_ = true;
800             break;
801         }
802     }
803 }
804 
SetAbilityTransitionInfo(const AppExecFwk::AbilityInfo &abilityInfo, sptr<AbilityTransitionInfo> &info) const805 void AbilityRecord::SetAbilityTransitionInfo(const AppExecFwk::AbilityInfo &abilityInfo,
806     sptr<AbilityTransitionInfo> &info) const
807 {
808     info->abilityName_ = abilityInfo.name;
809     info->bundleName_ = abilityInfo.bundleName;
810     info->windowModes_ = abilityInfo.windowModes;
811     info->orientation_ = abilityInfo.orientation;
812     info->apiCompatibleVersion_ = abilityInfo.applicationInfo.apiCompatibleVersion;
813     SetShowWhenLocked(abilityInfo, info);
814 }
815 
NotifyAnimationFromRecentTask(const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want) const816 void AbilityRecord::NotifyAnimationFromRecentTask(const std::shared_ptr<StartOptions> &startOptions,
817     const std::shared_ptr<Want> &want) const
818 {
819     auto windowHandler = GetWMSHandler();
820     if (!windowHandler) {
821         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, failed", __func__);
822         return;
823     }
824 
825     auto toInfo = CreateAbilityTransitionInfo(startOptions, want);
826     toInfo->abilityToken_ = token_;
827     toInfo->missionId_ = missionId_;
828     SetAbilityTransitionInfo(abilityInfo_, toInfo);
829     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
830     fromInfo->isRecent_ = true;
831     bool animaEnabled = false;
832     windowHandler->NotifyWindowTransition(fromInfo, toInfo, animaEnabled);
833 }
834 
NotifyAnimationFromStartingAbility(const std::shared_ptr<AbilityRecord> &callerAbility, const AbilityRequest &abilityRequest) const835 void AbilityRecord::NotifyAnimationFromStartingAbility(const std::shared_ptr<AbilityRecord> &callerAbility,
836     const AbilityRequest &abilityRequest) const
837 {
838     auto windowHandler = GetWMSHandler();
839     if (!windowHandler) {
840         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, failed", __func__);
841         return;
842     }
843 
844     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
845     if (callerAbility) {
846         auto callerAbilityInfo = callerAbility->GetAbilityInfo();
847         SetAbilityTransitionInfo(callerAbilityInfo, fromInfo);
848         fromInfo->abilityToken_ = callerAbility->GetToken();
849     } else {
850         fromInfo->abilityToken_ = abilityRequest.callerToken;
851     }
852 
853     auto toInfo = CreateAbilityTransitionInfo(abilityRequest);
854     toInfo->abilityToken_ = token_;
855     toInfo->missionId_ = missionId_;
856     SetAbilityTransitionInfo(abilityInfo_, toInfo);
857     bool animaEnabled = false;
858     windowHandler->NotifyWindowTransition(fromInfo, toInfo, animaEnabled);
859 }
860 
StartingWindowTask(bool isRecent, bool isCold, const AbilityRequest &abilityRequest, std::shared_ptr<StartOptions> &startOptions)861 void AbilityRecord::StartingWindowTask(bool isRecent, bool isCold, const AbilityRequest &abilityRequest,
862     std::shared_ptr<StartOptions> &startOptions)
863 {
864     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
865     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
866     if (isRecent) {
867         auto want = GetWantFromMission();
868         if (isCold) {
869             StartingWindowCold(startOptions, want, abilityRequest);
870         } else {
871             StartingWindowHot(startOptions, want, abilityRequest);
872         }
873     } else {
874         std::shared_ptr<Want> want = nullptr;
875         if (isCold) {
876             StartingWindowCold(startOptions, want, abilityRequest);
877         } else {
878             StartingWindowHot(startOptions, want, abilityRequest);
879         }
880     }
881 }
882 
PostCancelStartingWindowHotTask()883 void AbilityRecord::PostCancelStartingWindowHotTask()
884 {
885     if (IsDebug()) {
886         TAG_LOGI(AAFwkTag::ABILITYMGR, "debug mode, just return");
887         return;
888     }
889     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
890     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
891     CHECK_POINTER_LOG(handler, "Fail to get TaskHandler.");
892 
893     auto windowHandler = GetWMSHandler();
894     CHECK_POINTER_LOG(windowHandler, "PostCancelStartingWindowColdTask, Get WMS handler failed.");
895 
896     auto abilityRecord(shared_from_this());
897     auto delayTask = [windowHandler, abilityRecord] {
898         if (windowHandler && abilityRecord && abilityRecord->IsStartingWindow() &&
899             abilityRecord->GetAbilityState() != AbilityState::FOREGROUNDING) {
900             TAG_LOGD(AAFwkTag::ABILITYMGR, "PostCancelStartingWindowHotTask, call windowHandler CancelStartingWindow.");
901             windowHandler->CancelStartingWindow(abilityRecord->GetToken());
902             abilityRecord->SetStartingWindow(false);
903         }
904     };
905     auto taskName = std::to_string(missionId_) + "_hot";
906     int foregroundTimeout =
907         AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * FOREGROUND_TIMEOUT_MULTIPLE;
908     handler->SubmitTask(delayTask, taskName, foregroundTimeout);
909 }
910 
PostCancelStartingWindowColdTask()911 void AbilityRecord::PostCancelStartingWindowColdTask()
912 {
913     if (IsDebug()) {
914         TAG_LOGI(AAFwkTag::ABILITYMGR, "debug mode, just return");
915         return;
916     }
917     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
918     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
919     CHECK_POINTER_LOG(handler, "Fail to get TaskHandler.");
920 
921     auto windowHandler = GetWMSHandler();
922     CHECK_POINTER_LOG(windowHandler, "PostCancelStartingWindowColdTask, Get WMS handler failed.");
923 
924     auto abilityRecord(shared_from_this());
925     auto delayTask = [windowHandler, abilityRecord] {
926         if (windowHandler && abilityRecord && abilityRecord->IsStartingWindow() &&
927             (abilityRecord->GetScheduler() == nullptr ||
928             abilityRecord->GetAbilityState() != AbilityState::FOREGROUNDING)) {
929             TAG_LOGD(AAFwkTag::ABILITYMGR,
930                 "PostCancelStartingWindowColdTask, call windowHandler CancelStartingWindow.");
931             windowHandler->CancelStartingWindow(abilityRecord->GetToken());
932             abilityRecord->SetStartingWindow(false);
933         }
934     };
935     auto taskName = std::to_string(missionId_) + "_cold";
936     int loadTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * LOAD_TIMEOUT_MULTIPLE;
937     handler->SubmitTask(delayTask, taskName, loadTimeout);
938 }
939 
GetWMSHandler() const940 sptr<IWindowManagerServiceHandler> AbilityRecord::GetWMSHandler() const
941 {
942     auto abilityMgr = DelayedSingleton<AbilityManagerService>::GetInstance();
943     if (!abilityMgr) {
944         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, fail", __func__);
945         return nullptr;
946     }
947     return abilityMgr->GetWMSHandler();
948 }
949 
SetWindowModeAndDisplayId(sptr<AbilityTransitionInfo> &info, const std::shared_ptr<Want> &want) const950 void AbilityRecord::SetWindowModeAndDisplayId(sptr<AbilityTransitionInfo> &info,
951     const std::shared_ptr<Want> &want) const
952 {
953     if (!want) {
954         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, want invalid", __func__);
955         return;
956     }
957     auto mode = want->GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1);
958     auto displayId = want->GetIntParam(Want::PARAM_RESV_DISPLAY_ID, -1);
959     if (mode != -1) {
960         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: origin window mode: %{public}d", __func__, mode);
961         info->mode_ = static_cast<uint32_t>(mode);
962     }
963     if (displayId != -1) {
964         info->displayId_ = static_cast<uint64_t>(displayId);
965     }
966 }
967 
CreateAbilityTransitionInfo( const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want) const968 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo(
969     const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want) const
970 {
971     sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
972     if (startOptions != nullptr) {
973         info->mode_ = static_cast<uint32_t>(startOptions->GetWindowMode());
974         TAG_LOGI(AAFwkTag::ABILITYMGR, "window mode:%{public}d", info->mode_);
975         info->displayId_ = static_cast<uint64_t>(startOptions->GetDisplayID());
976     } else {
977         SetWindowModeAndDisplayId(info, want);
978     }
979     return info;
980 }
981 
CreateAbilityTransitionInfo(const AbilityRequest &abilityRequest) const982 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo(const AbilityRequest &abilityRequest) const
983 {
984     sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
985     auto abilityStartSetting = abilityRequest.startSetting;
986     if (abilityStartSetting) {
987         auto windowMode = abilityStartSetting->GetProperty(AbilityStartSetting::WINDOW_MODE_KEY);
988         auto displayId = abilityStartSetting->GetProperty(AbilityStartSetting::WINDOW_DISPLAY_ID_KEY);
989         try {
990             info->mode_ = static_cast<uint32_t>(std::stoi(windowMode));
991             info->displayId_ = static_cast<uint64_t>(std::stoi(displayId));
992         } catch (...) {
993             TAG_LOGW(AAFwkTag::ABILITYMGR, "windowMode: stoi(%{public}s) failed", windowMode.c_str());
994             TAG_LOGW(AAFwkTag::ABILITYMGR, "displayId: stoi(%{public}s) failed", displayId.c_str());
995         }
996     } else {
997         SetWindowModeAndDisplayId(info, std::make_shared<Want>(abilityRequest.want));
998     }
999     return info;
1000 }
1001 
CreateResourceManager() const1002 std::shared_ptr<Global::Resource::ResourceManager> AbilityRecord::CreateResourceManager() const
1003 {
1004     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1005     UErrorCode status = U_ZERO_ERROR;
1006     icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLocale(), status);
1007     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
1008     resConfig->SetLocaleInfo(locale);
1009     AppExecFwk::Configuration cfg;
1010     if (DelayedSingleton<AbilityManagerService>::GetInstance()->GetConfiguration(cfg) == 0) {
1011         std::string colormode = cfg.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
1012         TAG_LOGD(AAFwkTag::ABILITYMGR, "getcolormode is %{public}s.", colormode.c_str());
1013         resConfig->SetColorMode(AppExecFwk::ConvertColorMode(colormode));
1014     } else {
1015         TAG_LOGW(AAFwkTag::ABILITYMGR, "getcolormode failed");
1016     }
1017 
1018     std::shared_ptr<Global::Resource::ResourceManager> resourceMgr(Global::Resource::CreateResourceManager());
1019     resourceMgr->UpdateResConfig(*resConfig);
1020 
1021     std::string loadPath;
1022     if (!abilityInfo_.hapPath.empty()) {
1023         loadPath = abilityInfo_.hapPath;
1024     } else {
1025         loadPath = abilityInfo_.resourcePath;
1026     }
1027 
1028     if (loadPath.empty()) {
1029         TAG_LOGW(AAFwkTag::ABILITYMGR, "invalid app resource");
1030         return nullptr;
1031     }
1032 
1033     if (!resourceMgr->AddResource(loadPath.c_str())) {
1034         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, failed", __func__);
1035         return nullptr;
1036     }
1037     return resourceMgr;
1038 }
1039 
GetPixelMap(const uint32_t windowIconId, std::shared_ptr<Global::Resource::ResourceManager> resourceMgr) const1040 std::shared_ptr<Media::PixelMap> AbilityRecord::GetPixelMap(const uint32_t windowIconId,
1041     std::shared_ptr<Global::Resource::ResourceManager> resourceMgr) const
1042 {
1043     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1044     if (resourceMgr == nullptr) {
1045         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, null resourceMgr", __func__);
1046         return nullptr;
1047     }
1048 
1049     Media::SourceOptions opts;
1050     uint32_t errorCode = 0;
1051     std::unique_ptr<Media::ImageSource> imageSource;
1052     if (!abilityInfo_.hapPath.empty()) { // hap is not unzip
1053         std::unique_ptr<uint8_t[]> iconOut;
1054         size_t len;
1055         if (resourceMgr->GetMediaDataById(windowIconId, len, iconOut) != Global::Resource::RState::SUCCESS) {
1056             return nullptr;
1057         }
1058         imageSource = Media::ImageSource::CreateImageSource(iconOut.get(), len, opts, errorCode);
1059     } else { // already unzip hap
1060         std::string iconPath;
1061         if (resourceMgr->GetMediaById(windowIconId, iconPath) != Global::Resource::RState::SUCCESS) {
1062             return nullptr;
1063         }
1064         imageSource = Media::ImageSource::CreateImageSource(iconPath, opts, errorCode);
1065     }
1066 
1067     if (errorCode != 0 || imageSource == nullptr) {
1068         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed, id %{private}d err %{public}d", windowIconId, errorCode);
1069         return nullptr;
1070     }
1071 
1072     Media::DecodeOptions decodeOpts;
1073     auto pixelMapPtr = imageSource->CreatePixelMap(decodeOpts, errorCode);
1074     if (errorCode != 0) {
1075         TAG_LOGE(
1076             AAFwkTag::ABILITYMGR, "failed, id %{private}d err %{public}d", windowIconId, errorCode);
1077         return nullptr;
1078     }
1079     TAG_LOGD(AAFwkTag::ABILITYMGR, "OUT.");
1080     return std::shared_ptr<Media::PixelMap>(pixelMapPtr.release());
1081 }
1082 
CreateAbilityTransitionInfo( const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest)1083 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo(
1084     const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want,
1085     const AbilityRequest &abilityRequest)
1086 {
1087     sptr<AbilityTransitionInfo> info;
1088     if (startOptions) {
1089         info = CreateAbilityTransitionInfo(startOptions, want);
1090     } else {
1091         info = CreateAbilityTransitionInfo(abilityRequest);
1092     }
1093 
1094     SetAbilityTransitionInfo(info);
1095     SetStartingWindow(true);
1096     return info;
1097 }
1098 
StartingWindowHot(const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest)1099 void AbilityRecord::StartingWindowHot(const std::shared_ptr<StartOptions> &startOptions,
1100     const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest)
1101 {
1102     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1103     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
1104     auto windowHandler = GetWMSHandler();
1105     if (!windowHandler) {
1106         TAG_LOGW(AAFwkTag::ABILITYMGR, "get WMS failed");
1107         return;
1108     }
1109 
1110     auto missionListWrap = DelayedSingleton<AbilityManagerService>::GetInstance()->GetMissionListWrap();
1111     if (missionListWrap == nullptr) {
1112         TAG_LOGW(AAFwkTag::ABILITYMGR, "null missionListWrap");
1113         return;
1114     }
1115 
1116     auto pixelMap = missionListWrap->GetSnapshot(missionId_);
1117     if (!pixelMap) {
1118         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, failed", __func__);
1119     }
1120 
1121     auto info = CreateAbilityTransitionInfo(startOptions, want, abilityRequest);
1122     windowHandler->StartingWindow(info, pixelMap);
1123 }
1124 
StartingWindowCold(const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest)1125 void AbilityRecord::StartingWindowCold(const std::shared_ptr<StartOptions> &startOptions,
1126     const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest)
1127 {
1128     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1129     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
1130     auto windowHandler = GetWMSHandler();
1131     if (!windowHandler) {
1132         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, get WMS failed", __func__);
1133         return;
1134     }
1135 
1136     // get bg pixelmap and color.
1137     std::shared_ptr<Media::PixelMap> pixelMap = nullptr;
1138     uint32_t bgColor = 0;
1139     GetColdStartingWindowResource(pixelMap, bgColor);
1140 
1141     // start window
1142     auto info = CreateAbilityTransitionInfo(startOptions, want, abilityRequest);
1143     windowHandler->StartingWindow(info, pixelMap, bgColor);
1144     startingWindowBg_.reset();
1145 }
1146 
GetColdStartingWindowResource(std::shared_ptr<Media::PixelMap> &bg, uint32_t &bgColor)1147 void AbilityRecord::GetColdStartingWindowResource(std::shared_ptr<Media::PixelMap> &bg, uint32_t &bgColor)
1148 {
1149     bg = startingWindowBg_;
1150     bgColor = bgColor_;
1151     if (bg) {
1152         return;
1153     }
1154     auto resourceMgr = CreateResourceManager();
1155     if (!resourceMgr) {
1156         TAG_LOGW(AAFwkTag::ABILITYMGR, "get resourceMgr failed");
1157         return;
1158     }
1159 
1160     auto windowIconId = static_cast<uint32_t>(abilityInfo_.startWindowIconId);
1161     bg = GetPixelMap(windowIconId, resourceMgr);
1162 
1163     auto colorId = static_cast<uint32_t>(abilityInfo_.startWindowBackgroundId);
1164     auto colorErrval = resourceMgr->GetColorById(colorId, bgColor);
1165     if (colorErrval != OHOS::Global::Resource::RState::SUCCESS) {
1166         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed to GetColorById");
1167         bgColor = 0xdfffffff;
1168     }
1169     TAG_LOGD(AAFwkTag::ABILITYMGR, "colorId is %{public}u, bgColor is %{public}u.", colorId, bgColor);
1170 }
1171 
InitColdStartingWindowResource( const std::shared_ptr<Global::Resource::ResourceManager> &resourceMgr)1172 void AbilityRecord::InitColdStartingWindowResource(
1173     const std::shared_ptr<Global::Resource::ResourceManager> &resourceMgr)
1174 {
1175     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1176     if (!resourceMgr) {
1177         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid resourceManager");
1178         return;
1179     }
1180 
1181     startingWindowBg_ = GetPixelMap(static_cast<uint32_t>(abilityInfo_.startWindowIconId), resourceMgr);
1182     if (resourceMgr->GetColorById(static_cast<uint32_t>(abilityInfo_.startWindowBackgroundId), bgColor_) !=
1183         OHOS::Global::Resource::RState::SUCCESS) {
1184         TAG_LOGW(AAFwkTag::ABILITYMGR, "getColorById failed");
1185         bgColor_ = 0xdfffffff;
1186     }
1187 
1188     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
1189     if (startingWindowBg_ && handler) {
1190         auto delayTask = [me = weak_from_this()] {
1191             auto self = me.lock();
1192             if (!self || !self->startingWindowBg_) {
1193                 return;
1194             }
1195             self->startingWindowBg_.reset();
1196         };
1197         handler->SubmitTask(delayTask, "release_bg", RELEASE_STARTING_BG_TIMEOUT);
1198     }
1199 }
1200 
ReportAtomicServiceDrawnCompleteEvent()1201 bool AbilityRecord::ReportAtomicServiceDrawnCompleteEvent()
1202 {
1203     if (abilityInfo_.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE) {
1204         return false;
1205     }
1206     TAG_LOGD(AAFwkTag::ABILITYMGR, "Report atomic service first frame complete event.");
1207     AAFwk::EventInfo eventInfo;
1208     eventInfo.abilityName = abilityInfo_.name;
1209     eventInfo.moduleName = abilityInfo_.moduleName;
1210     eventInfo.bundleName = abilityInfo_.bundleName;
1211     auto eventName = AAFwk::EventName::ATOMIC_SERVICE_DRAWN_COMPLETE;
1212     AAFwk::EventReport::SendAtomicServiceEvent(eventName, HiSysEventType::BEHAVIOR, eventInfo);
1213     return true;
1214 }
1215 
SetCompleteFirstFrameDrawing(const bool flag)1216 void AbilityRecord::SetCompleteFirstFrameDrawing(const bool flag)
1217 {
1218     isCompleteFirstFrameDrawing_ = flag;
1219 }
1220 
IsCompleteFirstFrameDrawing() const1221 bool AbilityRecord::IsCompleteFirstFrameDrawing() const
1222 {
1223     return isCompleteFirstFrameDrawing_;
1224 }
1225 
GetColdStartFlag()1226 bool AbilityRecord::GetColdStartFlag()
1227 {
1228     return coldStart_;
1229 }
1230 
SetColdStartFlag(bool isColdStart)1231 void AbilityRecord::SetColdStartFlag(bool isColdStart)
1232 {
1233     coldStart_ = isColdStart;
1234 }
1235 #endif
1236 
BackgroundAbility(const Closure &task)1237 void AbilityRecord::BackgroundAbility(const Closure &task)
1238 {
1239     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1240     TAG_LOGI(AAFwkTag::ABILITYMGR, "BackgroundLifecycle: ability:%{public}s", GetURI().c_str());
1241     if (lifecycleDeal_ == nullptr) {
1242         TAG_LOGE(AAFwkTag::ABILITYMGR, "null lifecycleDeal_");
1243         return;
1244     }
1245 
1246     if (!IsDebug()) {
1247         auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
1248         if (handler && task) {
1249             int backgroundTimeout =
1250                 AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * BACKGROUND_TIMEOUT_MULTIPLE;
1251             handler->SubmitTask(task, "background_" + std::to_string(recordId_), backgroundTimeout, false);
1252 
1253             if (abilityInfo_.type == AppExecFwk::AbilityType::PAGE) {
1254                 std::string methodName = "BackgroundAbility";
1255                 g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::BACKGROUND, methodName);
1256             }
1257         }
1258     } else {
1259         TAG_LOGI(AAFwkTag::ABILITYMGR, "debug mode, no need to handle");
1260     }
1261 
1262     if (!IsTerminating() || IsRestarting()) {
1263         // schedule save ability state before moving to background.
1264         SaveAbilityState();
1265     }
1266 
1267     // schedule background after updating AbilityState and sending timeout message to avoid ability async callback
1268     // earlier than above actions.
1269 #ifdef SUPPORT_SCREEN
1270     SetAbilityStateInner(AbilityState::BACKGROUNDING);
1271 #endif // SUPPORT_SCREEN
1272     lifecycleDeal_->BackgroundNew(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
1273     std::lock_guard guard(wantLock_);
1274     isLaunching_ = false;
1275 }
1276 
PrepareTerminateAbility()1277 bool AbilityRecord::PrepareTerminateAbility()
1278 {
1279     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
1280     if (lifecycleDeal_ == nullptr) {
1281         TAG_LOGE(AAFwkTag::ABILITYMGR, "null lifecycleDeal_");
1282         return false;
1283     }
1284     return lifecycleDeal_->PrepareTerminateAbility();
1285 }
1286 
TerminateAbility()1287 int AbilityRecord::TerminateAbility()
1288 {
1289     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1290     TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", abilityInfo_.name.c_str());
1291 #ifdef WITH_DLP
1292     HandleDlpClosed();
1293 #endif // WITH_DLP
1294     AAFwk::EventInfo eventInfo;
1295     eventInfo.bundleName = GetAbilityInfo().bundleName;
1296     eventInfo.abilityName = GetAbilityInfo().name;
1297     if (clearMissionFlag_) {
1298         TAG_LOGD(AAFwkTag::ABILITYMGR, "deleteAbilityRecoverInfo before clearMission");
1299         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
1300             DeleteAbilityRecoverInfo(GetAbilityInfo().applicationInfo.accessTokenId, GetAbilityInfo().moduleName,
1301             GetAbilityInfo().name);
1302     }
1303     AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::TERMINATE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1304     eventInfo.errCode = DelayedSingleton<AppScheduler>::GetInstance()->TerminateAbility(token_, clearMissionFlag_);
1305     if (eventInfo.errCode != ERR_OK) {
1306         AAFwk::EventReport::SendAbilityEvent(
1307             AAFwk::EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1308     }
1309     return eventInfo.errCode;
1310 }
1311 
GetAbilityInfo() const1312 const AppExecFwk::AbilityInfo &AbilityRecord::GetAbilityInfo() const
1313 {
1314     return abilityInfo_;
1315 }
1316 
GetApplicationInfo() const1317 const AppExecFwk::ApplicationInfo &AbilityRecord::GetApplicationInfo() const
1318 {
1319     return abilityInfo_.applicationInfo;
1320 }
1321 
GetAbilityState() const1322 AbilityState AbilityRecord::GetAbilityState() const
1323 {
1324     return currentState_;
1325 }
1326 
GetAbilityWindowConfig() const1327 WindowConfig AbilityRecord::GetAbilityWindowConfig() const
1328 {
1329     return windowConfig_;
1330 }
1331 
IsForeground() const1332 bool AbilityRecord::IsForeground() const
1333 {
1334     return currentState_ == AbilityState::FOREGROUND || currentState_ == AbilityState::FOREGROUNDING;
1335 }
1336 
GetAbilityVisibilityState() const1337 AbilityVisibilityState AbilityRecord::GetAbilityVisibilityState() const
1338 {
1339     return abilityVisibilityState_.load();
1340 }
1341 
SetAbilityVisibilityState(AbilityVisibilityState state)1342 void AbilityRecord::SetAbilityVisibilityState(AbilityVisibilityState state)
1343 {
1344     abilityVisibilityState_.store(state);
1345 }
1346 
UpdateAbilityVisibilityState()1347 void AbilityRecord::UpdateAbilityVisibilityState()
1348 {
1349     if (GetAbilityVisibilityState() == AbilityVisibilityState::INITIAL) {
1350         auto state = AbilityVisibilityState::UNSPECIFIED;
1351         auto sessionInfo = GetSessionInfo();
1352         if (sessionInfo && sessionInfo->processOptions &&
1353             ProcessOptions::IsNewProcessMode(sessionInfo->processOptions->processMode)) {
1354             auto startupVisibility = sessionInfo->processOptions->startupVisibility;
1355             if (startupVisibility == StartupVisibility::STARTUP_SHOW) {
1356                 state = AbilityVisibilityState::FOREGROUND_SHOW;
1357             } else if (startupVisibility == StartupVisibility::STARTUP_HIDE) {
1358                 state = AbilityVisibilityState::FOREGROUND_HIDE;
1359             }
1360         }
1361         SetAbilityVisibilityState(state);
1362     }
1363 }
1364 #ifdef SUPPORT_SCREEN
SetAbilityStateInner(AbilityState state)1365 void AbilityRecord::SetAbilityStateInner(AbilityState state)
1366 {
1367     currentState_ = state;
1368     if (currentState_ == AbilityState::BACKGROUND) {
1369         isAbilityForegrounding_ = false;
1370     }
1371 
1372     auto collaborator = DelayedSingleton<AbilityManagerService>::GetInstance()->GetCollaborator(
1373         collaboratorType_);
1374     if (collaborator != nullptr) {
1375         TAG_LOGD(AAFwkTag::ABILITYMGR, "notify collaborator, missionId:%{public}d, state:%{public}d", missionId_,
1376             static_cast<int32_t>(state));
1377         int ret = ERR_OK;
1378         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1379             auto sessionInfo = GetSessionInfo();
1380             if (sessionInfo == nullptr) {
1381                 TAG_LOGE(AAFwkTag::ABILITYMGR, "null sessionInfo");
1382                 return;
1383             }
1384             int32_t persistentId = sessionInfo->persistentId;
1385             switch (state) {
1386                 case AbilityState::BACKGROUNDING: {
1387                     ret = collaborator->NotifyMoveMissionToBackground(persistentId);
1388                     break;
1389                 }
1390                 case AbilityState::TERMINATING: {
1391                     ret = collaborator->NotifyTerminateMission(persistentId);
1392                     break;
1393                 }
1394                 default:
1395                     break;
1396             }
1397             if (ret != ERR_OK) {
1398                 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed,err: %{public}d", ret);
1399             }
1400             return;
1401         }
1402         switch (state) {
1403             case AbilityState::FOREGROUNDING: {
1404                 ret = collaborator->NotifyMoveMissionToForeground(missionId_);
1405                 break;
1406             }
1407             case AbilityState::BACKGROUNDING: {
1408                 ret = collaborator->NotifyMoveMissionToBackground(missionId_);
1409                 break;
1410             }
1411             case AbilityState::TERMINATING: {
1412                 ret = collaborator->NotifyTerminateMission(missionId_);
1413                 break;
1414             }
1415             default:
1416                 break;
1417         }
1418         if (ret != ERR_OK) {
1419             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed, err: %{public}d", ret);
1420         }
1421     }
1422 
1423     auto missionListWrap = DelayedSingleton<AbilityManagerService>::GetInstance()->GetMissionListWrap();
1424     CHECK_POINTER(missionListWrap);
1425     missionListWrap->SetMissionAbilityState(missionId_, currentState_);
1426 }
1427 #endif // SUPPORT_SCREEN
GetAbilityForegroundingFlag() const1428 bool AbilityRecord::GetAbilityForegroundingFlag() const
1429 {
1430     return isAbilityForegrounding_;
1431 }
1432 
SetAbilityForegroundingFlag()1433 void AbilityRecord::SetAbilityForegroundingFlag()
1434 {
1435     isAbilityForegrounding_ = true;
1436     DelayedSingleton<AppScheduler>::GetInstance()->SetAbilityForegroundingFlagToAppRecord(pid_);
1437 }
1438 #ifdef SUPPORT_SCREEN
SetAbilityState(AbilityState state)1439 void AbilityRecord::SetAbilityState(AbilityState state)
1440 {
1441     SetAbilityStateInner(state);
1442     if (state == AbilityState::FOREGROUND || state == AbilityState::ACTIVE || state == AbilityState::BACKGROUND) {
1443         SetRestarting(false);
1444     }
1445     if (state == AbilityState::FOREGROUND) {
1446         ResSchedUtil::GetInstance().ReportLoadingEventToRss(LoadingStage::FOREGROUND_END, GetPid(), GetUid());
1447     }
1448 }
1449 #endif // SUPPORT_SCREEN
SetScheduler(const sptr<IAbilityScheduler> &scheduler)1450 void AbilityRecord::SetScheduler(const sptr<IAbilityScheduler> &scheduler)
1451 {
1452     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundle:%{public}s, ability: %{public}s",
1453         abilityInfo_.applicationInfo.bundleName.c_str(), abilityInfo_.name.c_str());
1454     CHECK_POINTER(lifecycleDeal_);
1455     if (scheduler != nullptr) {
1456         if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
1457             auto schedulerObject = scheduler_->AsObject();
1458             if (schedulerObject != nullptr) {
1459                 schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
1460             }
1461         }
1462         if (schedulerDeathRecipient_ == nullptr) {
1463             schedulerDeathRecipient_ =
1464                 new AbilitySchedulerRecipient([thisWeakPtr = weak_from_this()](const wptr<IRemoteObject> &remote) {
1465                     auto abilityRecord = thisWeakPtr.lock();
1466                     if (abilityRecord) {
1467                         abilityRecord->OnSchedulerDied(remote);
1468                     }
1469                 });
1470         }
1471         SetLoadState(AbilityLoadState::LOADED);
1472         scheduler_ = scheduler;
1473         lifecycleDeal_->SetScheduler(scheduler);
1474         auto schedulerObject = scheduler_->AsObject();
1475         if (schedulerObject == nullptr || !schedulerObject->AddDeathRecipient(schedulerDeathRecipient_)) {
1476             TAG_LOGE(AAFwkTag::ABILITYMGR, "AddDeathRecipient failed");
1477         }
1478         pid_ = static_cast<int32_t>(IPCSkeleton::GetCallingPid()); // set pid when ability attach to service.
1479         AfterLoaded();
1480         // add collaborator mission bind pid
1481         NotifyMissionBindPid();
1482 #ifdef WITH_DLP
1483         HandleDlpAttached();
1484 #endif // WITH_DLP
1485     } else {
1486         TAG_LOGE(AAFwkTag::ABILITYMGR, "scheduler is nullptr");
1487         SetLoadState(AbilityLoadState::FAILED);
1488         isWindowAttached_ = false;
1489         SetIsNewWant(false);
1490         if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
1491             auto schedulerObject = scheduler_->AsObject();
1492             if (schedulerObject != nullptr) {
1493                 TAG_LOGI(AAFwkTag::ABILITYMGR, "RemoveDeathRecipient");
1494                 schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
1495             }
1496         }
1497         scheduler_ = scheduler;
1498         pid_ = 0;
1499     }
1500 }
1501 
AfterLoaded()1502 void AbilityRecord::AfterLoaded()
1503 {
1504     FreezeUtil::GetInstance().DeleteAppLifecycleEvent(GetPid());
1505     ResSchedUtil::GetInstance().ReportLoadingEventToRss(LoadingStage::LOAD_END, GetPid(), GetUid());
1506     if (IsSceneBoard()) {
1507         TAG_LOGI(AAFwkTag::ABILITYMGR, "Sceneboard Added");
1508     }
1509 }
1510 
GetToken() const1511 sptr<Token> AbilityRecord::GetToken() const
1512 {
1513     return token_;
1514 }
1515 
SetPreAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)1516 void AbilityRecord::SetPreAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)
1517 {
1518     preAbilityRecord_ = abilityRecord;
1519 }
1520 
GetPreAbilityRecord() const1521 std::shared_ptr<AbilityRecord> AbilityRecord::GetPreAbilityRecord() const
1522 {
1523     return preAbilityRecord_.lock();
1524 }
1525 
SetNextAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)1526 void AbilityRecord::SetNextAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)
1527 {
1528     nextAbilityRecord_ = abilityRecord;
1529 }
1530 
GetNextAbilityRecord() const1531 std::shared_ptr<AbilityRecord> AbilityRecord::GetNextAbilityRecord() const
1532 {
1533     return nextAbilityRecord_.lock();
1534 }
1535 
IsReady() const1536 bool AbilityRecord::IsReady() const
1537 {
1538     return loadState_.load() == AbilityLoadState::LOADED;
1539 }
1540 
SetLoadState(AbilityLoadState loadState)1541 void AbilityRecord::SetLoadState(AbilityLoadState loadState)
1542 {
1543     loadState_.store(loadState);
1544 }
1545 
GetLoadState() const1546 AbilityLoadState AbilityRecord::GetLoadState() const
1547 {
1548     return loadState_.load();
1549 }
1550 
1551 #ifdef SUPPORT_SCREEN
IsWindowAttached() const1552 bool AbilityRecord::IsWindowAttached() const
1553 {
1554     return isWindowAttached_;
1555 }
1556 #endif
1557 
IsLauncherAbility() const1558 bool AbilityRecord::IsLauncherAbility() const
1559 {
1560     return isLauncherAbility_;
1561 }
1562 
IsTerminating() const1563 bool AbilityRecord::IsTerminating() const
1564 {
1565     return isTerminating_;
1566 }
1567 
SetTerminatingState()1568 void AbilityRecord::SetTerminatingState()
1569 {
1570     isTerminating_ = true;
1571 }
1572 
IsNewWant() const1573 bool AbilityRecord::IsNewWant() const
1574 {
1575     return lifeCycleStateInfo_.isNewWant;
1576 }
1577 
SetIsNewWant(bool isNewWant)1578 void AbilityRecord::SetIsNewWant(bool isNewWant)
1579 {
1580     lifeCycleStateInfo_.isNewWant = isNewWant;
1581 }
1582 
IsCreateByConnect() const1583 bool AbilityRecord::IsCreateByConnect() const
1584 {
1585     return isCreateByConnect_;
1586 }
1587 
SetCreateByConnectMode(bool isCreatedByConnect)1588 void AbilityRecord::SetCreateByConnectMode(bool isCreatedByConnect)
1589 {
1590     isCreateByConnect_ = isCreatedByConnect;
1591 }
1592 
Activate()1593 void AbilityRecord::Activate()
1594 {
1595     TAG_LOGI(AAFwkTag::ABILITYMGR, "activate");
1596     CHECK_POINTER(lifecycleDeal_);
1597 
1598     if (!IsDebug()) {
1599         int activeTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * ACTIVE_TIMEOUT_MULTIPLE;
1600         SendEvent(AbilityManagerService::ACTIVE_TIMEOUT_MSG, activeTimeout);
1601     }
1602 
1603     // schedule active after updating AbilityState and sending timeout message to avoid ability async callback
1604     // earlier than above actions.
1605 #ifdef SUPPORT_SCREEN
1606     SetAbilityStateInner(AbilityState::ACTIVATING);
1607 #endif // SUPPORT_SCREEN
1608     lifecycleDeal_->Activate(GetWant(), lifeCycleStateInfo_);
1609 }
1610 
Inactivate()1611 void AbilityRecord::Inactivate()
1612 {
1613     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1614     TAG_LOGD(AAFwkTag::ABILITYMGR, "ability:%{public}s.", abilityInfo_.name.c_str());
1615     CHECK_POINTER(lifecycleDeal_);
1616 
1617     if (!IsDebug()) {
1618         int inactiveTimeout =
1619             AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * INACTIVE_TIMEOUT_MULTIPLE;
1620         SendEvent(AbilityManagerService::INACTIVE_TIMEOUT_MSG, inactiveTimeout);
1621     }
1622 
1623     // schedule inactive after updating AbilityState and sending timeout message to avoid ability async callback
1624     // earlier than above actions.
1625 #ifdef SUPPORT_SCREEN
1626     SetAbilityStateInner(AbilityState::INACTIVATING);
1627 #endif // SUPPORT_SCREEN
1628     Want want = GetWant();
1629     UpdateDmsCallerInfo(want);
1630     lifecycleDeal_->Inactivate(want, lifeCycleStateInfo_, GetSessionInfo());
1631 }
1632 
Terminate(const Closure &task)1633 void AbilityRecord::Terminate(const Closure &task)
1634 {
1635     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1636     TAG_LOGD(AAFwkTag::ABILITYMGR, "ability: %{public}s.", GetURI().c_str());
1637     CHECK_POINTER(lifecycleDeal_);
1638     if (!IsDebug()) {
1639         auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
1640         if (handler && task) {
1641             if (abilityInfo_.applicationInfo.asanEnabled) {
1642                 int terminateTimeout =
1643                     AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * TERMINATE_TIMEOUT_ASANENABLED;
1644                 handler->SubmitTask(task, "terminate_" + std::to_string(recordId_), terminateTimeout);
1645             } else {
1646                 int terminateTimeout =
1647                     AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * TERMINATE_TIMEOUT_MULTIPLE;
1648                 handler->SubmitTask(task, "terminate_" + std::to_string(recordId_), terminateTimeout);
1649             }
1650         }
1651     } else {
1652         TAG_LOGI(AAFwkTag::ABILITYMGR, "debug mode, no need to handle");
1653     }
1654 #ifdef WITH_DLP
1655     HandleDlpClosed();
1656 #endif // WITH_DLP
1657     // schedule background after updating AbilityState and sending timeout message to avoid ability async callback
1658     // earlier than above actions.
1659 #ifdef SUPPORT_SCREEN
1660     SetAbilityStateInner(AbilityState::TERMINATING);
1661 #endif // SUPPORT_SCREEN
1662     lifecycleDeal_->Terminate(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
1663 }
1664 
ShareData(const int32_t &uniqueId)1665 void AbilityRecord::ShareData(const int32_t &uniqueId)
1666 {
1667     TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", abilityInfo_.name.c_str());
1668     CHECK_POINTER(lifecycleDeal_);
1669     if (!IsDebug()) {
1670         int loadTimeout =
1671             AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * SHAREDATA_TIMEOUT_MULTIPLE;
1672         TAG_LOGD(AAFwkTag::ABILITYMGR, "loadTimeOut %{public}d.", loadTimeout);
1673         SendEvent(AbilityManagerService::SHAREDATA_TIMEOUT_MSG, loadTimeout, uniqueId);
1674     }
1675     lifecycleDeal_->ShareData(uniqueId);
1676 }
1677 
ConnectAbility()1678 void AbilityRecord::ConnectAbility()
1679 {
1680     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called.", __func__);
1681     Want want = GetWant();
1682     UpdateDmsCallerInfo(want);
1683     ConnectAbilityWithWant(want);
1684 }
1685 
ConnectAbilityWithWant(const Want &want)1686 void AbilityRecord::ConnectAbilityWithWant(const Want &want)
1687 {
1688     TAG_LOGD(AAFwkTag::ABILITYMGR, "Connect ability.");
1689     CHECK_POINTER(lifecycleDeal_);
1690     if (isConnected) {
1691         TAG_LOGW(AAFwkTag::ABILITYMGR, "state err");
1692     }
1693     GrantUriPermissionForServiceExtension();
1694     lifecycleDeal_->ConnectAbility(want);
1695     isConnected = true;
1696 }
1697 
DisconnectAbility()1698 void AbilityRecord::DisconnectAbility()
1699 {
1700     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1701     TAG_LOGI(AAFwkTag::ABILITYMGR, "DisconnectAbility, bundle:%{public}s, ability:%{public}s.",
1702         abilityInfo_.applicationInfo.bundleName.c_str(), abilityInfo_.name.c_str());
1703     CHECK_POINTER(lifecycleDeal_);
1704     lifecycleDeal_->DisconnectAbility(GetWant());
1705     if (GetAbilityInfo().extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
1706         if (GetInProgressRecordCount() == 0) {
1707             isConnected = false;
1708         }
1709     } else {
1710         isConnected = false;
1711     }
1712 }
1713 
DisconnectAbilityWithWant(const Want &want)1714 void AbilityRecord::DisconnectAbilityWithWant(const Want &want)
1715 {
1716     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1717     TAG_LOGD(AAFwkTag::ABILITYMGR, "ability:%{public}s.", abilityInfo_.name.c_str());
1718     CHECK_POINTER(lifecycleDeal_);
1719     lifecycleDeal_->DisconnectAbility(want);
1720     if (GetInProgressRecordCount() == 0) {
1721         isConnected = false;
1722     }
1723 }
1724 
GrantUriPermissionForServiceExtension()1725 bool AbilityRecord::GrantUriPermissionForServiceExtension()
1726 {
1727     if (abilityInfo_.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE ||
1728         abilityInfo_.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
1729         std::lock_guard guard(wantLock_);
1730         auto callerTokenId = want_.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0);
1731         auto callerName = want_.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
1732         TAG_LOGD(AAFwkTag::ABILITYMGR,
1733             "CallerName is %{public}s, callerTokenId is %{public}u", callerName.c_str(), callerTokenId);
1734         GrantUriPermission(want_, abilityInfo_.applicationInfo.bundleName, false, callerTokenId);
1735         return true;
1736     }
1737     return false;
1738 }
1739 
CommandAbility()1740 void AbilityRecord::CommandAbility()
1741 {
1742     TAG_LOGI(AAFwkTag::ABILITYMGR, "startId_:%{public}d.", startId_);
1743     Want want = GetWant();
1744     UpdateDmsCallerInfo(want);
1745     CHECK_POINTER(lifecycleDeal_);
1746     lifecycleDeal_->CommandAbility(want, false, startId_);
1747 }
1748 
CommandAbilityWindow(const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd)1749 void AbilityRecord::CommandAbilityWindow(const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd)
1750 {
1751     CHECK_POINTER(lifecycleDeal_);
1752     lifecycleDeal_->CommandAbilityWindow(GetWant(), sessionInfo, winCmd);
1753 }
1754 
SaveAbilityState()1755 void AbilityRecord::SaveAbilityState()
1756 {
1757     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
1758     CHECK_POINTER(lifecycleDeal_);
1759     lifecycleDeal_->SaveAbilityState();
1760 }
1761 
SaveAbilityState(const PacMap &inState)1762 void AbilityRecord::SaveAbilityState(const PacMap &inState)
1763 {
1764     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
1765     stateDatas_ = inState;
1766 }
1767 
SaveAbilityWindowConfig(const WindowConfig &windowConfig)1768 void AbilityRecord::SaveAbilityWindowConfig(const WindowConfig &windowConfig)
1769 {
1770     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
1771     windowConfig_ = windowConfig;
1772 }
1773 
RestoreAbilityState()1774 void AbilityRecord::RestoreAbilityState()
1775 {
1776     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
1777     CHECK_POINTER(lifecycleDeal_);
1778     lifecycleDeal_->RestoreAbilityState(stateDatas_);
1779     stateDatas_.Clear();
1780     isRestarting_ = false;
1781 }
1782 
GetRequestCode() const1783 int AbilityRecord::GetRequestCode() const
1784 {
1785     return requestCode_;
1786 }
1787 
SetResult(const std::shared_ptr<AbilityResult> &result)1788 void AbilityRecord::SetResult(const std::shared_ptr<AbilityResult> &result)
1789 {
1790     std::lock_guard guard(resultLock_);
1791     result_ = result;
1792 }
1793 
GetResult() const1794 std::shared_ptr<AbilityResult> AbilityRecord::GetResult() const
1795 {
1796     std::lock_guard guard(resultLock_);
1797     return result_;
1798 }
1799 
SendResult(bool isSandboxApp, uint32_t tokeId)1800 void AbilityRecord::SendResult(bool isSandboxApp, uint32_t tokeId)
1801 {
1802     TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", abilityInfo_.name.c_str());
1803     std::lock_guard<ffrt::mutex> guard(lock_);
1804     CHECK_POINTER(scheduler_);
1805     auto result = GetResult();
1806     CHECK_POINTER(result);
1807     UriUtils::GetInstance().CheckUriPermissionForUIExtension(result->resultWant_,
1808         abilityInfo_.extensionAbilityType, tokeId);
1809     GrantUriPermission(result->resultWant_, abilityInfo_.applicationInfo.bundleName, isSandboxApp, tokeId);
1810     scheduler_->SendResult(result->requestCode_, result->resultCode_, result->resultWant_);
1811     // reset result to avoid send result next time
1812     SetResult(nullptr);
1813 }
1814 
SendResultByBackToCaller(const std::shared_ptr<AbilityResult> &result)1815 void AbilityRecord::SendResultByBackToCaller(const std::shared_ptr<AbilityResult> &result)
1816 {
1817     TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", abilityInfo_.name.c_str());
1818     std::lock_guard<ffrt::mutex> guard(lock_);
1819     CHECK_POINTER(scheduler_);
1820     CHECK_POINTER(result);
1821     scheduler_->SendResult(result->requestCode_, result->resultCode_, result->resultWant_);
1822 }
1823 
SendSandboxSavefileResult(const Want &want, int resultCode, int requestCode)1824 void AbilityRecord::SendSandboxSavefileResult(const Want &want, int resultCode, int requestCode)
1825 {
1826     TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", abilityInfo_.name.c_str());
1827 
1828     auto uriParam = want.GetParams().GetParam(PARAMS_FILE_SAVING_URL_KEY);
1829     auto uriArray = AAFwk::IArray::Query(uriParam);
1830     long arraySize = 0;
1831     if (uriArray && uriArray->GetLength(arraySize) == ERR_OK &&
1832         arraySize > 0 && AAFwk::Array::IsStringArray(uriArray)) {
1833         for (long i = 0; i < arraySize; i++) {
1834             sptr<AAFwk::IInterface> iface = nullptr;
1835             if (uriArray->Get(i, iface) != ERR_OK) {
1836                 continue;
1837             }
1838             AAFwk::IString* iuri = AAFwk::IString::Query(iface);
1839             if (!iuri) {
1840                 continue;
1841             }
1842             std::string uriStr;
1843             if (iuri->GetString(uriStr) != ERR_OK) {
1844                 continue;
1845             }
1846             Uri uri(uriStr);
1847             uint32_t initiatorTokenId = IPCSkeleton::GetCallingTokenID();
1848             bool flag = Want::FLAG_AUTH_WRITE_URI_PERMISSION;
1849             auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(uri,
1850                 flag, abilityInfo_.bundleName, appIndex_, initiatorTokenId, recordId_));
1851             if (ret != ERR_OK) {
1852                 TAG_LOGW(AAFwkTag::ABILITYMGR, "GrantUriPermission failed");
1853             }
1854         }
1855     } else {
1856         TAG_LOGW(AAFwkTag::ABILITYMGR, "uri illegal for request: %{public}d", requestCode);
1857     }
1858 
1859     auto scheduler = scheduler_;
1860     if (scheduler) {
1861         scheduler->SendResult(requestCode, resultCode, want);
1862     }
1863 }
1864 
SendResultToCallers(bool schedulerdied)1865 void AbilityRecord::SendResultToCallers(bool schedulerdied)
1866 {
1867     for (auto caller : GetCallerRecordList()) {
1868         if (caller == nullptr) {
1869             TAG_LOGW(AAFwkTag::ABILITYMGR, "null caller");
1870             continue;
1871         }
1872         std::shared_ptr<AbilityRecord> callerAbilityRecord = caller->GetCaller();
1873         if (callerAbilityRecord != nullptr && callerAbilityRecord->GetResult() != nullptr) {
1874             bool isSandboxApp = appIndex_ > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX ? true : false;
1875             callerAbilityRecord->SendResult(isSandboxApp, abilityInfo_.applicationInfo.accessTokenId);
1876         } else {
1877             std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord = caller->GetSaCaller();
1878             if (callerSystemAbilityRecord != nullptr) {
1879                 TAG_LOGI(AAFwkTag::ABILITYMGR, "send result to system ability");
1880                 callerSystemAbilityRecord->SendResultToSystemAbility(caller->GetRequestCode(),
1881                     callerSystemAbilityRecord, abilityInfo_.applicationInfo.uid,
1882                     abilityInfo_.applicationInfo.accessTokenId, schedulerdied);
1883             }
1884         }
1885     }
1886 }
1887 
GetCallerByRequestCode(int32_t requestCode, int32_t pid)1888 std::shared_ptr<AbilityRecord> AbilityRecord::GetCallerByRequestCode(int32_t requestCode, int32_t pid)
1889 {
1890     for (auto caller : GetCallerRecordList()) {
1891         if (caller == nullptr) {
1892             TAG_LOGI(AAFwkTag::ABILITYMGR, "null caller");
1893             continue;
1894         }
1895         std::shared_ptr<AbilityRecord> callerAbilityRecord = caller->GetCaller();
1896         if (callerAbilityRecord == nullptr || callerAbilityRecord->GetPid() != pid) {
1897             TAG_LOGI(AAFwkTag::ABILITYMGR, "callerAbility not match");
1898             continue;
1899         }
1900         if (caller->IsHistoryRequestCode(requestCode)) {
1901             TAG_LOGI(AAFwkTag::ABILITYMGR, "found callerAbility");
1902             return callerAbilityRecord;
1903         }
1904     }
1905     TAG_LOGI(AAFwkTag::ABILITYMGR, "Can't found caller");
1906     return nullptr;
1907 }
1908 
SaveResultToCallers(const int resultCode, const Want *resultWant)1909 void AbilityRecord::SaveResultToCallers(const int resultCode, const Want *resultWant)
1910 {
1911     auto callerRecordList = GetCallerRecordList();
1912     if (callerRecordList.empty()) {
1913         TAG_LOGW(AAFwkTag::ABILITYMGR, "callerRecordList empty");
1914         return;
1915     }
1916     auto latestCaller = callerRecordList.back();
1917     for (auto caller : callerRecordList) {
1918         if (caller == nullptr) {
1919             TAG_LOGW(AAFwkTag::ABILITYMGR, "null caller");
1920             continue;
1921         }
1922         if (caller == latestCaller) {
1923             TAG_LOGD(AAFwkTag::ABILITYMGR, "latestCaller");
1924             SaveResult(resultCode, resultWant, caller);
1925             continue;
1926         }
1927         SaveResult(SEND_RESULT_CANCELED, resultWant, caller);
1928     }
1929 }
1930 
SaveResult(int resultCode, const Want *resultWant, std::shared_ptr<CallerRecord> caller)1931 void AbilityRecord::SaveResult(int resultCode, const Want *resultWant, std::shared_ptr<CallerRecord> caller)
1932 {
1933     std::lock_guard<ffrt::mutex> guard(lock_);
1934     std::shared_ptr<AbilityRecord> callerAbilityRecord = caller->GetCaller();
1935     if (callerAbilityRecord != nullptr) {
1936         Want* newWant = const_cast<Want*>(resultWant);
1937         if (callerAbilityRecord->GetApplicationInfo().name == AppUtils::GetInstance().GetBrokerDelegateBundleName()) {
1938             newWant->SetParam(std::string(PARAM_SEND_RESULT_CALLER_BUNDLENAME), abilityInfo_.applicationInfo.name);
1939             newWant->SetParam(std::string(PARAM_SEND_RESULT_CALLER_TOKENID), static_cast<int32_t>(
1940                 abilityInfo_.applicationInfo.accessTokenId));
1941         }
1942         callerAbilityRecord->SetResult(
1943             std::make_shared<AbilityResult>(caller->GetRequestCode(), resultCode, *newWant));
1944     } else {
1945         std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord = caller->GetSaCaller();
1946         if (callerSystemAbilityRecord != nullptr) {
1947             TAG_LOGI(AAFwkTag::ABILITYMGR, "caller is system ability");
1948             Want* newWant = const_cast<Want*>(resultWant);
1949             callerSystemAbilityRecord->SetResultToSystemAbility(callerSystemAbilityRecord, *newWant,
1950                 resultCode);
1951         }
1952     }
1953 }
1954 
SetResultToSystemAbility( std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord, Want &resultWant, int resultCode)1955 void SystemAbilityCallerRecord::SetResultToSystemAbility(
1956     std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,
1957     Want &resultWant, int resultCode)
1958 {
1959     std::vector<std::string> data;
1960     std::string srcAbilityId = callerSystemAbilityRecord->GetSrcAbilityId();
1961     SplitStr(srcAbilityId, "_", data);
1962     if (data.size() != VECTOR_SIZE) {
1963         TAG_LOGE(AAFwkTag::ABILITYMGR, "check size failed");
1964         return;
1965     }
1966     std::string srcDeviceId = data[0];
1967     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get srcDeviceId = %{public}s", srcDeviceId.c_str());
1968     int missionId = atoi(data[1].c_str());
1969     TAG_LOGI(AAFwkTag::ABILITYMGR, "get missionId: %{public}d", missionId);
1970     resultWant.SetParam(DMS_SRC_NETWORK_ID, srcDeviceId);
1971     resultWant.SetParam(DMS_MISSION_ID, missionId);
1972     callerSystemAbilityRecord->SetResult(resultWant, resultCode);
1973 }
1974 
SendResultToSystemAbility(int requestCode, const std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord, int32_t callerUid, uint32_t accessToken, bool schedulerdied)1975 void SystemAbilityCallerRecord::SendResultToSystemAbility(int requestCode,
1976     const std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,
1977     int32_t callerUid, uint32_t accessToken, bool schedulerdied)
1978 {
1979     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
1980     if (callerSystemAbilityRecord == nullptr) {
1981         TAG_LOGE(AAFwkTag::ABILITYMGR, "null record");
1982         return;
1983     }
1984     int resultCode = callerSystemAbilityRecord->GetResultCode();
1985     Want resultWant = callerSystemAbilityRecord->GetResultWant();
1986     sptr<IRemoteObject> callerToken = callerSystemAbilityRecord->GetCallerToken();
1987     if (!schedulerdied) {
1988         callerUid = IPCSkeleton::GetCallingUid();
1989         accessToken = IPCSkeleton::GetCallingTokenID();
1990     }
1991     TAG_LOGI(AAFwkTag::ABILITYMGR, "Try to SendResult");
1992     if (callerToken == nullptr) {
1993         TAG_LOGE(AAFwkTag::ABILITYMGR, "null callerToken");
1994         return;
1995     }
1996     MessageParcel data;
1997     if (!data.WriteInterfaceToken(SYSTEM_ABILITY_TOKEN_CALLBACK)) {
1998         TAG_LOGE(AAFwkTag::ABILITYMGR, "write interface token failed");
1999         return;
2000     }
2001     if (!data.WriteParcelable(&resultWant)) {
2002         TAG_LOGE(AAFwkTag::ABILITYMGR, "writeParcelable failed");
2003         return;
2004     }
2005     data.WriteInt32(callerUid);
2006     data.WriteInt32(requestCode);
2007     data.WriteUint32(accessToken);
2008     data.WriteInt32(resultCode);
2009     MessageParcel reply;
2010     MessageOption option(MessageOption::TF_SYNC);
2011     int result = callerToken->SendRequest(ISystemAbilityTokenCallback::SEND_RESULT, data, reply, option);
2012     if (result != ERR_OK) {
2013         TAG_LOGE(AAFwkTag::ABILITYMGR, "error: %{public}d", result);
2014     }
2015 }
2016 
NeedConnectAfterCommand()2017 bool AbilityRecord::NeedConnectAfterCommand()
2018 {
2019     return !IsConnectListEmpty() && !isConnected;
2020 }
2021 
AddConnectRecordToList(const std::shared_ptr<ConnectionRecord> &connRecord)2022 void AbilityRecord::AddConnectRecordToList(const std::shared_ptr<ConnectionRecord> &connRecord)
2023 {
2024     CHECK_POINTER(connRecord);
2025     std::lock_guard guard(connRecordListMutex_);
2026     auto it = std::find(connRecordList_.begin(), connRecordList_.end(), connRecord);
2027     // found it
2028     if (it != connRecordList_.end()) {
2029         TAG_LOGD(AAFwkTag::ABILITYMGR, "Found it in list, so no need to add same connection");
2030         return;
2031     }
2032     // no found then add new connection to list
2033     TAG_LOGD(AAFwkTag::ABILITYMGR, "No found in list, so add new connection to list");
2034     connRecordList_.push_back(connRecord);
2035 }
2036 
GetConnectRecordList() const2037 std::list<std::shared_ptr<ConnectionRecord>> AbilityRecord::GetConnectRecordList() const
2038 {
2039     std::lock_guard guard(connRecordListMutex_);
2040     return connRecordList_;
2041 }
2042 
RemoveConnectRecordFromList(const std::shared_ptr<ConnectionRecord> &connRecord)2043 void AbilityRecord::RemoveConnectRecordFromList(const std::shared_ptr<ConnectionRecord> &connRecord)
2044 {
2045     CHECK_POINTER(connRecord);
2046     std::lock_guard guard(connRecordListMutex_);
2047     connRecordList_.remove(connRecord);
2048     if (connRecordList_.empty()) {
2049         isConnected = false;
2050     }
2051 }
2052 
RemoveSpecifiedWantParam(const std::string &key)2053 void AbilityRecord::RemoveSpecifiedWantParam(const std::string &key)
2054 {
2055     std::lock_guard guard(wantLock_);
2056     if (want_.HasParameter(key)) {
2057         want_.RemoveParam(key);
2058     }
2059 }
2060 
RemoveCallerRequestCode(std::shared_ptr<AbilityRecord> callerAbilityRecord, int32_t requestCode)2061 void AbilityRecord::RemoveCallerRequestCode(std::shared_ptr<AbilityRecord> callerAbilityRecord, int32_t requestCode)
2062 {
2063     if (callerAbilityRecord == nullptr) {
2064         TAG_LOGI(AAFwkTag::ABILITYMGR, "null record");
2065         return;
2066     }
2067     for (auto it = callerList_.begin(); it != callerList_.end(); it++) {
2068         if ((*it)->GetCaller() == callerAbilityRecord) {
2069             (*it)->RemoveHistoryRequestCode(requestCode);
2070             if ((*it)->GetRequestCodeSet().empty()) {
2071                 callerList_.erase(it);
2072                 TAG_LOGI(AAFwkTag::ABILITYMGR, "remove callerRecord");
2073             }
2074             return;
2075         }
2076     }
2077 }
2078 
AddCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode, const Want &want, std::string srcAbilityId, uint32_t callingTokenId)2079 void AbilityRecord::AddCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode, const Want &want,
2080     std::string srcAbilityId, uint32_t callingTokenId)
2081 {
2082     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2083     TAG_LOGD(AAFwkTag::ABILITYMGR, "call, callingTokenId:%{public}u", callingTokenId);
2084     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2085     if (abilityRecord == nullptr) {
2086         RecordSaCallerInfo(want);
2087     }
2088     if (!srcAbilityId.empty() && IsSystemAbilityCall(callerToken, callingTokenId)) {
2089         AddSystemAbilityCallerRecord(callerToken, requestCode, srcAbilityId);
2090         return;
2091     }
2092     CHECK_POINTER(abilityRecord);
2093 
2094     auto isExist = [&abilityRecord](const std::shared_ptr<CallerRecord> &callerRecord) {
2095         return (callerRecord->GetCaller() == abilityRecord);
2096     };
2097 
2098     auto record = std::find_if(callerList_.begin(), callerList_.end(), isExist);
2099     auto newCallerRecord = std::make_shared<CallerRecord>(requestCode, abilityRecord);
2100     if (record != callerList_.end()) {
2101         newCallerRecord->SetRequestCodeSet((*record)->GetRequestCodeSet());
2102         callerList_.erase(record);
2103     }
2104     newCallerRecord->AddHistoryRequestCode(requestCode);
2105     callerList_.emplace_back(newCallerRecord);
2106 
2107     lifeCycleStateInfo_.caller.requestCode = requestCode;
2108     lifeCycleStateInfo_.caller.deviceId = abilityRecord->GetAbilityInfo().deviceId;
2109     lifeCycleStateInfo_.caller.bundleName = abilityRecord->GetAbilityInfo().bundleName;
2110     lifeCycleStateInfo_.caller.abilityName = abilityRecord->GetAbilityInfo().name;
2111     TAG_LOGD(AAFwkTag::ABILITYMGR, "caller %{public}s, %{public}s, callerSize: %{public}zu",
2112         abilityRecord->GetAbilityInfo().bundleName.c_str(),
2113         abilityRecord->GetAbilityInfo().name.c_str(), callerList_.size());
2114 }
2115 
IsSystemAbilityCall(const sptr<IRemoteObject> &callerToken, uint32_t callingTokenId)2116 bool AbilityRecord::IsSystemAbilityCall(const sptr<IRemoteObject> &callerToken, uint32_t callingTokenId)
2117 {
2118     if (callerToken == nullptr) {
2119         return false;
2120     }
2121     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2122     if (abilityRecord != nullptr) {
2123         return false;
2124     }
2125     uint32_t tokenId = 0;
2126     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2127         tokenId = callingTokenId;
2128     } else {
2129         tokenId = IPCSkeleton::GetCallingTokenID();
2130     }
2131     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
2132     bool isNativeCall = tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE;
2133     if (!isNativeCall) {
2134         TAG_LOGI(AAFwkTag::ABILITYMGR, "not native call");
2135         return false;
2136     }
2137     AccessToken::NativeTokenInfo nativeTokenInfo;
2138     int32_t result = AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
2139     if (result == ERR_OK && nativeTokenInfo.processName == DMS_PROCESS_NAME) {
2140         TAG_LOGI(AAFwkTag::ABILITYMGR, "system ability call");
2141         return true;
2142     }
2143     return false;
2144 }
2145 
AddSystemAbilityCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode, std::string srcAbilityId)2146 void AbilityRecord::AddSystemAbilityCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode,
2147     std::string srcAbilityId)
2148 {
2149     TAG_LOGI(AAFwkTag::ABILITYMGR, "add system ability caller record");
2150     std::shared_ptr<SystemAbilityCallerRecord> systemAbilityRecord =
2151         std::make_shared<SystemAbilityCallerRecord>(srcAbilityId, callerToken);
2152     auto isExist = [&srcAbilityId](const std::shared_ptr<CallerRecord> &callerRecord) {
2153         std::shared_ptr<SystemAbilityCallerRecord> saCaller = callerRecord->GetSaCaller();
2154         return (saCaller != nullptr && saCaller->GetSrcAbilityId() == srcAbilityId);
2155     };
2156     auto record = std::find_if(callerList_.begin(), callerList_.end(), isExist);
2157     if (record != callerList_.end()) {
2158         TAG_LOGI(AAFwkTag::ABILITYMGR, "find same system ability caller record");
2159         callerList_.erase(record);
2160     }
2161     callerList_.emplace_back(std::make_shared<CallerRecord>(requestCode, systemAbilityRecord));
2162     TAG_LOGI(AAFwkTag::ABILITYMGR, "add system ability record end");
2163 }
2164 
RecordSaCallerInfo(const Want &want)2165 void AbilityRecord::RecordSaCallerInfo(const Want &want)
2166 {
2167     saCallerInfo_ = std::make_shared<CallerAbilityInfo>();
2168     saCallerInfo_->callerTokenId = want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0);
2169     saCallerInfo_->callerUid =  want.GetIntParam(Want::PARAM_RESV_CALLER_UID, 0);
2170     saCallerInfo_->callerPid =  want.GetIntParam(Want::PARAM_RESV_CALLER_PID, 0);
2171     saCallerInfo_->callerNativeName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
2172 }
2173 
GetCallerRecordList() const2174 std::list<std::shared_ptr<CallerRecord>> AbilityRecord::GetCallerRecordList() const
2175 {
2176     return callerList_;
2177 }
2178 
GetCallerRecord() const2179 std::shared_ptr<AbilityRecord> AbilityRecord::GetCallerRecord() const
2180 {
2181     if (callerList_.empty()) {
2182         return nullptr;
2183     }
2184     if (callerList_.back() == nullptr) {
2185         return nullptr;
2186     }
2187     return callerList_.back()->GetCaller();
2188 }
2189 
GetCallerInfo() const2190 std::shared_ptr<CallerAbilityInfo> AbilityRecord::GetCallerInfo() const
2191 {
2192     if (callerList_.empty() || callerList_.back() == nullptr) {
2193         return saCallerInfo_;
2194     }
2195     return callerList_.back()->GetCallerInfo();
2196 }
2197 
IsConnectListEmpty()2198 bool AbilityRecord::IsConnectListEmpty()
2199 {
2200     std::lock_guard guard(connRecordListMutex_);
2201     return connRecordList_.empty();
2202 }
2203 
GetConnectingRecord() const2204 std::shared_ptr<ConnectionRecord> AbilityRecord::GetConnectingRecord() const
2205 {
2206     std::lock_guard guard(connRecordListMutex_);
2207     auto connect =
2208         std::find_if(connRecordList_.begin(), connRecordList_.end(), [](std::shared_ptr<ConnectionRecord> record) {
2209             return record->GetConnectState() == ConnectionState::CONNECTING;
2210         });
2211     return (connect != connRecordList_.end()) ? *connect : nullptr;
2212 }
2213 
GetConnectingRecordList()2214 std::list<std::shared_ptr<ConnectionRecord>> AbilityRecord::GetConnectingRecordList()
2215 {
2216     std::lock_guard guard(connRecordListMutex_);
2217     std::list<std::shared_ptr<ConnectionRecord>> connectingList;
2218     for (auto record : connRecordList_) {
2219         if (record && record->GetConnectState() == ConnectionState::CONNECTING) {
2220             connectingList.push_back(record);
2221         }
2222     }
2223     return connectingList;
2224 }
2225 
GetInProgressRecordCount()2226 uint32_t AbilityRecord::GetInProgressRecordCount()
2227 {
2228     std::lock_guard guard(connRecordListMutex_);
2229     uint32_t count = 0;
2230     for (auto record : connRecordList_) {
2231         if (record && (record->GetConnectState() == ConnectionState::CONNECTING ||
2232             record->GetConnectState() == ConnectionState::CONNECTED)) {
2233             count++;
2234         }
2235     }
2236     return count;
2237 }
2238 
GetDisconnectingRecord() const2239 std::shared_ptr<ConnectionRecord> AbilityRecord::GetDisconnectingRecord() const
2240 {
2241     std::lock_guard guard(connRecordListMutex_);
2242     auto connect =
2243         std::find_if(connRecordList_.begin(), connRecordList_.end(), [](std::shared_ptr<ConnectionRecord> record) {
2244             return record->GetConnectState() == ConnectionState::DISCONNECTING;
2245         });
2246     return (connect != connRecordList_.end()) ? *connect : nullptr;
2247 }
2248 
GetAbilityTypeString(std::string &typeStr)2249 void AbilityRecord::GetAbilityTypeString(std::string &typeStr)
2250 {
2251     AppExecFwk::AbilityType type = GetAbilityInfo().type;
2252     switch (type) {
2253 #ifdef SUPPORT_GRAPHICS
2254         case AppExecFwk::AbilityType::PAGE: {
2255             typeStr = "PAGE";
2256             break;
2257         }
2258 #endif
2259         case AppExecFwk::AbilityType::SERVICE: {
2260             typeStr = UIExtensionUtils::IsUIExtension(GetAbilityInfo().extensionAbilityType) ?
2261                 "UIEXTENSION" : "SERVICE";
2262             break;
2263         }
2264         // for config.json type
2265         case AppExecFwk::AbilityType::DATA: {
2266             typeStr = "DATA";
2267             break;
2268         }
2269         default: {
2270             typeStr = "UNKNOWN";
2271             break;
2272         }
2273     }
2274 }
2275 
ConvertAbilityState(const AbilityState &state)2276 std::string AbilityRecord::ConvertAbilityState(const AbilityState &state)
2277 {
2278     return  StateUtils::StateToStrMap(state);
2279 }
2280 
ConvertAppState(const AppState &state)2281 std::string AbilityRecord::ConvertAppState(const AppState &state)
2282 {
2283     return StateUtils::AppStateToStrMap(state);
2284 }
2285 
ConvertLifeCycleToAbilityState(const AbilityLifeCycleState &state)2286 int AbilityRecord::ConvertLifeCycleToAbilityState(const AbilityLifeCycleState &state)
2287 {
2288     return StateUtils::ConvertStateMap(state);
2289 }
2290 
Dump(std::vector<std::string> &info)2291 void AbilityRecord::Dump(std::vector<std::string> &info)
2292 {
2293     std::string dumpInfo = "      AbilityRecord ID #" + std::to_string(recordId_);
2294     info.push_back(dumpInfo);
2295     dumpInfo = "        app name [" + GetAbilityInfo().applicationName + "]";
2296     info.push_back(dumpInfo);
2297     dumpInfo = "        main name [" + GetAbilityInfo().name + "]";
2298     info.push_back(dumpInfo);
2299     dumpInfo = "        bundle name [" + GetAbilityInfo().bundleName + "]";
2300     info.push_back(dumpInfo);
2301     std::string isKeepAlive = GetKeepAlive() ? "true" : "false";
2302     dumpInfo = "        isKeepAlive: " + isKeepAlive;
2303     info.push_back(dumpInfo);
2304     // get ability type(unknown/page/service/provider)
2305     std::string typeStr;
2306     GetAbilityTypeString(typeStr);
2307     dumpInfo = "        ability type [" + typeStr + "]";
2308     info.push_back(dumpInfo);
2309     std::shared_ptr<AbilityRecord> preAbility = GetPreAbilityRecord();
2310     if (preAbility == nullptr) {
2311         dumpInfo = "        previous ability app name [NULL]";
2312         dumpInfo.append("\n");
2313         dumpInfo += "        previous ability file name [NULL]";
2314     } else {
2315         dumpInfo =
2316             "        previous ability app name [" + preAbility->GetAbilityInfo().applicationName + "]";
2317         dumpInfo.append("\n");
2318         dumpInfo += "        previous ability file name [" + preAbility->GetAbilityInfo().name + "]";
2319     }
2320     info.push_back(dumpInfo);
2321     std::shared_ptr<AbilityRecord> nextAbility = GetNextAbilityRecord();
2322     if (nextAbility == nullptr) {
2323         dumpInfo = "        next ability app name [NULL]";
2324         dumpInfo.append("\n");
2325         dumpInfo += "        next ability file name [NULL]";
2326     } else {
2327         dumpInfo =
2328             "        next ability app name [" + nextAbility->GetAbilityInfo().applicationName + "]";
2329         dumpInfo.append("\n");
2330         dumpInfo += "        next ability main name [" + nextAbility->GetAbilityInfo().name + "]";
2331     }
2332     info.push_back(dumpInfo);
2333     dumpInfo = "        state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + "  start time [" +
2334                std::to_string(startTime_) + "]";
2335     info.push_back(dumpInfo);
2336     dumpInfo = "        app state #" + AbilityRecord::ConvertAppState(appState_);
2337     info.push_back(dumpInfo);
2338     dumpInfo = "        ready #" + std::to_string(IsReady()) + "  window attached #" +
2339                std::to_string(isWindowAttached_) + "  launcher #" + std::to_string(isLauncherAbility_);
2340     info.push_back(dumpInfo);
2341 
2342     if (isLauncherRoot_) {
2343         dumpInfo = "        can restart num #" + std::to_string(restartCount_);
2344         info.push_back(dumpInfo);
2345     }
2346 }
2347 
DumpUIExtensionRootHostInfo(std::vector<std::string> &info) const2348 void AbilityRecord::DumpUIExtensionRootHostInfo(std::vector<std::string> &info) const
2349 {
2350     if (!UIExtensionUtils::IsUIExtension(GetAbilityInfo().extensionAbilityType)) {
2351         // Dump host info only for uiextension.
2352         return;
2353     }
2354 
2355     sptr<IRemoteObject> token = GetToken();
2356     if (token == nullptr) {
2357         TAG_LOGE(AAFwkTag::ABILITYMGR, "null token");
2358         return;
2359     }
2360 
2361     UIExtensionHostInfo hostInfo;
2362     auto ret = IN_PROCESS_CALL(AAFwk::AbilityManagerClient::GetInstance()->GetUIExtensionRootHostInfo(token, hostInfo));
2363     if (ret != ERR_OK) {
2364         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed: %{public}d", ret);
2365         return;
2366     }
2367 
2368     std::string dumpInfo = "      root host bundle name [" + hostInfo.elementName_.GetBundleName() + "]";
2369     info.emplace_back(dumpInfo);
2370     dumpInfo = "      root host module name [" + hostInfo.elementName_.GetModuleName() + "]";
2371     info.emplace_back(dumpInfo);
2372     dumpInfo = "      root host ability name [" + hostInfo.elementName_.GetAbilityName() + "]";
2373     info.emplace_back(dumpInfo);
2374 }
2375 
DumpAbilityState( std::vector<std::string> &info, bool isClient, const std::vector<std::string> &params)2376 void AbilityRecord::DumpAbilityState(
2377     std::vector<std::string> &info, bool isClient, const std::vector<std::string> &params)
2378 {
2379     std::string dumpInfo = "      AbilityRecord ID #" + std::to_string(recordId_);
2380     info.push_back(dumpInfo);
2381     dumpInfo = "        app name [" + GetAbilityInfo().applicationName + "]";
2382     info.push_back(dumpInfo);
2383     dumpInfo = "        main name [" + GetAbilityInfo().name + "]";
2384     info.push_back(dumpInfo);
2385     dumpInfo = "        bundle name [" + GetAbilityInfo().bundleName + "]";
2386     info.push_back(dumpInfo);
2387     std::string typeStr;
2388     GetAbilityTypeString(typeStr);
2389     dumpInfo = "        ability type [" + typeStr + "]";
2390     info.push_back(dumpInfo);
2391 
2392     dumpInfo = "        state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + "  start time [" +
2393                std::to_string(startTime_) + "]";
2394     info.push_back(dumpInfo);
2395     dumpInfo = "        app state #" + AbilityRecord::ConvertAppState(appState_);
2396     info.push_back(dumpInfo);
2397     dumpInfo = "        ready #" + std::to_string(IsReady()) + "  window attached #" +
2398                std::to_string(isWindowAttached_) + "  launcher #" + std::to_string(isLauncherAbility_);
2399     info.push_back(dumpInfo);
2400     dumpInfo = "        callee connections: ";
2401     info.push_back(dumpInfo);
2402     if (callContainer_) {
2403         callContainer_->Dump(info);
2404     }
2405 
2406     std::string isKeepAlive = GetKeepAlive() ? "true" : "false";
2407     dumpInfo = "        isKeepAlive: " + isKeepAlive;
2408     info.push_back(dumpInfo);
2409     if (isLauncherRoot_) {
2410         dumpInfo = "        can restart num #" + std::to_string(restartCount_);
2411         info.push_back(dumpInfo);
2412     }
2413 
2414     auto missionAffinity = GetMissionAffinity();
2415     if (!missionAffinity.empty()) {
2416         dumpInfo = "        missionAffinity: " + missionAffinity;
2417         info.push_back(dumpInfo);
2418     }
2419 
2420     // add dump client info
2421     DumpClientInfo(info, params, isClient, params.empty());
2422 }
2423 
SetStartTime()2424 void AbilityRecord::SetStartTime()
2425 {
2426     if (startTime_ == 0) {
2427         startTime_ = AbilityUtil::SystemTimeMillis();
2428     }
2429 }
2430 
GetStartTime() const2431 int64_t AbilityRecord::GetStartTime() const
2432 {
2433     return startTime_;
2434 }
2435 
DumpService(std::vector<std::string> &info, bool isClient) const2436 void AbilityRecord::DumpService(std::vector<std::string> &info, bool isClient) const
2437 {
2438     std::vector<std::string> params;
2439     DumpService(info, params, isClient);
2440 }
2441 
DumpService(std::vector<std::string> &info, std::vector<std::string> &params, bool isClient) const2442 void AbilityRecord::DumpService(std::vector<std::string> &info, std::vector<std::string> &params, bool isClient) const
2443 {
2444     info.emplace_back("      AbilityRecord ID #" + std::to_string(GetRecordId()) + "   state #" +
2445                       AbilityRecord::ConvertAbilityState(GetAbilityState()) + "   start time [" +
2446                       std::to_string(GetStartTime()) + "]");
2447     info.emplace_back("      main name [" + GetAbilityInfo().name + "]");
2448     info.emplace_back("      bundle name [" + GetAbilityInfo().bundleName + "]");
2449     bool isUIExtension = UIExtensionUtils::IsUIExtension(GetAbilityInfo().extensionAbilityType);
2450     if (isUIExtension) {
2451         info.emplace_back("      ability type [UIEXTENSION]");
2452     } else {
2453         if (GetAbilityInfo().extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2454             info.emplace_back("      ability type [UI_SERVICE]");
2455             info.emplace_back("      windowConfig windowType [" +
2456                 std::to_string(GetAbilityWindowConfig().windowType) + "]");
2457             info.emplace_back("      windowConfig windowId [" +
2458                 std::to_string(GetAbilityWindowConfig().windowId) + "]");
2459         } else {
2460             info.emplace_back("      ability type [SERVICE]");
2461         }
2462     }
2463     info.emplace_back("      app state #" + AbilityRecord::ConvertAppState(appState_));
2464 
2465     std::string isKeepAlive = GetKeepAlive() ? "true" : "false";
2466     info.emplace_back("        isKeepAlive: " + isKeepAlive);
2467     if (isLauncherRoot_) {
2468         info.emplace_back("      can restart num #" + std::to_string(restartCount_));
2469     }
2470     decltype(connRecordList_) connRecordListCpy;
2471     {
2472         std::lock_guard guard(connRecordListMutex_);
2473         connRecordListCpy = connRecordList_;
2474     }
2475 
2476     info.emplace_back("      Connections: " + std::to_string(connRecordListCpy.size()));
2477     for (auto &&conn : connRecordListCpy) {
2478         if (conn) {
2479             conn->Dump(info);
2480         }
2481     }
2482     // add dump client info
2483     DumpClientInfo(info, params, isClient);
2484     DumpUIExtensionRootHostInfo(info);
2485     DumpUIExtensionPid(info, isUIExtension);
2486 }
2487 
DumpUIExtensionPid(std::vector<std::string> &info, bool isUIExtension) const2488 void AbilityRecord::DumpUIExtensionPid(std::vector<std::string> &info, bool isUIExtension) const
2489 {
2490     if (!isUIExtension) {
2491         TAG_LOGD(AAFwkTag::ABILITYMGR, "Not ui extension type.");
2492         return;
2493     }
2494 
2495     auto appScheduler = DelayedSingleton<AppScheduler>::GetInstance();
2496     if (appScheduler == nullptr) {
2497         TAG_LOGE(AAFwkTag::ABILITYMGR, "null appScheduler");
2498         return;
2499     }
2500     AppExecFwk::RunningProcessInfo processInfo;
2501     appScheduler->GetRunningProcessInfoByToken(GetToken(), processInfo);
2502     info.emplace_back("      pid: " + std::to_string(processInfo.pid_));
2503 }
2504 
RemoveAbilityDeathRecipient() const2505 void AbilityRecord::RemoveAbilityDeathRecipient() const
2506 {
2507     if (scheduler_ == nullptr) {
2508         TAG_LOGW(AAFwkTag::ABILITYMGR, "null scheduler_");
2509         return;
2510     }
2511 
2512     if (schedulerDeathRecipient_ == nullptr) {
2513         TAG_LOGW(AAFwkTag::ABILITYMGR, "null schedulerDeathRecipient_");
2514         return;
2515     }
2516 
2517     auto schedulerObject = scheduler_->AsObject();
2518     if (schedulerObject != nullptr) {
2519         TAG_LOGD(AAFwkTag::ABILITYMGR, "RemoveDeathRecipient");
2520         schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
2521     }
2522 }
2523 
OnSchedulerDied(const wptr<IRemoteObject> &remote)2524 void AbilityRecord::OnSchedulerDied(const wptr<IRemoteObject> &remote)
2525 {
2526     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
2527     std::lock_guard<ffrt::mutex> guard(lock_);
2528     CHECK_POINTER(scheduler_);
2529 
2530     auto object = remote.promote();
2531     CHECK_POINTER(object);
2532 
2533     if (object != scheduler_->AsObject()) {
2534         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability died: scheduler not matches remote");
2535         return;
2536     }
2537 
2538     RevokeUriPermission();
2539     if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
2540         auto schedulerObject = scheduler_->AsObject();
2541         if (schedulerObject != nullptr) {
2542             schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
2543         }
2544     }
2545     CHECK_POINTER(lifecycleDeal_);
2546     lifecycleDeal_->SetScheduler(nullptr);
2547     isWindowAttached_ = false;
2548 
2549     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
2550     CHECK_POINTER(handler);
2551 
2552     TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability on scheduler died: '%{public}s'", abilityInfo_.name.c_str());
2553     auto task = [ability = shared_from_this()]() {
2554         DelayedSingleton<AbilityManagerService>::GetInstance()->OnAbilityDied(ability);
2555     };
2556     handler->SubmitTask(task);
2557     auto uriTask = [want = GetWant(), ability = shared_from_this()]() {
2558         ability->SaveResultToCallers(-1, &want);
2559         ability->SendResultToCallers(true);
2560     };
2561     handler->SubmitTask(uriTask);
2562 #ifdef SUPPORT_GRAPHICS
2563     NotifyAnimationAbilityDied();
2564 #endif
2565 #ifdef WITH_DLP
2566     HandleDlpClosed();
2567 #endif // WITH_DLP
2568     NotifyRemoveShellProcess(CollaboratorType::RESERVE_TYPE);
2569     NotifyRemoveShellProcess(CollaboratorType::OTHERS_TYPE);
2570 }
2571 
OnProcessDied()2572 void AbilityRecord::OnProcessDied()
2573 {
2574     std::lock_guard<ffrt::mutex> guard(lock_);
2575     if (!IsSceneBoard() && scheduler_ != nullptr) {
2576         TAG_LOGD(AAFwkTag::ABILITYMGR, "OnProcessDied: '%{public}s', attached.", abilityInfo_.name.c_str());
2577         return;
2578     }
2579     isWindowAttached_ = false;
2580     SetLoadState(AbilityLoadState::FAILED);
2581 
2582     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
2583     CHECK_POINTER(handler);
2584 
2585     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnProcessDied: '%{public}s'", abilityInfo_.name.c_str());
2586     auto task = [ability = shared_from_this()]() {
2587         DelayedSingleton<AbilityManagerService>::GetInstance()->OnAbilityDied(ability);
2588     };
2589     if (IsSceneBoard()) {
2590         handler->SubmitTask(task, RESTART_SCENEBOARD_DELAY);
2591     } else {
2592         handler->SubmitTask(task);
2593     }
2594     auto uriTask = [want = GetWant(), ability = shared_from_this()]() {
2595         ability->SaveResultToCallers(-1, &want);
2596         ability->SendResultToCallers(true);
2597     };
2598     handler->SubmitTask(uriTask);
2599 #ifdef SUPPORT_GRAPHICS
2600     NotifyAnimationAbilityDied();
2601 #endif
2602 #ifdef WITH_DLP
2603     HandleDlpClosed();
2604 #endif // WITH_DLP
2605     NotifyRemoveShellProcess(CollaboratorType::RESERVE_TYPE);
2606     NotifyRemoveShellProcess(CollaboratorType::OTHERS_TYPE);
2607 }
2608 
NotifyAnimationAbilityDied()2609 void AbilityRecord::NotifyAnimationAbilityDied()
2610 {
2611     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2612         return;
2613     }
2614     // notify winddow manager service the ability died
2615     if (missionId_ != -1) {
2616 #ifdef SUPPORT_SCREEN
2617         if (GetWMSHandler()) {
2618             sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
2619             SetAbilityTransitionInfo(info);
2620             TAG_LOGI(AAFwkTag::ABILITYMGR, "UIAbiltiy abnormal death");
2621             GetWMSHandler()->NotifyAnimationAbilityDied(info);
2622         }
2623 #endif // SUPPORT_SCREEN
2624     }
2625 }
2626 
SetConnRemoteObject(const sptr<IRemoteObject> &remoteObject)2627 void AbilityRecord::SetConnRemoteObject(const sptr<IRemoteObject> &remoteObject)
2628 {
2629     connRemoteObject_ = remoteObject;
2630 }
2631 
GetConnRemoteObject() const2632 sptr<IRemoteObject> AbilityRecord::GetConnRemoteObject() const
2633 {
2634     return connRemoteObject_;
2635 }
2636 
AddStartId()2637 void AbilityRecord::AddStartId()
2638 {
2639     startId_++;
2640 }
GetStartId() const2641 int AbilityRecord::GetStartId() const
2642 {
2643     return startId_;
2644 }
2645 
SetIsUninstallAbility()2646 void AbilityRecord::SetIsUninstallAbility()
2647 {
2648     isUninstall_ = true;
2649 }
2650 
IsUninstallAbility() const2651 bool AbilityRecord::IsUninstallAbility() const
2652 {
2653     return isUninstall_;
2654 }
2655 
SetLauncherRoot()2656 void AbilityRecord::SetLauncherRoot()
2657 {
2658     isLauncherRoot_ = true;
2659 }
2660 
IsLauncherRoot() const2661 bool AbilityRecord::IsLauncherRoot() const
2662 {
2663     return isLauncherRoot_;
2664 }
2665 
IsAbilityState(const AbilityState &state) const2666 bool AbilityRecord::IsAbilityState(const AbilityState &state) const
2667 {
2668     return (currentState_ == state);
2669 }
2670 
IsActiveState() const2671 bool AbilityRecord::IsActiveState() const
2672 {
2673     return (IsAbilityState(AbilityState::ACTIVE) || IsAbilityState(AbilityState::ACTIVATING) ||
2674             IsAbilityState(AbilityState::INITIAL) || IsAbilityState(AbilityState::FOREGROUND) ||
2675             IsAbilityState(AbilityState::FOREGROUNDING));
2676 }
2677 
SendEvent(uint32_t msg, uint32_t timeOut, int32_t param, bool isExtension)2678 void AbilityRecord::SendEvent(uint32_t msg, uint32_t timeOut, int32_t param, bool isExtension)
2679 {
2680     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetEventHandler();
2681     CHECK_POINTER(handler);
2682     param = (param == -1) ? recordId_ : param;
2683     auto eventWrap = EventWrap(msg, param, isExtension);
2684     eventWrap.SetTimeout(timeOut);
2685     if (!handler->SendEvent(eventWrap, timeOut, false)) {
2686         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed: %{public}u, %{public}d", msg, param);
2687     }
2688 }
2689 
SetWant(const Want &want)2690 void AbilityRecord::SetWant(const Want &want)
2691 {
2692     std::lock_guard guard(wantLock_);
2693     if (abilityInfo_.type == AppExecFwk::AbilityType::PAGE && isLaunching_) {
2694         TAG_LOGW(AAFwkTag::ABILITYMGR, "uIAbility launching");
2695         return;
2696     }
2697     auto multiThread = want_.GetBoolParam(MULTI_THREAD, false);
2698     auto errorInfoEnhance = want_.GetBoolParam(ERROR_INFO_ENHANCE, false);
2699     want_.CloseAllFd();
2700 
2701     want_ = want;
2702     if (launchDebugInfo_.isDebugAppSet) {
2703         want_.SetParam(DEBUG_APP, launchDebugInfo_.debugApp);
2704     } else {
2705         want_.RemoveParam(DEBUG_APP);
2706     }
2707     if (launchDebugInfo_.isNativeDebugSet) {
2708         want_.SetParam(NATIVE_DEBUG, launchDebugInfo_.nativeDebug);
2709     } else {
2710         want_.RemoveParam(NATIVE_DEBUG);
2711     }
2712     if (launchDebugInfo_.isPerfCmdSet) {
2713         want_.SetParam(PERF_CMD, launchDebugInfo_.perfCmd);
2714     } else {
2715         want_.RemoveParam(PERF_CMD);
2716     }
2717     if (multiThread) {
2718         want_.SetParam(MULTI_THREAD, true);
2719     }
2720     if (errorInfoEnhance) {
2721         want_.SetParam(ERROR_INFO_ENHANCE, true);
2722     }
2723     if (want_.HasParameter(UISERVICEHOSTPROXY_KEY)) {
2724         want_.RemoveParam(UISERVICEHOSTPROXY_KEY);
2725     }
2726 }
2727 
GetWant() const2728 Want AbilityRecord::GetWant() const
2729 {
2730     std::lock_guard guard(wantLock_);
2731     return want_;
2732 }
2733 
RemoveSignatureInfo()2734 void AbilityRecord::RemoveSignatureInfo()
2735 {
2736     std::lock_guard guard(wantLock_);
2737     want_.RemoveParam(Want::PARAM_RESV_CALLER_APP_ID);
2738     want_.RemoveParam(Want::PARAM_RESV_CALLER_APP_IDENTIFIER);
2739 }
2740 
GetElementName() const2741 AppExecFwk::ElementName AbilityRecord::GetElementName() const
2742 {
2743     std::lock_guard guard(wantLock_);
2744     return want_.GetElement();
2745 }
2746 
IsDebugApp() const2747 bool AbilityRecord::IsDebugApp() const
2748 {
2749     std::lock_guard guard(wantLock_);
2750     return launchDebugInfo_.debugApp;
2751 }
2752 
IsDebug() const2753 bool AbilityRecord::IsDebug() const
2754 {
2755     std::lock_guard guard(wantLock_);
2756     if (launchDebugInfo_.debugApp || launchDebugInfo_.nativeDebug ||
2757         !launchDebugInfo_.perfCmd.empty() || isAttachDebug_ || isAssertDebug_) {
2758         TAG_LOGI(AAFwkTag::ABILITYMGR, "debug mode, no need to handle");
2759         return true;
2760     }
2761     return false;
2762 }
2763 
SetWindowMode(int32_t windowMode)2764 void AbilityRecord::SetWindowMode(int32_t windowMode)
2765 {
2766     std::lock_guard guard(wantLock_);
2767     want_.SetParam(Want::PARAM_RESV_WINDOW_MODE, windowMode);
2768 }
2769 
RemoveWindowMode()2770 void AbilityRecord::RemoveWindowMode()
2771 {
2772     std::lock_guard guard(wantLock_);
2773     want_.RemoveParam(Want::PARAM_RESV_WINDOW_MODE);
2774 }
2775 
UpdateRecoveryInfo(bool hasRecoverInfo)2776 void AbilityRecord::UpdateRecoveryInfo(bool hasRecoverInfo)
2777 {
2778     if (hasRecoverInfo) {
2779         std::lock_guard guard(wantLock_);
2780         want_.SetParam(Want::PARAM_ABILITY_RECOVERY_RESTART, true);
2781         SetLaunchReason(LaunchReason::LAUNCHREASON_APP_RECOVERY);
2782     }
2783 }
2784 
GetRecoveryInfo()2785 bool AbilityRecord::GetRecoveryInfo()
2786 {
2787     std::lock_guard guard(wantLock_);
2788     return want_.GetBoolParam(Want::PARAM_ABILITY_RECOVERY_RESTART, false);
2789 }
2790 
SetStartSetting(const std::shared_ptr<AbilityStartSetting> &setting)2791 void AbilityRecord::SetStartSetting(const std::shared_ptr<AbilityStartSetting> &setting)
2792 {
2793     lifeCycleStateInfo_.setting = setting;
2794 }
2795 
GetStartSetting() const2796 std::shared_ptr<AbilityStartSetting> AbilityRecord::GetStartSetting() const
2797 {
2798     return lifeCycleStateInfo_.setting;
2799 }
2800 
SetRestarting(const bool isRestart)2801 void AbilityRecord::SetRestarting(const bool isRestart)
2802 {
2803     isRestarting_ = isRestart;
2804     TAG_LOGD(AAFwkTag::ABILITYMGR, "SetRestarting: %{public}d", isRestarting_);
2805     if ((isLauncherRoot_ && IsLauncherAbility()) || GetKeepAlive()) {
2806         restartCount_ = isRestart ? (--restartCount_) : restartMax_;
2807         TAG_LOGD(AAFwkTag::ABILITYMGR, "root launcher or resident process's restart count: %{public}d", restartCount_);
2808     }
2809 }
2810 
SetRestarting(const bool isRestart, int32_t canRestartCount)2811 void AbilityRecord::SetRestarting(const bool isRestart, int32_t canRestartCount)
2812 {
2813     isRestarting_ = isRestart;
2814     TAG_LOGD(
2815         AAFwkTag::ABILITYMGR, "SetRestarting: %{public}d, restart count: %{public}d", isRestarting_, canRestartCount);
2816 
2817     if ((isLauncherRoot_ && IsLauncherAbility()) || GetKeepAlive()) {
2818         restartCount_ = isRestart ? canRestartCount : restartMax_;
2819         TAG_LOGI(AAFwkTag::ABILITYMGR, "root launcher or resident process's restart count: %{public}d", restartCount_);
2820     }
2821 }
2822 
GetRestartCount() const2823 int32_t AbilityRecord::GetRestartCount() const
2824 {
2825     return restartCount_;
2826 }
2827 
SetRestartCount(int32_t restartCount)2828 void AbilityRecord::SetRestartCount(int32_t restartCount)
2829 {
2830     restartCount_ = restartCount;
2831 }
2832 
IsRestarting() const2833 bool AbilityRecord::IsRestarting() const
2834 {
2835     return isRestarting_;
2836 }
2837 
GetKeepAlive() const2838 bool AbilityRecord::GetKeepAlive() const
2839 {
2840     // Special ability
2841     std::vector<std::pair<std::string, std::string>> trustAbilities{
2842         { AbilityConfig::SCENEBOARD_BUNDLE_NAME, AbilityConfig::SCENEBOARD_ABILITY_NAME },
2843         { AbilityConfig::SYSTEM_UI_BUNDLE_NAME, AbilityConfig::SYSTEM_UI_ABILITY_NAME },
2844         { AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME }
2845     };
2846     for (const auto &pair : trustAbilities) {
2847         if (pair.first == abilityInfo_.bundleName && pair.second == abilityInfo_.name) {
2848             return true;
2849         }
2850     }
2851     bool keepAliveEnable = keepAliveBundle_;
2852     AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(
2853         abilityInfo_.applicationInfo.bundleName, keepAliveEnable);
2854     return keepAliveEnable;
2855 }
2856 
SetLoading(bool status)2857 void AbilityRecord::SetLoading(bool status)
2858 {
2859     isLoading_ = status;
2860 }
2861 
IsLoading() const2862 bool AbilityRecord::IsLoading() const
2863 {
2864     return isLoading_;
2865 }
2866 
GetRestartTime()2867 int64_t AbilityRecord::GetRestartTime()
2868 {
2869     return restartTime_;
2870 }
2871 
SetRestartTime(const int64_t restartTime)2872 void AbilityRecord::SetRestartTime(const int64_t restartTime)
2873 {
2874     restartTime_ = restartTime;
2875 }
2876 
SetAppState(const AppState &state)2877 void AbilityRecord::SetAppState(const AppState &state)
2878 {
2879     appState_ = state;
2880 }
2881 
GetAppState() const2882 AppState AbilityRecord::GetAppState() const
2883 {
2884     return appState_;
2885 }
2886 
SetLaunchReason(const LaunchReason &reason)2887 void AbilityRecord::SetLaunchReason(const LaunchReason &reason)
2888 {
2889     if (isAppAutoStartup_) {
2890         lifeCycleStateInfo_.launchParam.launchReason = LaunchReason::LAUNCHREASON_AUTO_STARTUP;
2891         return;
2892     }
2893     lifeCycleStateInfo_.launchParam.launchReason = reason;
2894 }
2895 
SetLastExitReason(const ExitReason &exitReason)2896 void AbilityRecord::SetLastExitReason(const ExitReason &exitReason)
2897 {
2898     lifeCycleStateInfo_.launchParam.lastExitReason = CovertAppExitReasonToLastReason(exitReason.reason);
2899     lifeCycleStateInfo_.launchParam.lastExitMessage = exitReason.exitMsg;
2900 }
2901 
CovertAppExitReasonToLastReason(const Reason exitReason)2902 LastExitReason AbilityRecord::CovertAppExitReasonToLastReason(const Reason exitReason)
2903 {
2904     switch (exitReason) {
2905         case REASON_NORMAL:
2906             return LASTEXITREASON_NORMAL;
2907         case REASON_CPP_CRASH:
2908             return LASTEXITREASON_CPP_CRASH;
2909         case REASON_JS_ERROR:
2910             return LASTEXITREASON_JS_ERROR;
2911         case REASON_APP_FREEZE:
2912             return LASTEXITREASON_APP_FREEZE;
2913         case REASON_PERFORMANCE_CONTROL:
2914             return LASTEXITREASON_PERFORMANCE_CONTROL;
2915         case REASON_RESOURCE_CONTROL:
2916             return LASTEXITREASON_RESOURCE_CONTROL;
2917         case REASON_UPGRADE:
2918             return LASTEXITREASON_UPGRADE;
2919         case REASON_UNKNOWN:
2920         default:
2921             return LASTEXITREASON_UNKNOWN;
2922     }
2923 }
2924 
NotifyContinuationResult(int32_t result)2925 void AbilityRecord::NotifyContinuationResult(int32_t result)
2926 {
2927     TAG_LOGI(AAFwkTag::ABILITYMGR, "NotifyContinuationResult");
2928     CHECK_POINTER(lifecycleDeal_);
2929 
2930     lifecycleDeal_->NotifyContinuationResult(result);
2931 }
2932 
SetMissionId(int32_t missionId)2933 void AbilityRecord::SetMissionId(int32_t missionId)
2934 {
2935     std::lock_guard guard(wantLock_);
2936     missionId_ = missionId;
2937     want_.RemoveParam(KEY_MISSION_ID);
2938     want_.SetParam(KEY_MISSION_ID, missionId_);
2939 }
2940 
SetSessionInfo(sptr<SessionInfo> sessionInfo)2941 void AbilityRecord::SetSessionInfo(sptr<SessionInfo> sessionInfo)
2942 {
2943     std::lock_guard guard(sessionLock_);
2944     sessionInfo_ = sessionInfo;
2945 }
2946 
GetSessionInfo() const2947 sptr<SessionInfo> AbilityRecord::GetSessionInfo() const
2948 {
2949     std::lock_guard guard(sessionLock_);
2950     return sessionInfo_;
2951 }
2952 
UpdateSessionInfo(sptr<IRemoteObject> sessionToken)2953 void AbilityRecord::UpdateSessionInfo(sptr<IRemoteObject> sessionToken)
2954 {
2955     {
2956         std::lock_guard guard(sessionLock_);
2957         if (sessionInfo_ == nullptr) {
2958             TAG_LOGW(AAFwkTag::ABILITYMGR, "null sessionInfo_");
2959             return;
2960         }
2961         sessionInfo_->sessionToken = sessionToken;
2962     }
2963     CHECK_POINTER(lifecycleDeal_);
2964     lifecycleDeal_->UpdateSessionToken(sessionToken);
2965 }
2966 
SetMinimizeReason(bool fromUser)2967 void AbilityRecord::SetMinimizeReason(bool fromUser)
2968 {
2969     minimizeReason_ = fromUser;
2970 }
2971 
SetSceneFlag(uint32_t sceneFlag)2972 void AbilityRecord::SetSceneFlag(uint32_t sceneFlag)
2973 {
2974     lifeCycleStateInfo_.sceneFlag = sceneFlag;
2975 }
2976 
SetAppIndex(const int32_t appIndex)2977 void AbilityRecord::SetAppIndex(const int32_t appIndex)
2978 {
2979     appIndex_ = appIndex;
2980 }
2981 
GetAppIndex() const2982 int32_t AbilityRecord::GetAppIndex() const
2983 {
2984     return appIndex_;
2985 }
2986 
IsMinimizeFromUser() const2987 bool AbilityRecord::IsMinimizeFromUser() const
2988 {
2989     return minimizeReason_;
2990 }
2991 
SetClearMissionFlag(bool clearMissionFlag)2992 void AbilityRecord::SetClearMissionFlag(bool clearMissionFlag)
2993 {
2994     clearMissionFlag_= clearMissionFlag;
2995 }
2996 
IsClearMissionFlag()2997 bool AbilityRecord::IsClearMissionFlag()
2998 {
2999     return clearMissionFlag_;
3000 }
3001 
GetMissionId() const3002 int32_t AbilityRecord::GetMissionId() const
3003 {
3004     return missionId_;
3005 }
3006 
SetSpecifiedFlag(const std::string &flag)3007 void AbilityRecord::SetSpecifiedFlag(const std::string &flag)
3008 {
3009     specifiedFlag_ = flag;
3010 }
3011 
GetSpecifiedFlag() const3012 std::string AbilityRecord::GetSpecifiedFlag() const
3013 {
3014     return specifiedFlag_;
3015 }
3016 
3017 // new version  --start
IsStartedByCall() const3018 bool AbilityRecord::IsStartedByCall() const
3019 {
3020     return isStartedByCall_;
3021 }
3022 
SetStartedByCall(const bool isFlag)3023 void AbilityRecord::SetStartedByCall(const bool isFlag)
3024 {
3025     isStartedByCall_ = isFlag;
3026 }
3027 
IsStartToBackground() const3028 bool AbilityRecord::IsStartToBackground() const
3029 {
3030     return isStartToBackground_;
3031 }
3032 
SetStartToBackground(const bool flag)3033 void AbilityRecord::SetStartToBackground(const bool flag)
3034 {
3035     isStartToBackground_ = flag;
3036 }
3037 
IsStartToForeground() const3038 bool AbilityRecord::IsStartToForeground() const
3039 {
3040     return isStartToForeground_;
3041 }
3042 
SetStartToForeground(const bool flag)3043 void AbilityRecord::SetStartToForeground(const bool flag)
3044 {
3045     isStartToForeground_ = flag;
3046 }
3047 
CallRequest()3048 void AbilityRecord::CallRequest()
3049 {
3050     CHECK_POINTER(scheduler_);
3051     // Async call request
3052     scheduler_->CallRequest();
3053 }
3054 
CallRequestDone(const sptr<IRemoteObject> &callStub) const3055 bool AbilityRecord::CallRequestDone(const sptr<IRemoteObject> &callStub) const
3056 {
3057     CHECK_POINTER_RETURN_BOOL(callContainer_);
3058     if (!callContainer_->CallRequestDone(callStub)) {
3059         TAG_LOGE(AAFwkTag::ABILITYMGR, "call failed");
3060         return false;
3061     }
3062     return true;
3063 }
3064 
Resolve(const AbilityRequest &abilityRequest)3065 ResolveResultType AbilityRecord::Resolve(const AbilityRequest &abilityRequest)
3066 {
3067     auto callback = abilityRequest.connect;
3068     if (abilityRequest.callType != AbilityCallType::CALL_REQUEST_TYPE || !callback) {
3069         TAG_LOGE(AAFwkTag::ABILITYMGR, "only callType can create call record");
3070         return ResolveResultType::NG_INNER_ERROR;
3071     }
3072     if (!callContainer_) {
3073         callContainer_ = std::make_shared<CallContainer>();
3074         if (!callContainer_) {
3075             TAG_LOGE(AAFwkTag::ABILITYMGR, "mark_shared error");
3076             return ResolveResultType::NG_INNER_ERROR;
3077         }
3078     }
3079 
3080     TAG_LOGD(AAFwkTag::ABILITYMGR, "create call record for this resolve. callerUid:%{public}d ,targetname:%{public}s",
3081         abilityRequest.callerUid,
3082         abilityRequest.abilityInfo.name.c_str());
3083 
3084     std::shared_ptr<CallRecord> callRecord = callContainer_->GetCallRecord(callback);
3085     if (!callRecord) {
3086         callRecord = CallRecord::CreateCallRecord(
3087             abilityRequest.callerUid, shared_from_this(), callback, abilityRequest.callerToken);
3088         if (!callRecord) {
3089             TAG_LOGE(AAFwkTag::ABILITYMGR, "mark_shared error");
3090             return ResolveResultType::NG_INNER_ERROR;
3091         }
3092     }
3093 
3094     callContainer_->AddCallRecord(callback, callRecord);
3095 
3096     if (callRecord->IsCallState(CallState::REQUESTED) && callRecord->GetCallStub()) {
3097         TAG_LOGD(AAFwkTag::ABILITYMGR, "this record has requested.");
3098         if (!callRecord->SchedulerConnectDone()) {
3099             TAG_LOGD(AAFwkTag::ABILITYMGR, "this callrecord has requested, but callback failed.");
3100             return ResolveResultType::NG_INNER_ERROR;
3101         }
3102         return ResolveResultType::OK_HAS_REMOTE_OBJ;
3103     }
3104 
3105     callRecord->SetCallState(CallState::REQUESTING);
3106     return ResolveResultType::OK_NO_REMOTE_OBJ;
3107 }
3108 
ReleaseCall(const sptr<IAbilityConnection>& connect)3109 bool AbilityRecord::ReleaseCall(const sptr<IAbilityConnection>& connect)
3110 {
3111     TAG_LOGD(AAFwkTag::ABILITYMGR, "ability release call record by callback.");
3112     CHECK_POINTER_RETURN_BOOL(callContainer_);
3113 
3114     return callContainer_->RemoveCallRecord(connect);
3115 }
3116 
IsExistConnection(const sptr<IAbilityConnection> &connect)3117 bool AbilityRecord::IsExistConnection(const sptr<IAbilityConnection> &connect)
3118 {
3119     TAG_LOGD(AAFwkTag::ABILITYMGR, "ability find call record by callback.");
3120     CHECK_POINTER_RETURN_BOOL(callContainer_);
3121 
3122     return callContainer_->IsExistConnection(connect);
3123 }
3124 
IsNeedToCallRequest() const3125 bool AbilityRecord::IsNeedToCallRequest() const
3126 {
3127     TAG_LOGD(AAFwkTag::ABILITYMGR, "ability release call record by callback.");
3128     if (callContainer_ == nullptr) {
3129         return false;
3130     }
3131 
3132     return callContainer_->IsNeedToCallRequest();
3133 }
3134 
ContinueAbility(const std::string& deviceId, uint32_t versionCode)3135 void AbilityRecord::ContinueAbility(const std::string& deviceId, uint32_t versionCode)
3136 {
3137     TAG_LOGI(AAFwkTag::ABILITYMGR, "ContinueAbility");
3138     CHECK_POINTER(lifecycleDeal_);
3139 
3140     lifecycleDeal_->ContinueAbility(deviceId, versionCode);
3141 }
3142 
SetSwitchingPause(bool state)3143 void AbilityRecord::SetSwitchingPause(bool state)
3144 {
3145     isSwitchingPause_ = state;
3146 }
3147 
IsSwitchingPause()3148 bool AbilityRecord::IsSwitchingPause()
3149 {
3150     return isSwitchingPause_;
3151 }
3152 
SetOwnerMissionUserId(int32_t userId)3153 void AbilityRecord::SetOwnerMissionUserId(int32_t userId)
3154 {
3155     ownerMissionUserId_ = userId;
3156 }
3157 
GetOwnerMissionUserId()3158 int32_t AbilityRecord::GetOwnerMissionUserId()
3159 {
3160     return ownerMissionUserId_;
3161 }
3162 
DumpClientInfo(std::vector<std::string> &info, const std::vector<std::string> &params, bool isClient, bool dumpConfig) const3163 void AbilityRecord::DumpClientInfo(std::vector<std::string> &info, const std::vector<std::string> &params,
3164     bool isClient, bool dumpConfig) const
3165 {
3166     if (!scheduler_ || !IsReady()) {
3167         TAG_LOGE(AAFwkTag::ABILITYMGR, "something nullptr.");
3168         return;
3169     }
3170     if (!isClient) {
3171         return;
3172     }
3173     std::unique_lock<ffrt::mutex> lock(dumpLock_);
3174     scheduler_->DumpAbilityInfo(params, info);
3175 
3176     TAG_LOGI(AAFwkTag::ABILITYMGR, "dump begin wait");
3177     isDumpTimeout_ = false;
3178     std::chrono::milliseconds timeout { DUMP_TIMEOUT_MULTIPLE };
3179     if (dumpCondition_.wait_for(lock, timeout) == ffrt::cv_status::timeout) {
3180         isDumpTimeout_ = true;
3181     }
3182     TAG_LOGI(AAFwkTag::ABILITYMGR, "dump done and begin parse");
3183     if (!isDumpTimeout_) {
3184         std::lock_guard<ffrt::mutex> infoLock(dumpInfoLock_);
3185         for (auto one : dumpInfos_) {
3186             info.emplace_back(one);
3187         }
3188     }
3189 
3190     if (!dumpConfig) {
3191         TAG_LOGI(AAFwkTag::ABILITYMGR, "not dumpConfig");
3192         return;
3193     }
3194     AppExecFwk::Configuration config;
3195     if (DelayedSingleton<AppScheduler>::GetInstance()->GetConfiguration(config) == ERR_OK) {
3196         info.emplace_back("          configuration: " + config.GetName());
3197     }
3198 }
3199 
DumpAbilityInfoDone(std::vector<std::string> &infos)3200 void AbilityRecord::DumpAbilityInfoDone(std::vector<std::string> &infos)
3201 {
3202     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
3203     if (isDumpTimeout_) {
3204         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, time out", __func__);
3205         return;
3206     }
3207     {
3208         std::lock_guard<ffrt::mutex> infoLock(dumpInfoLock_);
3209         dumpInfos_.clear();
3210         for (auto info : infos) {
3211             dumpInfos_.emplace_back(info);
3212         }
3213     }
3214     dumpCondition_.notify_all();
3215 }
3216 
PublishFileOpenEvent(const Want &want)3217 void AbilityRecord::PublishFileOpenEvent(const Want &want)
3218 {
3219     auto wangUri = want.GetUri();
3220     std::string uriStr = wangUri.ToString();
3221     if (!uriStr.empty() && wangUri.GetScheme() == "file") {
3222         TAG_LOGI(AAFwkTag::ABILITYMGR, "ability record, file uri: %{private}s, isGranted: %{public}d",
3223             uriStr.c_str(), isGrantedUriPermission_);
3224         Want msgWant;
3225         msgWant.SetAction("file.event.OPEN_TIME");
3226         msgWant.SetParam("uri", uriStr);
3227         auto timeNow = std::chrono::duration_cast<std::chrono::milliseconds>(
3228             std::chrono::system_clock::now().time_since_epoch()).count();
3229         std::string currentTime = std::to_string(timeNow);
3230         msgWant.SetParam("viewTime", currentTime);
3231         EventFwk::CommonEventData commonData{msgWant};
3232         EventFwk::CommonEventPublishInfo commonEventPublishInfo;
3233         std::vector<std::string> subscriberPermissions = {"ohos.permission.MANAGE_LOCAL_ACCOUNTS"};
3234         commonEventPublishInfo.SetSubscriberPermissions(subscriberPermissions);
3235         IN_PROCESS_CALL(EventFwk::CommonEventManager::PublishCommonEvent(commonData, commonEventPublishInfo));
3236     }
3237 }
3238 
GrantUriPermission(Want &want, std::string targetBundleName, bool isSandboxApp, uint32_t tokenId)3239 void AbilityRecord::GrantUriPermission(Want &want, std::string targetBundleName, bool isSandboxApp, uint32_t tokenId)
3240 {
3241     if (specifyTokenId_ > 0) {
3242         TAG_LOGI(AAFwkTag::ABILITYMGR, "specifyTokenId: %{public}u, cleaned", specifyTokenId_);
3243         tokenId = specifyTokenId_;
3244         specifyTokenId_ = 0;
3245     }
3246     // reject sandbox to grant uri permission by start ability
3247     if (!callerList_.empty() && callerList_.back()) {
3248         auto caller = callerList_.back()->GetCaller();
3249         if (caller && caller->appIndex_ > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
3250             TAG_LOGE(AAFwkTag::ABILITYMGR, "sandbox can not grant UriPermission");
3251             return;
3252         }
3253     }
3254     // reject sandbox to grant uri permission by terminate self with result
3255     if (isSandboxApp) {
3256         TAG_LOGE(AAFwkTag::ABILITYMGR, "sandbox can not grant UriPermission");
3257         return;
3258     }
3259     if (targetBundleName == AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
3260         collaboratorType_ == CollaboratorType::OTHERS_TYPE) {
3261         TAG_LOGD(AAFwkTag::ABILITYMGR, "reject shell application to grant uri permission");
3262         return;
3263     }
3264 
3265     if (!UriUtils::GetInstance().IsGrantUriPermissionFlag(want)) {
3266         TAG_LOGD(AAFwkTag::ABILITYMGR, "Do not call uriPermissionMgr.");
3267         return;
3268     }
3269     if (IsDmsCall(want)) {
3270         GrantDmsUriPermission(want, targetBundleName);
3271         return;
3272     }
3273     std::vector<std::string> uriVec;
3274     if (!UriUtils::GetInstance().GetUriListFromWant(want, uriVec)) {
3275         TAG_LOGE(AAFwkTag::ABILITYMGR, "get uri list failed");
3276         return;
3277     }
3278 
3279     auto callerPkg = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
3280     if (callerPkg == AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
3281         GrantPermissionToShell(uriVec, want.GetFlags(), targetBundleName)) {
3282         TAG_LOGI(AAFwkTag::ABILITYMGR, "permission to shell");
3283         return;
3284     }
3285     TAG_LOGW(AAFwkTag::ABILITYMGR, "sharing file uri to specific bundlename be denied");
3286     GrantUriPermissionInner(want, uriVec, targetBundleName, tokenId);
3287     PublishFileOpenEvent(want);
3288 }
3289 
GrantUriPermissionInner(Want &want, std::vector<std::string> &uriVec, const std::string &targetBundleName, uint32_t tokenId)3290 void AbilityRecord::GrantUriPermissionInner(Want &want, std::vector<std::string> &uriVec,
3291     const std::string &targetBundleName, uint32_t tokenId)
3292 {
3293     auto callerTokenId = tokenId > 0 ? tokenId :
3294         static_cast<uint32_t>(want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0));
3295     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerTokenId:%{public}u, tokenId:%{public}u", callerTokenId, tokenId);
3296     if (callerTokenId == 0) {
3297         TAG_LOGW(AAFwkTag::ABILITYMGR, "callerTokenId invalid");
3298         return;
3299     }
3300     uint32_t flag = want.GetFlags();
3301     std::vector<Uri> permissionUris;
3302     if (!UriUtils::GetInstance().IsPermissionPreCheckedType(abilityInfo_.extensionAbilityType)) {
3303         auto checkResults = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().CheckUriAuthorization(
3304             uriVec, flag, callerTokenId));
3305         permissionUris = UriUtils::GetInstance().GetPermissionedUriList(uriVec, checkResults, want);
3306     } else {
3307         TAG_LOGI(AAFwkTag::ABILITYMGR, "target is Service Extension.");
3308         // for service extension, uri permission checked ahead
3309         for (auto &uriStr: uriVec) {
3310             Uri uri(uriStr);
3311             if (uri.GetScheme() == "file") {
3312                 permissionUris.emplace_back(uri);
3313             }
3314         }
3315     }
3316     if (permissionUris.empty()) {
3317         TAG_LOGE(AAFwkTag::ABILITYMGR, "uris not permissioned.");
3318         return;
3319     }
3320     auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermissionPrivileged(permissionUris,
3321         flag, targetBundleName, appIndex_, callerTokenId, recordId_));
3322     if (ret != ERR_OK) {
3323         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed, err:%{public}d", ret);
3324         return;
3325     }
3326     isGrantedUriPermission_ = true;
3327 }
3328 
GrantPermissionToShell(const std::vector<std::string> &strUriVec, uint32_t flag, std::string targetPkg)3329 bool AbilityRecord::GrantPermissionToShell(const std::vector<std::string> &strUriVec, uint32_t flag,
3330     std::string targetPkg)
3331 {
3332     TAG_LOGD(AAFwkTag::ABILITYMGR, "Grant uri permission to shell.");
3333     std::vector<Uri> uriVec;
3334     for (auto&& str : strUriVec) {
3335         Uri uri(str);
3336         auto&& scheme = uri.GetScheme();
3337         if (scheme != "content") {
3338             return false;
3339         }
3340         uriVec.emplace_back(uri);
3341     }
3342 
3343     uint32_t initiatorTokenId = IPCSkeleton::GetCallingTokenID();
3344     for (auto&& uri : uriVec) {
3345         auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(uri, flag, targetPkg,
3346             appIndex_, initiatorTokenId, recordId_));
3347         if (ret == ERR_OK) {
3348             isGrantedUriPermission_ = true;
3349         }
3350     }
3351     return true;
3352 }
3353 
IsDmsCall(Want &want)3354 bool AbilityRecord::IsDmsCall(Want &want)
3355 {
3356     auto fromTokenId = static_cast<uint32_t>(want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
3357     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(fromTokenId);
3358     bool isNativeCall = tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE;
3359     if (!isNativeCall) {
3360         TAG_LOGI(AAFwkTag::ABILITYMGR, "not native call");
3361         return false;
3362     }
3363     AccessToken::NativeTokenInfo nativeTokenInfo;
3364     int32_t result = AccessToken::AccessTokenKit::GetNativeTokenInfo(fromTokenId, nativeTokenInfo);
3365     if (result == ERR_OK && nativeTokenInfo.processName == DMS_PROCESS_NAME) {
3366         TAG_LOGI(AAFwkTag::ABILITYMGR, "dms ability call");
3367         return true;
3368     }
3369     return false;
3370 }
3371 
GrantDmsUriPermission(Want &want, std::string targetBundleName)3372 void AbilityRecord::GrantDmsUriPermission(Want &want, std::string targetBundleName)
3373 {
3374     std::vector<std::string> uriStrVec = want.GetStringArrayParam(PARAMS_URI);
3375     TAG_LOGD(AAFwkTag::ABILITYMGR, "GrantDmsUriPermission uriVec size: %{public}zu", uriStrVec.size());
3376     if (uriStrVec.empty()) {
3377         TAG_LOGW(AAFwkTag::ABILITYMGR, "no need to grant uri permission");
3378         return;
3379     }
3380     std::vector<Uri> uriVec;
3381     for (auto &uriStr: uriVec) {
3382         uriVec.emplace_back(uriStr);
3383     }
3384     auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermissionPrivileged(uriVec,
3385         want.GetFlags(), targetBundleName, appIndex_));
3386     if (ret == ERR_OK) {
3387         TAG_LOGI(AAFwkTag::ABILITYMGR, "grant uri permission success");
3388         isGrantedUriPermission_ = true;
3389     }
3390     uriStrVec.clear();
3391     want.SetParam(PARAMS_URI, uriStrVec);
3392 }
3393 
RevokeUriPermission()3394 void AbilityRecord::RevokeUriPermission()
3395 {
3396     if (isGrantedUriPermission_) {
3397         TAG_LOGD(AAFwkTag::ABILITYMGR, "To remove uri permission.");
3398         UriPermissionManagerClient::GetInstance().RevokeUriPermission(
3399             abilityInfo_.applicationInfo.accessTokenId, recordId_);
3400         isGrantedUriPermission_ = false;
3401     }
3402 }
3403 
3404 #ifdef WITH_DLP
HandleDlpAttached()3405 void AbilityRecord::HandleDlpAttached()
3406 {
3407     if (abilityInfo_.bundleName == DLP_BUNDLE_NAME) {
3408         DelayedSingleton<ConnectionStateManager>::GetInstance()->AddDlpManager(shared_from_this());
3409     }
3410 
3411     if (appIndex_ > 0) {
3412         DelayedSingleton<ConnectionStateManager>::GetInstance()->AddDlpAbility(shared_from_this());
3413     }
3414 }
3415 
HandleDlpClosed()3416 void AbilityRecord::HandleDlpClosed()
3417 {
3418     if (abilityInfo_.bundleName == DLP_BUNDLE_NAME) {
3419         DelayedSingleton<ConnectionStateManager>::GetInstance()->RemoveDlpManager(shared_from_this());
3420     }
3421 
3422     if (appIndex_ > 0) {
3423         DelayedSingleton<ConnectionStateManager>::GetInstance()->RemoveDlpAbility(shared_from_this());
3424     }
3425 }
3426 #endif // WITH_DLP
3427 
NotifyRemoveShellProcess(int32_t type)3428 void AbilityRecord::NotifyRemoveShellProcess(int32_t type)
3429 {
3430     TAG_LOGD(AAFwkTag::ABILITYMGR, "type is : %{public}d", type);
3431     if (abilityInfo_.bundleName == AppUtils::GetInstance().GetBrokerDelegateBundleName()) {
3432         auto collaborator = DelayedSingleton<AbilityManagerService>::GetInstance()->GetCollaborator(type);
3433         if (collaborator == nullptr) {
3434             TAG_LOGD(AAFwkTag::ABILITYMGR, "collaborator is nullptr");
3435             return;
3436         }
3437         int ret = collaborator->NotifyRemoveShellProcess(pid_, SHELL_ASSISTANT_DIETYPE, SHELL_ASSISTANT_DIEREASON);
3438         TAG_LOGI(AAFwkTag::ABILITYMGR, "notify broker params pid: %{public}d", pid_);
3439         if (ret != ERR_OK) {
3440             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed, err: %{public}d", ret);
3441         }
3442     }
3443 }
3444 
NotifyMissionBindPid()3445 void AbilityRecord::NotifyMissionBindPid()
3446 {
3447     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3448         return;
3449     }
3450     auto sessionInfo = GetSessionInfo();
3451     if (sessionInfo == nullptr) {
3452         TAG_LOGD(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
3453         return;
3454     }
3455     int32_t persistentId = sessionInfo->persistentId;
3456     if (abilityInfo_.bundleName == AppUtils::GetInstance().GetBrokerDelegateBundleName()) {
3457         auto collaborator = DelayedSingleton<AbilityManagerService>::GetInstance()->GetCollaborator(
3458             CollaboratorType::RESERVE_TYPE);
3459         if (collaborator == nullptr) {
3460             TAG_LOGD(AAFwkTag::ABILITYMGR, "collaborator is nullptr");
3461             return;
3462         }
3463         collaborator->NotifyMissionBindPid(persistentId, pid_);
3464     }
3465 }
3466 
GetCurrentAccountId() const3467 int32_t AbilityRecord::GetCurrentAccountId() const
3468 {
3469     std::vector<int32_t> osActiveAccountIds;
3470     ErrCode ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
3471             QueryActiveOsAccountIds(osActiveAccountIds);
3472     if (ret != ERR_OK) {
3473         TAG_LOGE(AAFwkTag::ABILITYMGR, "queryActiveOsAccountIds failed");
3474         return DEFAULT_USER_ID;
3475     }
3476     if (osActiveAccountIds.empty()) {
3477         TAG_LOGE(AAFwkTag::ABILITYMGR, "empty QueryActiveOsAccountIds");
3478         return DEFAULT_USER_ID;
3479     }
3480 
3481     return osActiveAccountIds.front();
3482 }
3483 
SetPendingState(AbilityState state)3484 void AbilityRecord::SetPendingState(AbilityState state)
3485 {
3486     pendingState_.store(state);
3487 }
3488 
GetPendingState() const3489 AbilityState AbilityRecord::GetPendingState() const
3490 {
3491     return pendingState_.load();
3492 }
3493 
IsNeedBackToOtherMissionStack()3494 bool AbilityRecord::IsNeedBackToOtherMissionStack()
3495 {
3496     return isNeedBackToOtherMissionStack_;
3497 }
3498 
SetNeedBackToOtherMissionStack(bool isNeedBackToOtherMissionStack)3499 void AbilityRecord::SetNeedBackToOtherMissionStack(bool isNeedBackToOtherMissionStack)
3500 {
3501     isNeedBackToOtherMissionStack_ = isNeedBackToOtherMissionStack;
3502 }
3503 
GetOtherMissionStackAbilityRecord() const3504 std::shared_ptr<AbilityRecord> AbilityRecord::GetOtherMissionStackAbilityRecord() const
3505 {
3506     return otherMissionStackAbilityRecord_.lock();
3507 }
3508 
SetOtherMissionStackAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)3509 void AbilityRecord::SetOtherMissionStackAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)
3510 {
3511     otherMissionStackAbilityRecord_ = abilityRecord;
3512 }
3513 
GetCollaboratorType() const3514 int32_t AbilityRecord::GetCollaboratorType() const
3515 {
3516     return collaboratorType_;
3517 }
3518 
GetMissionAffinity() const3519 std::string AbilityRecord::GetMissionAffinity() const
3520 {
3521     return missionAffinity_;
3522 }
3523 
SetLockedState(bool lockedState)3524 void AbilityRecord::SetLockedState(bool lockedState)
3525 {
3526     lockedState_ = lockedState;
3527 }
3528 
GetLockedState()3529 bool AbilityRecord::GetLockedState()
3530 {
3531     return lockedState_;
3532 }
3533 
SetAttachDebug(const bool isAttachDebug)3534 void AbilityRecord::SetAttachDebug(const bool isAttachDebug)
3535 {
3536     isAttachDebug_ = isAttachDebug;
3537 }
3538 
SetAssertDebug(bool isAssertDebug)3539 void AbilityRecord::SetAssertDebug(bool isAssertDebug)
3540 {
3541     isAssertDebug_ = isAssertDebug;
3542 }
3543 
AddAbilityWindowStateMap(uint64_t uiExtensionComponentId, AbilityWindowState abilityWindowState)3544 void AbilityRecord::AddAbilityWindowStateMap(uint64_t uiExtensionComponentId,
3545     AbilityWindowState abilityWindowState)
3546 {
3547     abilityWindowStateMap_[uiExtensionComponentId] = abilityWindowState;
3548 }
3549 
RemoveAbilityWindowStateMap(uint64_t uiExtensionComponentId)3550 void AbilityRecord::RemoveAbilityWindowStateMap(uint64_t uiExtensionComponentId)
3551 {
3552     if (abilityWindowStateMap_.find(uiExtensionComponentId) != abilityWindowStateMap_.end()) {
3553         abilityWindowStateMap_.erase(uiExtensionComponentId);
3554     }
3555 }
3556 
IsAbilityWindowReady()3557 bool AbilityRecord::IsAbilityWindowReady()
3558 {
3559     for (auto &item:abilityWindowStateMap_) {
3560         if (item.second == AbilityWindowState::BACKGROUNDING ||
3561             item.second == AbilityWindowState::TERMINATING) {
3562             return false;
3563         }
3564     }
3565     return true;
3566 }
3567 
SetAbilityWindowState(const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd, bool isFinished)3568 void AbilityRecord::SetAbilityWindowState(const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd, bool isFinished)
3569 {
3570     if (sessionInfo == nullptr) {
3571         TAG_LOGE(AAFwkTag::ABILITYMGR, "null sessionInfo");
3572         return;
3573     }
3574     if (isFinished) {
3575         if (winCmd == WIN_CMD_FOREGROUND) {
3576             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::FOREGROUND);
3577         } else if (winCmd == WIN_CMD_BACKGROUND) {
3578             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::BACKGROUND);
3579         } else if (winCmd == WIN_CMD_DESTROY) {
3580             RemoveAbilityWindowStateMap(sessionInfo->uiExtensionComponentId);
3581         }
3582     } else {
3583         if (winCmd == WIN_CMD_FOREGROUND) {
3584             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::FOREGROUNDING);
3585         } else if (winCmd == WIN_CMD_BACKGROUND) {
3586             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::BACKGROUNDING);
3587         } else if (winCmd == WIN_CMD_DESTROY) {
3588             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::TERMINATING);
3589         }
3590     }
3591 }
3592 
CreateModalUIExtension(const Want &want)3593 int32_t AbilityRecord::CreateModalUIExtension(const Want &want)
3594 {
3595     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
3596     CHECK_POINTER_AND_RETURN(scheduler_, INNER_ERR);
3597     return scheduler_->CreateModalUIExtension(want);
3598 }
3599 
SetURI(const std::string &uri)3600 void AbilityRecord::SetURI(const std::string &uri)
3601 {
3602     uri_ = uri;
3603 }
3604 
GetURI() const3605 std::string AbilityRecord::GetURI() const
3606 {
3607     if (uri_.empty()) {
3608         auto bundleName = abilityInfo_.bundleName;
3609         if (MultiInstanceUtils::IsMultiInstanceApp(abilityInfo_.applicationInfo)) {
3610             bundleName = bundleName + '-' + GetInstanceKey();
3611         } else if (AbilityRuntime::StartupUtil::IsSupportAppClone(abilityInfo_.extensionAbilityType)) {
3612             if (appIndex_ > 0) {
3613                 bundleName = std::to_string(appIndex_) + bundleName;
3614             }
3615         }
3616         return AppExecFwk::ElementName(abilityInfo_.deviceId, bundleName,
3617             abilityInfo_.name, abilityInfo_.moduleName).GetURI();
3618     }
3619     return uri_;
3620 }
3621 
SetProcessName(const std::string &process)3622 void AbilityRecord::SetProcessName(const std::string &process)
3623 {
3624     abilityInfo_.process = process;
3625 }
3626 
GetProcessName() const3627 std::string AbilityRecord::GetProcessName() const
3628 {
3629     return abilityInfo_.process;
3630 }
3631 
SetUIExtensionAbilityId(const int32_t uiExtensionAbilityId)3632 void AbilityRecord::SetUIExtensionAbilityId(const int32_t uiExtensionAbilityId)
3633 {
3634     uiExtensionAbilityId_ = uiExtensionAbilityId;
3635 }
3636 
GetUIExtensionAbilityId() const3637 int32_t AbilityRecord::GetUIExtensionAbilityId() const
3638 {
3639     return uiExtensionAbilityId_;
3640 }
3641 
BackgroundAbilityWindowDelayed()3642 bool AbilityRecord::BackgroundAbilityWindowDelayed()
3643 {
3644     return backgroundAbilityWindowDelayed_.load();
3645 }
3646 
DoBackgroundAbilityWindowDelayed(bool needBackground)3647 void AbilityRecord::DoBackgroundAbilityWindowDelayed(bool needBackground)
3648 {
3649     backgroundAbilityWindowDelayed_.store(needBackground);
3650 }
3651 
IsSceneBoard() const3652 bool AbilityRecord::IsSceneBoard() const
3653 {
3654     return AbilityUtil::IsSceneBoard(abilityInfo_.bundleName, abilityInfo_.name);
3655 }
3656 
SetRestartAppFlag(bool isRestartApp)3657 void AbilityRecord::SetRestartAppFlag(bool isRestartApp)
3658 {
3659     isRestartApp_ = isRestartApp;
3660 }
3661 
GetRestartAppFlag() const3662 bool AbilityRecord::GetRestartAppFlag() const
3663 {
3664     return isRestartApp_;
3665 }
3666 
UpdateUIExtensionInfo(const WantParams &wantParams)3667 void AbilityRecord::UpdateUIExtensionInfo(const WantParams &wantParams)
3668 {
3669     if (!UIExtensionUtils::IsUIExtension(GetAbilityInfo().extensionAbilityType)) {
3670         return;
3671     }
3672 
3673     std::lock_guard guard(wantLock_);
3674     if (want_.HasParameter(UIEXTENSION_ABILITY_ID)) {
3675         want_.RemoveParam(UIEXTENSION_ABILITY_ID);
3676     }
3677     want_.SetParam(UIEXTENSION_ABILITY_ID, wantParams.GetIntParam(UIEXTENSION_ABILITY_ID, -1));
3678 
3679     if (want_.HasParameter(UIEXTENSION_ROOT_HOST_PID)) {
3680         want_.RemoveParam(UIEXTENSION_ROOT_HOST_PID);
3681     }
3682     want_.SetParam(UIEXTENSION_ROOT_HOST_PID, wantParams.GetIntParam(UIEXTENSION_ROOT_HOST_PID, -1));
3683 }
3684 
SetSpecifyTokenId(uint32_t specifyTokenId)3685 void AbilityRecord::SetSpecifyTokenId(uint32_t specifyTokenId)
3686 {
3687     specifyTokenId_ = specifyTokenId;
3688 }
3689 
SetDebugAppByWaitingDebugFlag()3690 void AbilityRecord::SetDebugAppByWaitingDebugFlag()
3691 {
3692     if (!(abilityInfo_.applicationInfo.debug &&
3693         abilityInfo_.applicationInfo.appProvisionType == APP_PROVISION_TYPE_DEBUG) ||
3694         !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
3695         TAG_LOGD(AAFwkTag::ABILITYMGR, "Not meeting the set debugging conditions.");
3696         return;
3697     }
3698 
3699     if (IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->IsWaitingDebugApp(
3700         abilityInfo_.applicationInfo.bundleName))) {
3701         want_.SetParam(DEBUG_APP, true);
3702         launchDebugInfo_.isDebugAppSet = true;
3703         launchDebugInfo_.debugApp = true;
3704         IN_PROCESS_CALL_WITHOUT_RET(
3705             DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->ClearNonPersistWaitingDebugFlag());
3706     }
3707 }
3708 
SaveConnectWant(const Want &want)3709 void AbilityRecord::SaveConnectWant(const Want &want)
3710 {
3711     std::lock_guard guard(connectWantLock_);
3712     if (connectWant_ == nullptr) {
3713         connectWant_ = std::make_shared<Want>(want);
3714     }
3715 }
3716 
UpdateConnectWant()3717 void AbilityRecord::UpdateConnectWant()
3718 {
3719     std::lock_guard guard(connectWantLock_);
3720     if (connectWant_ != nullptr) {
3721         SetWant(*connectWant_);
3722     }
3723 }
3724 
RemoveConnectWant()3725 void AbilityRecord::RemoveConnectWant()
3726 {
3727     std::lock_guard guard(connectWantLock_);
3728     connectWant_.reset();
3729 }
3730 
UpdateDmsCallerInfo(Want &want)3731 void AbilityRecord::UpdateDmsCallerInfo(Want &want)
3732 {
3733     if (want.GetIntParam(Want::PARAM_RESV_CALLER_UID, 0) != DMS_UID) {
3734         return;
3735     }
3736     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, -1);
3737     want.SetParam(Want::PARAM_RESV_CALLER_UID, -1);
3738     want.SetParam(Want::PARAM_RESV_CALLER_PID, -1);
3739 
3740     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, want.GetStringParam(DMS_CALLER_BUNDLE_NAME));
3741     want.RemoveParam(DMS_CALLER_BUNDLE_NAME);
3742     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, want.GetStringParam(DMS_CALLER_ABILITY_NAME));
3743     want.RemoveParam(DMS_CALLER_ABILITY_NAME);
3744     want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME, want.GetStringParam(DMS_CALLER_NATIVE_NAME));
3745     want.RemoveParam(DMS_CALLER_NATIVE_NAME);
3746     want.SetParam(Want::PARAM_RESV_CALLER_APP_ID, want.GetStringParam(DMS_CALLER_APP_ID));
3747     want.RemoveParam(DMS_CALLER_APP_ID);
3748     want.SetParam(Want::PARAM_RESV_CALLER_APP_IDENTIFIER, want.GetStringParam(DMS_CALLER_APP_IDENTIFIER));
3749     want.RemoveParam(DMS_CALLER_APP_IDENTIFIER);
3750 }
3751 }  // namespace AAFwk
3752 }  // namespace OHOS
3753