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