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