• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2023 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 <filesystem>
19 #include <singleton.h>
20 #include <vector>
21 #include <unordered_map>
22 
23 #include "constants.h"
24 #include "ability_app_state_observer.h"
25 #include "ability_event_handler.h"
26 #include "ability_manager_service.h"
27 #include "ability_scheduler_stub.h"
28 #include "ability_util.h"
29 #include "app_utils.h"
30 #include "appfreeze_manager.h"
31 #include "array_wrapper.h"
32 #include "accesstoken_kit.h"
33 #include "bundle_mgr_client.h"
34 #include "configuration_convertor.h"
35 #include "connection_state_manager.h"
36 #include "freeze_util.h"
37 #include "hitrace_meter.h"
38 #include "image_source.h"
39 #include "in_process_call_wrapper.h"
40 #include "errors.h"
41 #include "event_report.h"
42 #include "hilog_wrapper.h"
43 #include "os_account_manager_wrapper.h"
44 #include "parameters.h"
45 #include "scene_board_judgement.h"
46 #include "system_ability_token_callback.h"
47 #include "ui_extension_utils.h"
48 #include "uri_permission_manager_client.h"
49 #include "permission_constants.h"
50 #ifdef SUPPORT_GRAPHICS
51 #include "image_source.h"
52 #include "locale_config.h"
53 #include "mission_info_mgr.h"
54 #endif
55 #ifdef EFFICIENCY_MANAGER_ENABLE
56 #include "suspend_manager_client.h"
57 #endif // EFFICIENCY_MANAGER_ENABLE
58 
59 
60 namespace OHOS {
61 using AbilityRuntime::FreezeUtil;
62 namespace AAFwk {
63 using namespace OHOS::Security;
64 using namespace OHOS::AAFwk::PermissionConstants;
65 const std::string DEBUG_APP = "debugApp";
66 const std::string NATIVE_DEBUG = "nativeDebug";
67 const std::string PERF_CMD = "perfCmd";
68 const std::string DMS_PROCESS_NAME = "distributedsched";
69 const std::string DMS_MISSION_ID = "dmsMissionId";
70 const std::string DMS_SRC_NETWORK_ID = "dmsSrcNetworkId";
71 const std::string ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
72 const std::u16string SYSTEM_ABILITY_TOKEN_CALLBACK = u"ohos.aafwk.ISystemAbilityTokenCallback";
73 const std::string SHOW_ON_LOCK_SCREEN = "ShowOnLockScreen";
74 const std::string DLP_INDEX = "ohos.dlp.params.index";
75 const std::string DLP_BUNDLE_NAME = "com.ohos.dlpmanager";
76 const std::string COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
77 const std::string KEY_MISSION_ID = "ohos.anco.param.missionId";
78 const std::string NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
79 const std::string PARAMS_URI = "ability.verify.uri";
80 const std::string PARAMS_FILE_SAVING_URL_KEY = "pick_path_return";
81 const uint32_t RELEASE_STARTING_BG_TIMEOUT = 15000; // release starting window resource timeout.
82 const std::string SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant";
83 const std::string SHELL_ASSISTANT_DIEREASON = "crash_die";
84 const char* GRANT_PERSISTABLE_URI_PERMISSION_ENABLE_PARAMETER = "persist.sys.prepare_terminate";
85 constexpr int32_t GRANT_PERSISTABLE_URI_PERMISSION_ENABLE_SIZE = 6;
86 const std::string PARAM_MISSION_AFFINITY_KEY = "ohos.anco.param.missionAffinity";
87 const std::string DISTRIBUTED_FILES_PATH = "/data/storage/el2/distributedfiles/";
88 const int32_t SHELL_ASSISTANT_DIETYPE = 0;
89 int64_t AbilityRecord::abilityRecordId = 0;
90 const int32_t DEFAULT_USER_ID = 0;
91 const int32_t SEND_RESULT_CANCELED = -1;
92 const int VECTOR_SIZE = 2;
93 const int LOAD_TIMEOUT_ASANENABLED = 150;
94 const int TERMINATE_TIMEOUT_ASANENABLED = 150;
95 const int HALF_TIMEOUT = 2;
96 const int MAX_URI_COUNT = 500;
97 const int32_t BROKER_UID = 5557;
98 #ifdef SUPPORT_ASAN
99 const int COLDSTART_TIMEOUT_MULTIPLE = 15000;
100 const int LOAD_TIMEOUT_MULTIPLE = 15000;
101 const int FOREGROUND_TIMEOUT_MULTIPLE = 7500;
102 const int BACKGROUND_TIMEOUT_MULTIPLE = 4500;
103 const int ACTIVE_TIMEOUT_MULTIPLE = 7500;
104 const int TERMINATE_TIMEOUT_MULTIPLE = 15000;
105 const int INACTIVE_TIMEOUT_MULTIPLE = 800;
106 const int DUMP_TIMEOUT_MULTIPLE = 1500;
107 const int SHAREDATA_TIMEOUT_MULTIPLE = 7500;
108 #else
109 const int COLDSTART_TIMEOUT_MULTIPLE = 10;
110 const int LOAD_TIMEOUT_MULTIPLE = 10;
111 const int FOREGROUND_TIMEOUT_MULTIPLE = 5;
112 const int BACKGROUND_TIMEOUT_MULTIPLE = 3;
113 const int ACTIVE_TIMEOUT_MULTIPLE = 5;
114 const int TERMINATE_TIMEOUT_MULTIPLE = 10;
115 const int INACTIVE_TIMEOUT_MULTIPLE = 1;
116 const int DUMP_TIMEOUT_MULTIPLE = 1000;
117 const int SHAREDATA_TIMEOUT_MULTIPLE = 5;
118 const int32_t TYPE_RESERVE = 1;
119 const int32_t TYPE_OTHERS = 2;
120 #endif
121 const std::map<AbilityState, std::string> AbilityRecord::stateToStrMap = {
122     std::map<AbilityState, std::string>::value_type(INITIAL, "INITIAL"),
123     std::map<AbilityState, std::string>::value_type(INACTIVE, "INACTIVE"),
124     std::map<AbilityState, std::string>::value_type(ACTIVE, "ACTIVE"),
125     std::map<AbilityState, std::string>::value_type(INACTIVATING, "INACTIVATING"),
126     std::map<AbilityState, std::string>::value_type(ACTIVATING, "ACTIVATING"),
127     std::map<AbilityState, std::string>::value_type(TERMINATING, "TERMINATING"),
128     std::map<AbilityState, std::string>::value_type(FOREGROUND, "FOREGROUND"),
129     std::map<AbilityState, std::string>::value_type(BACKGROUND, "BACKGROUND"),
130     std::map<AbilityState, std::string>::value_type(FOREGROUNDING, "FOREGROUNDING"),
131     std::map<AbilityState, std::string>::value_type(BACKGROUNDING, "BACKGROUNDING"),
132     std::map<AbilityState, std::string>::value_type(FOREGROUND_FAILED, "FOREGROUND_FAILED"),
133     std::map<AbilityState, std::string>::value_type(FOREGROUND_INVALID_MODE, "FOREGROUND_INVALID_MODE"),
134     std::map<AbilityState, std::string>::value_type(FOREGROUND_WINDOW_FREEZED, "FOREGROUND_WINDOW_FREEZED"),
135     std::map<AbilityState, std::string>::value_type(FOREGROUND_DO_NOTHING, "FOREGROUND_DO_NOTHING"),
136     std::map<AbilityState, std::string>::value_type(BACKGROUND_FAILED, "BACKGROUND_FAILED"),
137 };
138 const std::map<AppState, std::string> AbilityRecord::appStateToStrMap_ = {
139     std::map<AppState, std::string>::value_type(AppState::BEGIN, "BEGIN"),
140     std::map<AppState, std::string>::value_type(AppState::READY, "READY"),
141     std::map<AppState, std::string>::value_type(AppState::FOREGROUND, "FOREGROUND"),
142     std::map<AppState, std::string>::value_type(AppState::BACKGROUND, "BACKGROUND"),
143     std::map<AppState, std::string>::value_type(AppState::SUSPENDED, "SUSPENDED"),
144     std::map<AppState, std::string>::value_type(AppState::TERMINATED, "TERMINATED"),
145     std::map<AppState, std::string>::value_type(AppState::END, "END"),
146     std::map<AppState, std::string>::value_type(AppState::FOCUS, "FOCUS"),
147 };
148 const std::map<AbilityLifeCycleState, AbilityState> AbilityRecord::convertStateMap = {
149     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_INITIAL, INITIAL),
150     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_INACTIVE, INACTIVE),
151     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_ACTIVE, ACTIVE),
152     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_FOREGROUND_NEW, FOREGROUND),
153     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_BACKGROUND_NEW, BACKGROUND),
154     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_FOREGROUND_FAILED, FOREGROUND_FAILED),
155     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_INVALID_WINDOW_MODE,
156         FOREGROUND_INVALID_MODE),
157     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_WINDOW_FREEZED,
158         FOREGROUND_WINDOW_FREEZED),
159     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_DO_NOTHING, FOREGROUND_DO_NOTHING),
160     std::map<AbilityLifeCycleState, AbilityState>::value_type(ABILITY_STATE_BACKGROUND_FAILED, BACKGROUND_FAILED),
161 };
162 
__anon41b48bf70102(sptr<Token> token, FreezeUtil::TimeoutState state, std::string &methodName) 163 auto g_addLifecycleEventTask = [](sptr<Token> token, FreezeUtil::TimeoutState state, std::string &methodName) {
164     CHECK_POINTER_LOG(token, "token is nullptr");
165     FreezeUtil::LifecycleFlow flow = { token->AsObject(), state };
166     auto entry = std::to_string(AbilityUtil::SystemTimeMillis()) + "; AbilityRecord::" + methodName +
167         "; the " + methodName + " lifecycle starts.";
168     FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
169 };
170 
Token(std::weak_ptr<AbilityRecord> abilityRecord)171 Token::Token(std::weak_ptr<AbilityRecord> abilityRecord) : abilityRecord_(abilityRecord)
172 {}
173 
~Token()174 Token::~Token()
175 {}
176 
GetAbilityRecordByToken(const sptr<IRemoteObject> & token)177 std::shared_ptr<AbilityRecord> Token::GetAbilityRecordByToken(const sptr<IRemoteObject> &token)
178 {
179     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
180     if (token == nullptr) {
181         return nullptr;
182     }
183 
184     std::string descriptor = Str16ToStr8(token->GetObjectDescriptor());
185     if (descriptor != "ohos.aafwk.AbilityToken") {
186         HILOG_ERROR("Input token is not an AbilityToken, token->GetObjectDescriptor(): %{public}s",
187             descriptor.c_str());
188         return nullptr;
189     }
190 
191     // Double check if token is valid
192     sptr<IAbilityToken> theToken = iface_cast<IAbilityToken>(token);
193     if (!theToken) {
194         return nullptr;
195     }
196     if (theToken->GetDescriptor() != u"ohos.aafwk.AbilityToken") {
197         return nullptr;
198     }
199 
200     return (static_cast<Token *>(token.GetRefPtr()))->GetAbilityRecord();
201 }
202 
GetAbilityRecord() const203 std::shared_ptr<AbilityRecord> Token::GetAbilityRecord() const
204 {
205     return abilityRecord_.lock();
206 }
207 
AbilityRecord(const Want & want,const AppExecFwk::AbilityInfo & abilityInfo,const AppExecFwk::ApplicationInfo & applicationInfo,int requestCode)208 AbilityRecord::AbilityRecord(const Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
209     const AppExecFwk::ApplicationInfo &applicationInfo, int requestCode)
210     : want_(want), abilityInfo_(abilityInfo), applicationInfo_(applicationInfo), requestCode_(requestCode)
211 {
212     recordId_ = abilityRecordId++;
213     auto abilityMgr = DelayedSingleton<AbilityManagerService>::GetInstance();
214     if (abilityMgr) {
215         bool isRootLauncher = (applicationInfo_.bundleName == LAUNCHER_BUNDLE_NAME);
216         restartMax_ = AmsConfigurationParameter::GetInstance().GetMaxRestartNum(isRootLauncher);
217         bool flag = abilityMgr->GetStartUpNewRuleFlag();
218         want_.SetParam(COMPONENT_STARTUP_NEW_RULES, flag);
219     }
220     restartCount_ = restartMax_;
221     appIndex_ = want.GetIntParam(DLP_INDEX, 0);
222     isAppAutoStartup_ = want_.GetBoolParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, false);
223     if (want_.HasParameter(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON)) {
224         want_.RemoveParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON);
225     }
226 }
227 
~AbilityRecord()228 AbilityRecord::~AbilityRecord()
229 {
230     if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
231         auto object = scheduler_->AsObject();
232         if (object != nullptr) {
233             object->RemoveDeathRecipient(schedulerDeathRecipient_);
234         }
235     }
236     RemoveAppStateObserver();
237 }
238 
CreateAbilityRecord(const AbilityRequest & abilityRequest)239 std::shared_ptr<AbilityRecord> AbilityRecord::CreateAbilityRecord(const AbilityRequest &abilityRequest)
240 {
241     std::shared_ptr<AbilityRecord> abilityRecord = std::make_shared<AbilityRecord>(
242         abilityRequest.want, abilityRequest.abilityInfo, abilityRequest.appInfo, abilityRequest.requestCode);
243     CHECK_POINTER_AND_RETURN(abilityRecord, nullptr);
244     abilityRecord->SetUid(abilityRequest.uid);
245     abilityRecord->SetAppIndex(abilityRequest.want.GetIntParam(DLP_INDEX, 0));
246     abilityRecord->SetCallerAccessTokenId(abilityRequest.callerAccessTokenId);
247     abilityRecord->sessionInfo_ = abilityRequest.sessionInfo;
248     if (!abilityRecord->Init()) {
249         HILOG_ERROR("failed to init new ability record");
250         return nullptr;
251     }
252     if (abilityRequest.startSetting != nullptr) {
253         HILOG_DEBUG("abilityRequest.startSetting...");
254         abilityRecord->SetStartSetting(abilityRequest.startSetting);
255     }
256     if (abilityRequest.IsCallType(AbilityCallType::CALL_REQUEST_TYPE)) {
257         HILOG_DEBUG("abilityRequest.callType is CALL_REQUEST_TYPE.");
258         abilityRecord->SetStartedByCall(true);
259     }
260     abilityRecord->collaboratorType_ = abilityRequest.collaboratorType;
261     abilityRecord->missionAffinity_ = abilityRequest.want.GetStringParam(PARAM_MISSION_AFFINITY_KEY);
262 
263     if (abilityRecord->IsDebug()) {
264         abilityRecord->abilityAppStateObserver_ = sptr<AbilityAppStateObserver>(
265             new AbilityAppStateObserver(abilityRecord));
266         DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->RegisterApplicationStateObserver(
267             abilityRecord->abilityAppStateObserver_, {abilityRequest.abilityInfo.bundleName});
268     }
269     return abilityRecord;
270 }
271 
RemoveAppStateObserver()272 void AbilityRecord::RemoveAppStateObserver()
273 {
274     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
275     if (handler && abilityAppStateObserver_) {
276         handler->SubmitTask([appStateObserver = abilityAppStateObserver_]() {
277                 DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->UnregisterApplicationStateObserver(
278                     appStateObserver);
279             });
280         abilityAppStateObserver_ = nullptr;
281     }
282 }
283 
Init()284 bool AbilityRecord::Init()
285 {
286     lifecycleDeal_ = std::make_unique<LifecycleDeal>();
287     CHECK_POINTER_RETURN_BOOL(lifecycleDeal_);
288 
289     token_ = new (std::nothrow) Token(weak_from_this());
290     CHECK_POINTER_RETURN_BOOL(token_);
291 
292     if (applicationInfo_.isLauncherApp) {
293         isLauncherAbility_ = true;
294     }
295     InitPersistableUriPermissionConfig();
296     return true;
297 }
298 
SetUid(int32_t uid)299 void AbilityRecord::SetUid(int32_t uid)
300 {
301     uid_ = uid;
302 }
303 
GetUid()304 int32_t AbilityRecord::GetUid()
305 {
306     return uid_;
307 }
308 
GetPid()309 int32_t AbilityRecord::GetPid()
310 {
311     return pid_;
312 }
313 
LoadUIAbility()314 void AbilityRecord::LoadUIAbility()
315 {
316     SetLoading(true);
317     int loadTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * LOAD_TIMEOUT_MULTIPLE;
318     if (applicationInfo_.asanEnabled) {
319         loadTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * LOAD_TIMEOUT_ASANENABLED;
320         SendEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, loadTimeout / HALF_TIMEOUT);
321     } else {
322         int coldStartTimeout =
323             AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * COLDSTART_TIMEOUT_MULTIPLE;
324         std::lock_guard guard(wantLock_);
325         auto delayTime = want_.GetBoolParam("coldStart", false) ? coldStartTimeout : loadTimeout;
326         SendEvent(AbilityManagerService::LOAD_TIMEOUT_MSG, delayTime / HALF_TIMEOUT);
327     }
328     std::string methodName = "LoadAbility";
329     g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::LOAD, methodName);
330 }
331 
LoadAbility()332 int AbilityRecord::LoadAbility()
333 {
334     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
335     HILOG_INFO("LoadLifecycle: abilityName:%{public}s.", abilityInfo_.name.c_str());
336     startTime_ = AbilityUtil::SystemTimeMillis();
337     CHECK_POINTER_AND_RETURN(token_, ERR_INVALID_VALUE);
338     // only for UIAbility
339     if (!IsDebug() && abilityInfo_.type != AppExecFwk::AbilityType::DATA) {
340         LoadUIAbility();
341     }
342 
343     std::string appName = applicationInfo_.name;
344     if (appName.empty()) {
345         HILOG_ERROR("app name is empty");
346         return ERR_INVALID_VALUE;
347     }
348 
349     if (!CanRestartRootLauncher()) {
350         HILOG_ERROR("Root launcher restart is out of max count.");
351         return ERR_INVALID_VALUE;
352     }
353 
354     if (isRestarting_) {
355         restartTime_ = AbilityUtil::SystemTimeMillis();
356     }
357 
358     sptr<Token> callerToken_ = nullptr;
359     if (!callerList_.empty() && callerList_.back()) {
360         auto caller = callerList_.back()->GetCaller();
361         if (caller) {
362             callerToken_ = caller->GetToken();
363         }
364     }
365 
366     std::lock_guard guard(wantLock_);
367     want_.SetParam(ABILITY_OWNER_USERID, ownerMissionUserId_);
368     want_.SetParam("ohos.ability.launch.reason", static_cast<int>(lifeCycleStateInfo_.launchParam.launchReason));
369     auto result = DelayedSingleton<AppScheduler>::GetInstance()->LoadAbility(
370         token_, callerToken_, abilityInfo_, applicationInfo_, want_);
371     want_.RemoveParam(ABILITY_OWNER_USERID);
372 
373     auto isAttachDebug = DelayedSingleton<AppScheduler>::GetInstance()->IsAttachDebug(abilityInfo_.bundleName);
374     if (isAttachDebug) {
375         SetAttachDebug(true);
376     }
377     return result;
378 }
379 
CanRestartRootLauncher()380 bool AbilityRecord::CanRestartRootLauncher()
381 {
382     if (isLauncherRoot_ && isRestarting_ && IsLauncherAbility() && (restartCount_ < 0)) {
383         HILOG_ERROR("Root launcher restart is out of max count.");
384         return false;
385     }
386     return true;
387 }
388 
CanRestartResident()389 bool AbilityRecord::CanRestartResident()
390 {
391     HILOG_DEBUG("isKeepAlive: %{public}d, isRestarting: %{public}d, restartCount: %{public}d",
392         isKeepAlive_, isRestarting_, restartCount_);
393     if (isKeepAlive_ && isRestarting_ && (restartCount_ < 0)) {
394         int restartIntervalTime = 0;
395         auto abilityMgr = DelayedSingleton<AbilityManagerService>::GetInstance();
396         if (abilityMgr) {
397             restartIntervalTime = AmsConfigurationParameter::GetInstance().GetRestartIntervalTime();
398         }
399         HILOG_DEBUG("restartTime: %{public}lld, now: %{public}lld, intervalTine:%{public}d",
400             static_cast<unsigned long long>(restartTime_),
401             static_cast<unsigned long long>(AbilityUtil::SystemTimeMillis()), restartIntervalTime);
402         if ((AbilityUtil::SystemTimeMillis() - restartTime_) < restartIntervalTime) {
403             HILOG_ERROR("Resident restart is out of max count");
404             return false;
405         }
406     }
407     return true;
408 }
409 
410 // only for UIAbility
ForegroundAbility(uint32_t sceneFlag)411 void AbilityRecord::ForegroundAbility(uint32_t sceneFlag)
412 {
413     isWindowStarted_ = true;
414     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
415     HILOG_INFO("ForegroundLifecycle: name:%{public}s.", abilityInfo_.name.c_str());
416     CHECK_POINTER(lifecycleDeal_);
417 
418     if (!IsDebug()) {
419         int foregroundTimeout =
420             AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * FOREGROUND_TIMEOUT_MULTIPLE;
421         SendEvent(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, foregroundTimeout / HALF_TIMEOUT);
422         std::string methodName = "ForegroundAbility";
423         g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::FOREGROUND, methodName);
424     }
425 
426     // schedule active after updating AbilityState and sending timeout message to avoid ability async callback
427     // earlier than above actions
428     SetAbilityStateInner(AbilityState::FOREGROUNDING);
429     lifeCycleStateInfo_.sceneFlag = sceneFlag;
430     lifecycleDeal_->ForegroundNew(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
431     lifeCycleStateInfo_.sceneFlag = 0;
432     lifeCycleStateInfo_.sceneFlagBak = 0;
433     {
434         std::lock_guard guard(wantLock_);
435         InsightIntentExecuteParam::RemoveInsightIntent(want_);
436     }
437 
438     // update ability state to appMgr service when restart.
439     if (IsNewWant()) {
440         sptr<Token> preToken = nullptr;
441         if (GetPreAbilityRecord()) {
442             preToken = GetPreAbilityRecord()->GetToken();
443         }
444         DelayedSingleton<AppScheduler>::GetInstance()->AbilityBehaviorAnalysis(token_, preToken, 1, 1, 1);
445     }
446 }
447 
ForegroundAbility(const Closure & task,sptr<SessionInfo> sessionInfo,uint32_t sceneFlag)448 void AbilityRecord::ForegroundAbility(const Closure &task, sptr<SessionInfo> sessionInfo, uint32_t sceneFlag)
449 {
450     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
451     HILOG_INFO("ability: %{public}s.", GetURI().c_str());
452     CHECK_POINTER(lifecycleDeal_);
453     // grant uri permission
454     {
455         std::lock_guard guard(wantLock_);
456         GrantUriPermission(want_, applicationInfo_.bundleName, false, 0);
457     }
458 
459     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
460     if (handler && task) {
461         std::lock_guard guard(wantLock_);
462         if (!want_.GetBoolParam(DEBUG_APP, false) && !want_.GetBoolParam(NATIVE_DEBUG, false) && !isAttachDebug_) {
463             int foregroundTimeout =
464                 AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * FOREGROUND_TIMEOUT_MULTIPLE;
465             handler->SubmitTask(task, "foreground_" + std::to_string(recordId_), foregroundTimeout, false);
466         } else {
467             HILOG_INFO("Is debug mode, no need to handle time out.");
468         }
469     }
470 
471     // schedule active after updating AbilityState and sending timeout message to avoid ability async callback
472     // earlier than above actions.
473     SetAbilityStateInner(AbilityState::FOREGROUNDING);
474     lifeCycleStateInfo_.sceneFlag = sceneFlag;
475     lifecycleDeal_->ForegroundNew(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
476     lifeCycleStateInfo_.sceneFlag = 0;
477     lifeCycleStateInfo_.sceneFlagBak = 0;
478     {
479         std::lock_guard guard(wantLock_);
480         InsightIntentExecuteParam::RemoveInsightIntent(want_);
481     }
482 
483     // update ability state to appMgr service when restart
484     if (IsNewWant()) {
485         sptr<Token> preToken = nullptr;
486         if (GetPreAbilityRecord()) {
487             preToken = GetPreAbilityRecord()->GetToken();
488         }
489         DelayedSingleton<AppScheduler>::GetInstance()->AbilityBehaviorAnalysis(token_, preToken, 1, 1, 1);
490     }
491 }
492 
ProcessForegroundAbility(uint32_t tokenId,uint32_t sceneFlag)493 void AbilityRecord::ProcessForegroundAbility(uint32_t tokenId, uint32_t sceneFlag)
494 {
495     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
496     std::string element = GetElementName().GetURI();
497     HILOG_DEBUG("ability record: %{public}s", element.c_str());
498     {
499         std::lock_guard guard(wantLock_);
500         GrantUriPermission(want_, applicationInfo_.bundleName, false, tokenId);
501     }
502 
503     if (isReady_) {
504         if (IsAbilityState(AbilityState::FOREGROUND)) {
505             HILOG_DEBUG("Activate %{public}s", element.c_str());
506             ForegroundAbility(sceneFlag);
507         } else {
508             // background to active state
509             HILOG_DEBUG("MoveToForeground, %{public}s", element.c_str());
510             lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
511 #ifdef EFFICIENCY_MANAGER_ENABLE
512             std::string bundleName = GetAbilityInfo().bundleName;
513             int32_t uid = GetUid();
514             SuspendManager::SuspendManagerClient::GetInstance().ThawOneApplication(
515                 uid, bundleName, "THAW_BY_FOREGROUND_ABILITY");
516 #endif // EFFICIENCY_MANAGER_ENABLE
517             DelayedSingleton<AppScheduler>::GetInstance()->MoveToForeground(token_);
518         }
519     } else {
520         HILOG_DEBUG("To load ability.");
521         lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
522         LoadAbility();
523     }
524 }
525 
GetLabel()526 std::string AbilityRecord::GetLabel()
527 {
528     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
529     std::string strLabel = applicationInfo_.label;
530 
531     if (abilityInfo_.resourcePath.empty()) {
532         HILOG_WARN("resource path is empty.");
533         return strLabel;
534     }
535 
536 #ifdef SUPPORT_GRAPHICS
537     auto resourceMgr = CreateResourceManager();
538     if (!resourceMgr) {
539         return strLabel;
540     }
541 
542     auto result = resourceMgr->GetStringById(applicationInfo_.labelId, strLabel);
543     if (result != OHOS::Global::Resource::RState::SUCCESS) {
544         HILOG_WARN("%{public}s. Failed to GetStringById.", __func__);
545     }
546 
547     InitColdStartingWindowResource(resourceMgr);
548 #endif
549 
550     return strLabel;
551 }
552 
553 #ifdef SUPPORT_GRAPHICS
ProcessForegroundAbility(const std::shared_ptr<AbilityRecord> & callerAbility,bool needExit,uint32_t sceneFlag)554 void AbilityRecord::ProcessForegroundAbility(const std::shared_ptr<AbilityRecord> &callerAbility, bool needExit,
555     uint32_t sceneFlag)
556 {
557     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
558     std::string element = GetElementName().GetURI();
559     HILOG_DEBUG("SUPPORT_GRAPHICS: ability record: %{public}s", element.c_str());
560 
561     StartingWindowHot();
562     auto flag = !IsForeground();
563     NotifyAnimationFromTerminatingAbility(callerAbility, needExit, flag);
564     PostCancelStartingWindowHotTask();
565 
566     if (IsAbilityState(AbilityState::FOREGROUND)) {
567         HILOG_DEBUG("Activate %{public}s", element.c_str());
568         ForegroundAbility(sceneFlag);
569     } else {
570         // background to active state
571         HILOG_DEBUG("MoveToForeground, %{public}s", element.c_str());
572         lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
573         DelayedSingleton<AppScheduler>::GetInstance()->MoveToForeground(token_);
574     }
575 }
576 
NotifyAnimationFromTerminatingAbility(const std::shared_ptr<AbilityRecord> & callerAbility,bool needExit,bool flag)577 void AbilityRecord::NotifyAnimationFromTerminatingAbility(const std::shared_ptr<AbilityRecord>& callerAbility,
578     bool needExit, bool flag)
579 {
580     auto windowHandler = GetWMSHandler();
581     if (!windowHandler) {
582         HILOG_WARN("Get WMS handler failed.");
583         return;
584     }
585 
586     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
587     if (callerAbility) {
588         auto callerAbilityInfo = callerAbility->GetAbilityInfo();
589         SetAbilityTransitionInfo(callerAbilityInfo, fromInfo);
590         fromInfo->abilityToken_ = callerAbility->GetToken();
591     }
592 
593     if (flag && needExit) {
594         fromInfo->reason_ = TransitionReason::BACK_TRANSITION;
595     } else if (flag && !needExit) {
596         fromInfo->reason_ = TransitionReason::BACKGROUND_TRANSITION;
597     } else {
598         fromInfo->reason_ = TransitionReason::CLOSE;
599     }
600 
601     auto toInfo = CreateAbilityTransitionInfo();
602     SetAbilityTransitionInfo(abilityInfo_, toInfo);
603     bool animaEnabled = false;
604     windowHandler->NotifyWindowTransition(fromInfo, toInfo, animaEnabled);
605 }
606 
NotifyAnimationFromTerminatingAbility() const607 void AbilityRecord::NotifyAnimationFromTerminatingAbility() const
608 {
609     auto windowHandler = GetWMSHandler();
610     if (!windowHandler) {
611         HILOG_WARN("Get WMS handler failed.");
612         return;
613     }
614 
615     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
616     SetAbilityTransitionInfo(fromInfo);
617     fromInfo->reason_ = TransitionReason::CLOSE;
618     bool animaEnabled = false;
619     windowHandler->NotifyWindowTransition(fromInfo, nullptr, animaEnabled);
620 }
621 
NotifyAnimationFromMinimizeAbility(bool & animaEnabled)622 void AbilityRecord::NotifyAnimationFromMinimizeAbility(bool& animaEnabled)
623 {
624     auto windowHandler = GetWMSHandler();
625     if (!windowHandler) {
626         HILOG_WARN("Get WMS handler failed.");
627         return;
628     }
629     HILOG_INFO("Notify Animation From MinimizeAbility");
630     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
631     SetAbilityTransitionInfo(fromInfo);
632     fromInfo->reason_ = TransitionReason::MINIMIZE;
633     windowHandler->NotifyWindowTransition(fromInfo, nullptr, animaEnabled);
634 }
635 
SetAbilityTransitionInfo(sptr<AbilityTransitionInfo> & info) const636 void AbilityRecord::SetAbilityTransitionInfo(sptr<AbilityTransitionInfo>& info) const
637 {
638     info->abilityToken_ = token_;
639     info->missionId_ = missionId_;
640     info->abilityName_ = abilityInfo_.name;
641     info->bundleName_ = abilityInfo_.bundleName;
642     info->windowModes_ = abilityInfo_.windowModes;
643     info->maxWindowRatio_ = abilityInfo_.maxWindowRatio;
644     info->minWindowRatio_ = abilityInfo_.minWindowRatio;
645     info->maxWindowWidth_ = abilityInfo_.maxWindowWidth;
646     info->minWindowWidth_ = abilityInfo_.minWindowWidth;
647     info->maxWindowHeight_ = abilityInfo_.maxWindowHeight;
648     info->minWindowHeight_ = abilityInfo_.minWindowHeight;
649     info->orientation_ = abilityInfo_.orientation;
650     info->apiCompatibleVersion_ = abilityInfo_.applicationInfo.apiCompatibleVersion;
651 }
652 
CreateAbilityTransitionInfo()653 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo()
654 {
655     sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
656     SetAbilityTransitionInfo(info);
657     SetStartingWindow(true);
658     return info;
659 }
660 
StartingWindowHot()661 void AbilityRecord::StartingWindowHot()
662 {
663     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
664     auto windowHandler = GetWMSHandler();
665     if (!windowHandler) {
666         HILOG_WARN("Get WMS handler failed.");
667         return;
668     }
669 
670     auto pixelMap = DelayedSingleton<MissionInfoMgr>::GetInstance()->GetSnapshot(missionId_);
671     if (!pixelMap) {
672         HILOG_WARN("Get snapshot failed.");
673     }
674 
675     auto info = CreateAbilityTransitionInfo();
676     HILOG_INFO("Notify wms to start StartingWindow.");
677     windowHandler->StartingWindow(info, pixelMap);
678 }
679 
ProcessForegroundAbility(bool isRecent,const AbilityRequest & abilityRequest,std::shared_ptr<StartOptions> & startOptions,const std::shared_ptr<AbilityRecord> & callerAbility,uint32_t sceneFlag)680 void AbilityRecord::ProcessForegroundAbility(bool isRecent, const AbilityRequest &abilityRequest,
681     std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility,
682     uint32_t sceneFlag)
683 {
684     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
685     std::string element = GetElementName().GetURI();
686     HILOG_DEBUG("SUPPORT_GRAPHICS: ability record: %{public}s", element.c_str());
687     {
688         std::lock_guard guard(wantLock_);
689         GrantUriPermission(want_, applicationInfo_.bundleName, false, 0);
690     }
691 
692     if (isReady_) {
693         auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
694         if (!handler) {
695             HILOG_ERROR("Fail to get AbilityEventHandler.");
696             return;
697         }
698         auto taskName = std::to_string(missionId_) + "_hot";
699         handler->CancelTask(taskName);
700 
701         if (isWindowStarted_) {
702             StartingWindowTask(isRecent, false, abilityRequest, startOptions);
703             AnimationTask(isRecent, abilityRequest, startOptions, callerAbility);
704             PostCancelStartingWindowHotTask();
705         } else {
706             StartingWindowTask(isRecent, true, abilityRequest, startOptions);
707             AnimationTask(isRecent, abilityRequest, startOptions, callerAbility);
708             PostCancelStartingWindowColdTask();
709         }
710         if (IsAbilityState(AbilityState::FOREGROUND)) {
711             HILOG_DEBUG("Activate %{public}s", element.c_str());
712             ForegroundAbility(sceneFlag);
713         } else {
714             // background to active state
715             HILOG_DEBUG("MoveToForeground, %{public}s", element.c_str());
716             lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
717             DelayedSingleton<AppScheduler>::GetInstance()->MoveToForeground(token_);
718         }
719     } else {
720         HILOG_DEBUG("SUPPORT_GRAPHICS: to load ability.");
721         lifeCycleStateInfo_.sceneFlagBak = sceneFlag;
722         auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
723         auto needStartingWindow = abilityRequest.want.GetBoolParam(NEED_STARTINGWINDOW, true);
724         if (!isSaCall || needStartingWindow) {
725             StartingWindowTask(isRecent, true, abilityRequest, startOptions);
726             AnimationTask(isRecent, abilityRequest, startOptions, callerAbility);
727             PostCancelStartingWindowColdTask();
728         }
729         LoadAbility();
730     }
731 }
732 
GetWantFromMission() const733 std::shared_ptr<Want> AbilityRecord::GetWantFromMission() const
734 {
735     InnerMissionInfo innerMissionInfo;
736     int getMission = DelayedSingleton<MissionInfoMgr>::GetInstance()->GetInnerMissionInfoById(
737         missionId_, innerMissionInfo);
738     if (getMission != ERR_OK) {
739         HILOG_ERROR("cannot find mission info from MissionInfoList by missionId: %{public}d", missionId_);
740         return nullptr;
741     }
742 
743     return std::make_shared<Want>(innerMissionInfo.missionInfo.want);
744 }
745 
AnimationTask(bool isRecent,const AbilityRequest & abilityRequest,const std::shared_ptr<StartOptions> & startOptions,const std::shared_ptr<AbilityRecord> & callerAbility)746 void AbilityRecord::AnimationTask(bool isRecent, const AbilityRequest &abilityRequest,
747     const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<AbilityRecord> &callerAbility)
748 {
749     HILOG_DEBUG("called.");
750     if (isRecent) {
751         auto want = GetWantFromMission();
752         NotifyAnimationFromRecentTask(startOptions, want);
753     } else {
754         if (!IsForeground()) {
755             NotifyAnimationFromStartingAbility(callerAbility, abilityRequest);
756         }
757     }
758 }
759 
SetShowWhenLocked(const AppExecFwk::AbilityInfo & abilityInfo,sptr<AbilityTransitionInfo> & info) const760 void AbilityRecord::SetShowWhenLocked(const AppExecFwk::AbilityInfo &abilityInfo,
761     sptr<AbilityTransitionInfo> &info) const
762 {
763     for (const auto &data : abilityInfo.metaData.customizeData) {
764         if (data.name == SHOW_ON_LOCK_SCREEN) {
765             info->isShowWhenLocked_ = true;
766             break;
767         }
768     }
769 }
770 
SetAbilityTransitionInfo(const AppExecFwk::AbilityInfo & abilityInfo,sptr<AbilityTransitionInfo> & info) const771 void AbilityRecord::SetAbilityTransitionInfo(const AppExecFwk::AbilityInfo &abilityInfo,
772     sptr<AbilityTransitionInfo> &info) const
773 {
774     info->abilityName_ = abilityInfo.name;
775     info->bundleName_ = abilityInfo.bundleName;
776     info->windowModes_ = abilityInfo.windowModes;
777     info->orientation_ = abilityInfo.orientation;
778     info->apiCompatibleVersion_ = abilityInfo.applicationInfo.apiCompatibleVersion;
779     SetShowWhenLocked(abilityInfo, info);
780 }
781 
NotifyAnimationFromRecentTask(const std::shared_ptr<StartOptions> & startOptions,const std::shared_ptr<Want> & want) const782 void AbilityRecord::NotifyAnimationFromRecentTask(const std::shared_ptr<StartOptions> &startOptions,
783     const std::shared_ptr<Want> &want) const
784 {
785     auto windowHandler = GetWMSHandler();
786     if (!windowHandler) {
787         HILOG_WARN("%{public}s, Get WMS handler failed.", __func__);
788         return;
789     }
790 
791     auto toInfo = CreateAbilityTransitionInfo(startOptions, want);
792     toInfo->abilityToken_ = token_;
793     toInfo->missionId_ = missionId_;
794     SetAbilityTransitionInfo(abilityInfo_, toInfo);
795     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
796     fromInfo->isRecent_ = true;
797     bool animaEnabled = false;
798     windowHandler->NotifyWindowTransition(fromInfo, toInfo, animaEnabled);
799 }
800 
NotifyAnimationFromStartingAbility(const std::shared_ptr<AbilityRecord> & callerAbility,const AbilityRequest & abilityRequest) const801 void AbilityRecord::NotifyAnimationFromStartingAbility(const std::shared_ptr<AbilityRecord> &callerAbility,
802     const AbilityRequest &abilityRequest) const
803 {
804     auto windowHandler = GetWMSHandler();
805     if (!windowHandler) {
806         HILOG_WARN("%{public}s, Get WMS handler failed.", __func__);
807         return;
808     }
809 
810     sptr<AbilityTransitionInfo> fromInfo = new AbilityTransitionInfo();
811     if (callerAbility) {
812         auto callerAbilityInfo = callerAbility->GetAbilityInfo();
813         SetAbilityTransitionInfo(callerAbilityInfo, fromInfo);
814         fromInfo->abilityToken_ = callerAbility->GetToken();
815     } else {
816         fromInfo->abilityToken_ = abilityRequest.callerToken;
817     }
818 
819     auto toInfo = CreateAbilityTransitionInfo(abilityRequest);
820     toInfo->abilityToken_ = token_;
821     toInfo->missionId_ = missionId_;
822     SetAbilityTransitionInfo(abilityInfo_, toInfo);
823     bool animaEnabled = false;
824     windowHandler->NotifyWindowTransition(fromInfo, toInfo, animaEnabled);
825 }
826 
StartingWindowTask(bool isRecent,bool isCold,const AbilityRequest & abilityRequest,std::shared_ptr<StartOptions> & startOptions)827 void AbilityRecord::StartingWindowTask(bool isRecent, bool isCold, const AbilityRequest &abilityRequest,
828     std::shared_ptr<StartOptions> &startOptions)
829 {
830     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
831     HILOG_DEBUG("%{public}s was called.", __func__);
832     if (isRecent) {
833         auto want = GetWantFromMission();
834         if (isCold) {
835             StartingWindowCold(startOptions, want, abilityRequest);
836         } else {
837             StartingWindowHot(startOptions, want, abilityRequest);
838         }
839     } else {
840         std::shared_ptr<Want> want = nullptr;
841         if (isCold) {
842             StartingWindowCold(startOptions, want, abilityRequest);
843         } else {
844             StartingWindowHot(startOptions, want, abilityRequest);
845         }
846     }
847 }
848 
PostCancelStartingWindowHotTask()849 void AbilityRecord::PostCancelStartingWindowHotTask()
850 {
851     if (IsDebug()) {
852         HILOG_INFO("PostCancelStartingWindowHotTask was called, debug mode, just return.");
853         return;
854     }
855     HILOG_INFO("PostCancelStartingWindowHotTask was called.");
856     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
857     CHECK_POINTER_LOG(handler, "Fail to get TaskHandler.");
858 
859     auto windowHandler = GetWMSHandler();
860     CHECK_POINTER_LOG(windowHandler, "PostCancelStartingWindowColdTask, Get WMS handler failed.");
861 
862     auto abilityRecord(shared_from_this());
863     auto delayTask = [windowHandler, abilityRecord] {
864         if (windowHandler && abilityRecord && abilityRecord->IsStartingWindow() &&
865             abilityRecord->GetAbilityState() != AbilityState::FOREGROUNDING) {
866             HILOG_DEBUG("PostCancelStartingWindowHotTask, call windowHandler CancelStartingWindow.");
867             windowHandler->CancelStartingWindow(abilityRecord->GetToken());
868             abilityRecord->SetStartingWindow(false);
869         }
870     };
871     auto taskName = std::to_string(missionId_) + "_hot";
872     int foregroundTimeout =
873         AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * FOREGROUND_TIMEOUT_MULTIPLE;
874     handler->SubmitTask(delayTask, taskName, foregroundTimeout);
875 }
876 
PostCancelStartingWindowColdTask()877 void AbilityRecord::PostCancelStartingWindowColdTask()
878 {
879     if (IsDebug()) {
880         HILOG_INFO("PostCancelStartingWindowColdTask was called, debug mode, just return.");
881         return;
882     }
883     HILOG_DEBUG("PostCancelStartingWindowColdTask was called.");
884     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
885     CHECK_POINTER_LOG(handler, "Fail to get TaskHandler.");
886 
887     auto windowHandler = GetWMSHandler();
888     CHECK_POINTER_LOG(windowHandler, "PostCancelStartingWindowColdTask, Get WMS handler failed.");
889 
890     auto abilityRecord(shared_from_this());
891     auto delayTask = [windowHandler, abilityRecord] {
892         if (windowHandler && abilityRecord && abilityRecord->IsStartingWindow() &&
893             (abilityRecord->GetScheduler() == nullptr ||
894             abilityRecord->GetAbilityState() != AbilityState::FOREGROUNDING)) {
895             HILOG_DEBUG("PostCancelStartingWindowColdTask, call windowHandler CancelStartingWindow.");
896             windowHandler->CancelStartingWindow(abilityRecord->GetToken());
897             abilityRecord->SetStartingWindow(false);
898         }
899     };
900     auto taskName = std::to_string(missionId_) + "_cold";
901     int loadTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * LOAD_TIMEOUT_MULTIPLE;
902     handler->SubmitTask(delayTask, taskName, loadTimeout);
903 }
904 
GetWMSHandler() const905 sptr<IWindowManagerServiceHandler> AbilityRecord::GetWMSHandler() const
906 {
907     auto abilityMgr = DelayedSingleton<AbilityManagerService>::GetInstance();
908     if (!abilityMgr) {
909         HILOG_WARN("%{public}s, Get Ability Manager Service failed.", __func__);
910         return nullptr;
911     }
912     return abilityMgr->GetWMSHandler();
913 }
914 
SetWindowModeAndDisplayId(sptr<AbilityTransitionInfo> & info,const std::shared_ptr<Want> & want) const915 void AbilityRecord::SetWindowModeAndDisplayId(sptr<AbilityTransitionInfo> &info,
916     const std::shared_ptr<Want> &want) const
917 {
918     if (!want) {
919         HILOG_WARN("%{public}s, want is invalid.", __func__);
920         return;
921     }
922     auto mode = want->GetIntParam(Want::PARAM_RESV_WINDOW_MODE, -1);
923     auto displayId = want->GetIntParam(Want::PARAM_RESV_DISPLAY_ID, -1);
924     if (mode != -1) {
925         HILOG_INFO("%{public}s: origin window mode is %{public}d.", __func__, mode);
926         info->mode_ = static_cast<uint32_t>(mode);
927     }
928     if (displayId != -1) {
929         info->displayId_ = static_cast<uint64_t>(displayId);
930     }
931 }
932 
CreateAbilityTransitionInfo(const std::shared_ptr<StartOptions> & startOptions,const std::shared_ptr<Want> & want) const933 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo(
934     const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want) const
935 {
936     sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
937     if (startOptions != nullptr) {
938         info->mode_ = static_cast<uint32_t>(startOptions->GetWindowMode());
939         HILOG_INFO("window mode:%{public}d.", info->mode_);
940         info->displayId_ = static_cast<uint64_t>(startOptions->GetDisplayID());
941     } else {
942         SetWindowModeAndDisplayId(info, want);
943     }
944     return info;
945 }
946 
CreateAbilityTransitionInfo(const AbilityRequest & abilityRequest) const947 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo(const AbilityRequest &abilityRequest) const
948 {
949     sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
950     auto abilityStartSetting = abilityRequest.startSetting;
951     if (abilityStartSetting) {
952         auto windowMode = abilityStartSetting->GetProperty(AbilityStartSetting::WINDOW_MODE_KEY);
953         auto displayId = abilityStartSetting->GetProperty(AbilityStartSetting::WINDOW_DISPLAY_ID_KEY);
954         try {
955             info->mode_ = static_cast<uint32_t>(std::stoi(windowMode));
956             info->displayId_ = static_cast<uint64_t>(std::stoi(displayId));
957         } catch (...) {
958             HILOG_WARN("windowMode: stoi(%{public}s) failed", windowMode.c_str());
959             HILOG_WARN("displayId: stoi(%{public}s) failed", displayId.c_str());
960         }
961     } else {
962         SetWindowModeAndDisplayId(info, std::make_shared<Want>(abilityRequest.want));
963     }
964     return info;
965 }
966 
CreateResourceManager() const967 std::shared_ptr<Global::Resource::ResourceManager> AbilityRecord::CreateResourceManager() const
968 {
969     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
970     UErrorCode status = U_ZERO_ERROR;
971     icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status);
972     std::unique_ptr<Global::Resource::ResConfig> resConfig(Global::Resource::CreateResConfig());
973     resConfig->SetLocaleInfo(locale);
974     AppExecFwk::Configuration cfg;
975     if (DelayedSingleton<AbilityManagerService>::GetInstance()->GetConfiguration(cfg) == 0) {
976         std::string colormode = cfg.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE);
977         HILOG_DEBUG("getcolormode is %{public}s.", colormode.c_str());
978         resConfig->SetColorMode(AppExecFwk::ConvertColorMode(colormode));
979     } else {
980         HILOG_WARN("getcolormode failed.");
981     }
982 
983     std::shared_ptr<Global::Resource::ResourceManager> resourceMgr(Global::Resource::CreateResourceManager());
984     resourceMgr->UpdateResConfig(*resConfig);
985 
986     std::string loadPath;
987     if (!abilityInfo_.hapPath.empty()) {
988         loadPath = abilityInfo_.hapPath;
989     } else {
990         loadPath = abilityInfo_.resourcePath;
991     }
992 
993     if (loadPath.empty()) {
994         HILOG_WARN("Invalid app resource.");
995         return nullptr;
996     }
997 
998     if (!resourceMgr->AddResource(loadPath.c_str())) {
999         HILOG_WARN("%{public}s AddResource failed.", __func__);
1000         return nullptr;
1001     }
1002     return resourceMgr;
1003 }
1004 
GetPixelMap(const uint32_t windowIconId,std::shared_ptr<Global::Resource::ResourceManager> resourceMgr) const1005 std::shared_ptr<Media::PixelMap> AbilityRecord::GetPixelMap(const uint32_t windowIconId,
1006     std::shared_ptr<Global::Resource::ResourceManager> resourceMgr) const
1007 {
1008     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1009     if (resourceMgr == nullptr) {
1010         HILOG_WARN("%{public}s resource manager does not exist.", __func__);
1011         return nullptr;
1012     }
1013 
1014     Media::SourceOptions opts;
1015     uint32_t errorCode = 0;
1016     std::unique_ptr<Media::ImageSource> imageSource;
1017     if (!abilityInfo_.hapPath.empty()) { // hap is not unzip
1018         std::unique_ptr<uint8_t[]> iconOut;
1019         size_t len;
1020         if (resourceMgr->GetMediaDataById(windowIconId, len, iconOut) != Global::Resource::RState::SUCCESS) {
1021             return nullptr;
1022         }
1023         imageSource = Media::ImageSource::CreateImageSource(iconOut.get(), len, opts, errorCode);
1024     } else { // already unzip hap
1025         std::string iconPath;
1026         if (resourceMgr->GetMediaById(windowIconId, iconPath) != Global::Resource::RState::SUCCESS) {
1027             return nullptr;
1028         }
1029         imageSource = Media::ImageSource::CreateImageSource(iconPath, opts, errorCode);
1030     }
1031 
1032     if (errorCode != 0 || imageSource == nullptr) {
1033         HILOG_ERROR("Failed to create icon id %{private}d err %{public}d", windowIconId, errorCode);
1034         return nullptr;
1035     }
1036 
1037     Media::DecodeOptions decodeOpts;
1038     auto pixelMapPtr = imageSource->CreatePixelMap(decodeOpts, errorCode);
1039     if (errorCode != 0) {
1040         HILOG_ERROR("Failed to create PixelMap id %{private}d err %{public}d", windowIconId, errorCode);
1041         return nullptr;
1042     }
1043     HILOG_DEBUG("OUT.");
1044     return std::shared_ptr<Media::PixelMap>(pixelMapPtr.release());
1045 }
1046 
CreateAbilityTransitionInfo(const std::shared_ptr<StartOptions> & startOptions,const std::shared_ptr<Want> & want,const AbilityRequest & abilityRequest)1047 sptr<AbilityTransitionInfo> AbilityRecord::CreateAbilityTransitionInfo(
1048     const std::shared_ptr<StartOptions> &startOptions, const std::shared_ptr<Want> &want,
1049     const AbilityRequest &abilityRequest)
1050 {
1051     sptr<AbilityTransitionInfo> info;
1052     if (startOptions) {
1053         info = CreateAbilityTransitionInfo(startOptions, want);
1054     } else {
1055         info = CreateAbilityTransitionInfo(abilityRequest);
1056     }
1057 
1058     SetAbilityTransitionInfo(info);
1059     SetStartingWindow(true);
1060     return info;
1061 }
1062 
StartingWindowHot(const std::shared_ptr<StartOptions> & startOptions,const std::shared_ptr<Want> & want,const AbilityRequest & abilityRequest)1063 void AbilityRecord::StartingWindowHot(const std::shared_ptr<StartOptions> &startOptions,
1064     const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest)
1065 {
1066     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1067     HILOG_DEBUG("call");
1068     auto windowHandler = GetWMSHandler();
1069     if (!windowHandler) {
1070         HILOG_WARN("Get WMS handler failed.");
1071         return;
1072     }
1073 
1074     auto pixelMap = DelayedSingleton<MissionInfoMgr>::GetInstance()->GetSnapshot(missionId_);
1075     if (!pixelMap) {
1076         HILOG_WARN("%{public}s, Get snapshot failed.", __func__);
1077     }
1078 
1079     auto info = CreateAbilityTransitionInfo(startOptions, want, abilityRequest);
1080     windowHandler->StartingWindow(info, pixelMap);
1081 }
1082 
StartingWindowCold(const std::shared_ptr<StartOptions> & startOptions,const std::shared_ptr<Want> & want,const AbilityRequest & abilityRequest)1083 void AbilityRecord::StartingWindowCold(const std::shared_ptr<StartOptions> &startOptions,
1084     const std::shared_ptr<Want> &want, const AbilityRequest &abilityRequest)
1085 {
1086     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1087     HILOG_DEBUG("call");
1088     auto windowHandler = GetWMSHandler();
1089     if (!windowHandler) {
1090         HILOG_WARN("%{public}s, Get WMS handler failed.", __func__);
1091         return;
1092     }
1093 
1094     // get bg pixelmap and color.
1095     std::shared_ptr<Media::PixelMap> pixelMap = nullptr;
1096     uint32_t bgColor = 0;
1097     GetColdStartingWindowResource(pixelMap, bgColor);
1098 
1099     // start window
1100     auto info = CreateAbilityTransitionInfo(startOptions, want, abilityRequest);
1101     windowHandler->StartingWindow(info, pixelMap, bgColor);
1102     startingWindowBg_.reset();
1103 }
1104 
GetColdStartingWindowResource(std::shared_ptr<Media::PixelMap> & bg,uint32_t & bgColor)1105 void AbilityRecord::GetColdStartingWindowResource(std::shared_ptr<Media::PixelMap> &bg, uint32_t &bgColor)
1106 {
1107     bg = startingWindowBg_;
1108     bgColor = bgColor_;
1109     if (bg) {
1110         return;
1111     }
1112     auto resourceMgr = CreateResourceManager();
1113     if (!resourceMgr) {
1114         HILOG_WARN("Get resourceMgr failed.");
1115         return;
1116     }
1117 
1118     auto windowIconId = static_cast<uint32_t>(abilityInfo_.startWindowIconId);
1119     bg = GetPixelMap(windowIconId, resourceMgr);
1120 
1121     auto colorId = static_cast<uint32_t>(abilityInfo_.startWindowBackgroundId);
1122     auto colorErrval = resourceMgr->GetColorById(colorId, bgColor);
1123     if (colorErrval != OHOS::Global::Resource::RState::SUCCESS) {
1124         HILOG_WARN("Failed to GetColorById.");
1125         bgColor = 0xdfffffff;
1126     }
1127     HILOG_DEBUG("colorId is %{public}u, bgColor is %{public}u.", colorId, bgColor);
1128 }
1129 
InitColdStartingWindowResource(const std::shared_ptr<Global::Resource::ResourceManager> & resourceMgr)1130 void AbilityRecord::InitColdStartingWindowResource(
1131     const std::shared_ptr<Global::Resource::ResourceManager> &resourceMgr)
1132 {
1133     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1134     if (!resourceMgr) {
1135         HILOG_ERROR("invalid resourceManager.");
1136         return;
1137     }
1138 
1139     startingWindowBg_ = GetPixelMap(static_cast<uint32_t>(abilityInfo_.startWindowIconId), resourceMgr);
1140     if (resourceMgr->GetColorById(static_cast<uint32_t>(abilityInfo_.startWindowBackgroundId), bgColor_) !=
1141         OHOS::Global::Resource::RState::SUCCESS) {
1142         HILOG_WARN("Failed to GetColorById.");
1143         bgColor_ = 0xdfffffff;
1144     }
1145 
1146     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
1147     if (startingWindowBg_ && handler) {
1148         auto delayTask = [me = weak_from_this()] {
1149             auto self = me.lock();
1150             if (!self || !self->startingWindowBg_) {
1151                 return;
1152             }
1153             self->startingWindowBg_.reset();
1154         };
1155         handler->SubmitTask(delayTask, "release_bg", RELEASE_STARTING_BG_TIMEOUT);
1156     }
1157 }
1158 
SetCompleteFirstFrameDrawing(const bool flag)1159 void AbilityRecord::SetCompleteFirstFrameDrawing(const bool flag)
1160 {
1161     isCompleteFirstFrameDrawing_ = flag;
1162 }
1163 
IsCompleteFirstFrameDrawing() const1164 bool AbilityRecord::IsCompleteFirstFrameDrawing() const
1165 {
1166     return isCompleteFirstFrameDrawing_;
1167 }
1168 #endif
1169 
BackgroundAbility(const Closure & task)1170 void AbilityRecord::BackgroundAbility(const Closure &task)
1171 {
1172     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1173     HILOG_INFO("BackgroundLifecycle: ability: %{public}s.", GetURI().c_str());
1174     if (lifecycleDeal_ == nullptr) {
1175         HILOG_ERROR("Move the ability to background fail, lifecycleDeal_ is null.");
1176         return;
1177     }
1178 
1179     if (!IsDebug()) {
1180         auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
1181         if (handler && task) {
1182             int backgroundTimeout =
1183                 AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * BACKGROUND_TIMEOUT_MULTIPLE;
1184             handler->SubmitTask(task, "background_" + std::to_string(recordId_), backgroundTimeout, false);
1185 
1186             if (abilityInfo_.type == AppExecFwk::AbilityType::PAGE) {
1187                 std::string methodName = "BackgroundAbility";
1188                 g_addLifecycleEventTask(token_, FreezeUtil::TimeoutState::BACKGROUND, methodName);
1189             }
1190         }
1191     } else {
1192         HILOG_INFO("Is debug mode, no need to handle time out.");
1193     }
1194 
1195     if (!IsTerminating() || IsRestarting()) {
1196         // schedule save ability state before moving to background.
1197         SaveAbilityState();
1198     }
1199 
1200     // schedule background after updating AbilityState and sending timeout message to avoid ability async callback
1201     // earlier than above actions.
1202     SetAbilityStateInner(AbilityState::BACKGROUNDING);
1203     lifecycleDeal_->BackgroundNew(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
1204 }
1205 
PrepareTerminateAbility()1206 bool AbilityRecord::PrepareTerminateAbility()
1207 {
1208     HILOG_DEBUG("call");
1209     if (lifecycleDeal_ == nullptr) {
1210         HILOG_ERROR("lifecycleDeal_ is nullptr.");
1211         return false;
1212     }
1213     return lifecycleDeal_->PrepareTerminateAbility();
1214 }
1215 
TerminateAbility()1216 int AbilityRecord::TerminateAbility()
1217 {
1218     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1219     HILOG_INFO("ability:%{public}s.", abilityInfo_.name.c_str());
1220     HandleDlpClosed();
1221     AAFwk::EventInfo eventInfo;
1222     eventInfo.bundleName = GetAbilityInfo().bundleName;
1223     eventInfo.abilityName = GetAbilityInfo().name;
1224     AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::TERMINATE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1225     eventInfo.errCode = DelayedSingleton<AppScheduler>::GetInstance()->TerminateAbility(token_, clearMissionFlag_);
1226     if (eventInfo.errCode != ERR_OK) {
1227         AAFwk::EventReport::SendAbilityEvent(
1228             AAFwk::EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1229     }
1230     return eventInfo.errCode;
1231 }
1232 
GetAbilityInfo() const1233 const AppExecFwk::AbilityInfo &AbilityRecord::GetAbilityInfo() const
1234 {
1235     return abilityInfo_;
1236 }
1237 
GetApplicationInfo() const1238 const AppExecFwk::ApplicationInfo &AbilityRecord::GetApplicationInfo() const
1239 {
1240     return applicationInfo_;
1241 }
1242 
GetAbilityState() const1243 AbilityState AbilityRecord::GetAbilityState() const
1244 {
1245     return currentState_;
1246 }
1247 
IsForeground() const1248 bool AbilityRecord::IsForeground() const
1249 {
1250     return currentState_ == AbilityState::FOREGROUND || currentState_ == AbilityState::FOREGROUNDING;
1251 }
1252 
SetAbilityStateInner(AbilityState state)1253 void AbilityRecord::SetAbilityStateInner(AbilityState state)
1254 {
1255     currentState_ = state;
1256     if (currentState_ == AbilityState::BACKGROUND) {
1257         isAbilityForegrounding_ = false;
1258     }
1259 
1260     auto collaborator = DelayedSingleton<AbilityManagerService>::GetInstance()->GetCollaborator(
1261         collaboratorType_);
1262     if (collaborator != nullptr) {
1263         HILOG_INFO("start notify collaborator, missionId:%{public}d, state:%{public}d", missionId_,
1264             static_cast<int32_t>(state));
1265         int ret = ERR_OK;
1266         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1267             auto sessionInfo = GetSessionInfo();
1268             if (sessionInfo == nullptr) {
1269                 HILOG_ERROR("sessionInfo is nullptr");
1270                 return;
1271             }
1272             int32_t persistentId = sessionInfo->persistentId;
1273             switch (state) {
1274                 case AbilityState::BACKGROUNDING: {
1275                     ret = collaborator->NotifyMoveMissionToBackground(persistentId);
1276                     break;
1277                 }
1278                 case AbilityState::TERMINATING: {
1279                     ret = collaborator->NotifyTerminateMission(persistentId);
1280                     break;
1281                 }
1282                 default:
1283                     break;
1284             }
1285             if (ret != ERR_OK) {
1286                 HILOG_ERROR("notify broker move mission to background failed, err: %{public}d", ret);
1287             }
1288             return;
1289         }
1290         switch (state) {
1291             case AbilityState::FOREGROUNDING: {
1292                 ret = collaborator->NotifyMoveMissionToForeground(missionId_);
1293                 break;
1294             }
1295             case AbilityState::BACKGROUNDING: {
1296                 ret = collaborator->NotifyMoveMissionToBackground(missionId_);
1297                 break;
1298             }
1299             case AbilityState::TERMINATING: {
1300                 ret = collaborator->NotifyTerminateMission(missionId_);
1301                 break;
1302             }
1303             default:
1304                 break;
1305         }
1306         if (ret != ERR_OK) {
1307             HILOG_ERROR("notify broker move mission to background failed, err: %{public}d", ret);
1308         }
1309     }
1310 
1311     DelayedSingleton<MissionInfoMgr>::GetInstance()->SetMissionAbilityState(missionId_, currentState_);
1312 }
1313 
GetAbilityForegroundingFlag() const1314 bool AbilityRecord::GetAbilityForegroundingFlag() const
1315 {
1316     return isAbilityForegrounding_;
1317 }
1318 
SetAbilityForegroundingFlag()1319 void AbilityRecord::SetAbilityForegroundingFlag()
1320 {
1321     isAbilityForegrounding_ = true;
1322     DelayedSingleton<AppScheduler>::GetInstance()->SetAbilityForegroundingFlagToAppRecord(pid_);
1323 }
1324 
SetAbilityState(AbilityState state)1325 void AbilityRecord::SetAbilityState(AbilityState state)
1326 {
1327     SetAbilityStateInner(state);
1328     if (state == AbilityState::FOREGROUND || state == AbilityState::ACTIVE || state == AbilityState::BACKGROUND) {
1329         SetRestarting(false);
1330     }
1331 }
1332 
SetScheduler(const sptr<IAbilityScheduler> & scheduler)1333 void AbilityRecord::SetScheduler(const sptr<IAbilityScheduler> &scheduler)
1334 {
1335     HILOG_DEBUG("bundle:%{public}s, ability: %{public}s", applicationInfo_.bundleName.c_str(),
1336         abilityInfo_.name.c_str());
1337     CHECK_POINTER(lifecycleDeal_);
1338     if (scheduler != nullptr) {
1339         if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
1340             auto schedulerObject = scheduler_->AsObject();
1341             if (schedulerObject != nullptr) {
1342                 schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
1343             }
1344         }
1345         if (schedulerDeathRecipient_ == nullptr) {
1346             std::weak_ptr<AbilityRecord> thisWeakPtr(shared_from_this());
1347             schedulerDeathRecipient_ =
1348                 new AbilitySchedulerRecipient([thisWeakPtr](const wptr<IRemoteObject> &remote) {
1349                     auto abilityRecord = thisWeakPtr.lock();
1350                     if (abilityRecord) {
1351                         abilityRecord->OnSchedulerDied(remote);
1352                     }
1353                 });
1354         }
1355         RemoveAppStateObserver();
1356         isReady_ = true;
1357         scheduler_ = scheduler;
1358         lifecycleDeal_->SetScheduler(scheduler);
1359         auto schedulerObject = scheduler_->AsObject();
1360         if (schedulerObject == nullptr || !schedulerObject->AddDeathRecipient(schedulerDeathRecipient_)) {
1361             HILOG_ERROR("AddDeathRecipient failed.");
1362         }
1363         if (IsSceneBoard()) {
1364             HILOG_INFO("Sceneboard DeathRecipient Added");
1365         }
1366         pid_ = static_cast<int32_t>(IPCSkeleton::GetCallingPid()); // set pid when ability attach to service.
1367         HandleDlpAttached();
1368     } else {
1369         HILOG_ERROR("scheduler is nullptr");
1370         isReady_ = false;
1371         isWindowAttached_ = false;
1372         SetIsNewWant(false);
1373         if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
1374             auto schedulerObject = scheduler_->AsObject();
1375             if (schedulerObject != nullptr) {
1376                 HILOG_INFO("RemoveDeathRecipient");
1377                 schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
1378             }
1379         }
1380         scheduler_ = scheduler;
1381         pid_ = 0;
1382     }
1383 }
1384 
GetToken() const1385 sptr<Token> AbilityRecord::GetToken() const
1386 {
1387     return token_;
1388 }
1389 
SetPreAbilityRecord(const std::shared_ptr<AbilityRecord> & abilityRecord)1390 void AbilityRecord::SetPreAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)
1391 {
1392     preAbilityRecord_ = abilityRecord;
1393 }
1394 
GetPreAbilityRecord() const1395 std::shared_ptr<AbilityRecord> AbilityRecord::GetPreAbilityRecord() const
1396 {
1397     return preAbilityRecord_.lock();
1398 }
1399 
SetNextAbilityRecord(const std::shared_ptr<AbilityRecord> & abilityRecord)1400 void AbilityRecord::SetNextAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)
1401 {
1402     nextAbilityRecord_ = abilityRecord;
1403 }
1404 
GetNextAbilityRecord() const1405 std::shared_ptr<AbilityRecord> AbilityRecord::GetNextAbilityRecord() const
1406 {
1407     return nextAbilityRecord_.lock();
1408 }
1409 
IsReady() const1410 bool AbilityRecord::IsReady() const
1411 {
1412     return isReady_;
1413 }
1414 
1415 #ifdef SUPPORT_GRAPHICS
IsWindowAttached() const1416 bool AbilityRecord::IsWindowAttached() const
1417 {
1418     return isWindowAttached_;
1419 }
1420 #endif
1421 
IsLauncherAbility() const1422 bool AbilityRecord::IsLauncherAbility() const
1423 {
1424     return isLauncherAbility_;
1425 }
1426 
IsTerminating() const1427 bool AbilityRecord::IsTerminating() const
1428 {
1429     return isTerminating_;
1430 }
1431 
SetTerminatingState()1432 void AbilityRecord::SetTerminatingState()
1433 {
1434     isTerminating_ = true;
1435 }
1436 
IsNewWant() const1437 bool AbilityRecord::IsNewWant() const
1438 {
1439     return lifeCycleStateInfo_.isNewWant;
1440 }
1441 
SetIsNewWant(bool isNewWant)1442 void AbilityRecord::SetIsNewWant(bool isNewWant)
1443 {
1444     lifeCycleStateInfo_.isNewWant = isNewWant;
1445 }
1446 
IsCreateByConnect() const1447 bool AbilityRecord::IsCreateByConnect() const
1448 {
1449     return isCreateByConnect_;
1450 }
1451 
SetCreateByConnectMode(bool isCreatedByConnect)1452 void AbilityRecord::SetCreateByConnectMode(bool isCreatedByConnect)
1453 {
1454     isCreateByConnect_ = isCreatedByConnect;
1455 }
1456 
Activate()1457 void AbilityRecord::Activate()
1458 {
1459     HILOG_INFO("Activate.");
1460     CHECK_POINTER(lifecycleDeal_);
1461 
1462     if (!IsDebug()) {
1463         int activeTimeout = AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * ACTIVE_TIMEOUT_MULTIPLE;
1464         SendEvent(AbilityManagerService::ACTIVE_TIMEOUT_MSG, activeTimeout);
1465     }
1466 
1467     // schedule active after updating AbilityState and sending timeout message to avoid ability async callback
1468     // earlier than above actions.
1469     SetAbilityStateInner(AbilityState::ACTIVATING);
1470     lifecycleDeal_->Activate(GetWant(), lifeCycleStateInfo_);
1471 
1472     // update ability state to appMgr service when restart
1473     if (IsNewWant()) {
1474         sptr<Token> preToken = nullptr;
1475         if (GetPreAbilityRecord()) {
1476             preToken = GetPreAbilityRecord()->GetToken();
1477         }
1478         DelayedSingleton<AppScheduler>::GetInstance()->AbilityBehaviorAnalysis(token_, preToken, 1, 1, 1);
1479     }
1480 }
1481 
Inactivate()1482 void AbilityRecord::Inactivate()
1483 {
1484     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1485     HILOG_DEBUG("ability:%{public}s.", abilityInfo_.name.c_str());
1486     CHECK_POINTER(lifecycleDeal_);
1487 
1488     if (!IsDebug()) {
1489         int inactiveTimeout =
1490             AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * INACTIVE_TIMEOUT_MULTIPLE;
1491         SendEvent(AbilityManagerService::INACTIVE_TIMEOUT_MSG, inactiveTimeout);
1492     }
1493 
1494     // schedule inactive after updating AbilityState and sending timeout message to avoid ability async callback
1495     // earlier than above actions.
1496     SetAbilityStateInner(AbilityState::INACTIVATING);
1497     lifecycleDeal_->Inactivate(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
1498 }
1499 
Terminate(const Closure & task)1500 void AbilityRecord::Terminate(const Closure &task)
1501 {
1502     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1503     HILOG_DEBUG("ability: %{public}s.", GetURI().c_str());
1504     CHECK_POINTER(lifecycleDeal_);
1505     if (!IsDebug()) {
1506         auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
1507         if (handler && task) {
1508             if (applicationInfo_.asanEnabled) {
1509                 int terminateTimeout =
1510                     AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * TERMINATE_TIMEOUT_ASANENABLED;
1511                 handler->SubmitTask(task, "terminate_" + std::to_string(recordId_), terminateTimeout);
1512             } else {
1513                 int terminateTimeout =
1514                     AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * TERMINATE_TIMEOUT_MULTIPLE;
1515                 handler->SubmitTask(task, "terminate_" + std::to_string(recordId_), terminateTimeout);
1516             }
1517         }
1518     } else {
1519         HILOG_INFO("Is debug mode, no need to handle time out.");
1520     }
1521     // schedule background after updating AbilityState and sending timeout message to avoid ability async callback
1522     // earlier than above actions.
1523     SetAbilityStateInner(AbilityState::TERMINATING);
1524     lifecycleDeal_->Terminate(GetWant(), lifeCycleStateInfo_, GetSessionInfo());
1525 }
1526 
ShareData(const int32_t & uniqueId)1527 void AbilityRecord::ShareData(const int32_t &uniqueId)
1528 {
1529     HILOG_INFO("ability:%{public}s.", abilityInfo_.name.c_str());
1530     CHECK_POINTER(lifecycleDeal_);
1531     if (!IsDebug()) {
1532         int loadTimeout =
1533             AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * SHAREDATA_TIMEOUT_MULTIPLE;
1534         HILOG_DEBUG("loadTimeOut %{public}d.", loadTimeout);
1535         SendEvent(AbilityManagerService::SHAREDATA_TIMEOUT_MSG, loadTimeout, uniqueId);
1536     }
1537     lifecycleDeal_->ShareData(uniqueId);
1538 }
1539 
ConnectAbility()1540 void AbilityRecord::ConnectAbility()
1541 {
1542     HILOG_DEBUG("Connect ability.");
1543     CHECK_POINTER(lifecycleDeal_);
1544     if (isConnected) {
1545         HILOG_WARN("connect state error.");
1546     }
1547     lifecycleDeal_->ConnectAbility(GetWant());
1548     isConnected = true;
1549 }
1550 
DisconnectAbility()1551 void AbilityRecord::DisconnectAbility()
1552 {
1553     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1554     HILOG_DEBUG("ability:%{public}s.", abilityInfo_.name.c_str());
1555     CHECK_POINTER(lifecycleDeal_);
1556     lifecycleDeal_->DisconnectAbility(GetWant());
1557     isConnected = false;
1558 }
1559 
CommandAbility()1560 void AbilityRecord::CommandAbility()
1561 {
1562     HILOG_DEBUG("startId_:%{public}d.", startId_);
1563     CHECK_POINTER(lifecycleDeal_);
1564     lifecycleDeal_->CommandAbility(GetWant(), false, startId_);
1565 }
1566 
CommandAbilityWindow(const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd)1567 void AbilityRecord::CommandAbilityWindow(const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd)
1568 {
1569     CHECK_POINTER(lifecycleDeal_);
1570     lifecycleDeal_->CommandAbilityWindow(GetWant(), sessionInfo, winCmd);
1571 }
1572 
SaveAbilityState()1573 void AbilityRecord::SaveAbilityState()
1574 {
1575     HILOG_DEBUG("call");
1576     CHECK_POINTER(lifecycleDeal_);
1577     lifecycleDeal_->SaveAbilityState();
1578 }
1579 
SaveAbilityState(const PacMap & inState)1580 void AbilityRecord::SaveAbilityState(const PacMap &inState)
1581 {
1582     HILOG_INFO("call");
1583     stateDatas_ = inState;
1584 }
1585 
RestoreAbilityState()1586 void AbilityRecord::RestoreAbilityState()
1587 {
1588     HILOG_INFO("call");
1589     CHECK_POINTER(lifecycleDeal_);
1590     lifecycleDeal_->RestoreAbilityState(stateDatas_);
1591     stateDatas_.Clear();
1592     isRestarting_ = false;
1593 }
1594 
GetRequestCode() const1595 int AbilityRecord::GetRequestCode() const
1596 {
1597     return requestCode_;
1598 }
1599 
SetResult(const std::shared_ptr<AbilityResult> & result)1600 void AbilityRecord::SetResult(const std::shared_ptr<AbilityResult> &result)
1601 {
1602     result_ = result;
1603 }
1604 
GetResult() const1605 std::shared_ptr<AbilityResult> AbilityRecord::GetResult() const
1606 {
1607     return result_;
1608 }
1609 
SendResult(bool isSandboxApp,uint32_t tokeId)1610 void AbilityRecord::SendResult(bool isSandboxApp, uint32_t tokeId)
1611 {
1612     HILOG_INFO("ability:%{public}s.", abilityInfo_.name.c_str());
1613     std::lock_guard<ffrt::mutex> guard(lock_);
1614     CHECK_POINTER(scheduler_);
1615     CHECK_POINTER(result_);
1616     GrantUriPermission(result_->resultWant_, applicationInfo_.bundleName, isSandboxApp, tokeId);
1617     scheduler_->SendResult(result_->requestCode_, result_->resultCode_, result_->resultWant_);
1618     // reset result to avoid send result next time
1619     result_.reset();
1620 }
1621 
SendSandboxSavefileResult(const Want & want,int resultCode,int requestCode)1622 void AbilityRecord::SendSandboxSavefileResult(const Want &want, int resultCode, int requestCode)
1623 {
1624     HILOG_INFO("ability:%{public}s.", abilityInfo_.name.c_str());
1625 
1626     auto uriParam = want.GetParams().GetParam(PARAMS_FILE_SAVING_URL_KEY);
1627     auto uriArray = AAFwk::IArray::Query(uriParam);
1628     long arraySize = 0;
1629     if (uriArray && uriArray->GetLength(arraySize) == ERR_OK &&
1630         arraySize > 0 && AAFwk::Array::IsStringArray(uriArray)) {
1631         for (long i = 0; i < arraySize; i++) {
1632             sptr<AAFwk::IInterface> iface = nullptr;
1633             if (uriArray->Get(i, iface) != ERR_OK) {
1634                 continue;
1635             }
1636             AAFwk::IString* iuri = AAFwk::IString::Query(iface);
1637             if (!iuri) {
1638                 continue;
1639             }
1640             std::string uriStr;
1641             if (iuri->GetString(uriStr) != ERR_OK) {
1642                 continue;
1643             }
1644             Uri uri(uriStr);
1645             uint32_t initiatorTokenId = IPCSkeleton::GetCallingTokenID();
1646             auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(uri,
1647                 Want::FLAG_AUTH_WRITE_URI_PERMISSION, abilityInfo_.bundleName, appIndex_, initiatorTokenId));
1648             if (ret != ERR_OK) {
1649                 HILOG_WARN("GrantUriPermission failed");
1650             }
1651         }
1652     } else {
1653         HILOG_WARN("Uri illigal for request: %{public}d.", requestCode);
1654     }
1655 
1656     auto scheduler = scheduler_;
1657     if (scheduler) {
1658         scheduler->SendResult(requestCode, resultCode, want);
1659     }
1660 }
1661 
SendResultToCallers(bool schedulerdied)1662 void AbilityRecord::SendResultToCallers(bool schedulerdied)
1663 {
1664     for (auto caller : GetCallerRecordList()) {
1665         if (caller == nullptr) {
1666             HILOG_WARN("Caller record is nullptr.");
1667             continue;
1668         }
1669         std::shared_ptr<AbilityRecord> callerAbilityRecord = caller->GetCaller();
1670         if (callerAbilityRecord != nullptr && callerAbilityRecord->GetResult() != nullptr) {
1671             bool isSandboxApp = appIndex_ > 0 ? true : false;
1672             callerAbilityRecord->SendResult(isSandboxApp, applicationInfo_.accessTokenId);
1673         } else {
1674             std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord = caller->GetSaCaller();
1675             if (callerSystemAbilityRecord != nullptr) {
1676                 HILOG_INFO("Send result to system ability.");
1677                 callerSystemAbilityRecord->SendResultToSystemAbility(caller->GetRequestCode(),
1678                     callerSystemAbilityRecord, abilityInfo_.applicationInfo.uid,
1679                     abilityInfo_.applicationInfo.accessTokenId, schedulerdied);
1680             }
1681         }
1682     }
1683 }
1684 
SaveResultToCallers(const int resultCode,const Want * resultWant)1685 void AbilityRecord::SaveResultToCallers(const int resultCode, const Want *resultWant)
1686 {
1687     auto callerRecordList = GetCallerRecordList();
1688     if (callerRecordList.empty()) {
1689         HILOG_WARN("callerRecordList is empty.");
1690         return;
1691     }
1692     auto latestCaller = callerRecordList.back();
1693     for (auto caller : callerRecordList) {
1694         if (caller == nullptr) {
1695             HILOG_WARN("Caller record is nullptr.");
1696             continue;
1697         }
1698         if (caller == latestCaller) {
1699             HILOG_INFO("Caller record is the latest.");
1700             SaveResult(resultCode, resultWant, caller);
1701             continue;
1702         }
1703         SaveResult(SEND_RESULT_CANCELED, resultWant, caller);
1704     }
1705 }
1706 
SaveResult(int resultCode,const Want * resultWant,std::shared_ptr<CallerRecord> caller)1707 void AbilityRecord::SaveResult(int resultCode, const Want *resultWant, std::shared_ptr<CallerRecord> caller)
1708 {
1709     std::lock_guard<ffrt::mutex> guard(lock_);
1710     std::shared_ptr<AbilityRecord> callerAbilityRecord = caller->GetCaller();
1711     if (callerAbilityRecord != nullptr) {
1712         callerAbilityRecord->SetResult(
1713             std::make_shared<AbilityResult>(caller->GetRequestCode(), resultCode, *resultWant));
1714     } else {
1715         std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord = caller->GetSaCaller();
1716         if (callerSystemAbilityRecord != nullptr) {
1717             HILOG_INFO("Caller is system ability.");
1718             Want* newWant = const_cast<Want*>(resultWant);
1719             callerSystemAbilityRecord->SetResultToSystemAbility(callerSystemAbilityRecord, *newWant,
1720                 resultCode);
1721         }
1722     }
1723 }
1724 
SetResultToSystemAbility(std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,Want & resultWant,int resultCode)1725 void SystemAbilityCallerRecord::SetResultToSystemAbility(
1726     std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,
1727     Want &resultWant, int resultCode)
1728 {
1729     std::vector<std::string> data;
1730     std::string srcAbilityId = callerSystemAbilityRecord->GetSrcAbilityId();
1731     SplitStr(srcAbilityId, "_", data);
1732     if (data.size() != VECTOR_SIZE) {
1733         HILOG_ERROR("Check data size failed");
1734         return;
1735     }
1736     std::string srcDeviceId = data[0];
1737     HILOG_DEBUG("Get srcDeviceId = %{public}s", srcDeviceId.c_str());
1738     int missionId = atoi(data[1].c_str());
1739     HILOG_INFO("Get missionId = %{public}d", missionId);
1740     resultWant.SetParam(DMS_SRC_NETWORK_ID, srcDeviceId);
1741     resultWant.SetParam(DMS_MISSION_ID, missionId);
1742     callerSystemAbilityRecord->SetResult(resultWant, resultCode);
1743 }
1744 
SendResultToSystemAbility(int requestCode,const std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,int32_t callerUid,uint32_t accessToken,bool schedulerdied)1745 void SystemAbilityCallerRecord::SendResultToSystemAbility(int requestCode,
1746     const std::shared_ptr<SystemAbilityCallerRecord> callerSystemAbilityRecord,
1747     int32_t callerUid, uint32_t accessToken, bool schedulerdied)
1748 {
1749     HILOG_INFO("call");
1750     if (callerSystemAbilityRecord == nullptr) {
1751         HILOG_ERROR("callerSystemAbilityRecord is nullptr");
1752         return;
1753     }
1754     int resultCode = callerSystemAbilityRecord->GetResultCode();
1755     Want resultWant = callerSystemAbilityRecord->GetResultWant();
1756     sptr<IRemoteObject> callerToken = callerSystemAbilityRecord->GetCallerToken();
1757     if (!schedulerdied) {
1758         callerUid = IPCSkeleton::GetCallingUid();
1759         accessToken = IPCSkeleton::GetCallingTokenID();
1760     }
1761     HILOG_INFO("Try to SendResult, callerUid = %{public}d, AccessTokenId = %{public}u",
1762         callerUid, accessToken);
1763     if (callerToken == nullptr) {
1764         HILOG_ERROR("CallerToken is nullptr");
1765         return;
1766     }
1767     MessageParcel data;
1768     if (!data.WriteInterfaceToken(SYSTEM_ABILITY_TOKEN_CALLBACK)) {
1769         HILOG_ERROR("SendResultToSystemAbility Write interface token failed.");
1770         return;
1771     }
1772     if (!data.WriteParcelable(&resultWant)) {
1773         HILOG_ERROR("fail to WriteParcelable");
1774         return;
1775     }
1776     data.WriteInt32(callerUid);
1777     data.WriteInt32(requestCode);
1778     data.WriteUint32(accessToken);
1779     data.WriteInt32(resultCode);
1780     MessageParcel reply;
1781     MessageOption option(MessageOption::TF_SYNC);
1782     int result = callerToken->SendRequest(ISystemAbilityTokenCallback::SEND_RESULT, data, reply, option);
1783     if (result != ERR_OK) {
1784         HILOG_ERROR("SendResultToSystemAbility error = %{public}d", result);
1785     }
1786 }
1787 
NeedConnectAfterCommand()1788 bool AbilityRecord::NeedConnectAfterCommand()
1789 {
1790     return !IsConnectListEmpty() && !isConnected;
1791 }
1792 
AddConnectRecordToList(const std::shared_ptr<ConnectionRecord> & connRecord)1793 void AbilityRecord::AddConnectRecordToList(const std::shared_ptr<ConnectionRecord> &connRecord)
1794 {
1795     CHECK_POINTER(connRecord);
1796     std::lock_guard guard(connRecordListMutex_);
1797     auto it = std::find(connRecordList_.begin(), connRecordList_.end(), connRecord);
1798     // found it
1799     if (it != connRecordList_.end()) {
1800         HILOG_DEBUG("Found it in list, so no need to add same connection");
1801         return;
1802     }
1803     // no found then add new connection to list
1804     HILOG_DEBUG("No found in list, so add new connection to list");
1805     connRecordList_.push_back(connRecord);
1806 }
1807 
GetConnectRecordList() const1808 std::list<std::shared_ptr<ConnectionRecord>> AbilityRecord::GetConnectRecordList() const
1809 {
1810     std::lock_guard guard(connRecordListMutex_);
1811     return connRecordList_;
1812 }
1813 
RemoveConnectRecordFromList(const std::shared_ptr<ConnectionRecord> & connRecord)1814 void AbilityRecord::RemoveConnectRecordFromList(const std::shared_ptr<ConnectionRecord> &connRecord)
1815 {
1816     CHECK_POINTER(connRecord);
1817     std::lock_guard guard(connRecordListMutex_);
1818     connRecordList_.remove(connRecord);
1819 }
1820 
AddCallerRecord(const sptr<IRemoteObject> & callerToken,int requestCode,std::string srcAbilityId,uint32_t callingTokenId)1821 void AbilityRecord::AddCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode, std::string srcAbilityId,
1822     uint32_t callingTokenId)
1823 {
1824     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1825     HILOG_DEBUG("Add caller record.");
1826     if (!srcAbilityId.empty() && IsSystemAbilityCall(callerToken, callingTokenId)) {
1827         AddSystemAbilityCallerRecord(callerToken, requestCode, srcAbilityId);
1828         return;
1829     }
1830     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1831     CHECK_POINTER(abilityRecord);
1832 
1833     auto isExist = [&abilityRecord](const std::shared_ptr<CallerRecord> &callerRecord) {
1834         return (callerRecord->GetCaller() == abilityRecord);
1835     };
1836 
1837     auto record = std::find_if(callerList_.begin(), callerList_.end(), isExist);
1838     if (record != callerList_.end()) {
1839         callerList_.erase(record);
1840     }
1841 
1842     callerList_.emplace_back(std::make_shared<CallerRecord>(requestCode, abilityRecord));
1843 
1844     lifeCycleStateInfo_.caller.requestCode = requestCode;
1845     lifeCycleStateInfo_.caller.deviceId = abilityRecord->GetAbilityInfo().deviceId;
1846     lifeCycleStateInfo_.caller.bundleName = abilityRecord->GetAbilityInfo().bundleName;
1847     lifeCycleStateInfo_.caller.abilityName = abilityRecord->GetAbilityInfo().name;
1848     HILOG_DEBUG("caller %{public}s, %{public}s",
1849         abilityRecord->GetAbilityInfo().bundleName.c_str(),
1850         abilityRecord->GetAbilityInfo().name.c_str());
1851 }
1852 
IsSystemAbilityCall(const sptr<IRemoteObject> & callerToken,uint32_t callingTokenId)1853 bool AbilityRecord::IsSystemAbilityCall(const sptr<IRemoteObject> &callerToken, uint32_t callingTokenId)
1854 {
1855     if (callerToken == nullptr) {
1856         return false;
1857     }
1858     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1859     if (abilityRecord != nullptr) {
1860         return false;
1861     }
1862     uint32_t tokenId = 0;
1863     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1864         tokenId = callingTokenId;
1865     } else {
1866         tokenId = IPCSkeleton::GetCallingTokenID();
1867     }
1868     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(tokenId);
1869     bool isNativeCall = tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE;
1870     if (!isNativeCall) {
1871         HILOG_INFO("Is not native call.");
1872         return false;
1873     }
1874     AccessToken::NativeTokenInfo nativeTokenInfo;
1875     int32_t result = AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
1876     if (result == ERR_OK && nativeTokenInfo.processName == DMS_PROCESS_NAME) {
1877         HILOG_INFO("Is system ability call.");
1878         return true;
1879     }
1880     return false;
1881 }
1882 
AddSystemAbilityCallerRecord(const sptr<IRemoteObject> & callerToken,int requestCode,std::string srcAbilityId)1883 void AbilityRecord::AddSystemAbilityCallerRecord(const sptr<IRemoteObject> &callerToken, int requestCode,
1884     std::string srcAbilityId)
1885 {
1886     HILOG_INFO("Add system ability caller record.");
1887     std::shared_ptr<SystemAbilityCallerRecord> systemAbilityRecord =
1888         std::make_shared<SystemAbilityCallerRecord>(srcAbilityId, callerToken);
1889     auto isExist = [&srcAbilityId](const std::shared_ptr<CallerRecord> &callerRecord) {
1890         std::shared_ptr<SystemAbilityCallerRecord> saCaller = callerRecord->GetSaCaller();
1891         return (saCaller != nullptr && saCaller->GetSrcAbilityId() == srcAbilityId);
1892     };
1893     auto record = std::find_if(callerList_.begin(), callerList_.end(), isExist);
1894     if (record != callerList_.end()) {
1895         HILOG_INFO("Find same system ability caller record.");
1896         callerList_.erase(record);
1897     }
1898     callerList_.emplace_back(std::make_shared<CallerRecord>(requestCode, systemAbilityRecord));
1899     HILOG_INFO("Add system ability record end.");
1900 }
1901 
GetCallerRecordList() const1902 std::list<std::shared_ptr<CallerRecord>> AbilityRecord::GetCallerRecordList() const
1903 {
1904     return callerList_;
1905 }
1906 
GetCallerRecord() const1907 std::shared_ptr<AbilityRecord> AbilityRecord::GetCallerRecord() const
1908 {
1909     if (callerList_.empty()) {
1910         return nullptr;
1911     }
1912     return callerList_.back()->GetCaller();
1913 }
1914 
IsConnectListEmpty()1915 bool AbilityRecord::IsConnectListEmpty()
1916 {
1917     std::lock_guard guard(connRecordListMutex_);
1918     return connRecordList_.empty();
1919 }
1920 
GetConnectingRecord() const1921 std::shared_ptr<ConnectionRecord> AbilityRecord::GetConnectingRecord() const
1922 {
1923     std::lock_guard guard(connRecordListMutex_);
1924     auto connect =
1925         std::find_if(connRecordList_.begin(), connRecordList_.end(), [](std::shared_ptr<ConnectionRecord> record) {
1926             return record->GetConnectState() == ConnectionState::CONNECTING;
1927         });
1928     return (connect != connRecordList_.end()) ? *connect : nullptr;
1929 }
1930 
GetConnectingRecordList()1931 std::list<std::shared_ptr<ConnectionRecord>> AbilityRecord::GetConnectingRecordList()
1932 {
1933     std::lock_guard guard(connRecordListMutex_);
1934     std::list<std::shared_ptr<ConnectionRecord>> connectingList;
1935     for (auto record : connRecordList_) {
1936         if (record && record->GetConnectState() == ConnectionState::CONNECTING) {
1937             connectingList.push_back(record);
1938         }
1939     }
1940     return connectingList;
1941 }
1942 
GetDisconnectingRecord() const1943 std::shared_ptr<ConnectionRecord> AbilityRecord::GetDisconnectingRecord() const
1944 {
1945     std::lock_guard guard(connRecordListMutex_);
1946     auto connect =
1947         std::find_if(connRecordList_.begin(), connRecordList_.end(), [](std::shared_ptr<ConnectionRecord> record) {
1948             return record->GetConnectState() == ConnectionState::DISCONNECTING;
1949         });
1950     return (connect != connRecordList_.end()) ? *connect : nullptr;
1951 }
1952 
GetAbilityTypeString(std::string & typeStr)1953 void AbilityRecord::GetAbilityTypeString(std::string &typeStr)
1954 {
1955     AppExecFwk::AbilityType type = GetAbilityInfo().type;
1956     switch (type) {
1957 #ifdef SUPPORT_GRAPHICS
1958         case AppExecFwk::AbilityType::PAGE: {
1959             typeStr = "PAGE";
1960             break;
1961         }
1962 #endif
1963         case AppExecFwk::AbilityType::SERVICE: {
1964             typeStr = UIExtensionUtils::IsUIExtension(GetAbilityInfo().extensionAbilityType) ?
1965                 "UIEXTENSION" : "SERVICE";
1966             break;
1967         }
1968         // for config.json type
1969         case AppExecFwk::AbilityType::DATA: {
1970             typeStr = "DATA";
1971             break;
1972         }
1973         default: {
1974             typeStr = "UNKNOWN";
1975             break;
1976         }
1977     }
1978 }
1979 
ConvertAbilityState(const AbilityState & state)1980 std::string AbilityRecord::ConvertAbilityState(const AbilityState &state)
1981 {
1982     auto it = stateToStrMap.find(state);
1983     if (it != stateToStrMap.end()) {
1984         return it->second;
1985     }
1986     return "INVALIDSTATE";
1987 }
1988 
ConvertAppState(const AppState & state)1989 std::string AbilityRecord::ConvertAppState(const AppState &state)
1990 {
1991     auto it = appStateToStrMap_.find(state);
1992     if (it != appStateToStrMap_.end()) {
1993         return it->second;
1994     }
1995     return "INVALIDSTATE";
1996 }
1997 
ConvertLifeCycleToAbilityState(const AbilityLifeCycleState & state)1998 int AbilityRecord::ConvertLifeCycleToAbilityState(const AbilityLifeCycleState &state)
1999 {
2000     auto it = convertStateMap.find(state);
2001     if (it != convertStateMap.end()) {
2002         return it->second;
2003     }
2004     return DEFAULT_INVAL_VALUE;
2005 }
2006 
Dump(std::vector<std::string> & info)2007 void AbilityRecord::Dump(std::vector<std::string> &info)
2008 {
2009     std::string dumpInfo = "      AbilityRecord ID #" + std::to_string(recordId_);
2010     info.push_back(dumpInfo);
2011     dumpInfo = "        app name [" + GetAbilityInfo().applicationName + "]";
2012     info.push_back(dumpInfo);
2013     dumpInfo = "        main name [" + GetAbilityInfo().name + "]";
2014     info.push_back(dumpInfo);
2015     dumpInfo = "        bundle name [" + GetAbilityInfo().bundleName + "]";
2016     info.push_back(dumpInfo);
2017     std::string isKeepAlive = isKeepAlive_ ? "true" : "false";
2018     dumpInfo = "        isKeepAlive: " + isKeepAlive;
2019     info.push_back(dumpInfo);
2020     // get ability type(unknown/page/service/provider)
2021     std::string typeStr;
2022     GetAbilityTypeString(typeStr);
2023     dumpInfo = "        ability type [" + typeStr + "]";
2024     info.push_back(dumpInfo);
2025     std::shared_ptr<AbilityRecord> preAbility = GetPreAbilityRecord();
2026     if (preAbility == nullptr) {
2027         dumpInfo = "        previous ability app name [NULL]";
2028         dumpInfo.append("\n");
2029         dumpInfo += "        previous ability file name [NULL]";
2030     } else {
2031         dumpInfo =
2032             "        previous ability app name [" + preAbility->GetAbilityInfo().applicationName + "]";
2033         dumpInfo.append("\n");
2034         dumpInfo += "        previous ability file name [" + preAbility->GetAbilityInfo().name + "]";
2035     }
2036     info.push_back(dumpInfo);
2037     std::shared_ptr<AbilityRecord> nextAbility = GetNextAbilityRecord();
2038     if (nextAbility == nullptr) {
2039         dumpInfo = "        next ability app name [NULL]";
2040         dumpInfo.append("\n");
2041         dumpInfo += "        next ability file name [NULL]";
2042     } else {
2043         dumpInfo =
2044             "        next ability app name [" + nextAbility->GetAbilityInfo().applicationName + "]";
2045         dumpInfo.append("\n");
2046         dumpInfo += "        next ability main name [" + nextAbility->GetAbilityInfo().name + "]";
2047     }
2048     info.push_back(dumpInfo);
2049     dumpInfo = "        state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + "  start time [" +
2050                std::to_string(startTime_) + "]";
2051     info.push_back(dumpInfo);
2052     dumpInfo = "        app state #" + AbilityRecord::ConvertAppState(appState_);
2053     info.push_back(dumpInfo);
2054     dumpInfo = "        ready #" + std::to_string(isReady_) + "  window attached #" +
2055                std::to_string(isWindowAttached_) + "  launcher #" + std::to_string(isLauncherAbility_);
2056     info.push_back(dumpInfo);
2057 
2058     if (isLauncherRoot_) {
2059         dumpInfo = "        can restart num #" + std::to_string(restartCount_);
2060         info.push_back(dumpInfo);
2061     }
2062 }
2063 
DumpAbilityState(std::vector<std::string> & info,bool isClient,const std::vector<std::string> & params)2064 void AbilityRecord::DumpAbilityState(
2065     std::vector<std::string> &info, bool isClient, const std::vector<std::string> &params)
2066 {
2067     HILOG_INFO("begin");
2068     std::string dumpInfo = "      AbilityRecord ID #" + std::to_string(recordId_);
2069     info.push_back(dumpInfo);
2070     dumpInfo = "        app name [" + GetAbilityInfo().applicationName + "]";
2071     info.push_back(dumpInfo);
2072     dumpInfo = "        main name [" + GetAbilityInfo().name + "]";
2073     info.push_back(dumpInfo);
2074     dumpInfo = "        bundle name [" + GetAbilityInfo().bundleName + "]";
2075     info.push_back(dumpInfo);
2076     std::string typeStr;
2077     GetAbilityTypeString(typeStr);
2078     dumpInfo = "        ability type [" + typeStr + "]";
2079     info.push_back(dumpInfo);
2080 
2081     dumpInfo = "        state #" + AbilityRecord::ConvertAbilityState(GetAbilityState()) + "  start time [" +
2082                std::to_string(startTime_) + "]";
2083     info.push_back(dumpInfo);
2084     dumpInfo = "        app state #" + AbilityRecord::ConvertAppState(appState_);
2085     info.push_back(dumpInfo);
2086     dumpInfo = "        ready #" + std::to_string(isReady_) + "  window attached #" +
2087                std::to_string(isWindowAttached_) + "  launcher #" + std::to_string(isLauncherAbility_);
2088     info.push_back(dumpInfo);
2089     dumpInfo = "        callee connections: ";
2090     info.push_back(dumpInfo);
2091     if (callContainer_) {
2092         callContainer_->Dump(info);
2093     }
2094 
2095     std::string isKeepAlive = isKeepAlive_ ? "true" : "false";
2096     dumpInfo = "        isKeepAlive: " + isKeepAlive;
2097     info.push_back(dumpInfo);
2098     if (isLauncherRoot_) {
2099         dumpInfo = "        can restart num #" + std::to_string(restartCount_);
2100         info.push_back(dumpInfo);
2101     }
2102 
2103     auto mission = GetMission();
2104     if (mission) {
2105         std::string missionAffinity = mission->GetMissionAffinity();
2106         dumpInfo = "        missionAffinity: " + missionAffinity;
2107         info.push_back(dumpInfo);
2108     }
2109 
2110     // add dump client info
2111     DumpClientInfo(info, params, isClient, params.empty());
2112 }
2113 
SetStartTime()2114 void AbilityRecord::SetStartTime()
2115 {
2116     if (startTime_ == 0) {
2117         startTime_ = AbilityUtil::SystemTimeMillis();
2118     }
2119 }
2120 
GetStartTime() const2121 int64_t AbilityRecord::GetStartTime() const
2122 {
2123     return startTime_;
2124 }
2125 
DumpService(std::vector<std::string> & info,bool isClient) const2126 void AbilityRecord::DumpService(std::vector<std::string> &info, bool isClient) const
2127 {
2128     std::vector<std::string> params;
2129     DumpService(info, params, isClient);
2130 }
2131 
DumpService(std::vector<std::string> & info,std::vector<std::string> & params,bool isClient) const2132 void AbilityRecord::DumpService(std::vector<std::string> &info, std::vector<std::string> &params, bool isClient) const
2133 {
2134     info.emplace_back("      AbilityRecord ID #" + std::to_string(GetRecordId()) + "   state #" +
2135                       AbilityRecord::ConvertAbilityState(GetAbilityState()) + "   start time [" +
2136                       std::to_string(GetStartTime()) + "]");
2137     info.emplace_back("      main name [" + GetAbilityInfo().name + "]");
2138     info.emplace_back("      bundle name [" + GetAbilityInfo().bundleName + "]");
2139     if (UIExtensionUtils::IsUIExtension(GetAbilityInfo().extensionAbilityType)) {
2140         info.emplace_back("      ability type [UIEXTENSION]");
2141     } else {
2142         info.emplace_back("      ability type [SERVICE]");
2143     }
2144     info.emplace_back("      app state #" + AbilityRecord::ConvertAppState(appState_));
2145 
2146     std::string isKeepAlive = isKeepAlive_ ? "true" : "false";
2147     info.emplace_back("        isKeepAlive: " + isKeepAlive);
2148     if (isLauncherRoot_) {
2149         info.emplace_back("      can restart num #" + std::to_string(restartCount_));
2150     }
2151     decltype(connRecordList_) connRecordListCpy;
2152     {
2153         std::lock_guard guard(connRecordListMutex_);
2154         connRecordListCpy = connRecordList_;
2155     }
2156 
2157     info.emplace_back("      Connections: " + std::to_string(connRecordListCpy.size()));
2158     for (auto &&conn : connRecordListCpy) {
2159         if (conn) {
2160             conn->Dump(info);
2161         }
2162     }
2163     // add dump client info
2164     DumpClientInfo(info, params, isClient);
2165 }
2166 
RemoveAbilityDeathRecipient() const2167 void AbilityRecord::RemoveAbilityDeathRecipient() const
2168 {
2169     if (scheduler_ == nullptr) {
2170         HILOG_WARN("scheduler_ is invalid.");
2171         return;
2172     }
2173 
2174     if (schedulerDeathRecipient_ == nullptr) {
2175         HILOG_WARN("schedulerDeathRecipient_ is invalid.");
2176         return;
2177     }
2178 
2179     auto schedulerObject = scheduler_->AsObject();
2180     if (schedulerObject != nullptr) {
2181         HILOG_DEBUG("RemoveDeathRecipient");
2182         schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
2183     }
2184 }
2185 
OnSchedulerDied(const wptr<IRemoteObject> & remote)2186 void AbilityRecord::OnSchedulerDied(const wptr<IRemoteObject> &remote)
2187 {
2188     HILOG_DEBUG("called.");
2189     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2190         auto mission = GetMission();
2191         if (mission) {
2192             HILOG_WARN("On scheduler died. Is app not response Reason:%{public}d", mission->IsANRState());
2193         }
2194     }
2195     std::lock_guard<ffrt::mutex> guard(lock_);
2196     CHECK_POINTER(scheduler_);
2197 
2198     auto object = remote.promote();
2199     CHECK_POINTER(object);
2200 
2201     if (object != scheduler_->AsObject()) {
2202         HILOG_ERROR("Ability on scheduler died: scheduler is not matches with remote.");
2203         return;
2204     }
2205 
2206     RevokeUriPermission();
2207     if (scheduler_ != nullptr && schedulerDeathRecipient_ != nullptr) {
2208         auto schedulerObject = scheduler_->AsObject();
2209         if (schedulerObject != nullptr) {
2210             schedulerObject->RemoveDeathRecipient(schedulerDeathRecipient_);
2211         }
2212     }
2213     CHECK_POINTER(lifecycleDeal_);
2214     lifecycleDeal_->SetScheduler(nullptr);
2215     isWindowAttached_ = false;
2216 
2217     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
2218     CHECK_POINTER(handler);
2219 
2220     HILOG_INFO("Ability on scheduler died: '%{public}s'", abilityInfo_.name.c_str());
2221     auto task = [ability = shared_from_this()]() {
2222         DelayedSingleton<AbilityManagerService>::GetInstance()->OnAbilityDied(ability);
2223     };
2224     handler->SubmitTask(task);
2225     auto uriTask = [want = GetWant(), ability = shared_from_this()]() {
2226         ability->SaveResultToCallers(-1, &want);
2227         ability->SendResultToCallers(true);
2228     };
2229     handler->SubmitTask(uriTask);
2230 #ifdef SUPPORT_GRAPHICS
2231     NotifyAnimationAbilityDied();
2232 #endif
2233     HandleDlpClosed();
2234     NotifyRemoveShellProcess(CollaboratorType::RESERVE_TYPE);
2235     NotifyRemoveShellProcess(CollaboratorType::OTHERS_TYPE);
2236     FreezeUtil::GetInstance().DeleteLifecycleEvent(object);
2237 }
2238 
OnProcessDied()2239 void AbilityRecord::OnProcessDied()
2240 {
2241     std::lock_guard<ffrt::mutex> guard(lock_);
2242     RemoveAppStateObserver();
2243     isWindowAttached_ = false;
2244 
2245     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
2246     CHECK_POINTER(handler);
2247 
2248     HILOG_DEBUG("Ability on scheduler died: '%{public}s'", abilityInfo_.name.c_str());
2249     auto task = [ability = shared_from_this()]() {
2250         DelayedSingleton<AbilityManagerService>::GetInstance()->OnAbilityDied(ability);
2251     };
2252     handler->SubmitTask(task);
2253     auto uriTask = [want = GetWant(), ability = shared_from_this()]() {
2254         ability->SaveResultToCallers(-1, &want);
2255         ability->SendResultToCallers(true);
2256     };
2257     handler->SubmitTask(uriTask);
2258 #ifdef SUPPORT_GRAPHICS
2259     NotifyAnimationAbilityDied();
2260 #endif
2261     HandleDlpClosed();
2262     NotifyRemoveShellProcess(CollaboratorType::RESERVE_TYPE);
2263     NotifyRemoveShellProcess(CollaboratorType::OTHERS_TYPE);
2264 }
2265 
NotifyAnimationAbilityDied()2266 void AbilityRecord::NotifyAnimationAbilityDied()
2267 {
2268     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2269         return;
2270     }
2271     // notify winddow manager service the ability died
2272     if (missionId_ != -1) {
2273         if (GetWMSHandler()) {
2274             sptr<AbilityTransitionInfo> info = new AbilityTransitionInfo();
2275             SetAbilityTransitionInfo(info);
2276             HILOG_INFO("Notification window manager UIAbiltiy abnormal death.");
2277             GetWMSHandler()->NotifyAnimationAbilityDied(info);
2278         }
2279     }
2280 }
2281 
SetConnRemoteObject(const sptr<IRemoteObject> & remoteObject)2282 void AbilityRecord::SetConnRemoteObject(const sptr<IRemoteObject> &remoteObject)
2283 {
2284     connRemoteObject_ = remoteObject;
2285 }
2286 
GetConnRemoteObject() const2287 sptr<IRemoteObject> AbilityRecord::GetConnRemoteObject() const
2288 {
2289     return connRemoteObject_;
2290 }
2291 
AddStartId()2292 void AbilityRecord::AddStartId()
2293 {
2294     startId_++;
2295 }
GetStartId() const2296 int AbilityRecord::GetStartId() const
2297 {
2298     return startId_;
2299 }
2300 
SetIsUninstallAbility()2301 void AbilityRecord::SetIsUninstallAbility()
2302 {
2303     isUninstall_ = true;
2304 }
2305 
IsUninstallAbility() const2306 bool AbilityRecord::IsUninstallAbility() const
2307 {
2308     return isUninstall_;
2309 }
2310 
SetLauncherRoot()2311 void AbilityRecord::SetLauncherRoot()
2312 {
2313     isLauncherRoot_ = true;
2314 }
2315 
IsLauncherRoot() const2316 bool AbilityRecord::IsLauncherRoot() const
2317 {
2318     return isLauncherRoot_;
2319 }
2320 
IsAbilityState(const AbilityState & state) const2321 bool AbilityRecord::IsAbilityState(const AbilityState &state) const
2322 {
2323     return (currentState_ == state);
2324 }
2325 
IsActiveState() const2326 bool AbilityRecord::IsActiveState() const
2327 {
2328     return (IsAbilityState(AbilityState::ACTIVE) || IsAbilityState(AbilityState::ACTIVATING) ||
2329             IsAbilityState(AbilityState::INITIAL) || IsAbilityState(AbilityState::FOREGROUND) ||
2330             IsAbilityState(AbilityState::FOREGROUNDING));
2331 }
2332 
SendEvent(uint32_t msg,uint32_t timeOut,int32_t param)2333 void AbilityRecord::SendEvent(uint32_t msg, uint32_t timeOut, int32_t param)
2334 {
2335     auto handler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetEventHandler();
2336     CHECK_POINTER(handler);
2337     param = (param == -1) ? recordId_ : param;
2338     auto eventWrap = EventWrap(msg, param);
2339     eventWrap.SetTimeout(timeOut);
2340     handler->SendEvent(eventWrap, timeOut);
2341 }
2342 
SetWant(const Want & want)2343 void AbilityRecord::SetWant(const Want &want)
2344 {
2345     std::lock_guard guard(wantLock_);
2346     auto debugApp = want_.GetBoolParam(DEBUG_APP, false);
2347     auto nativeDebug = want_.GetBoolParam(NATIVE_DEBUG, false);
2348     auto perfCmd = want_.GetStringParam(PERF_CMD);
2349 
2350     want_ = want;
2351     if (debugApp) {
2352         want_.SetParam(DEBUG_APP, true);
2353     }
2354     if (nativeDebug) {
2355         want_.SetParam(NATIVE_DEBUG, true);
2356     }
2357     if (!perfCmd.empty()) {
2358         want_.SetParam(PERF_CMD, perfCmd);
2359     }
2360 }
2361 
GetWant() const2362 Want AbilityRecord::GetWant() const
2363 {
2364     std::lock_guard guard(wantLock_);
2365     return want_;
2366 }
2367 
GetElementName() const2368 AppExecFwk::ElementName AbilityRecord::GetElementName() const
2369 {
2370     std::lock_guard guard(wantLock_);
2371     return want_.GetElement();
2372 }
2373 
IsDebugApp() const2374 bool AbilityRecord::IsDebugApp() const
2375 {
2376     std::lock_guard guard(wantLock_);
2377     return want_.GetBoolParam(DEBUG_APP, false);
2378 }
2379 
IsDebug() const2380 bool AbilityRecord::IsDebug() const
2381 {
2382     std::lock_guard guard(wantLock_);
2383     if (want_.GetBoolParam(DEBUG_APP, false) || want_.GetBoolParam(NATIVE_DEBUG, false) ||
2384         !want_.GetStringParam(PERF_CMD).empty() || isAttachDebug_) {
2385         HILOG_INFO("Is debug mode, no need to handle time out.");
2386         return true;
2387     }
2388     return false;
2389 }
2390 
SetWindowMode(int32_t windowMode)2391 void AbilityRecord::SetWindowMode(int32_t windowMode)
2392 {
2393     std::lock_guard guard(wantLock_);
2394     want_.SetParam(Want::PARAM_RESV_WINDOW_MODE, windowMode);
2395 }
2396 
RemoveWindowMode()2397 void AbilityRecord::RemoveWindowMode()
2398 {
2399     std::lock_guard guard(wantLock_);
2400     want_.RemoveParam(Want::PARAM_RESV_WINDOW_MODE);
2401 }
2402 
UpdateRecoveryInfo(bool hasRecoverInfo)2403 void AbilityRecord::UpdateRecoveryInfo(bool hasRecoverInfo)
2404 {
2405     if (hasRecoverInfo) {
2406         std::lock_guard guard(wantLock_);
2407         want_.SetParam(Want::PARAM_ABILITY_RECOVERY_RESTART, true);
2408         SetLaunchReason(LaunchReason::LAUNCHREASON_APP_RECOVERY);
2409     }
2410 }
2411 
GetRecoveryInfo()2412 bool AbilityRecord::GetRecoveryInfo()
2413 {
2414     std::lock_guard guard(wantLock_);
2415     return want_.GetBoolParam(Want::PARAM_ABILITY_RECOVERY_RESTART, false);
2416 }
2417 
SetStartSetting(const std::shared_ptr<AbilityStartSetting> & setting)2418 void AbilityRecord::SetStartSetting(const std::shared_ptr<AbilityStartSetting> &setting)
2419 {
2420     lifeCycleStateInfo_.setting = setting;
2421 }
2422 
GetStartSetting() const2423 std::shared_ptr<AbilityStartSetting> AbilityRecord::GetStartSetting() const
2424 {
2425     return lifeCycleStateInfo_.setting;
2426 }
2427 
SetRestarting(const bool isRestart)2428 void AbilityRecord::SetRestarting(const bool isRestart)
2429 {
2430     isRestarting_ = isRestart;
2431     HILOG_DEBUG("SetRestarting: %{public}d", isRestarting_);
2432     if ((isLauncherRoot_ && IsLauncherAbility()) || isKeepAlive_) {
2433         restartCount_ = isRestart ? (--restartCount_) : restartMax_;
2434         HILOG_DEBUG("root launcher or resident process's restart count: %{public}d", restartCount_);
2435     }
2436 }
2437 
SetRestarting(const bool isRestart,int32_t canRestartCount)2438 void AbilityRecord::SetRestarting(const bool isRestart, int32_t canRestartCount)
2439 {
2440     isRestarting_ = isRestart;
2441     HILOG_DEBUG("SetRestarting: %{public}d, restart count: %{public}d", isRestarting_, canRestartCount);
2442 
2443     if ((isLauncherRoot_ && IsLauncherAbility()) || isKeepAlive_) {
2444         restartCount_ = isRestart ? canRestartCount : restartMax_;
2445         HILOG_INFO("root launcher or resident process's restart count: %{public}d", restartCount_);
2446     }
2447 }
2448 
GetRestartCount() const2449 int32_t AbilityRecord::GetRestartCount() const
2450 {
2451     return restartCount_;
2452 }
2453 
SetRestartCount(int32_t restartCount)2454 void AbilityRecord::SetRestartCount(int32_t restartCount)
2455 {
2456     restartCount_ = restartCount;
2457 }
2458 
IsRestarting() const2459 bool AbilityRecord::IsRestarting() const
2460 {
2461     return isRestarting_;
2462 }
2463 
SetKeepAlive()2464 void AbilityRecord::SetKeepAlive()
2465 {
2466     isKeepAlive_ = true;
2467 }
2468 
GetKeepAlive() const2469 bool AbilityRecord::GetKeepAlive() const
2470 {
2471     return isKeepAlive_;
2472 }
2473 
SetLoading(bool status)2474 void AbilityRecord::SetLoading(bool status)
2475 {
2476     isLoading_ = status;
2477 }
2478 
IsLoading() const2479 bool AbilityRecord::IsLoading() const
2480 {
2481     return isLoading_;
2482 }
2483 
GetRestartTime()2484 int64_t AbilityRecord::GetRestartTime()
2485 {
2486     return restartTime_;
2487 }
2488 
SetRestartTime(const int64_t restartTime)2489 void AbilityRecord::SetRestartTime(const int64_t restartTime)
2490 {
2491     restartTime_ = restartTime;
2492 }
2493 
SetAppState(const AppState & state)2494 void AbilityRecord::SetAppState(const AppState &state)
2495 {
2496     appState_ = state;
2497 }
2498 
GetAppState() const2499 AppState AbilityRecord::GetAppState() const
2500 {
2501     return appState_;
2502 }
2503 
SetLaunchReason(const LaunchReason & reason)2504 void AbilityRecord::SetLaunchReason(const LaunchReason &reason)
2505 {
2506     if (isAppAutoStartup_) {
2507         lifeCycleStateInfo_.launchParam.launchReason = LaunchReason::LAUNCHREASON_AUTO_STARTUP;
2508         return;
2509     }
2510     lifeCycleStateInfo_.launchParam.launchReason = reason;
2511 }
2512 
SetLastExitReason(const LastExitReason & reason)2513 void AbilityRecord::SetLastExitReason(const LastExitReason &reason)
2514 {
2515     lifeCycleStateInfo_.launchParam.lastExitReason = reason;
2516 }
2517 
NotifyContinuationResult(int32_t result)2518 void AbilityRecord::NotifyContinuationResult(int32_t result)
2519 {
2520     HILOG_INFO("NotifyContinuationResult.");
2521     CHECK_POINTER(lifecycleDeal_);
2522 
2523     lifecycleDeal_->NotifyContinuationResult(result);
2524 }
2525 
GetOwnedMissionList() const2526 std::shared_ptr<MissionList> AbilityRecord::GetOwnedMissionList() const
2527 {
2528     return missionList_.lock();
2529 }
2530 
SetMissionList(const std::shared_ptr<MissionList> & missionList)2531 void AbilityRecord::SetMissionList(const std::shared_ptr<MissionList> &missionList)
2532 {
2533     missionList_ = missionList;
2534 }
2535 
SetMission(const std::shared_ptr<Mission> & mission)2536 void AbilityRecord::SetMission(const std::shared_ptr<Mission> &mission)
2537 {
2538     if (mission) {
2539         missionId_ = mission->GetMissionId();
2540         HILOG_DEBUG("SetMission come, missionId is %{public}d.", missionId_);
2541     }
2542     std::lock_guard guard(wantLock_);
2543     want_.RemoveParam(KEY_MISSION_ID);
2544     want_.SetParam(KEY_MISSION_ID, missionId_);
2545     mission_ = mission;
2546 }
2547 
SetSessionInfo(sptr<SessionInfo> sessionInfo)2548 void AbilityRecord::SetSessionInfo(sptr<SessionInfo> sessionInfo)
2549 {
2550     std::lock_guard guard(sessionLock_);
2551     sessionInfo_ = sessionInfo;
2552 }
2553 
GetSessionInfo() const2554 sptr<SessionInfo> AbilityRecord::GetSessionInfo() const
2555 {
2556     std::lock_guard guard(sessionLock_);
2557     return sessionInfo_;
2558 }
2559 
UpdateSessionInfo(sptr<IRemoteObject> sessionToken)2560 void AbilityRecord::UpdateSessionInfo(sptr<IRemoteObject> sessionToken)
2561 {
2562     {
2563         std::lock_guard guard(sessionLock_);
2564         if (sessionInfo_ == nullptr) {
2565             HILOG_WARN("sessionInfo_ is nullptr.");
2566             return;
2567         }
2568         sessionInfo_->sessionToken = sessionToken;
2569     }
2570     CHECK_POINTER(lifecycleDeal_);
2571     lifecycleDeal_->UpdateSessionToken(sessionToken);
2572 }
2573 
SetMinimizeReason(bool fromUser)2574 void AbilityRecord::SetMinimizeReason(bool fromUser)
2575 {
2576     minimizeReason_ = fromUser;
2577 }
2578 
SetAppIndex(const int32_t appIndex)2579 void AbilityRecord::SetAppIndex(const int32_t appIndex)
2580 {
2581     appIndex_ = appIndex;
2582 }
2583 
GetAppIndex() const2584 int32_t AbilityRecord::GetAppIndex() const
2585 {
2586     return appIndex_;
2587 }
2588 
IsMinimizeFromUser() const2589 bool AbilityRecord::IsMinimizeFromUser() const
2590 {
2591     return minimizeReason_;
2592 }
2593 
SetClearMissionFlag(bool clearMissionFlag)2594 void AbilityRecord::SetClearMissionFlag(bool clearMissionFlag)
2595 {
2596     clearMissionFlag_= clearMissionFlag;
2597 }
2598 
IsClearMissionFlag()2599 bool AbilityRecord::IsClearMissionFlag()
2600 {
2601     return clearMissionFlag_;
2602 }
2603 
GetMission() const2604 std::shared_ptr<Mission> AbilityRecord::GetMission() const
2605 {
2606     return mission_.lock();
2607 }
2608 
GetMissionId() const2609 int32_t AbilityRecord::GetMissionId() const
2610 {
2611     return missionId_;
2612 }
2613 
SetSpecifiedFlag(const std::string & flag)2614 void AbilityRecord::SetSpecifiedFlag(const std::string &flag)
2615 {
2616     specifiedFlag_ = flag;
2617 }
2618 
GetSpecifiedFlag() const2619 std::string AbilityRecord::GetSpecifiedFlag() const
2620 {
2621     return specifiedFlag_;
2622 }
2623 
2624 // new version  --start
IsStartedByCall() const2625 bool AbilityRecord::IsStartedByCall() const
2626 {
2627     return isStartedByCall_;
2628 }
2629 
SetStartedByCall(const bool isFlag)2630 void AbilityRecord::SetStartedByCall(const bool isFlag)
2631 {
2632     isStartedByCall_ = isFlag;
2633 }
2634 
IsStartToBackground() const2635 bool AbilityRecord::IsStartToBackground() const
2636 {
2637     return isStartToBackground_;
2638 }
2639 
SetStartToBackground(const bool flag)2640 void AbilityRecord::SetStartToBackground(const bool flag)
2641 {
2642     isStartToBackground_ = flag;
2643 }
2644 
IsStartToForeground() const2645 bool AbilityRecord::IsStartToForeground() const
2646 {
2647     return isStartToForeground_;
2648 }
2649 
SetStartToForeground(const bool flag)2650 void AbilityRecord::SetStartToForeground(const bool flag)
2651 {
2652     isStartToForeground_ = flag;
2653 }
2654 
CallRequest()2655 void AbilityRecord::CallRequest()
2656 {
2657     CHECK_POINTER(scheduler_);
2658     // Async call request
2659     scheduler_->CallRequest();
2660 }
2661 
CallRequestDone(const sptr<IRemoteObject> & callStub) const2662 bool AbilityRecord::CallRequestDone(const sptr<IRemoteObject> &callStub) const
2663 {
2664     CHECK_POINTER_RETURN_BOOL(callContainer_);
2665     if (!callContainer_->CallRequestDone(callStub)) {
2666         HILOG_ERROR("Call request failed.");
2667         return false;
2668     }
2669     return true;
2670 }
2671 
Resolve(const AbilityRequest & abilityRequest)2672 ResolveResultType AbilityRecord::Resolve(const AbilityRequest &abilityRequest)
2673 {
2674     auto callback = abilityRequest.connect;
2675     if (abilityRequest.callType != AbilityCallType::CALL_REQUEST_TYPE || !callback) {
2676         HILOG_ERROR("only start by call type can create a call record.");
2677         return ResolveResultType::NG_INNER_ERROR;
2678     }
2679     if (!callContainer_) {
2680         callContainer_ = std::make_shared<CallContainer>();
2681         if (!callContainer_) {
2682             HILOG_ERROR("mark_shared error.");
2683             return ResolveResultType::NG_INNER_ERROR;
2684         }
2685     }
2686 
2687     HILOG_DEBUG("create call record for this resolve. callerUid:%{public}d ,targetname:%{public}s",
2688         abilityRequest.callerUid,
2689         abilityRequest.abilityInfo.name.c_str());
2690 
2691     std::shared_ptr<CallRecord> callRecord = callContainer_->GetCallRecord(callback);
2692     if (!callRecord) {
2693         callRecord = CallRecord::CreateCallRecord(
2694             abilityRequest.callerUid, shared_from_this(), callback, abilityRequest.callerToken);
2695         if (!callRecord) {
2696             HILOG_ERROR("mark_shared error.");
2697             return ResolveResultType::NG_INNER_ERROR;
2698         }
2699     }
2700 
2701     callContainer_->AddCallRecord(callback, callRecord);
2702 
2703     if (callRecord->IsCallState(CallState::REQUESTED) && callRecord->GetCallStub()) {
2704         HILOG_DEBUG("this record has requested.");
2705         if (!callRecord->SchedulerConnectDone()) {
2706             HILOG_DEBUG("this callrecord has requested, but callback failed.");
2707             return ResolveResultType::NG_INNER_ERROR;
2708         }
2709         return ResolveResultType::OK_HAS_REMOTE_OBJ;
2710     }
2711 
2712     callRecord->SetCallState(CallState::REQUESTING);
2713     return ResolveResultType::OK_NO_REMOTE_OBJ;
2714 }
2715 
ReleaseCall(const sptr<IAbilityConnection> & connect)2716 bool AbilityRecord::ReleaseCall(const sptr<IAbilityConnection>& connect)
2717 {
2718     HILOG_DEBUG("ability release call record by callback.");
2719     CHECK_POINTER_RETURN_BOOL(callContainer_);
2720 
2721     return callContainer_->RemoveCallRecord(connect);
2722 }
2723 
IsExistConnection(const sptr<IAbilityConnection> & connect)2724 bool AbilityRecord::IsExistConnection(const sptr<IAbilityConnection> &connect)
2725 {
2726     HILOG_DEBUG("ability find call record by callback.");
2727     CHECK_POINTER_RETURN_BOOL(callContainer_);
2728 
2729     return callContainer_->IsExistConnection(connect);
2730 }
2731 
IsNeedToCallRequest() const2732 bool AbilityRecord::IsNeedToCallRequest() const
2733 {
2734     HILOG_DEBUG("ability release call record by callback.");
2735     if (callContainer_ == nullptr) {
2736         return false;
2737     }
2738 
2739     return callContainer_->IsNeedToCallRequest();
2740 }
2741 
ContinueAbility(const std::string & deviceId,uint32_t versionCode)2742 void AbilityRecord::ContinueAbility(const std::string& deviceId, uint32_t versionCode)
2743 {
2744     HILOG_INFO("ContinueAbility.");
2745     CHECK_POINTER(lifecycleDeal_);
2746 
2747     lifecycleDeal_->ContinueAbility(deviceId, versionCode);
2748 }
2749 
SetSwitchingPause(bool state)2750 void AbilityRecord::SetSwitchingPause(bool state)
2751 {
2752     isSwitchingPause_ = state;
2753 }
2754 
IsSwitchingPause()2755 bool AbilityRecord::IsSwitchingPause()
2756 {
2757     return isSwitchingPause_;
2758 }
2759 
SetOwnerMissionUserId(int32_t userId)2760 void AbilityRecord::SetOwnerMissionUserId(int32_t userId)
2761 {
2762     ownerMissionUserId_ = userId;
2763 }
2764 
GetOwnerMissionUserId()2765 int32_t AbilityRecord::GetOwnerMissionUserId()
2766 {
2767     return ownerMissionUserId_;
2768 }
2769 
DumpClientInfo(std::vector<std::string> & info,const std::vector<std::string> & params,bool isClient,bool dumpConfig) const2770 void AbilityRecord::DumpClientInfo(std::vector<std::string> &info, const std::vector<std::string> &params,
2771     bool isClient, bool dumpConfig) const
2772 {
2773     if (!isClient || !scheduler_ || !isReady_) {
2774         HILOG_ERROR("something nullptr.");
2775         return;
2776     }
2777     std::unique_lock<ffrt::mutex> lock(dumpLock_);
2778     scheduler_->DumpAbilityInfo(params, info);
2779 
2780     HILOG_INFO("Dump begin wait.");
2781     isDumpTimeout_ = false;
2782     std::chrono::milliseconds timeout { DUMP_TIMEOUT_MULTIPLE };
2783     if (dumpCondition_.wait_for(lock, timeout) == ffrt::cv_status::timeout) {
2784         isDumpTimeout_ = true;
2785     }
2786     HILOG_INFO("Dump done and begin parse.");
2787     if (!isDumpTimeout_) {
2788         std::lock_guard<ffrt::mutex> infoLock(dumpInfoLock_);
2789         for (auto one : dumpInfos_) {
2790             info.emplace_back(one);
2791         }
2792     }
2793 
2794     if (!dumpConfig) {
2795         HILOG_INFO("not dumpConfig.");
2796         return;
2797     }
2798     AppExecFwk::Configuration config;
2799     if (DelayedSingleton<AppScheduler>::GetInstance()->GetConfiguration(config) == ERR_OK) {
2800         info.emplace_back("          configuration: " + config.GetName());
2801     }
2802 }
2803 
DumpAbilityInfoDone(std::vector<std::string> & infos)2804 void AbilityRecord::DumpAbilityInfoDone(std::vector<std::string> &infos)
2805 {
2806     HILOG_INFO("call");
2807     if (isDumpTimeout_) {
2808         HILOG_WARN("%{public}s, dump time out.", __func__);
2809         return;
2810     }
2811     {
2812         std::lock_guard<ffrt::mutex> infoLock(dumpInfoLock_);
2813         dumpInfos_.clear();
2814         for (auto info : infos) {
2815             dumpInfos_.emplace_back(info);
2816         }
2817     }
2818     dumpCondition_.notify_all();
2819 }
2820 
GrantUriPermission(Want & want,std::string targetBundleName,bool isSandboxApp,uint32_t tokenId)2821 void AbilityRecord::GrantUriPermission(Want &want, std::string targetBundleName, bool isSandboxApp, uint32_t tokenId)
2822 {
2823     // reject sandbox to grant uri permission by start ability
2824     if (!callerList_.empty() && callerList_.back()) {
2825         auto caller = callerList_.back()->GetCaller();
2826         if (caller && caller->appIndex_ > 0) {
2827             HILOG_ERROR("Sandbox can not grant UriPermission by start ability.");
2828             return;
2829         }
2830     }
2831     // reject sandbox to grant uri permission by terminate self with result
2832     if (isSandboxApp) {
2833         HILOG_ERROR("Sandbox can not grant uriPermission by terminate self with result.");
2834         return;
2835     }
2836     if (targetBundleName == SHELL_ASSISTANT_BUNDLENAME && collaboratorType_ == CollaboratorType::OTHERS_TYPE) {
2837         HILOG_DEBUG("reject shell application to grant uri permission");
2838         return;
2839     }
2840 
2841     if ((want.GetFlags() & (Want::FLAG_AUTH_READ_URI_PERMISSION | Want::FLAG_AUTH_WRITE_URI_PERMISSION)) == 0) {
2842         HILOG_WARN("Do not call uriPermissionMgr.");
2843         return;
2844     }
2845     if (IsDmsCall(want)) {
2846         GrantDmsUriPermission(want, targetBundleName);
2847         return;
2848     }
2849     std::vector<std::string> uriVec;
2850     std::string uriStr = want.GetUri().ToString();
2851     uriVec = want.GetStringArrayParam(AbilityConfig::PARAMS_STREAM);
2852     if (!uriStr.empty()) {
2853         uriVec.emplace_back(uriStr);
2854     }
2855     HILOG_DEBUG("GrantUriPermission uriVec size: %{public}zu", uriVec.size());
2856     if (uriVec.size() == 0) {
2857         return;
2858     }
2859     if (uriVec.size() > MAX_URI_COUNT) {
2860         HILOG_ERROR("size of uriVec is more than %{public}i", MAX_URI_COUNT);
2861         return;
2862     }
2863 
2864     auto callerPkg = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
2865     if (callerPkg == SHELL_ASSISTANT_BUNDLENAME
2866         && GrantPermissionToShell(uriVec, want.GetFlags(), targetBundleName)) {
2867         HILOG_INFO("permission to shell");
2868         return;
2869     }
2870     if (AppUtils::GetInstance().JudgePCDevice()) {
2871         GrantUriPermissionFor2In1Inner(want, uriVec, targetBundleName, tokenId);
2872         return;
2873     }
2874     GrantUriPermissionInner(want, uriVec, targetBundleName, tokenId);
2875 }
2876 
CheckUriPermission(Uri & uri,uint32_t & flag,uint32_t callerTokenId,bool permission,int32_t userId)2877 bool AbilityRecord::CheckUriPermission(Uri &uri, uint32_t &flag, uint32_t callerTokenId, bool permission,
2878     int32_t userId)
2879 {
2880     auto bundleFlag = AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO;
2881     auto &&authority = uri.GetAuthority();
2882     HILOG_INFO("uri authority is %{public}s.", authority.c_str());
2883     if (!isGrantPersistableUriPermissionEnable_ || authority != "docs") {
2884         flag &= (~Want::FLAG_AUTH_PERSISTABLE_URI_PERMISSION);
2885     }
2886     if (permission) {
2887         return true;
2888     }
2889     if (authority == "media") {
2890         HILOG_WARN("the type of uri media, have no permission.");
2891         return false;
2892     }
2893     if (authority == "docs") {
2894         if (!isGrantPersistableUriPermissionEnable_ ||
2895             !AAFwk::UriPermissionManagerClient::GetInstance().CheckPersistableUriPermissionProxy(
2896                 uri, flag, callerTokenId)) {
2897             HILOG_WARN("the type of uri docs, have no permission.");
2898             return false;
2899         }
2900         flag |= Want::FLAG_AUTH_PERSISTABLE_URI_PERMISSION;
2901         return true;
2902     }
2903     // uri of bundle name type
2904     auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
2905     if (bundleMgrHelper == nullptr) {
2906         HILOG_ERROR("bundleMgrHelper is nullptr");
2907         return false;
2908     };
2909     AppExecFwk::BundleInfo uriBundleInfo;
2910     if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo(authority, bundleFlag, uriBundleInfo, userId))) {
2911         HILOG_WARN("To fail to get bundle info according to uri.");
2912         return false;
2913     }
2914     auto authorityAccessTokenId = uriBundleInfo.applicationInfo.accessTokenId;
2915     if (authorityAccessTokenId != callerAccessTokenId_ && authorityAccessTokenId != callerTokenId) {
2916         HILOG_ERROR("the uri does not belong to caller, have not permission");
2917         return false;
2918     }
2919     return true;
2920 }
2921 
GrantUriPermissionInner(Want & want,std::vector<std::string> & uriVec,const std::string & targetBundleName,uint32_t tokenId)2922 void AbilityRecord::GrantUriPermissionInner(Want &want, std::vector<std::string> &uriVec,
2923     const std::string &targetBundleName, uint32_t tokenId)
2924 {
2925     auto callerTokenId = static_cast<uint32_t>(want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId));
2926     auto permission = AAFwk::UriPermissionManagerClient::GetInstance().IsAuthorizationUriAllowed(callerTokenId);
2927     auto userId = GetCurrentAccountId();
2928     HILOG_INFO("callerTokenId = %{public}u, tokenId = %{public}u, permission = %{public}i",
2929         callerTokenId, tokenId, static_cast<int>(permission));
2930     std::unordered_map<uint32_t, std::vector<Uri>> uriVecMap; // flag, vector
2931     uint32_t flag = want.GetFlags();
2932     for (auto&& str : uriVec) {
2933         Uri uri(str);
2934         auto &&scheme = uri.GetScheme();
2935         HILOG_INFO("uri is %{private}s, scheme is %{public}s.", str.c_str(), scheme.c_str());
2936         // only support file scheme
2937         if (scheme != "file") {
2938             HILOG_WARN("only support file uri.");
2939             continue;
2940         }
2941         if (!CheckUriPermission(uri, flag, callerTokenId, permission, userId)) {
2942             HILOG_ERROR("no permission to grant uri.");
2943             continue;
2944         }
2945         if (uriVecMap.find(flag) == uriVecMap.end()) {
2946             std::vector<Uri> uriVec;
2947             uriVecMap.emplace(flag, uriVec);
2948         }
2949         uriVecMap[flag].emplace_back(uri);
2950     }
2951     for (const auto &item : uriVecMap) {
2952         auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(item.second, item.first,
2953             targetBundleName, appIndex_, callerTokenId));
2954         if (ret == ERR_OK) {
2955             isGrantedUriPermission_ = true;
2956         }
2957     }
2958 }
2959 
GrantPermissionToShell(const std::vector<std::string> & strUriVec,uint32_t flag,std::string targetPkg)2960 bool AbilityRecord::GrantPermissionToShell(const std::vector<std::string> &strUriVec, uint32_t flag,
2961     std::string targetPkg)
2962 {
2963     std::vector<Uri> uriVec;
2964     for (auto&& str : strUriVec) {
2965         Uri uri(str);
2966         auto&& scheme = uri.GetScheme();
2967         if (scheme != "content") {
2968             return false;
2969         } else {
2970             uriVec.emplace_back(uri);
2971         }
2972     }
2973 
2974     uint32_t initiatorTokenId = IPCSkeleton::GetCallingTokenID();
2975     for (auto&& uri : uriVec) {
2976         auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(uri, flag, targetPkg,
2977             appIndex_, initiatorTokenId));
2978         if (ret == ERR_OK) {
2979             isGrantedUriPermission_ = true;
2980         }
2981     }
2982     return true;
2983 }
2984 
GrantUriPermissionFor2In1Inner(Want & want,std::vector<std::string> & uriVec,const std::string & targetBundleName,uint32_t tokenId)2985 void AbilityRecord::GrantUriPermissionFor2In1Inner(Want &want, std::vector<std::string> &uriVec,
2986     const std::string &targetBundleName, uint32_t tokenId)
2987 {
2988     std::vector<std::string> uriOtherVec;
2989     std::vector<Uri> uri2In1Vec;
2990     for (auto &&str : uriVec) {
2991         Uri uri(str);
2992         auto &&authority = uri.GetAuthority();
2993         if (authority == "docs") {
2994             uri2In1Vec.emplace_back(uri);
2995         } else {
2996             uriOtherVec.emplace_back(str);
2997         }
2998     }
2999     if (!uri2In1Vec.empty()) {
3000         uint32_t flag = want.GetFlags();
3001         auto isSystemAppCall = PermissionVerification::GetInstance()->IsSystemAppCall();
3002         IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().GrantUriPermissionFor2In1(
3003             uri2In1Vec, flag, targetBundleName, appIndex_, isSystemAppCall));
3004     }
3005     if (!uriOtherVec.empty()) {
3006         GrantUriPermissionInner(want, uriOtherVec, targetBundleName, tokenId);
3007     }
3008 }
3009 
IsDmsCall(Want & want)3010 bool AbilityRecord::IsDmsCall(Want &want)
3011 {
3012     auto fromTokenId = static_cast<uint32_t>(want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
3013     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(fromTokenId);
3014     bool isNativeCall = tokenType == Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE;
3015     if (!isNativeCall) {
3016         HILOG_INFO("Is not native call.");
3017         return false;
3018     }
3019     AccessToken::NativeTokenInfo nativeTokenInfo;
3020     int32_t result = AccessToken::AccessTokenKit::GetNativeTokenInfo(fromTokenId, nativeTokenInfo);
3021     if (result == ERR_OK && nativeTokenInfo.processName == DMS_PROCESS_NAME) {
3022         HILOG_INFO("Is dms ability call.");
3023         return true;
3024     }
3025     return false;
3026 }
3027 
GrantDmsUriPermission(Want & want,std::string targetBundleName)3028 void AbilityRecord::GrantDmsUriPermission(Want &want, std::string targetBundleName)
3029 {
3030     std::vector<std::string> uriVec = want.GetStringArrayParam(PARAMS_URI);
3031     HILOG_DEBUG("GrantDmsUriPermission uriVec size: %{public}zu", uriVec.size());
3032     for (auto&& str : uriVec) {
3033         Uri uri(str);
3034         auto&& scheme = uri.GetScheme();
3035         HILOG_INFO("uri scheme is %{public}s.", scheme.c_str());
3036         // only support file scheme
3037         if (scheme != "file") {
3038             HILOG_WARN("only support file uri.");
3039             continue;
3040         }
3041         std::string srcPath = uri.GetPath();
3042         if (std::filesystem::exists(srcPath) && std::filesystem::is_symlink(srcPath)) {
3043             HILOG_ERROR("soft links are not allowed.");
3044             continue;
3045         }
3046         std::string absolutePath;
3047         if (uri.IsRelative()) {
3048             char path[PATH_MAX] = {0};
3049             if (realpath(srcPath.c_str(), path) == nullptr) {
3050                 HILOG_ERROR("realpath get failed, errno is %{public}d", errno);
3051                 continue;
3052             }
3053             absolutePath = path;
3054         } else {
3055             absolutePath = srcPath;
3056         }
3057         if (absolutePath.compare(0, DISTRIBUTED_FILES_PATH.size(), DISTRIBUTED_FILES_PATH) != 0) {
3058             HILOG_ERROR("uri is not distributed path");
3059             continue;
3060         }
3061         uint32_t initiatorTokenId = IPCSkeleton::GetCallingTokenID();
3062         auto ret = IN_PROCESS_CALL(UriPermissionManagerClient::GetInstance().GrantUriPermission(uri, want.GetFlags(),
3063             targetBundleName, appIndex_, initiatorTokenId));
3064         if (ret == 0) {
3065             isGrantedUriPermission_ = true;
3066         }
3067     }
3068     uriVec.clear();
3069     want.SetParam(PARAMS_URI, uriVec);
3070 }
3071 
RevokeUriPermission()3072 void AbilityRecord::RevokeUriPermission()
3073 {
3074     if (isGrantedUriPermission_) {
3075         HILOG_DEBUG("To remove uri permission.");
3076         UriPermissionManagerClient::GetInstance().RevokeUriPermission(applicationInfo_.accessTokenId);
3077         isGrantedUriPermission_ = false;
3078     }
3079 }
3080 
HandleDlpAttached()3081 void AbilityRecord::HandleDlpAttached()
3082 {
3083     if (abilityInfo_.bundleName == DLP_BUNDLE_NAME) {
3084         DelayedSingleton<ConnectionStateManager>::GetInstance()->AddDlpManager(shared_from_this());
3085     }
3086 
3087     if (appIndex_ > 0) {
3088         DelayedSingleton<ConnectionStateManager>::GetInstance()->AddDlpAbility(shared_from_this());
3089     }
3090 }
3091 
HandleDlpClosed()3092 void AbilityRecord::HandleDlpClosed()
3093 {
3094     if (abilityInfo_.bundleName == DLP_BUNDLE_NAME) {
3095         DelayedSingleton<ConnectionStateManager>::GetInstance()->RemoveDlpManager(shared_from_this());
3096     }
3097 
3098     if (appIndex_ > 0) {
3099         DelayedSingleton<ConnectionStateManager>::GetInstance()->RemoveDlpAbility(shared_from_this());
3100     }
3101 }
3102 
NotifyRemoveShellProcess(int32_t type)3103 void AbilityRecord::NotifyRemoveShellProcess(int32_t type)
3104 {
3105     HILOG_DEBUG("type is : %{public}d", type);
3106     if (abilityInfo_.bundleName == SHELL_ASSISTANT_BUNDLENAME) {
3107         auto collaborator = DelayedSingleton<AbilityManagerService>::GetInstance()->GetCollaborator(type);
3108         if (collaborator == nullptr) {
3109             HILOG_DEBUG("collaborator is nullptr");
3110             return;
3111         }
3112         int ret = collaborator->NotifyRemoveShellProcess(pid_, SHELL_ASSISTANT_DIETYPE, SHELL_ASSISTANT_DIEREASON);
3113         HILOG_INFO("notify broker params pid is: %{public}d", pid_);
3114         if (ret != ERR_OK) {
3115             HILOG_ERROR("notify broker remove shell process failed, err: %{public}d", ret);
3116         }
3117     }
3118 }
3119 
GetCurrentAccountId() const3120 int32_t AbilityRecord::GetCurrentAccountId() const
3121 {
3122     std::vector<int32_t> osActiveAccountIds;
3123     ErrCode ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
3124             QueryActiveOsAccountIds(osActiveAccountIds);
3125     if (ret != ERR_OK) {
3126         HILOG_ERROR("QueryActiveOsAccountIds failed.");
3127         return DEFAULT_USER_ID;
3128     }
3129     if (osActiveAccountIds.empty()) {
3130         HILOG_ERROR("QueryActiveOsAccountIds is empty, no accounts.");
3131         return DEFAULT_USER_ID;
3132     }
3133 
3134     return osActiveAccountIds.front();
3135 }
3136 
SetPendingState(AbilityState state)3137 void AbilityRecord::SetPendingState(AbilityState state)
3138 {
3139     pendingState_.store(state);
3140 }
3141 
GetPendingState() const3142 AbilityState AbilityRecord::GetPendingState() const
3143 {
3144     return pendingState_.load();
3145 }
3146 
3147 #ifdef ABILITY_COMMAND_FOR_TEST
BlockAbility()3148 int AbilityRecord::BlockAbility()
3149 {
3150     HILOG_INFO("BlockAbility.");
3151     if (scheduler_) {
3152         HILOG_INFO("scheduler_ begin to call BlockAbility %{public}s", __func__);
3153         return scheduler_->BlockAbility();
3154     }
3155     return ERR_NO_INIT;
3156 }
3157 #endif
3158 
IsNeedBackToOtherMissionStack()3159 bool AbilityRecord::IsNeedBackToOtherMissionStack()
3160 {
3161     return isNeedBackToOtherMissionStack_;
3162 }
3163 
SetNeedBackToOtherMissionStack(bool isNeedBackToOtherMissionStack)3164 void AbilityRecord::SetNeedBackToOtherMissionStack(bool isNeedBackToOtherMissionStack)
3165 {
3166     isNeedBackToOtherMissionStack_ = isNeedBackToOtherMissionStack;
3167 }
3168 
GetOtherMissionStackAbilityRecord() const3169 std::shared_ptr<AbilityRecord> AbilityRecord::GetOtherMissionStackAbilityRecord() const
3170 {
3171     return otherMissionStackAbilityRecord_.lock();
3172 }
3173 
SetOtherMissionStackAbilityRecord(const std::shared_ptr<AbilityRecord> & abilityRecord)3174 void AbilityRecord::SetOtherMissionStackAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)
3175 {
3176     otherMissionStackAbilityRecord_ = abilityRecord;
3177 }
3178 
GetCollaboratorType() const3179 int32_t AbilityRecord::GetCollaboratorType() const
3180 {
3181     return collaboratorType_;
3182 }
3183 
InitPersistableUriPermissionConfig()3184 void AbilityRecord::InitPersistableUriPermissionConfig()
3185 {
3186     char value[GRANT_PERSISTABLE_URI_PERMISSION_ENABLE_SIZE] = "false";
3187     int retSysParam = GetParameter(GRANT_PERSISTABLE_URI_PERMISSION_ENABLE_PARAMETER, "false", value,
3188         GRANT_PERSISTABLE_URI_PERMISSION_ENABLE_SIZE);
3189     HILOG_DEBUG("GrantPersistableUriPermissionEnable, %{public}s value is %{public}s.",
3190         GRANT_PERSISTABLE_URI_PERMISSION_ENABLE_PARAMETER, value);
3191     if (retSysParam > 0 && !std::strcmp(value, "true")) {
3192         isGrantPersistableUriPermissionEnable_ = true;
3193     }
3194 }
3195 
GetMissionAffinity() const3196 std::string AbilityRecord::GetMissionAffinity() const
3197 {
3198     return missionAffinity_;
3199 }
3200 
SetLockedState(bool lockedState)3201 void AbilityRecord::SetLockedState(bool lockedState)
3202 {
3203     lockedState_ = lockedState;
3204 }
3205 
GetLockedState()3206 bool AbilityRecord::GetLockedState()
3207 {
3208     return lockedState_;
3209 }
3210 
SetAttachDebug(const bool isAttachDebug)3211 void AbilityRecord::SetAttachDebug(const bool isAttachDebug)
3212 {
3213     isAttachDebug_ = isAttachDebug;
3214 }
3215 
AddAbilityWindowStateMap(uint64_t uiExtensionComponentId,AbilityWindowState abilityWindowState)3216 void AbilityRecord::AddAbilityWindowStateMap(uint64_t uiExtensionComponentId,
3217     AbilityWindowState abilityWindowState)
3218 {
3219     abilityWindowStateMap_[uiExtensionComponentId] = abilityWindowState;
3220 }
3221 
RemoveAbilityWindowStateMap(uint64_t uiExtensionComponentId)3222 void AbilityRecord::RemoveAbilityWindowStateMap(uint64_t uiExtensionComponentId)
3223 {
3224     if (abilityWindowStateMap_.find(uiExtensionComponentId) != abilityWindowStateMap_.end()) {
3225         abilityWindowStateMap_.erase(uiExtensionComponentId);
3226     }
3227 }
3228 
IsAbilityWindowReady()3229 bool AbilityRecord::IsAbilityWindowReady()
3230 {
3231     for (auto &item:abilityWindowStateMap_) {
3232         if (item.second == AbilityWindowState::BACKGROUNDING ||
3233             item.second == AbilityWindowState::TERMINATING) {
3234             return false;
3235         }
3236     }
3237     return true;
3238 }
3239 
SetAbilityWindowState(const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd,bool isFinished)3240 void AbilityRecord::SetAbilityWindowState(const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd, bool isFinished)
3241 {
3242     if (sessionInfo == nullptr) {
3243         HILOG_ERROR("sessionInfo is nullptr");
3244         return;
3245     }
3246     if (isFinished) {
3247         if (winCmd == WIN_CMD_FOREGROUND) {
3248             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::FOREGROUND);
3249         } else if (winCmd == WIN_CMD_BACKGROUND) {
3250             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::BACKGROUND);
3251         } else if (winCmd == WIN_CMD_DESTROY) {
3252             RemoveAbilityWindowStateMap(sessionInfo->uiExtensionComponentId);
3253         }
3254     } else {
3255         if (winCmd == WIN_CMD_FOREGROUND) {
3256             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::FOREGROUNDING);
3257         } else if (winCmd == WIN_CMD_BACKGROUND) {
3258             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::BACKGROUNDING);
3259         } else if (winCmd == WIN_CMD_DESTROY) {
3260             AddAbilityWindowStateMap(sessionInfo->uiExtensionComponentId, AbilityWindowState::TERMINATING);
3261         }
3262     }
3263 }
3264 
CreateModalUIExtension(const Want & want)3265 int32_t AbilityRecord::CreateModalUIExtension(const Want &want)
3266 {
3267     HILOG_DEBUG("call");
3268     CHECK_POINTER_AND_RETURN(scheduler_, INNER_ERR);
3269     return scheduler_->CreateModalUIExtension(want);
3270 }
3271 
SetURI(const std::string & uri)3272 void AbilityRecord::SetURI(const std::string &uri)
3273 {
3274     uri_ = uri;
3275 }
3276 
GetURI() const3277 std::string AbilityRecord::GetURI() const
3278 {
3279     if (uri_.empty()) {
3280         return AppExecFwk::ElementName(abilityInfo_.deviceId, abilityInfo_.bundleName,
3281             abilityInfo_.name, abilityInfo_.moduleName).GetURI();
3282     }
3283     return uri_;
3284 }
3285 
SetProcessName(const std::string & process)3286 void AbilityRecord::SetProcessName(const std::string &process)
3287 {
3288     abilityInfo_.process = process;
3289 }
3290 
SetUIExtensionAbilityId(const int32_t uiExtensionAbilityId)3291 void AbilityRecord::SetUIExtensionAbilityId(const int32_t uiExtensionAbilityId)
3292 {
3293     uiExtensionAbilityId_ = uiExtensionAbilityId;
3294 }
3295 
GetUIExtensionAbilityId() const3296 int32_t AbilityRecord::GetUIExtensionAbilityId() const
3297 {
3298     return uiExtensionAbilityId_;
3299 }
3300 
BackgroundAbilityWindowDelayed()3301 bool AbilityRecord::BackgroundAbilityWindowDelayed()
3302 {
3303     return backgroundAbilityWindowDelayed_.load();
3304 }
3305 
DoBackgroundAbilityWindowDelayed(bool needBackground)3306 void AbilityRecord::DoBackgroundAbilityWindowDelayed(bool needBackground)
3307 {
3308     backgroundAbilityWindowDelayed_.store(needBackground);
3309 }
3310 
IsSceneBoard() const3311 bool AbilityRecord::IsSceneBoard() const
3312 {
3313     return GetAbilityInfo().name == AbilityConfig::SCENEBOARD_ABILITY_NAME &&
3314         GetAbilityInfo().bundleName == AbilityConfig::SCENEBOARD_BUNDLE_NAME;
3315 }
3316 }  // namespace AAFwk
3317 }  // namespace OHOS
3318