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