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