1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ability_manager_service.h"
17 
18 #include "ability_background_connection.h"
19 #include "ability_connect_manager.h"
20 #include "ability_manager_radar.h"
21 #include "ability_resident_process_rdb.h"
22 #include "accesstoken_kit.h"
23 #include "ability_manager_xcollie.h"
24 #ifdef APP_DOMAIN_VERIFY_ENABLED
25 #include "ag_convert_callback_impl.h"
26 #include "app_domain_verify_mgr_client.h"
27 #endif
28 #include "app_utils.h"
29 #include "app_exit_reason_data_manager.h"
30 #include "application_util.h"
31 #include "recovery_info_timer.h"
32 #include "assert_fault_callback_death_mgr.h"
33 #include "concurrent_task_client.h"
34 #include "connection_state_manager.h"
35 #include "display_manager.h"
36 #include "distributed_client.h"
37 #ifdef WITH_DLP
38 #include "dlp_utils.h"
39 #endif // WITH_DLP
40 #include "freeze_util.h"
41 #include "global_constant.h"
42 #include "hitrace_meter.h"
43 #include "insight_intent_execute_manager.h"
44 #include "interceptor/ability_jump_interceptor.h"
45 #include "interceptor/control_interceptor.h"
46 #include "interceptor/crowd_test_interceptor.h"
47 #include "interceptor/disposed_rule_interceptor.h"
48 #include "interceptor/ecological_rule_interceptor.h"
49 #include "interceptor/extension_control_interceptor.h"
50 #include "interceptor/screen_unlock_interceptor.h"
51 #include "interceptor/start_other_app_interceptor.h"
52 #include "ipc_skeleton.h"
53 #include "iservice_registry.h"
54 #include "mock_session_manager_service.h"
55 #include "modal_system_ui_extension.h"
56 #include "os_account_manager_wrapper.h"
57 #include "permission_constants.h"
58 #include "process_options.h"
59 #include "recovery_param.h"
60 #include "res_sched_util.h"
61 #include "restart_app_manager.h"
62 #include "scene_board_judgement.h"
63 #include "server_constant.h"
64 #include "session_manager_lite.h"
65 #include "softbus_bus_center.h"
66 #include "start_ability_handler/start_ability_sandbox_savefile.h"
67 #include "start_ability_utils.h"
68 #include "startup_util.h"
69 #include "status_bar_delegate_interface.h"
70 #include "string_wrapper.h"
71 #include "ui_extension_utils.h"
72 #include "ui_service_extension_connection_constants.h"
73 #include "unlock_screen_manager.h"
74 #include "uri_permission_manager_client.h"
75 #include "uri_utils.h"
76 #include "view_data.h"
77 #include "xcollie/watchdog.h"
78 #include "config_policy_utils.h"
79 #include "utils/ability_permission_util.h"
80 #include "utils/app_mgr_util.h"
81 #include "utils/dump_utils.h"
82 #include "utils/extension_permissions_util.h"
83 #include "utils/window_options_utils.h"
84 #ifdef SUPPORT_GRAPHICS
85 #include "dialog_session_manager.h"
86 #include "application_anr_listener.h"
87 #include "input_manager.h"
88 #include "ability_first_frame_state_observer_manager.h"
89 #include "session_manager_lite.h"
90 #include "session/host/include/zidl/session_interface.h"
91 #include "window_focus_changed_listener.h"
92 #include "wm_common.h"
93 #endif
94 
95 using OHOS::AppExecFwk::ElementName;
96 using OHOS::Security::AccessToken::AccessTokenKit;
97 
98 namespace OHOS {
99 using AbilityRuntime::FreezeUtil;
100 namespace AAFwk {
101 using AutoStartupInfo = AbilityRuntime::AutoStartupInfo;
102 using GetExtensionAbilityInfoFlag = AppExecFwk::GetExtensionAbilityInfoFlag;
103 namespace {
104 #define CHECK_CALLER_IS_SYSTEM_APP                                                             \
105     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
106         TAG_LOGE(AAFwkTag::ABILITYMGR,                                                         \
107         "The caller is not system-app, can not use system-api");                               \
108         return ERR_NOT_SYSTEM_APP;                                                             \
109     }
110 
111 constexpr const char* ARGS_USER_ID = "-u";
112 constexpr const char* ARGS_CLIENT = "-c";
113 constexpr const char* ILLEGAL_INFOMATION = "The arguments are illegal and you can enter '-h' for help.";
114 
115 
116 constexpr int32_t NEW_RULE_VALUE_SIZE = 6;
117 constexpr int32_t APP_ALIVE_TIME_MS = 1000;  // Allow background startup within 1 second after application startup
118 constexpr int32_t REGISTER_FOCUS_DELAY = 5000;
119 constexpr size_t OFFSET = 32;
120 constexpr const char* IS_DELEGATOR_CALL = "isDelegatorCall";
121 
122 // Startup rule switch
123 constexpr const char* COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
124 constexpr const char* NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI = "component.startup.newRules.except.LauncherSystemUI";
125 constexpr const char* BACKGROUND_JUDGE_FLAG = "component.startup.backgroundJudge.flag";
126 constexpr const char* WHITE_LIST_ASS_WAKEUP_FLAG = "component.startup.whitelist.associatedWakeUp";
127 
128 // White list app
129 constexpr const char* BUNDLE_NAME_SETTINGSDATA = "com.ohos.settingsdata";
130 // Support prepare terminate
131 constexpr int32_t PREPARE_TERMINATE_ENABLE_SIZE = 6;
132 constexpr const char* PREPARE_TERMINATE_ENABLE_PARAMETER = "persist.sys.prepare_terminate";
133 // UIExtension type
134 constexpr const char* UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType";
135 constexpr const char* UIEXTENSION_TARGET_TYPE_KEY = "ability.want.params.uiExtensionTargetType";
136 constexpr const char* SYSTEM_SHARE = "share";
137 constexpr const char* SYSTEM_SHARE_TYPE = "sysPicker/share";
138 // Share picker params
139 constexpr char SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY[] = "const.system.sharePicker.bundleName";
140 constexpr char SHARE_PICKER_DIALOG_ABILITY_NAME_KEY[] = "const.system.sharePicker.abilityName";
141 constexpr char SHARE_PICKER_UIEXTENSION_NAME_KEY[] = "const.system.sharePicker.UIExtensionAbilityName";
142 constexpr char SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME[] = "com.ohos.sharepickerdialog";
143 constexpr char SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME[] = "PickerDialog";
144 constexpr char TOKEN_KEY[] = "ohos.ability.params.token";
145 // Developer mode param
146 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
147 constexpr char PRODUCT_APPBOOT_SETTING_ENABLED[] = "const.product.appboot.setting.enabled";
148 // Broker params key
149 constexpr const char* KEY_VISIBLE_ID = "ohos.anco.param.visible";
150 constexpr const char* START_ABILITY_TYPE = "ABILITY_INNER_START_WITH_ACCOUNT";
151 constexpr const char* SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant";
152 constexpr const char* SHELL_ASSISTANT_ABILITYNAME = "MainAbility";
153 constexpr const char* BUNDLE_NAME_DIALOG = "com.ohos.amsdialog";
154 constexpr const char* STR_PHONE = "phone";
155 constexpr const char* PARAM_RESV_ANCO_CALLER_UID = "ohos.anco.param.callerUid";
156 constexpr const char* PARAM_RESV_ANCO_CALLER_BUNDLENAME = "ohos.anco.param.callerBundleName";
157 // Distributed continued session Id
158 constexpr const char* DMS_CONTINUED_SESSION_ID = "ohos.dms.continueSessionId";
159 constexpr const char* DMS_PERSISTENT_ID = "ohos.dms.persistentId";
160 constexpr const char* DMS_CALLER_BUNDLE_NAME = "ohos.dms.param.sourceCallerBundleName";
161 constexpr const char* DMS_CALLER_ABILITY_NAME = "ohos.dms.param.sourceCallerAbilityName";
162 constexpr const char* DMS_CALLER_NATIVE_NAME = "ohos.dms.param.sourceCallerNativeName";
163 constexpr const char* DMS_CALLER_APP_ID = "ohos.dms.param.sourceCallerAppId";
164 constexpr const char* DMS_CALLER_APP_IDENTIFIER = "ohos.dms.param.sourceCallerAppIdentifier";
165 
166 constexpr const char* DEBUG_APP = "debugApp";
167 constexpr const char* NATIVE_DEBUG = "nativeDebug";
168 constexpr const char* AUTO_FILL_PASSWORD_TPYE = "autoFill/password";
169 constexpr const char* AUTO_FILL_SMART_TPYE = "autoFill/smart";
170 constexpr size_t INDEX_ZERO = 0;
171 constexpr size_t INDEX_ONE = 1;
172 constexpr size_t INDEX_TWO = 2;
173 constexpr size_t ARGC_THREE = 3;
174 constexpr static char WANT_PARAMS_VIEW_DATA_KEY[] = "ohos.ability.params.viewData";
175 constexpr const char* WANT_PARAMS_HOST_WINDOW_ID_KEY = "ohos.extra.param.key.hostwindowid";
176 constexpr const char* WANT_PARAMS_APP_RESTART_FLAG = "ohos.aafwk.app.restart";
177 
178 constexpr int32_t FOUNDATION_UID = 5523;
179 constexpr const char* FRS_BUNDLE_NAME = "com.ohos.formrenderservice";
180 constexpr const char* FOUNDATION_PROCESS_NAME = "foundation";
181 constexpr const char* RSS_PROCESS_NAME = "resource_schedule_service";
182 constexpr const char* IS_PRELOAD_UIEXTENSION_ABILITY = "ability.want.params.is_preload_uiextension_ability";
183 constexpr const char* UIEXTENSION_MODAL_TYPE = "ability.want.params.modalType";
184 constexpr const char* SUPPORT_CLOSE_ON_BLUR = "supportCloseOnBlur";
185 constexpr const char* ATOMIC_SERVICE_PREFIX = "com.atomicservice.";
186 constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohosSpecifiedProcessFlag";
187 constexpr const char* VERIFY_DOMINATE_SCREEN = "persist.sys.abilityms.verify_start_ability_without_caller_token";
188 constexpr const char* CALLER_REQUEST_CODE = "ohos.extra.param.key.callerRequestCode";
189 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
190 constexpr const char* IS_SHELL_CALL = "isShellCall";
191 
192 constexpr char ASSERT_FAULT_DETAIL[] = "assertFaultDialogDetail";
193 constexpr char PRODUCT_ASSERT_FAULT_DIALOG_ENABLED[] = "persisit.sys.abilityms.support_assert_fault_dialog";
194 constexpr const char* ABILITYMS_ENABLE_UISERVICE = "const.abilityms.enable_uiservice";
195 
196 constexpr int32_t RESOURCE_SCHEDULE_UID = 1096;
197 constexpr int32_t UPDATE_CONFIG_FLAG_COVER = 1;
198 constexpr int32_t UPDATE_CONFIG_FLAG_APPEND = 2;
199 
200 const std::unordered_set<std::string> COMMON_PICKER_TYPE = {
201     "share", "action"
202 };
203 std::atomic<bool> g_isDmsAlive = false;
204 
SendAbilityEvent(const EventName & eventName,HiSysEventType type,const EventInfo & eventInfo)205 void SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo)
206 {
207     auto taskHandler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
208     if (taskHandler == nullptr) {
209         TAG_LOGI(AAFwkTag::ABILITYMGR, "task handler null.");
210         return;
211     }
212     taskHandler->SubmitTask([eventName, type, eventInfo]() {
213         EventReport::SendAbilityEvent(eventName, type, eventInfo);
214         });
215 }
216 } // namespace
217 
218 using namespace std::chrono;
219 using namespace std::chrono_literals;
220 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
221 using namespace BackgroundTaskMgr;
222 #endif
223 const bool CONCURRENCY_MODE_FALSE = false;
224 constexpr int32_t MAIN_USER_ID = 100;
225 constexpr auto DATA_ABILITY_START_TIMEOUT = 5s;
226 constexpr int32_t NON_ANONYMIZE_LENGTH = 6;
227 constexpr uint32_t SCENE_FLAG_NORMAL = 0;
228 constexpr int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20;
229 constexpr int32_t SWITCH_ACCOUNT_TRY = 3;
230 constexpr int32_t CONVERT_CALLBACK_TIMEOUT_SECONDS = 2; // 2s
231 constexpr const char* EMPTY_DEVICE_ID = "";
232 constexpr int32_t APP_MEMORY_SIZE = 512;
233 constexpr int32_t GET_PARAMETER_INCORRECT = -9;
234 constexpr int32_t GET_PARAMETER_OTHER = -1;
235 constexpr int32_t SIZE_10 = 10;
236 constexpr int32_t HIDUMPER_SERVICE_UID = 1212;
237 constexpr int32_t ACCOUNT_MGR_SERVICE_UID = 3058;
238 constexpr int32_t BROKER_UID = 5557;
239 constexpr int32_t BROKER_RESERVE_UID = 5005;
240 constexpr int32_t DMS_UID = 5522;
241 constexpr int32_t PREPARE_TERMINATE_TIMEOUT_MULTIPLE = 10;
242 constexpr int32_t BOOTEVENT_COMPLETED_DELAY_TIME = 1000;
243 constexpr int32_t BOOTEVENT_BOOT_ANIMATION_READY_SIZE = 6;
244 constexpr const char* BUNDLE_NAME_KEY = "bundleName";
245 constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager";
246 constexpr const char* ACTION_CHOOSE = "ohos.want.action.select";
247 constexpr const char* HIGHEST_PRIORITY_ABILITY_ENTITY = "flag.home.intent.from.system";
248 constexpr const char* DMS_API_VERSION = "dmsApiVersion";
249 constexpr const char* DMS_IS_CALLER_BACKGROUND = "dmsIsCallerBackGround";
250 constexpr const char* DMS_PROCESS_NAME = "distributedsched";
251 constexpr const char* DMS_MISSION_ID = "dmsMissionId";
252 constexpr const char* BOOTEVENT_APPFWK_READY = "bootevent.appfwk.ready";
253 constexpr const char* BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed";
254 constexpr const char* BOOTEVENT_BOOT_ANIMATION_STARTED = "bootevent.bootanimation.started";
255 constexpr const char* BOOTEVENT_BOOT_ANIMATION_READY = "bootevent.bootanimation.ready";
256 constexpr const char* NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
257 constexpr const char* PERMISSIONMGR_BUNDLE_NAME = "com.ohos.permissionmanager";
258 constexpr const char* PERMISSIONMGR_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility";
259 constexpr const char* IS_CALL_BY_SCB = "isCallBySCB";
260 constexpr const char* SPECIFY_TOKEN_ID = "specifyTokenId";
261 constexpr const char* PROCESS_SUFFIX = "embeddable";
262 constexpr int32_t DEFAULT_DMS_MISSION_ID = -1;
263 constexpr const char* PARAM_PREVENT_STARTABILITY = "persist.sys.abilityms.prevent_startability";
264 constexpr const char* SUSPEND_SERVICE_CONFIG_FILE = "/etc/efficiency_manager/prevent_startability_whitelist.json";
265 constexpr int32_t MAX_BUFFER = 2048;
266 constexpr int32_t API12 = 12;
267 constexpr int32_t API_VERSION_MOD = 100;
268 constexpr const char* WHITE_LIST = "white_list";
269 
270 const bool REGISTER_RESULT =
271     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<AbilityManagerService>::GetInstance().get());
272 sptr<AbilityManagerService> AbilityManagerService::instance_;
273 
AbilityManagerService()274 AbilityManagerService::AbilityManagerService()
275     : SystemAbility(ABILITY_MGR_SERVICE_ID, true),
276       state_(ServiceRunningState::STATE_NOT_START),
277       bundleMgrHelper_(nullptr)
278 {}
279 
~AbilityManagerService()280 AbilityManagerService::~AbilityManagerService()
281 {}
282 
GetPubInstance()283 std::shared_ptr<AbilityManagerService> AbilityManagerService::GetPubInstance()
284 {
285     return DelayedSingleton<AbilityManagerService>::GetInstance();
286 }
287 
OnStart()288 void AbilityManagerService::OnStart()
289 {
290     if (state_ == ServiceRunningState::STATE_RUNNING) {
291         TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service has already started.");
292         return;
293     }
294     TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service starting.");
295     if (!Init()) {
296         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to init ability manager service.");
297         return;
298     }
299     state_ = ServiceRunningState::STATE_RUNNING;
300     /* Publish service maybe failed, so we need call this function at the last,
301      * so it can't affect the TDD test program */
302     instance_ = DelayedSingleton<AbilityManagerService>::GetInstance().get();
303     if (instance_ == nullptr) {
304         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability manager service enter OnStart, but instance_ is nullptr!");
305         return;
306     }
307     bool ret = Publish(instance_);
308     if (!ret) {
309         TAG_LOGE(AAFwkTag::ABILITYMGR, "Publish ability manager service failed!");
310         return;
311     }
312 
313     SetParameter(BOOTEVENT_APPFWK_READY, "true");
314     AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
315     AddSystemAbilityListener(DISTRIBUTED_SCHED_SA_ID);
316     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
317 #ifdef SUPPORT_SCREEN
318     AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
319 #endif
320     TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service start success.");
321     auto pid = getpid();
322     std::unordered_map<std::string, std::string> payload;
323     payload["pid"] = std::to_string(pid);
324     OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload);
325 }
326 
Init()327 bool AbilityManagerService::Init()
328 {
329     HiviewDFX::Watchdog::GetInstance().InitFfrtWatchdog(); // For ffrt watchdog available in foundation
330     taskHandler_ = TaskHandlerWrap::CreateQueueHandler(AbilityConfig::NAME_ABILITY_MGR_SERVICE);
331     eventHandler_ = std::make_shared<AbilityEventHandler>(taskHandler_, weak_from_this());
332     freeInstallManager_ = std::make_shared<FreeInstallManager>(weak_from_this());
333     CHECK_POINTER_RETURN_BOOL(freeInstallManager_);
334 
335     // init user controller.
336     userController_ = std::make_shared<UserController>();
337     userController_->Init();
338     AmsConfigurationParameter::GetInstance().Parse();
339     TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service config parse");
340     subManagersHelper_ = std::make_shared<SubManagersHelper>(taskHandler_, eventHandler_);
341     subManagersHelper_->InitSubManagers(MAIN_USER_ID, true);
342     SwitchManagers(U0_USER_ID, false);
343 #ifdef SUPPORT_GRAPHICS
344     implicitStartProcessor_ = std::make_shared<ImplicitStartProcessor>();
345     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
346         InitFocusListener();
347     }
348     AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().Init();
349 #endif
350 
351     DelayedSingleton<ConnectionStateManager>::GetInstance()->Init(taskHandler_);
352 
353     InitInterceptor();
354     InitStartAbilityChain();
355     InitDeepLinkReserve();
356 
357     abilityAutoStartupService_ = std::make_shared<AbilityRuntime::AbilityAutoStartupService>();
358     InitPushTask();
359     AbilityCacheManager::GetInstance().Init(AppUtils::GetInstance().GetLimitMaximumExtensionsPerDevice(),
360         AppUtils::GetInstance().GetLimitMaximumExtensionsPerProc());
361 
362     SubscribeScreenUnlockedEvent();
363     appExitReasonHelper_ = std::make_shared<AppExitReasonHelper>(subManagersHelper_);
364     TAG_LOGI(AAFwkTag::ABILITYMGR, "Init success.");
365     return true;
366 }
367 
InitDeepLinkReserve()368 void AbilityManagerService::InitDeepLinkReserve()
369 {
370     if (!DeepLinkReserveConfig::GetInstance().LoadConfiguration()) {
371         TAG_LOGE(AAFwkTag::ABILITYMGR, "InitDeepLinkReserve failed.");
372     }
373 }
374 
InitInterceptor()375 void AbilityManagerService::InitInterceptor()
376 {
377     interceptorExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
378     interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
379     interceptorExecuter_->AddInterceptor("CrowdTest", std::make_shared<CrowdTestInterceptor>());
380     interceptorExecuter_->AddInterceptor("Control", std::make_shared<ControlInterceptor>());
381     afterCheckExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
382     afterCheckExecuter_->AddInterceptor("ExtensionControl", std::make_shared<ExtensionControlInterceptor>());
383     afterCheckExecuter_->AddInterceptor("StartOtherApp", std::make_shared<StartOtherAppInterceptor>());
384     afterCheckExecuter_->AddInterceptor("DisposedRule", std::make_shared<DisposedRuleInterceptor>());
385     afterCheckExecuter_->AddInterceptor("EcologicalRule", std::make_shared<EcologicalRuleInterceptor>());
386     afterCheckExecuter_->SetTaskHandler(taskHandler_);
387     bool isAppJumpEnabled = OHOS::system::GetBoolParameter(
388         OHOS::AppExecFwk::PARAMETER_APP_JUMP_INTERCEPTOR_ENABLE, false);
389     if (isAppJumpEnabled) {
390         TAG_LOGI(AAFwkTag::ABILITYMGR, "App jump intercetor enabled, add AbilityJumpInterceptor to Executer");
391         interceptorExecuter_->AddInterceptor("AbilityJump", std::make_shared<AbilityJumpInterceptor>());
392     }
393 }
394 
InitInterceptorForScreenUnlock()395 void AbilityManagerService::InitInterceptorForScreenUnlock()
396 {
397     if (interceptorExecuter_) {
398         interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
399     }
400 }
401 
InitPushTask()402 void AbilityManagerService::InitPushTask()
403 {
404     if (taskHandler_ == nullptr) {
405         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler_ is nullptr.");
406         return;
407     }
408 
409     auto initStartupFlagTask = [aams = shared_from_this()]() { aams->InitStartupFlag(); };
410     taskHandler_->SubmitTask(initStartupFlagTask, "InitStartupFlag");
411 
412     auto initPrepareTerminateConfigTask = [aams = shared_from_this()]() { aams->InitPrepareTerminateConfig(); };
413     taskHandler_->SubmitTask(initPrepareTerminateConfigTask, "InitPrepareTerminateConfig");
414 
415     auto initExtensionConfigTask = []() {
416         DelayedSingleton<ExtensionConfig>::GetInstance()->LoadExtensionConfiguration();
417     };
418     taskHandler_->SubmitTask(initExtensionConfigTask, "InitExtensionConfigTask");
419 
420     auto bootCompletedTask = [handler = taskHandler_]() {
421         if (ApplicationUtil::IsBootCompleted()) {
422             auto task = []() {
423                 ApplicationUtil::AppFwkBootEventCallback(BOOTEVENT_BOOT_COMPLETED, "true", nullptr);
424             };
425             handler->SubmitTask(task, "BootCompletedDelayTask", BOOTEVENT_COMPLETED_DELAY_TIME);
426         } else {
427             WatchParameter(BOOTEVENT_BOOT_COMPLETED, ApplicationUtil::AppFwkBootEventCallback, nullptr);
428             TAG_LOGI(AAFwkTag::ABILITYMGR, "init call, InitPushTask suc");
429         }
430     };
431     if (!ParseJsonFromBoot(SUSPEND_SERVICE_CONFIG_FILE)) {
432         TAG_LOGE(AAFwkTag::ABILITYMGR, "Parse json from boot fail");
433     }
434     isParamStartAbilityEnable_ = system::GetBoolParameter(PARAM_PREVENT_STARTABILITY, false);
435     taskHandler_->SubmitTask(bootCompletedTask, "BootCompletedTask");
436 }
437 
InitStartupFlag()438 void AbilityManagerService::InitStartupFlag()
439 {
440     startUpNewRule_ = CheckNewRuleSwitchState(COMPONENT_STARTUP_NEW_RULES);
441     newRuleExceptLauncherSystemUI_ = CheckNewRuleSwitchState(NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI);
442     backgroundJudgeFlag_ = CheckNewRuleSwitchState(BACKGROUND_JUDGE_FLAG);
443     whiteListassociatedWakeUpFlag_ = CheckNewRuleSwitchState(WHITE_LIST_ASS_WAKEUP_FLAG);
444 }
445 
InitStartAbilityChain()446 void AbilityManagerService::InitStartAbilityChain()
447 {
448     auto startSandboxSaveFile = std::make_shared<StartAbilitySandboxSavefile>();
449     startAbilityChain_.emplace(startSandboxSaveFile->GetPriority(), startSandboxSaveFile);
450 }
451 
OnStop()452 void AbilityManagerService::OnStop()
453 {
454     TAG_LOGI(AAFwkTag::ABILITYMGR, "Stop ability manager service.");
455 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
456     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
457     if (bgtaskObserver_) {
458         int ret = BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver_);
459         if (ret != ERR_OK) {
460             TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bgtask failed, err:%{public}d.", ret);
461         }
462     }
463 #endif
464     if (abilityBundleEventCallback_) {
465         auto bms = GetBundleManager();
466         if (bms) {
467             bool ret = IN_PROCESS_CALL(bms->UnregisterBundleEventCallback(abilityBundleEventCallback_));
468             if (ret != ERR_OK) {
469                 TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bundle event callback failed, err:%{public}d.", ret);
470             }
471         }
472     }
473     eventHandler_.reset();
474     taskHandler_.reset();
475     state_ = ServiceRunningState::STATE_NOT_START;
476 }
477 
QueryServiceState() const478 ServiceRunningState AbilityManagerService::QueryServiceState() const
479 {
480     return state_;
481 }
482 
StartAbility(const Want & want,int32_t userId,int requestCode)483 int AbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode)
484 {
485     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
486     bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
487     bool hasWindowOptions = (want.HasParameter(Want::PARAM_RESV_WINDOW_LEFT) ||
488         want.HasParameter(Want::PARAM_RESV_WINDOW_TOP) ||
489         want.HasParameter(Want::PARAM_RESV_WINDOW_HEIGHT) ||
490         want.HasParameter(Want::PARAM_RESV_WINDOW_WIDTH));
491     TAG_LOGD(AAFwkTag::ABILITYMGR, "isDebugApp=%{public}d, hasWindowOptions=%{public}d",
492         static_cast<int>(isDebugApp), static_cast<int>(hasWindowOptions));
493     bool checkDeveloperModeFlag = (isDebugApp || hasWindowOptions);
494     if (checkDeveloperModeFlag) {
495         if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
496             TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
497             return ERR_NOT_DEVELOPER_MODE;
498         }
499     }
500     if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
501         TAG_LOGE(AAFwkTag::ABILITYMGR, "Screen need passord to unlock");
502         return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
503     }
504     TAG_LOGD(AAFwkTag::ABILITYMGR, "coldStart:%{public}d", want.GetBoolParam("coldStart", false));
505     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
506     if (startWithAccount || IsCrossUserCall(userId)) {
507         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
508         CHECK_CALLER_IS_SYSTEM_APP;
509     }
510     if (hasWindowOptions && !AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
511         TAG_LOGE(AAFwkTag::ABILITYMGR, "window options not supported");
512         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
513     }
514     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
515     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
516     EventInfo eventInfo = BuildEventInfo(want, userId);
517     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
518     int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
519     AAFWK::ContinueRadar::GetInstance().ClickIconStartAbility("StartAbilityWrap", want.GetFlags(), ret);
520     if (ret != ERR_OK) {
521         eventInfo.errCode = ret;
522         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
523     }
524     return ret;
525 }
526 
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)527 int AbilityManagerService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
528     int32_t userId, int requestCode)
529 {
530     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
531     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
532     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
533     return StartAbilityByFreeInstall(want, callerToken, userId, requestCode);
534 }
535 
StartAbilityByFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int32_t requestCode)536 int32_t AbilityManagerService::StartAbilityByFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
537     int32_t userId, int32_t requestCode)
538 {
539     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
540     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
541     if (startWithAccount || IsCrossUserCall(userId)) {
542         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
543         CHECK_CALLER_IS_SYSTEM_APP;
544     }
545     auto flags = want.GetFlags();
546     EventInfo eventInfo = BuildEventInfo(want, userId);
547     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
548     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
549         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed!");
550         eventInfo.errCode = ERR_INVALID_VALUE;
551         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
552         return ERR_INVALID_CONTINUATION_FLAG;
553     }
554 
555     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d",
556         want.GetElement().GetAbilityName().c_str(), userId);
557 
558     int32_t ret = StartAbilityWrap(want, callerToken, requestCode, false, userId);
559     if (ret != ERR_OK) {
560         eventInfo.errCode = ret;
561         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
562     }
563     return ret;
564 }
565 
StartAbilityWithSpecifyTokenId(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,int32_t userId,int requestCode)566 int AbilityManagerService::StartAbilityWithSpecifyTokenId(const Want &want, const sptr<IRemoteObject> &callerToken,
567     uint32_t specifyTokenId, int32_t userId, int requestCode)
568 {
569     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
570         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with specialId, the current process is not foundation process.");
571         return ERR_INVALID_CONTINUATION_FLAG;
572     }
573     return StartAbilityWithSpecifyTokenIdInner(want, callerToken, specifyTokenId, false, userId, requestCode);
574 }
575 
StartAbilityWithSpecifyTokenIdInner(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,bool isPendingWantCaller,int32_t userId,int requestCode)576 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const sptr<IRemoteObject> &callerToken,
577     uint32_t specifyTokenId, bool isPendingWantCaller, int32_t userId, int requestCode)
578 {
579     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
580     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
581     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
582     auto flags = want.GetFlags();
583     EventInfo eventInfo = BuildEventInfo(want, userId);
584     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
585     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
586         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed.");
587         eventInfo.errCode = ERR_INVALID_VALUE;
588         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
589         return ERR_INVALID_CONTINUATION_FLAG;
590     }
591 
592     TAG_LOGI(AAFwkTag::ABILITYMGR,
593         "Start ability come, ability is %{public}s, userId is %{public}d, specifyTokenId is %{public}u.",
594         want.GetElement().GetAbilityName().c_str(), userId, specifyTokenId);
595 
596     int32_t ret = StartAbilityWrap(want, callerToken, requestCode, isPendingWantCaller, userId, false, specifyTokenId);
597     if (ret != ERR_OK) {
598         eventInfo.errCode = ret;
599         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
600     }
601     return ret;
602 }
603 
StartAbilityWithSpecifyTokenIdInner(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId)604 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const StartOptions &startOptions,
605     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller,
606     int32_t userId, int requestCode, uint32_t callerTokenId)
607 {
608     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions by trigger.");
609     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
610     return StartUIAbilityForOptionWrap(
611         want, startOptions, callerToken, isPendingWantCaller, userId, requestCode, callerTokenId);
612 }
613 
StartAbilityByInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,uint64_t intentId,int32_t userId)614 int32_t AbilityManagerService::StartAbilityByInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken,
615     uint64_t intentId, int32_t userId)
616 {
617     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
618     std::string bundleNameFromWant = want.GetElement().GetBundleName();
619     std::string bundleNameFromIntentMgr = "";
620     if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->
621         GetBundleName(intentId, bundleNameFromIntentMgr) != ERR_OK) {
622         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched intentId");
623         return ERR_INVALID_VALUE;
624     }
625     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
626     if (abilityRecord == nullptr) {
627         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched token");
628         return ERR_INVALID_VALUE;
629     }
630     std::string bundleNameFromAbilityRecord = abilityRecord->GetAbilityInfo().bundleName;
631     if (!bundleNameFromWant.empty() && bundleNameFromWant == bundleNameFromIntentMgr &&
632         bundleNameFromWant == bundleNameFromAbilityRecord) {
633         AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
634         TAG_LOGI(AAFwkTag::ABILITYMGR, "bundleName match");
635         return StartAbility(want, callerToken, userId, -1);
636     }
637     TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleName not match");
638     return ERR_INSIGHT_INTENT_START_INVALID_COMPONENT;
639 }
640 
StartAbilityByUIContentSession(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)641 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const sptr<IRemoteObject> &callerToken,
642     const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
643 {
644     if (!callerToken || !sessionInfo) {
645         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo is nullptr");
646         return ERR_INVALID_VALUE;
647     }
648     sptr<IRemoteObject> token;
649     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
650         Rosen::FocusChangeInfo focusChangeInfo;
651         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
652         token = focusChangeInfo.abilityToken_;
653     } else {
654         if (!wmsHandler_) {
655             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
656             return ERR_INVALID_VALUE;
657         }
658         wmsHandler_->GetFocusWindow(token);
659     }
660 
661     if (!token) {
662         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
663         return ERR_INVALID_VALUE;
664     }
665 
666     if (token != sessionInfo->callerToken) {
667         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken is not equal to top ablity token");
668         return NOT_TOP_ABILITY;
669     }
670     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
671     return StartAbility(want, callerToken, userId, requestCode);
672 }
673 
StartAbilityByUIContentSession(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)674 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const StartOptions &startOptions,
675     const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
676 {
677     if (!callerToken || !sessionInfo) {
678         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo is nullptr");
679         return ERR_INVALID_VALUE;
680     }
681     sptr<IRemoteObject> token;
682     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
683         Rosen::FocusChangeInfo focusChangeInfo;
684         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
685         token = focusChangeInfo.abilityToken_;
686     } else {
687         if (!wmsHandler_) {
688             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
689             return ERR_INVALID_VALUE;
690         }
691         wmsHandler_->GetFocusWindow(token);
692     }
693 
694     if (!token) {
695         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
696         return ERR_INVALID_VALUE;
697     }
698 
699     if (token != sessionInfo->callerToken) {
700         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken is not equal to top ablity token");
701         return NOT_TOP_ABILITY;
702     }
703     return StartAbility(want, startOptions, callerToken, userId, requestCode);
704 }
705 
StartAbilityOnlyUIAbility(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId)706 int AbilityManagerService::StartAbilityOnlyUIAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
707     uint32_t specifyTokenId)
708 {
709     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
710         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with specialId, the current process is not foundation process.");
711         return ERR_INVALID_CONTINUATION_FLAG;
712     }
713 
714     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
715     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
716     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
717     auto flags = want.GetFlags();
718     EventInfo eventInfo = BuildEventInfo(want, DEFAULT_INVAL_VALUE);
719     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
720     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
721         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed.");
722         eventInfo.errCode = ERR_INVALID_VALUE;
723         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
724         return ERR_INVALID_CONTINUATION_FLAG;
725     }
726 
727     TAG_LOGI(AAFwkTag::ABILITYMGR,
728         "Start ability come, ability is %{public}s, userId is %{public}d, specifyTokenId is %{public}u.",
729         want.GetElement().GetAbilityName().c_str(), DEFAULT_INVAL_VALUE, specifyTokenId);
730 
731     int32_t ret = StartAbilityWrap(want, callerToken, DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, specifyTokenId, false, false, true);
732     if (ret != ERR_OK) {
733         eventInfo.errCode = ret;
734         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
735     }
736     return ret;
737 }
738 
StartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)739 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
740     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
741 {
742     return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, requestCode);
743 }
744 
ImplicitStartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)745 int AbilityManagerService::ImplicitStartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
746     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
747 {
748     return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId,
749         requestCode, true);
750 }
751 
StartAbilityAsCallerDetails(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode,bool isImplicit,bool isAppCloneSelector)752 int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const sptr<IRemoteObject> &callerToken,
753     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode, bool isImplicit, bool isAppCloneSelector)
754 {
755     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
756     CHECK_CALLER_IS_SYSTEM_APP;
757     auto flags = want.GetFlags();
758     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
759     EventInfo eventInfo = BuildEventInfo(want, userId);
760     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
761     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
762         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed!");
763         eventInfo.errCode = ERR_INVALID_VALUE;
764         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
765         return ERR_INVALID_CONTINUATION_FLAG;
766     }
767 
768     AAFwk::Want newWant = want;
769     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
770     TAG_LOGI(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d",
771         want.GetElement().GetAbilityName().c_str(), userId);
772     std::string callerPkg;
773     std::string targetPkg;
774     if (AbilityUtil::CheckJumpInterceptorWant(newWant, callerPkg, targetPkg)) {
775         TAG_LOGI(AAFwkTag::ABILITYMGR,
776             "the call is from interceptor dialog, callerPkg:%{public}s, targetPkg:%{public}s",
777             callerPkg.c_str(), targetPkg.c_str());
778         AbilityUtil::AddAbilityJumpRuleToBms(callerPkg, targetPkg, GetUserId());
779     }
780     int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true,
781         0, false, isImplicit, false, isAppCloneSelector);
782     if (ret != ERR_OK) {
783         eventInfo.errCode = ret;
784         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
785     }
786     return ret;
787 }
788 
StartAbilityPublicPrechainCheck(StartAbilityParams & params)789 int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams &params)
790 {
791     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
792     // 1. CheckCallerToken
793     if (params.callerToken != nullptr && !VerificationAllToken(params.callerToken)) {
794         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
795             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
796         if (!isSpecificSA) {
797             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
798             return ERR_INVALID_CALLER;
799         }
800         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__);
801     }
802 
803     // 2. validUserId, multi-user
804     if (!JudgeMultiUserConcurrency(params.GetValidUserId())) {
805         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
806         return ERR_CROSS_USER;
807     }
808 
809     return ERR_OK;
810 }
811 
StartAbilityPrechainInterceptor(StartAbilityParams & params)812 int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams &params)
813 {
814     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
815     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(params.want, params.requestCode,
816         GetUserId(), true, nullptr);
817     auto interceptorResult = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
818         interceptorExecuter_->DoProcess(interceptorParam);
819     if (interceptorResult != ERR_OK) {
820         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
821         return interceptorResult;
822     }
823 
824     return ERR_OK;
825 }
826 
StartAbilityInChain(StartAbilityParams & params,int & result)827 bool AbilityManagerService::StartAbilityInChain(StartAbilityParams &params, int &result)
828 {
829     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
830     std::shared_ptr<StartAbilityHandler> reqHandler;
831     for (const auto &item : startAbilityChain_) {
832         if (item.second->MatchStartRequest(params)) {
833             reqHandler = item.second;
834             break;
835         }
836     }
837 
838     if (!reqHandler) {
839         return false;
840     }
841 
842     result = StartAbilityPublicPrechainCheck(params);
843     if (result != ERR_OK) {
844         return true;
845     }
846     result = StartAbilityPrechainInterceptor(params);
847     if (result != ERR_OK) {
848         return true;
849     }
850     result = reqHandler->HandleStartRequest(params);
851     return true;
852 }
853 
StartAbilityWrap(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,bool isPendingWantCaller,int32_t userId,bool isStartAsCaller,uint32_t specifyToken,bool isForegroundToRestartApp,bool isImplicit,bool isUIAbilityOnly,bool isAppCloneSelector)854 int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr<IRemoteObject> &callerToken,
855     int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyToken,
856     bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly, bool isAppCloneSelector)
857 {
858     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
859     StartAbilityParams startParams(const_cast<Want &>(want));
860     startParams.callerToken = callerToken;
861     startParams.userId = userId;
862     startParams.requestCode = requestCode;
863     startParams.isStartAsCaller = isStartAsCaller;
864     startParams.SetValidUserId(GetValidUserId(userId));
865 
866     int result = ERR_OK;
867     if (StartAbilityInChain(startParams, result)) {
868         return result;
869     }
870 
871     return StartAbilityInner(want, callerToken, requestCode, isPendingWantCaller, userId, isStartAsCaller, specifyToken,
872         isForegroundToRestartApp, isImplicit, isUIAbilityOnly, isAppCloneSelector);
873 }
874 
SetReserveInfo(const std::string & linkString,AbilityRequest & abilityRequest)875 void AbilityManagerService::SetReserveInfo(const std::string &linkString, AbilityRequest& abilityRequest)
876 {
877     if (!linkString.size()) {
878         return;
879     }
880 
881     std::string reservedBundleName = "";
882     if (DeepLinkReserveConfig::GetInstance().isLinkReserved(linkString, reservedBundleName)) {
883         abilityRequest.uriReservedFlag = true;
884         abilityRequest.reservedBundleName = reservedBundleName;
885     } else {
886         abilityRequest.uriReservedFlag = false;
887         abilityRequest.reservedBundleName = reservedBundleName;
888     }
889 }
890 
CheckExtensionCallPermission(const Want & want,const AbilityRequest & abilityRequest,uint32_t specifyTokenId)891 int AbilityManagerService::CheckExtensionCallPermission(const Want& want, const AbilityRequest& abilityRequest,
892     uint32_t specifyTokenId)
893 {
894     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "startExtensionCheck");
895     auto isSACall = AAFwk::PermissionVerification::GetInstance()->IsSACallByTokenId(specifyTokenId);
896     auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCallByTokenId(specifyTokenId);
897     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCallByTokenId(specifyTokenId);
898     auto isToPermissionMgr = IsTargetPermission(want);
899     if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) {
900         TAG_LOGE(AAFwkTag::ABILITYMGR,
901             "Cannot start extension by start ability, use startServiceExtensionAbility.");
902         return ERR_WRONG_INTERFACE_CALL;
903     }
904     int result = CheckCallServicePermission(abilityRequest);
905     if (result != ERR_OK) {
906         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
907     }
908     return result;
909 }
910 
CheckServiceCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)911 int AbilityManagerService::CheckServiceCallPermission(const AbilityRequest& abilityRequest,
912     const AppExecFwk::AbilityInfo& abilityInfo)
913 {
914     TAG_LOGD(AAFwkTag::ABILITYMGR,
915         "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
916     int result = CheckCallServicePermission(abilityRequest);
917     if (result != ERR_OK) {
918         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
919     }
920     return result;
921 }
922 
CheckBrokerCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)923 int AbilityManagerService::CheckBrokerCallPermission(const AbilityRequest& abilityRequest,
924     const AppExecFwk::AbilityInfo& abilityInfo)
925 {
926     // temp add for broker, remove when delete issacall
927     if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) {
928         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check permission failed");
929         return CHECK_PERMISSION_FAILED;
930     }
931     TAG_LOGD(AAFwkTag::ABILITYMGR,
932         "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
933     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
934     if (collaborator == nullptr) {
935         TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator is nullptr.");
936         return CHECK_PERMISSION_FAILED;
937     }
938     int result = collaborator->CheckCallAbilityPermission(abilityRequest.want);
939     if (result != ERR_OK) {
940         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker.");
941         return CHECK_PERMISSION_FAILED;
942     }
943     return result;
944 }
945 
CheckAbilityCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,uint32_t specifyTokenId)946 int AbilityManagerService::CheckAbilityCallPermission(const AbilityRequest& abilityRequest,
947     const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId)
948 {
949     TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
950     int result = CheckCallAbilityPermission(abilityRequest, specifyTokenId);
951     if (result != ERR_OK) {
952         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
953     }
954     return result;
955 }
956 
CheckCallPermission(const Want & want,const AppExecFwk::AbilityInfo & abilityInfo,const AbilityRequest & abilityRequest,bool isForegroundToRestartApp,bool isSendDialogResult,uint32_t specifyTokenId,const std::string & callerBundleName)957 int AbilityManagerService::CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
958     const AbilityRequest& abilityRequest, bool isForegroundToRestartApp,
959     bool isSendDialogResult, uint32_t specifyTokenId,
960     const std::string& callerBundleName)
961 {
962     auto type = abilityInfo.type;
963     if (type == AppExecFwk::AbilityType::DATA) {
964         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot start data ability by start ability.");
965         return ERR_WRONG_INTERFACE_CALL;
966     }
967     if (type == AppExecFwk::AbilityType::EXTENSION) {
968         return CheckExtensionCallPermission(want, abilityRequest, specifyTokenId);
969     }
970     if (type == AppExecFwk::AbilityType::SERVICE) {
971         return CheckServiceCallPermission(abilityRequest, abilityInfo);
972     }
973     if ((callerBundleName == SHELL_ASSISTANT_BUNDLENAME && AppUtils::GetInstance().IsSupportAncoApp()) ||
974         IPCSkeleton::GetCallingUid() == BROKER_UID) {
975         return CheckBrokerCallPermission(abilityRequest, abilityInfo);
976     }
977     if (!isForegroundToRestartApp && (!isSendDialogResult || want.GetBoolParam("isSelector", false))) {
978         return CheckAbilityCallPermission(abilityRequest, abilityInfo, specifyTokenId);
979     }
980     return ERR_OK;
981 }
982 
StartAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,bool isPendingWantCaller,int32_t userId,bool isStartAsCaller,uint32_t specifyTokenId,bool isForegroundToRestartApp,bool isImplicit,bool isUIAbilityOnly,bool isAppCloneSelector)983 int AbilityManagerService::StartAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
984     int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyTokenId,
985     bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly, bool isAppCloneSelector)
986 {
987     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
988     std::string dialogSessionId = want.GetStringParam("dialogSessionId");
989     bool isSendDialogResult = false;
990 #ifdef SUPPORT_SCREEN
991     if (!dialogSessionId.empty() &&
992         DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId) != nullptr) {
993         isSendDialogResult = true;
994     }
995 #endif // SUPPORT_SCREEN
996 
997     // prevent the app from dominating the screen
998     if (system::GetBoolParameter(VERIFY_DOMINATE_SCREEN, true) &&
999         callerToken == nullptr && !IsCallerSceneBoard() && !isSendDialogResult && !isForegroundToRestartApp &&
1000         AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1001         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is invalid.");
1002         return ERR_INVALID_CALLER;
1003     }
1004     {
1005 #ifdef WITH_DLP
1006         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1007         if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1008             VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1009             !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1010             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed.", __func__);
1011             return CHECK_PERMISSION_FAILED;
1012         }
1013 
1014         if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1015             InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1016             return StartExtensionAbilityInner(want, callerToken, userId,
1017                 AppExecFwk::ExtensionAbilityType::SERVICE, false, false, true, isStartAsCaller);
1018         }
1019 #endif // WITH_DLP
1020     }
1021 
1022     AbilityUtil::RemoveWindowModeKey(const_cast<Want &>(want));
1023     if (callerToken != nullptr && !VerificationAllToken(callerToken) && !isSendDialogResult) {
1024         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
1025             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
1026         if (!isSpecificSA) {
1027             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
1028             return ERR_INVALID_CALLER;
1029         }
1030         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__);
1031     }
1032 
1033     int32_t oriValidUserId = GetValidUserId(userId);
1034     int32_t validUserId = oriValidUserId;
1035     SetTargetCloneIndexInSameBundle(want, callerToken);
1036     int32_t appIndex = 0;
1037     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1038         return ERR_APP_CLONE_INDEX_INVALID;
1039     }
1040     if (!isForegroundToRestartApp) {
1041         auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1042             validUserId, appIndex, callerToken);
1043         if (checkRet != ERR_OK) {
1044             return checkRet;
1045         }
1046     }
1047     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1048     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1049         true, nullptr);
1050     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1051         interceptorExecuter_->DoProcess(interceptorParam);
1052     if (result != ERR_OK) {
1053         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1054         return result;
1055     }
1056 
1057     if (callerToken != nullptr && CheckIfOperateRemote(want)) {
1058         TAG_LOGI(AAFwkTag::ABILITYMGR, "try to StartRemoteAbility");
1059         return StartRemoteAbility(want, requestCode, validUserId, callerToken);
1060     }
1061 
1062     if (!JudgeMultiUserConcurrency(validUserId)) {
1063         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1064         return ERR_CROSS_USER;
1065     }
1066 
1067     AbilityRequest abilityRequest;
1068 #ifdef SUPPORT_GRAPHICS
1069     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1070         auto checkResult = AbilityUtil::CheckInstanceKey(want);
1071         if (checkResult != ERR_OK) {
1072             return checkResult;
1073         }
1074         abilityRequest.Voluation(want, requestCode, callerToken);
1075         if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1076             UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1077         } else if (!isStartAsCaller) {
1078             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1079             UpdateCallerInfo(abilityRequest.want, callerToken);
1080         } else {
1081             TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1082         }
1083         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1084         SetReserveInfo(want.GetUriString(), abilityRequest);
1085         return implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1086     }
1087     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1088         return ShowPickerDialog(want, validUserId, callerToken);
1089     }
1090 #endif
1091     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1092     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1093     std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
1094     bool selfFreeInstallEnable = (result == RESOLVE_ABILITY_ERR && want.GetElement().GetModuleName() != "" &&
1095                                   want.GetElement().GetBundleName() == callerBundleName);
1096     bool isStartFreeInstallByWant = AbilityUtil::IsStartFreeInstall(want);
1097     if (isStartFreeInstallByWant || selfFreeInstallEnable) {
1098         Want localWant;
1099         auto freeInstallResult = PreStartFreeInstall(want, callerToken, specifyTokenId, isStartAsCaller, localWant);
1100         if (freeInstallResult != ERR_OK) {
1101             TAG_LOGE(AAFwkTag::ABILITYMGR, "PreStartFreeInstall failed.");
1102             return freeInstallResult;
1103         }
1104 
1105         if (isStartFreeInstallByWant) {
1106             return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode,
1107                 callerToken, true, specifyTokenId);
1108         }
1109         int32_t ret = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, false);
1110         if (ret == ERR_OK) {
1111             result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1112         }
1113     }
1114 
1115     if (result != ERR_OK) {
1116         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
1117         return result;
1118     }
1119 
1120     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1121         UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1122     } else if (!isStartAsCaller) {
1123         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1124         UpdateCallerInfo(abilityRequest.want, callerToken);
1125     } else if (callerBundleName == BUNDLE_NAME_DIALOG ||
1126         (isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1127         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1128         int32_t flag = false;
1129         if (callerBundleName == BUNDLE_NAME_DIALOG) {
1130             flag = true;
1131         }
1132         implicitStartProcessor_->ResetCallingIdentityAsCaller(
1133             abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), flag);
1134     }
1135 
1136     auto abilityInfo = abilityRequest.abilityInfo;
1137     if (isUIAbilityOnly && abilityInfo.type != AbilityType::PAGE) {
1138         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability type is not UIAbility");
1139         return ERR_INVALID_VALUE;
1140     }
1141     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1142     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
1143         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1144 
1145     if ((isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1146         isImplicit = true;
1147     }
1148     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1149         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1150     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1151         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1152         return ERR_STATIC_CFG_PERMISSION;
1153     }
1154 
1155     if (!isAppCloneSelector) {
1156         result = CheckCallPermission(want, abilityInfo, abilityRequest, isForegroundToRestartApp,
1157             isSendDialogResult, specifyTokenId, callerBundleName);
1158         if (result != ERR_OK) {
1159             TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallPermission error, result is %{public}d.", result);
1160             return result;
1161         }
1162 
1163         Want newWant = abilityRequest.want;
1164         AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1165             true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1166         result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1167             afterCheckExecuter_->DoProcess(afterCheckParam);
1168         bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1169         newWant.RemoveParam("queryWantFromErms");
1170         if (result != ERR_OK && isReplaceWantExist == false) {
1171             TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
1172             return result;
1173         }
1174     #ifdef SUPPORT_SCREEN
1175         if (result != ERR_OK && isReplaceWantExist && !isSendDialogResult &&
1176             callerBundleName != BUNDLE_NAME_DIALOG) {
1177             return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1178         }
1179         if (result == ERR_OK &&
1180             DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1181             TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1182             return CreateCloneSelectorDialog(abilityRequest, GetUserId());
1183         }
1184     #endif
1185     }
1186     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1187         TAG_LOGD(AAFwkTag::ABILITYMGR, "PreLoadAppDataAbilities:%{public}s.", abilityInfo.bundleName.c_str());
1188         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1189         if (result != ERR_OK) {
1190             TAG_LOGE(AAFwkTag::ABILITYMGR,
1191                 "StartAbility: App data ability preloading failed, '%{public}s', %{public}d.",
1192                 abilityInfo.bundleName.c_str(), result);
1193             return result;
1194         }
1195     }
1196 
1197     if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
1198         abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
1199         SendStartAbilityOtherExtensionEvent(abilityInfo, abilityRequest.want, specifyTokenId);
1200         return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
1201     }
1202 
1203     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1204         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s.", abilityInfo.bundleName.c_str());
1205         return ERR_WOULD_BLOCK;
1206     }
1207 
1208     auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1209     UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1210     StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1211 
1212     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1213     if (specifyTokenId > 0) {
1214         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
1215         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1216         abilityRequest.specifyTokenId = specifyTokenId;
1217     }
1218     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1219     // sceneboard
1220     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1221         ReportEventToRSS(abilityInfo, abilityRequest.callerToken);
1222         abilityRequest.userId = oriValidUserId;
1223         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1224         // other sa or shell can not use continueSessionId and persistentId
1225         auto abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
1226         if (abilityRecord == nullptr &&
1227             !PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
1228             TAG_LOGW(AAFwkTag::ABILITYMGR, "StartAbilityInner, Remove continueSessionId and persistentId");
1229             abilityRequest.want.RemoveParam(DMS_CONTINUED_SESSION_ID);
1230             abilityRequest.want.RemoveParam(DMS_PERSISTENT_ID);
1231         }
1232         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1233         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1234         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1235     }
1236 
1237     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1238     if (missionListManager == nullptr) {
1239         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is nullptr. userId=%{public}d", validUserId);
1240         return ERR_INVALID_VALUE;
1241     }
1242 
1243     ReportAbilityStartInfoToRSS(abilityInfo);
1244     ReportEventToRSS(abilityInfo, callerToken);
1245     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability, name is %{public}s.", abilityInfo.name.c_str());
1246     return missionListManager->StartAbility(abilityRequest);
1247 }
1248 
PreStartFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,uint32_t specifyTokenId,bool isStartAsCaller,Want & localWant)1249 int AbilityManagerService::PreStartFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
1250     uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant)
1251 {
1252     if (freeInstallManager_ == nullptr) {
1253         return ERR_INVALID_VALUE;
1254     }
1255     (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1256     localWant = want;
1257     if (!localWant.GetDeviceId().empty()) {
1258         localWant.SetDeviceId("");
1259     }
1260     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1261         UpdateCallerInfoFromToken(localWant, callerToken);
1262     } else if (!isStartAsCaller) {
1263         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1264         UpdateCallerInfo(localWant, callerToken);
1265     } else {
1266         TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1267     }
1268     return ERR_OK;
1269 }
1270 
StartAbilityByConnectManager(const Want & want,const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,int validUserId,sptr<IRemoteObject> callerToken)1271 int AbilityManagerService::StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest,
1272     const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr<IRemoteObject> callerToken)
1273 {
1274     auto connectManager = GetConnectManagerByUserId(validUserId);
1275     if (!connectManager) {
1276         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
1277         return ERR_INVALID_VALUE;
1278     }
1279     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start service or extension, name is %{public}s.", abilityInfo.name.c_str());
1280     ReportEventToRSS(abilityInfo, callerToken);
1281     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1282     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(const_cast<Want &>(abilityRequest.want),
1283         abilityRequest.abilityInfo.extensionAbilityType);
1284     return connectManager->StartAbility(abilityRequest);
1285 }
1286 
StartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1287 int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1288     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1289 {
1290     return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode);
1291 }
1292 
ImplicitStartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1293 int AbilityManagerService::ImplicitStartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1294     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1295 {
1296     return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode, true);
1297 }
1298 
StartAbilityDetails(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode,bool isImplicit)1299 int AbilityManagerService::StartAbilityDetails(const Want &want, const AbilityStartSetting &abilityStartSetting,
1300     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isImplicit)
1301 {
1302     if (want.GetBoolParam(DEBUG_APP, false) && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
1303         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
1304         return ERR_NOT_DEVELOPER_MODE;
1305     }
1306     if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
1307         TAG_LOGE(AAFwkTag::ABILITYMGR, "Screen need passord to unlock");
1308         return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
1309     }
1310     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1311     StartAbilityParams startParams(const_cast<Want &>(want));
1312     startParams.callerToken = callerToken;
1313     startParams.userId = userId;
1314     startParams.requestCode = requestCode;
1315     startParams.SetValidUserId(GetValidUserId(userId));
1316 
1317     int result = ERR_OK;
1318     if (StartAbilityInChain(startParams, result)) {
1319         return result;
1320     }
1321 
1322     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1323     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability setting.");
1324     if (IsCrossUserCall(userId)) {
1325         CHECK_CALLER_IS_SYSTEM_APP;
1326     }
1327     EventInfo eventInfo = BuildEventInfo(want, userId);
1328     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1329 
1330 #ifdef WITH_DLP
1331     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1332         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1333         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1334         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
1335         eventInfo.errCode = CHECK_PERMISSION_FAILED;
1336         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1337         return CHECK_PERMISSION_FAILED;
1338     }
1339 #endif // WITH_DLP
1340 
1341     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1342         eventInfo.errCode = ERR_INVALID_VALUE;
1343         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1344         return ERR_INVALID_CALLER;
1345     }
1346 
1347     int32_t oriValidUserId = GetValidUserId(userId);
1348     int32_t validUserId = oriValidUserId;
1349     int32_t appIndex = 0;
1350     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1351         return ERR_APP_CLONE_INDEX_INVALID;
1352     }
1353     auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1354         validUserId, appIndex, callerToken);
1355     if (checkRet != ERR_OK) {
1356         return checkRet;
1357     }
1358     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1359     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1360         true, nullptr);
1361     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1362         interceptorExecuter_->DoProcess(interceptorParam);
1363     if (result != ERR_OK) {
1364         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1365         eventInfo.errCode = result;
1366         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1367         return result;
1368     }
1369 
1370     if (AbilityUtil::IsStartFreeInstall(want)) {
1371         if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1372             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1373             return ERR_INVALID_VALUE;
1374         }
1375         (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1376         Want localWant = want;
1377         UpdateCallerInfo(localWant, callerToken);
1378         return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true);
1379     }
1380 
1381     if (!JudgeMultiUserConcurrency(validUserId)) {
1382         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1383         eventInfo.errCode = ERR_INVALID_VALUE;
1384         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1385         return ERR_CROSS_USER;
1386     }
1387 
1388     AbilityRequest abilityRequest;
1389 #ifdef SUPPORT_GRAPHICS
1390     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1391         auto checkResult = AbilityUtil::CheckInstanceKey(want);
1392         if (checkResult != ERR_OK) {
1393             return checkResult;
1394         }
1395         abilityRequest.Voluation(
1396             want, requestCode, callerToken, std::make_shared<AbilityStartSetting>(abilityStartSetting));
1397         abilityRequest.callType = AbilityCallType::START_SETTINGS_TYPE;
1398         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1399         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1400         if (result != ERR_OK) {
1401             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error.");
1402             eventInfo.errCode = result;
1403             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1404         }
1405         return result;
1406     }
1407     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1408         return ShowPickerDialog(want, validUserId, callerToken);
1409     }
1410 #endif
1411     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1412     if (result != ERR_OK) {
1413         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
1414         eventInfo.errCode = result;
1415         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1416         return result;
1417     }
1418     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1419 
1420     auto abilityInfo = abilityRequest.abilityInfo;
1421     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1422     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1423         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1424 
1425     result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
1426     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1427         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1428         eventInfo.errCode = result;
1429         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1430         return ERR_STATIC_CFG_PERMISSION;
1431     }
1432     result = CheckCallAbilityPermission(abilityRequest);
1433     if (result != ERR_OK) {
1434         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error.", __func__);
1435         eventInfo.errCode = result;
1436         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1437         return result;
1438     }
1439 
1440     abilityRequest.startSetting = std::make_shared<AbilityStartSetting>(abilityStartSetting);
1441 
1442     if (abilityInfo.type == AppExecFwk::AbilityType::DATA) {
1443         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot start data ability, use 'AcquireDataAbility()' instead.");
1444         eventInfo.errCode = ERR_INVALID_VALUE;
1445         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1446         return ERR_WRONG_INTERFACE_CALL;
1447     }
1448 
1449     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
1450         GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
1451     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1452         afterCheckExecuter_->DoProcess(afterCheckParam);
1453     if (result != ERR_OK) {
1454         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
1455         return result;
1456     }
1457 
1458     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1459         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1460         if (result != ERR_OK) {
1461             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
1462                 abilityInfo.bundleName.c_str(),
1463                 result);
1464             eventInfo.errCode = result;
1465             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1466             return result;
1467         }
1468     }
1469 #ifdef SUPPORT_GRAPHICS
1470     if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1471         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support for page type ability.");
1472         eventInfo.errCode = ERR_INVALID_VALUE;
1473         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1474         return ERR_WRONG_INTERFACE_CALL;
1475     }
1476 #endif
1477     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1478         eventInfo.errCode = ERR_WOULD_BLOCK;
1479         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1480         return ERR_WOULD_BLOCK;
1481     }
1482     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1483         UpdateCallerInfo(abilityRequest.want, callerToken);
1484         abilityRequest.userId = oriValidUserId;
1485         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1486         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1487         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1488         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1489     }
1490     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1491     if (missionListManager == nullptr) {
1492         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", validUserId);
1493         eventInfo.errCode = ERR_INVALID_VALUE;
1494         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1495         return ERR_INVALID_VALUE;
1496     }
1497     UpdateCallerInfo(abilityRequest.want, callerToken);
1498     auto ret = missionListManager->StartAbility(abilityRequest);
1499     if (ret != ERR_OK) {
1500         eventInfo.errCode = ret;
1501         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1502     }
1503     return ret;
1504 }
1505 
StartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1506 int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions,
1507     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1508 {
1509     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1510     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions.");
1511     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1512     return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode);
1513 }
1514 
ImplicitStartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1515 int AbilityManagerService::ImplicitStartAbility(const Want &want, const StartOptions &startOptions,
1516     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1517 {
1518     TAG_LOGD(AAFwkTag::ABILITYMGR, "Implicit Start ability with startOptions.");
1519     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1520     return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode, 0, true);
1521 }
1522 
StartUIAbilityForOptionWrap(const Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId,bool isImplicit,bool isCallByShortcut)1523 int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options,
1524     sptr<IRemoteObject> callerToken, bool isPendingWantCaller, int32_t userId,
1525     int requestCode, uint32_t callerTokenId, bool isImplicit,
1526     bool isCallByShortcut)
1527 {
1528     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1529     auto ret = CheckProcessOptions(want, options, userId);
1530     if (ret != ERR_OK) {
1531         return ret;
1532     }
1533     return StartAbilityForOptionWrap(want, options, callerToken, isPendingWantCaller, userId, requestCode, false,
1534         callerTokenId, isImplicit, isCallByShortcut);
1535 }
1536 
StartAbilityAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)1537 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOptions &startOptions,
1538     const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken,
1539     int32_t userId, int requestCode)
1540 {
1541     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability as caller with startOptions.");
1542     CHECK_CALLER_IS_SYSTEM_APP;
1543 
1544     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1545     AAFwk::Want newWant = want;
1546     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1547     return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1548 }
1549 
StartAbilityForResultAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1550 int AbilityManagerService::StartAbilityForResultAsCaller(
1551     const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1552 {
1553     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1554     CHECK_CALLER_IS_SYSTEM_APP;
1555     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1556 
1557     AAFwk::Want newWant = want;
1558     auto connectManager = GetCurrentConnectManager();
1559     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1560     auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1561     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1562     return StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true);
1563 }
1564 
StartAbilityForResultAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1565 int AbilityManagerService::StartAbilityForResultAsCaller(const Want &want, const StartOptions &startOptions,
1566     const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1567 {
1568     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1569     CHECK_CALLER_IS_SYSTEM_APP;
1570 
1571     AAFwk::Want newWant = want;
1572     auto connectManager = GetCurrentConnectManager();
1573     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1574     auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1575     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1576     return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1577 }
1578 
StartAbilityForOptionWrap(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,bool isStartAsCaller,uint32_t callerTokenId,bool isImplicit,bool isCallByShortcut)1579 int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const StartOptions &startOptions,
1580     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1581     bool isStartAsCaller, uint32_t callerTokenId, bool isImplicit, bool isCallByShortcut)
1582 {
1583     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1584     StartAbilityParams startParams(const_cast<Want &>(want));
1585     startParams.callerToken = callerToken;
1586     startParams.userId = userId;
1587     startParams.requestCode = requestCode;
1588     startParams.isStartAsCaller = isStartAsCaller;
1589     startParams.startOptions = &startOptions;
1590     startParams.SetValidUserId(GetValidUserId(userId));
1591 
1592     int result = ERR_OK;
1593     if (StartAbilityInChain(startParams, result)) {
1594         return result;
1595     }
1596 
1597     return StartAbilityForOptionInner(want, startOptions, callerToken, isPendingWantCaller, userId, requestCode,
1598         isStartAsCaller, callerTokenId, isImplicit, isCallByShortcut);
1599 }
1600 
StartAbilityForOptionInner(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,bool isStartAsCaller,uint32_t specifyTokenId,bool isImplicit,bool isCallByShortcut)1601 int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const StartOptions &startOptions,
1602     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1603     bool isStartAsCaller, uint32_t specifyTokenId, bool isImplicit, bool isCallByShortcut)
1604 {
1605     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1606     // prevent the app from dominating the screen
1607     if (system::GetBoolParameter(VERIFY_DOMINATE_SCREEN, true) &&
1608         callerToken == nullptr && !IsCallerSceneBoard() && !isCallByShortcut &&
1609         AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1610         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is invalid.");
1611         return ERR_INVALID_CALLER;
1612     }
1613 
1614     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
1615     if (startWithAccount || IsCrossUserCall(userId)) {
1616         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
1617         CHECK_CALLER_IS_SYSTEM_APP;
1618     }
1619     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1620     EventInfo eventInfo = BuildEventInfo(want, userId);
1621     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1622 
1623 #ifdef WITH_DLP
1624     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1625         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1626         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1627         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
1628         eventInfo.errCode = CHECK_PERMISSION_FAILED;
1629         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1630         return CHECK_PERMISSION_FAILED;
1631     }
1632 #endif // WITH_DLP
1633 
1634     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1635         eventInfo.errCode = ERR_INVALID_VALUE;
1636         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1637         return ERR_INVALID_CALLER;
1638     }
1639 
1640     int32_t oriValidUserId = GetValidUserId(userId);
1641     int32_t validUserId = oriValidUserId;
1642     SetTargetCloneIndexInSameBundle(want, callerToken);
1643     int32_t appIndex = 0;
1644     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1645         return ERR_APP_CLONE_INDEX_INVALID;
1646     }
1647     auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1648         validUserId, appIndex, callerToken);
1649     if (checkRet != ERR_OK) {
1650         return checkRet;
1651     }
1652     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1653     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1654         true, nullptr);
1655     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1656         interceptorExecuter_->DoProcess(interceptorParam);
1657     if (result != ERR_OK) {
1658         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1659         eventInfo.errCode = result;
1660         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1661         return result;
1662     }
1663 
1664     if (AbilityUtil::IsStartFreeInstall(want)) {
1665         if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1666             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1667             return ERR_INVALID_VALUE;
1668         }
1669         (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1670         Want localWant = want;
1671         if (!isStartAsCaller) {
1672             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1673             UpdateCallerInfo(localWant, callerToken);
1674         } else {
1675             TAG_LOGI(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1676         }
1677         return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode,
1678             callerToken, true, specifyTokenId);
1679     }
1680     if (!JudgeMultiUserConcurrency(validUserId)) {
1681         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1682         eventInfo.errCode = ERR_INVALID_VALUE;
1683         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1684         return ERR_CROSS_USER;
1685     }
1686 
1687     AbilityRequest abilityRequest;
1688 #ifdef SUPPORT_GRAPHICS
1689     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1690         auto checkResult = AbilityUtil::CheckInstanceKey(want);
1691         if (checkResult != ERR_OK) {
1692             return checkResult;
1693         }
1694         abilityRequest.Voluation(want, requestCode, callerToken);
1695         if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
1696             bool windowFocused = startOptions.GetWindowFocused();
1697             abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowFocused);
1698         } else {
1699             abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
1700         }
1701         if (startOptions.GetDisplayID() == 0) {
1702             abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1703                 static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1704         } else {
1705             abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1706         }
1707         WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
1708         abilityRequest.callType = AbilityCallType::START_OPTIONS_TYPE;
1709         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1710         if (specifyTokenId > 0 && callerToken) { // for sa specify tokenId and caller token
1711             UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1712         } else if (!isStartAsCaller) {
1713             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1714             UpdateCallerInfo(abilityRequest.want, callerToken);
1715         } else {
1716             TAG_LOGI(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1717         }
1718         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId,
1719             startOptions.GetWindowMode());
1720         if (result != ERR_OK) {
1721             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error.");
1722             eventInfo.errCode = result;
1723             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1724         }
1725         return result;
1726     }
1727     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1728         return ShowPickerDialog(want, validUserId, callerToken);
1729     }
1730 #endif
1731     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1732     if (result != ERR_OK) {
1733         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
1734         eventInfo.errCode = result;
1735         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1736         return result;
1737     }
1738 
1739     if (!isStartAsCaller) {
1740         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1741         UpdateCallerInfo(abilityRequest.want, callerToken);
1742     } else {
1743         TAG_LOGI(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1744     }
1745     auto abilityInfo = abilityRequest.abilityInfo;
1746     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1747     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1748         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1749 
1750     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1751         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1752     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1753         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1754         eventInfo.errCode = result;
1755         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1756         return ERR_STATIC_CFG_PERMISSION;
1757     }
1758     result = CheckCallAbilityPermission(abilityRequest, 0, isCallByShortcut);
1759     if (result != ERR_OK) {
1760         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error.", __func__);
1761         eventInfo.errCode = result;
1762         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1763         return result;
1764     }
1765 
1766     if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1767         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support for page type ability.");
1768         eventInfo.errCode = ERR_INVALID_VALUE;
1769         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1770         return ERR_INVALID_VALUE;
1771     }
1772 
1773     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1774         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1775         if (result != ERR_OK) {
1776             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
1777                 abilityInfo.bundleName.c_str(),
1778                 result);
1779             eventInfo.errCode = result;
1780             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1781             return result;
1782         }
1783     }
1784 
1785     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1786         eventInfo.errCode = ERR_WOULD_BLOCK;
1787         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1788         return ERR_WOULD_BLOCK;
1789     }
1790 #ifdef SUPPORT_GRAPHICS
1791     if (abilityInfo.isStageBasedModel && !CheckWindowMode(startOptions.GetWindowMode(), abilityInfo.windowModes)) {
1792         return ERR_AAFWK_INVALID_WINDOW_MODE;
1793     }
1794 #endif
1795     if (startOptions.GetDisplayID() == 0) {
1796         abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1797             static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1798     } else {
1799         abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1800     }
1801     AbilityUtil::ProcessWindowMode(abilityRequest.want, abilityInfo.applicationInfo.accessTokenId,
1802         startOptions.GetWindowMode());
1803 
1804     WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
1805 
1806     if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
1807         bool focused = abilityRequest.want.GetBoolParam(Want::PARAM_RESV_WINDOW_FOCUSED, true);
1808         if (focused) {
1809             bool windowfocused = startOptions.GetWindowFocused();
1810             abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowfocused);
1811         }
1812     } else {
1813         abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
1814     }
1815 
1816     Want newWant = abilityRequest.want;
1817     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1818         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1819     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1820         afterCheckExecuter_->DoProcess(afterCheckParam);
1821     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1822     newWant.RemoveParam("queryWantFromErms");
1823 #ifdef SUPPORT_SCREEN
1824     if (result != ERR_OK && isReplaceWantExist == false) {
1825         TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
1826         return result;
1827     }
1828     if (result != ERR_OK && isReplaceWantExist) {
1829         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1830     }
1831     if (result == ERR_OK &&
1832         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1833         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1834         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
1835     }
1836 #endif
1837 
1838     auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1839     UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1840     StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1841 
1842     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1843     if (specifyTokenId > 0) {
1844         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
1845         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1846         abilityRequest.specifyTokenId = specifyTokenId;
1847     }
1848     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1849     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1850         abilityRequest.userId = oriValidUserId;
1851         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1852         abilityRequest.processOptions = startOptions.processOptions;
1853         if (IPCSkeleton::GetCallingTokenID() == abilityRequest.appInfo.accessTokenId) {
1854             abilityRequest.startWindowOption = startOptions.startWindowOption;
1855         }
1856         abilityRequest.supportWindowModes = startOptions.supportWindowModes_;
1857         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1858         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1859         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1860     }
1861     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1862     if (missionListManager == nullptr) {
1863         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", oriValidUserId);
1864         eventInfo.errCode = ERR_INVALID_VALUE;
1865         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1866         return ERR_INVALID_VALUE;
1867     }
1868 
1869     auto ret = missionListManager->StartAbility(abilityRequest);
1870     if (ret != ERR_OK) {
1871         eventInfo.errCode = ret;
1872         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1873     }
1874     return ret;
1875 }
1876 
RequestDialogService(const Want & want,const sptr<IRemoteObject> & callerToken)1877 int32_t AbilityManagerService::RequestDialogService(const Want &want, const sptr<IRemoteObject> &callerToken)
1878 {
1879     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1880     auto flags = want.GetFlags();
1881     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
1882         TAG_LOGE(AAFwkTag::ABILITYMGR, "RequestDialogService with continuation flags is not allowed!");
1883         return ERR_INVALID_CONTINUATION_FLAG;
1884     }
1885 
1886     TAG_LOGI(AAFwkTag::ABILITYMGR, "request dialog service, target is %{public}s", want.GetElement().GetURI().c_str());
1887     return RequestDialogServiceInner(want, callerToken, -1, -1);
1888 }
1889 
ReportDrawnCompleted(const sptr<IRemoteObject> & callerToken)1890 int32_t AbilityManagerService::ReportDrawnCompleted(const sptr<IRemoteObject> &callerToken)
1891 {
1892     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1893     if (callerToken == nullptr) {
1894         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken is nullptr");
1895         return INNER_ERR;
1896     }
1897 
1898     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1899     if (abilityRecord == nullptr) {
1900         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr");
1901         return INNER_ERR;
1902     }
1903     auto abilityInfo = abilityRecord->GetAbilityInfo();
1904 
1905     EventInfo eventInfo;
1906     eventInfo.userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
1907     eventInfo.pid = IPCSkeleton::GetCallingPid();
1908     eventInfo.bundleName = abilityInfo.bundleName;
1909     eventInfo.moduleName = abilityInfo.moduleName;
1910     eventInfo.abilityName = abilityInfo.name;
1911     EventReport::SendAppEvent(EventName::DRAWN_COMPLETED, HiSysEventType::BEHAVIOR, eventInfo);
1912     return ERR_OK;
1913 }
1914 
RequestDialogServiceInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1915 int32_t AbilityManagerService::RequestDialogServiceInner(const Want &want, const sptr<IRemoteObject> &callerToken,
1916     int requestCode, int32_t userId)
1917 {
1918     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1919     if (callerToken == nullptr || !VerificationAllToken(callerToken)) {
1920         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller is invalid.");
1921         return ERR_INVALID_CALLER;
1922     }
1923 
1924     {
1925 #ifdef WITH_DLP
1926         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1927         if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1928             !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1929             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed.", __func__);
1930             return CHECK_PERMISSION_FAILED;
1931         }
1932 
1933         if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1934             TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot handle dlp by RequestDialogService.");
1935             return ERR_WRONG_INTERFACE_CALL;
1936         }
1937 #endif // WITH_DLP
1938     }
1939 
1940     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1941     int32_t validUserId = GetValidUserId(userId);
1942     StartAbilityInfoWrap threadLocalInfo;
1943     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1944         true, nullptr);
1945     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1946         interceptorExecuter_->DoProcess(interceptorParam);
1947     if (result != ERR_OK) {
1948         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1949         return result;
1950     }
1951 
1952     if (!JudgeMultiUserConcurrency(validUserId)) {
1953         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1954         return ERR_CROSS_USER;
1955     }
1956     AbilityRequest abilityRequest;
1957     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
1958     if (result != ERR_OK) {
1959         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error when RequestDialogService.");
1960         return result;
1961     }
1962     UpdateCallerInfo(abilityRequest.want, callerToken);
1963 
1964     auto abilityInfo = abilityRequest.abilityInfo;
1965     threadLocalInfo.SetStartAbilityInfo(abilityInfo);
1966     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1967     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
1968         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1969 
1970     result = CheckStaticCfgPermission(abilityRequest, false, -1);
1971     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1972         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1973         return ERR_STATIC_CFG_PERMISSION;
1974     }
1975 
1976     auto type = abilityInfo.type;
1977     if (type == AppExecFwk::AbilityType::EXTENSION &&
1978         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
1979         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
1980         result = CheckCallServicePermission(abilityRequest);
1981         if (result != ERR_OK) {
1982             TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
1983             return result;
1984         }
1985     } else {
1986         TAG_LOGE(AAFwkTag::ABILITYMGR, "RequestDialogService do not support other component.");
1987         return ERR_WRONG_INTERFACE_CALL;
1988     }
1989 
1990     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
1991         GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
1992     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1993         afterCheckExecuter_->DoProcess(afterCheckParam);
1994     if (result != ERR_OK) {
1995         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
1996         return result;
1997     }
1998 
1999     auto connectManager = GetConnectManagerByUserId(validUserId);
2000     if (!connectManager) {
2001         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
2002         return ERR_INVALID_VALUE;
2003     }
2004     TAG_LOGD(AAFwkTag::ABILITYMGR,
2005         "request dialog service, start service extension,name is %{public}s.", abilityInfo.name.c_str());
2006     ReportEventToRSS(abilityInfo, callerToken);
2007     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
2008         abilityRequest.abilityInfo.extensionAbilityType);
2009     return connectManager->StartAbility(abilityRequest);
2010 }
2011 
OpenAtomicService(AAFwk::Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,int32_t requestCode,int32_t userId)2012 int32_t AbilityManagerService::OpenAtomicService(AAFwk::Want& want, const StartOptions &options,
2013     sptr<IRemoteObject> callerToken, int32_t requestCode, int32_t userId)
2014 {
2015     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2016     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
2017     if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
2018         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is not hap.");
2019         return CHECK_PERMISSION_FAILED;
2020     }
2021     want.SetParam(AAFwk::SCREEN_MODE_KEY, AAFwk::ScreenMode::JUMP_SCREEN_MODE);
2022     return StartUIAbilityForOptionWrap(want, options, callerToken, false, userId, requestCode);
2023 }
2024 
StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo,bool & isColdStart,uint32_t sceneFlag)2025 int AbilityManagerService::StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo, bool &isColdStart, uint32_t sceneFlag)
2026 {
2027     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2028     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call, sceneFlag: %{public}u", sceneFlag);
2029     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
2030         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
2031         return ERR_INVALID_VALUE;
2032     }
2033 
2034     if (!IsCallerSceneBoard()) {
2035         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
2036         return ERR_WRONG_INTERFACE_CALL;
2037     }
2038 
2039     if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
2040         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2041     }
2042 
2043     std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
2044     if (sessionId.empty()) {
2045         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2046     }
2047 
2048     TAG_LOGI(AAFwkTag::ABILITYMGR, "sessionId=%{public}s", sessionId.c_str());
2049 
2050     if (freeInstallManager_ == nullptr) {
2051         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
2052         return ERR_INVALID_VALUE;
2053     }
2054     FreeInstallInfo taskInfo;
2055     if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
2056         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed to find free install task");
2057         if ((sessionInfo->want).GetElement().GetAbilityName().empty() ||
2058             (sessionInfo->want).GetElement().GetModuleName().empty()) {
2059             auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
2060             CHECK_POINTER_AND_RETURN(bundleMgrHelper, ERR_INVALID_VALUE);
2061             Want launchWant;
2062             auto errCode = IN_PROCESS_CALL(bundleMgrHelper->GetLaunchWantForBundle(
2063                 (sessionInfo->want).GetBundle(), launchWant, GetValidUserId(sessionInfo->userId)));
2064             if (errCode != ERR_OK) {
2065                 TAG_LOGE(AAFwkTag::ABILITYMGR, "GetLaunchWantForBundle returns %{public}d.", errCode);
2066                 return errCode;
2067             }
2068             (sessionInfo->want).SetElement(launchWant.GetElement());
2069         }
2070         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2071         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2072         if (uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo) == nullptr) {
2073             TAG_LOGI(AAFwkTag::ABILITYMGR, "first time open");
2074             auto err = StartUIAbilityByPreInstallInner(sessionInfo, 0, sceneFlag, isColdStart);
2075             if (err != ERR_OK) {
2076                 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUIAbilityByPreInstallInner failed");
2077             }
2078             return err;
2079         }
2080         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2081     }
2082 
2083     if (taskInfo.isFreeInstallFinished) {
2084         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task is already finished");
2085         if (!taskInfo.isInstalled) {
2086             TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
2087                 taskInfo.resultCode);
2088             return taskInfo.resultCode;
2089         }
2090         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeds");
2091         auto err = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, sceneFlag, isColdStart);
2092         if (err != ERR_OK) {
2093             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilityByPreInstallInner failed.");
2094         }
2095         return err;
2096     }
2097 
2098     {
2099         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
2100         preStartSessionMap_[sessionId] = sessionInfo;
2101     }
2102 
2103     TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task is still in progress");
2104     const Want& want = sessionInfo->want;
2105     freeInstallManager_->SetSCBCallStatus(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(),
2106         want.GetStringParam(Want::PARAM_RESV_START_TIME), true);
2107     return ERR_OK;
2108 }
2109 
StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2110 int AbilityManagerService::StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo, uint32_t sceneFlag,
2111     bool &isColdStart)
2112 {
2113     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2114     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
2115 
2116     auto currentUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2117     if (sessionInfo->userId == DEFAULT_INVAL_VALUE) {
2118         sessionInfo->userId = currentUserId;
2119     }
2120 
2121     (sessionInfo->want).RemoveParam(AAFwk::SCREEN_MODE_KEY);
2122     EventInfo eventInfo = BuildEventInfo(sessionInfo->want, currentUserId);
2123     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
2124 
2125     auto requestCode = sessionInfo->requestCode;
2126     int32_t appIndex = 0;
2127     if (!StartAbilityUtils::GetAppIndex(sessionInfo->want, sessionInfo->callerToken, appIndex)) {
2128         return ERR_APP_CLONE_INDEX_INVALID;
2129     }
2130     StartAbilityInfoWrap threadLocalInfo(sessionInfo->want, currentUserId, appIndex, sessionInfo->callerToken);
2131     if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2132         TAG_LOGD(AAFwkTag::ABILITYMGR, "interceptorExecuter_ called");
2133         AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(sessionInfo->want, requestCode,
2134             currentUserId, true, nullptr);
2135         auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2136         interceptorExecuter_->DoProcess(interceptorParam);
2137         if (result != ERR_OK) {
2138             TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
2139             eventInfo.errCode = result;
2140             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2141             return result;
2142         }
2143     }
2144 
2145     AbilityRequest abilityRequest;
2146     auto result = GenerateAbilityRequest(sessionInfo->want, requestCode, abilityRequest,
2147         sessionInfo->callerToken, currentUserId);
2148     if (result != ERR_OK) {
2149         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
2150         return result;
2151     }
2152 
2153     if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2154         if (sessionInfo->startSetting != nullptr) {
2155             TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb, last not.");
2156             sessionInfo->startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2157         }
2158 
2159         if (abilityRequest.startSetting != nullptr) {
2160             TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb.");
2161             abilityRequest.startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2162         }
2163     }
2164 
2165     abilityRequest.collaboratorType = sessionInfo->collaboratorType;
2166     uint32_t specifyTokenId = static_cast<uint32_t>(sessionInfo->want.GetIntParam(SPECIFY_TOKEN_ID, 0));
2167     (sessionInfo->want).RemoveParam(SPECIFY_TOKEN_ID);
2168     abilityRequest.specifyTokenId = specifyTokenId;
2169 
2170     auto abilityInfo = abilityRequest.abilityInfo;
2171     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall() &&
2172         abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
2173         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support for page type ability.");
2174         return ERR_INVALID_VALUE;
2175     }
2176 
2177     if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2178         TAG_LOGD(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ called");
2179         Want newWant = abilityRequest.want;
2180         AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(), true,
2181             sessionInfo->callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2182         result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2183             afterCheckExecuter_->DoProcess(afterCheckParam);
2184         bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2185         newWant.RemoveParam("queryWantFromErms");
2186         if (result != ERR_OK) {
2187             if (isReplaceWantExist == false) {
2188                 TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
2189                 return result;
2190             }
2191             return DialogSessionManager::GetInstance().HandleErmsResultBySCB(abilityRequest, newWant);
2192         }
2193     }
2194 
2195     return StartUIAbilityBySCBDefaultCommon(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2196 }
2197 
StartUIAbilityBySCBDefaultCommon(AbilityRequest & abilityRequest,sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2198 int32_t AbilityManagerService::StartUIAbilityBySCBDefaultCommon(AbilityRequest &abilityRequest,
2199     sptr<SessionInfo> sessionInfo, uint32_t sceneFlag, bool &isColdStart)
2200 {
2201     auto abilityInfo = abilityRequest.abilityInfo;
2202     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
2203         int32_t result = PreLoadAppDataAbilities(abilityInfo.bundleName, IPCSkeleton::GetCallingUid() / BASE_USER_RANGE);
2204         if (result != ERR_OK) {
2205             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
2206                 abilityInfo.bundleName.c_str(), result);
2207             return result;
2208         }
2209     }
2210 
2211     ReportAbilityStartInfoToRSS(abilityInfo);
2212     ReportAbilityAssociatedStartInfoToRSS(abilityInfo, RES_TYPE_SCB_START_ABILITY, sessionInfo->callerToken);
2213     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2214     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2215     return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2216 }
2217 
NotifySCBToRecoveryAfterInterception(const AbilityRequest & abilityRequest)2218 int32_t AbilityManagerService::NotifySCBToRecoveryAfterInterception(const AbilityRequest &abilityRequest)
2219 {
2220     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2221     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2222     return uiAbilityManager->NotifySCBToRecoveryAfterInterception(abilityRequest);
2223 }
2224 
CheckCallingTokenId(const std::string & bundleName,int32_t userId,int32_t appIndex)2225 bool AbilityManagerService::CheckCallingTokenId(const std::string &bundleName, int32_t userId, int32_t appIndex)
2226 {
2227     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2228     auto bundleMgrHelper = DelayedSingleton<AppExecFwk::BundleMgrHelper>::GetInstance();
2229     CHECK_POINTER_AND_RETURN(bundleMgrHelper, false);
2230     auto validUserId = GetValidUserId(userId);
2231     AppExecFwk::ApplicationInfo appInfo;
2232     IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->GetApplicationInfoWithAppIndex(bundleName,
2233         appIndex, validUserId, appInfo));
2234     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2235     if (accessTokenId != appInfo.accessTokenId) {
2236         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
2237         return false;
2238     }
2239     return true;
2240 }
2241 
IsCallerSceneBoard()2242 bool AbilityManagerService::IsCallerSceneBoard()
2243 {
2244     int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2245     auto connectManager = GetConnectManagerByUserId(userId);
2246     CHECK_POINTER_AND_RETURN(connectManager, false);
2247     auto sceneBoardTokenId = connectManager->GetSceneBoardTokenId();
2248     if (sceneBoardTokenId != 0 && IPCSkeleton::GetCallingTokenID() == sceneBoardTokenId) {
2249         return true;
2250     }
2251     return false;
2252 }
2253 
IsBackgroundTaskUid(const int uid)2254 bool AbilityManagerService::IsBackgroundTaskUid(const int uid)
2255 {
2256 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2257     std::lock_guard<ffrt::mutex> lock(bgtaskObserverMutex_);
2258     if (bgtaskObserver_) {
2259         return bgtaskObserver_->IsBackgroundTaskUid(uid);
2260     }
2261     return false;
2262 #else
2263     return false;
2264 #endif
2265 }
2266 
IsDmsAlive() const2267 bool AbilityManagerService::IsDmsAlive() const
2268 {
2269     return g_isDmsAlive.load();
2270 }
2271 
AppUpgradeCompleted(const std::string & bundleName,int32_t uid)2272 void AbilityManagerService::AppUpgradeCompleted(const std::string &bundleName, int32_t uid)
2273 {
2274     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2275         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sa call");
2276         return;
2277     }
2278 
2279     auto bms = GetBundleManager();
2280     CHECK_POINTER(bms);
2281     auto userId = uid / BASE_USER_RANGE;
2282     if (userId != U0_USER_ID && userId != GetUserId()) {
2283         TAG_LOGI(AAFwkTag::ABILITYMGR, "not current user");
2284         return;
2285     }
2286 
2287     AppExecFwk::BundleInfo bundleInfo;
2288     if (!IN_PROCESS_CALL(
2289         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId))) {
2290         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info.");
2291         return;
2292     }
2293 
2294     bool keepAliveEnable = bundleInfo.isKeepAlive;
2295     AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfo.name, keepAliveEnable);
2296     if (!keepAliveEnable) {
2297         TAG_LOGW(AAFwkTag::ABILITYMGR, "Not a resident application.");
2298         return;
2299     }
2300 
2301     std::vector<AppExecFwk::BundleInfo> bundleInfos = { bundleInfo };
2302     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId);
2303 
2304     if (!bundleInfos.empty()) {
2305         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
2306     }
2307 }
2308 
RecordAppExitReason(const ExitReason & exitReason)2309 int32_t AbilityManagerService::RecordAppExitReason(const ExitReason &exitReason)
2310 {
2311     TAG_LOGI(AAFwkTag::ABILITYMGR, "RecordAppExitReason reason:%{public}d, exitMsg: %{public}s", exitReason.reason,
2312         exitReason.exitMsg.c_str());
2313 
2314     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2315     return appExitReasonHelper_->RecordAppExitReason(exitReason);
2316 }
2317 
RecordProcessExitReason(const int32_t pid,const ExitReason & exitReason)2318 int32_t AbilityManagerService::RecordProcessExitReason(const int32_t pid, const ExitReason &exitReason)
2319 {
2320     TAG_LOGI(AAFwkTag::ABILITYMGR, "RecordProcessExitReason pid:%{public}d, reason:%{public}d, exitMsg: %{public}s",
2321         pid, exitReason.reason, exitReason.exitMsg.c_str());
2322 
2323     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
2324         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
2325         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sa call");
2326         return ERR_PERMISSION_DENIED;
2327     }
2328 
2329     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2330     return appExitReasonHelper_->RecordProcessExitReason(pid, exitReason);
2331 }
2332 
ForceExitApp(const int32_t pid,const ExitReason & exitReason)2333 int32_t AbilityManagerService::ForceExitApp(const int32_t pid, const ExitReason &exitReason)
2334 {
2335     TAG_LOGI(AAFwkTag::ABILITYMGR, "ForceExitApp pid:%{public}d, reason:%{public}d, exitMsg: %{public}s",
2336         pid, exitReason.reason, exitReason.exitMsg.c_str());
2337 
2338     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
2339         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
2340         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sa or shell call");
2341         return ERR_PERMISSION_DENIED;
2342     }
2343 
2344     AppExecFwk::ApplicationInfo application;
2345     bool debug = false;
2346     auto ret = IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->GetApplicationInfoByProcessID(pid,
2347         application, debug));
2348     if (ret != ERR_OK) {
2349         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetApplicationInfoByProcessID failed.");
2350         return ret;
2351     }
2352 
2353     std::string bundleName = application.bundleName;
2354     int32_t uid = application.uid;
2355     int32_t appIndex = application.appIndex;
2356 
2357     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2358     appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
2359 
2360     return DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName);
2361 }
2362 
GetConfiguration(AppExecFwk::Configuration & config)2363 int32_t AbilityManagerService::GetConfiguration(AppExecFwk::Configuration& config)
2364 {
2365     auto appMgr = GetAppMgr();
2366     if (appMgr == nullptr) {
2367         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
2368         return -1;
2369     }
2370 
2371     return appMgr->GetConfiguration(config);
2372 }
2373 
GetAppMgr()2374 OHOS::sptr<OHOS::AppExecFwk::IAppMgr> AbilityManagerService::GetAppMgr()
2375 {
2376     if (appMgr_) {
2377         return appMgr_;
2378     }
2379 
2380     OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
2381         OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2382     if (!systemAbilityManager) {
2383         return nullptr;
2384     }
2385     OHOS::sptr<OHOS::IRemoteObject> object = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID);
2386     appMgr_ = OHOS::iface_cast<OHOS::AppExecFwk::IAppMgr>(object);
2387     return appMgr_;
2388 }
2389 
CheckOptExtensionAbility(const Want & want,AbilityRequest & abilityRequest,int32_t validUserId,AppExecFwk::ExtensionAbilityType extensionType,bool isImplicit,bool isStartAsCaller)2390 int AbilityManagerService::CheckOptExtensionAbility(const Want &want, AbilityRequest &abilityRequest,
2391     int32_t validUserId, AppExecFwk::ExtensionAbilityType extensionType, bool isImplicit, bool isStartAsCaller)
2392 {
2393     auto abilityInfo = abilityRequest.abilityInfo;
2394     auto type = abilityInfo.type;
2395     if (type != AppExecFwk::AbilityType::EXTENSION) {
2396         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not extension ability, not allowed.");
2397         return ERR_WRONG_INTERFACE_CALL;
2398     }
2399     if (extensionType != AppExecFwk::ExtensionAbilityType::UNSPECIFIED &&
2400         extensionType != abilityInfo.extensionAbilityType) {
2401         TAG_LOGE(AAFwkTag::ABILITYMGR, "Extension ability type not match, set type: %{public}d, real type: %{public}d",
2402             static_cast<int32_t>(extensionType), static_cast<int32_t>(abilityInfo.extensionAbilityType));
2403         return ERR_WRONG_INTERFACE_CALL;
2404     }
2405 
2406     auto result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
2407     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2408         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
2409         return ERR_STATIC_CFG_PERMISSION;
2410     }
2411 
2412     if (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
2413         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE ||
2414         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2415         result = CheckCallServiceExtensionPermission(abilityRequest);
2416         if (result != ERR_OK) {
2417             return result;
2418         }
2419     } else {
2420         result = CheckCallOtherExtensionPermission(abilityRequest);
2421         if (result != ERR_OK) {
2422             return result;
2423         }
2424     }
2425     if (!isStartAsCaller) {
2426         UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
2427     }
2428     return ERR_OK;
2429 }
2430 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2431 void AbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2432 {
2433     TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d add", systemAbilityId);
2434     switch (systemAbilityId) {
2435         case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2436             SubscribeBackgroundTask();
2437             break;
2438         }
2439         case DISTRIBUTED_SCHED_SA_ID: {
2440             g_isDmsAlive.store(true);
2441             break;
2442         }
2443         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2444             SubscribeBundleEventCallback();
2445             break;
2446         }
2447 #ifdef SUPPORT_SCREEN
2448         case MULTIMODAL_INPUT_SERVICE_ID: {
2449             auto anrListener = std::make_shared<ApplicationAnrListener>();
2450             MMI::InputManager::GetInstance()->SetAnrObserver(anrListener);
2451             break;
2452         }
2453 #endif
2454         default:
2455             break;
2456     }
2457 }
2458 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2459 void AbilityManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2460 {
2461     TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d remove", systemAbilityId);
2462     switch (systemAbilityId) {
2463         case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2464             UnSubscribeBackgroundTask();
2465             break;
2466         }
2467         case DISTRIBUTED_SCHED_SA_ID: {
2468             g_isDmsAlive.store(false);
2469             break;
2470         }
2471         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2472             UnsubscribeBundleEventCallback();
2473             break;
2474         }
2475         default:
2476             break;
2477     }
2478 }
2479 
SubscribeBackgroundTask()2480 void AbilityManagerService::SubscribeBackgroundTask()
2481 {
2482 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2483     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2484     if (!bgtaskObserver_) {
2485         bgtaskObserver_ = std::make_shared<BackgroundTaskObserver>();
2486     }
2487     int ret = BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver_);
2488     if (ret != ERR_OK) {
2489         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s failed, err:%{public}d.", __func__, ret);
2490         return;
2491     }
2492     bgtaskObserver_->GetContinuousTaskApps();
2493     bgtaskObserver_->GetEfficiencyResourcesTaskApps();
2494     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success.", __func__);
2495 #endif
2496 }
2497 
UnSubscribeBackgroundTask()2498 void AbilityManagerService::UnSubscribeBackgroundTask()
2499 {
2500 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2501     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2502     if (!bgtaskObserver_) {
2503         return;
2504     }
2505     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success.", __func__);
2506 #endif
2507 }
2508 
SubscribeBundleEventCallback()2509 void AbilityManagerService::SubscribeBundleEventCallback()
2510 {
2511     TAG_LOGI(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback begin.");
2512     if (taskHandler_) {
2513         TAG_LOGI(AAFwkTag::ABILITYMGR, "submit startResidentApps task");
2514         auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(U0_USER_ID); };
2515         taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps");
2516     }
2517 
2518     if (abilityBundleEventCallback_) {
2519         return;
2520     }
2521 
2522     // Register abilityBundleEventCallback to receive hap updates
2523     abilityBundleEventCallback_ =
2524         new (std::nothrow) AbilityBundleEventCallback(taskHandler_, abilityAutoStartupService_);
2525     auto bms = GetBundleManager();
2526     if (bms) {
2527         bool ret = IN_PROCESS_CALL(bms->RegisterBundleEventCallback(abilityBundleEventCallback_));
2528         if (!ret) {
2529             TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterBundleEventCallback failed!");
2530         }
2531     } else {
2532         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get BundleManager failed!");
2533     }
2534     TAG_LOGD(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback success.");
2535 }
2536 
UnsubscribeBundleEventCallback()2537 void AbilityManagerService::UnsubscribeBundleEventCallback()
2538 {
2539     if (!abilityBundleEventCallback_) {
2540         return;
2541     }
2542     abilityBundleEventCallback_ = nullptr;
2543     TAG_LOGD(AAFwkTag::ABILITYMGR, "UnsubscribeBundleEventCallback success.");
2544 }
2545 
ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo)2546 void AbilityManagerService::ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo)
2547 {
2548     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2549     if (abilityInfo.type == AppExecFwk::AbilityType::PAGE &&
2550         abilityInfo.launchMode != AppExecFwk::LaunchMode::SPECIFIED) {
2551         std::vector<AppExecFwk::RunningProcessInfo> runningProcessInfos;
2552         if (IN_PROCESS_CALL(GetProcessRunningInfos(runningProcessInfos)) != ERR_OK) {
2553             return;
2554         }
2555         bool isColdStart = true;
2556         int32_t pid = 0;
2557         for (auto const &info : runningProcessInfos) {
2558             if (info.uid_ == abilityInfo.applicationInfo.uid) {
2559                 isColdStart = false;
2560                 pid = info.pid_;
2561                 break;
2562             }
2563         }
2564         ResSchedUtil::GetInstance().ReportAbilityStartInfoToRSS(abilityInfo, pid, isColdStart);
2565     }
2566 }
2567 
ReportAbilityAssociatedStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo,int64_t type,const sptr<IRemoteObject> & callerToken)2568 void AbilityManagerService::ReportAbilityAssociatedStartInfoToRSS(
2569     const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr<IRemoteObject> &callerToken)
2570 {
2571     CHECK_POINTER_LOG(callerToken, "associated start caller token is nullptr");
2572     auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2573     CHECK_POINTER_LOG(callerAbility, "associated start caller ability is nullptr");
2574     int32_t callerUid = callerAbility->GetUid();
2575     int32_t callerPid = callerAbility->GetPid();
2576     ResSchedUtil::GetInstance().ReportAbilityAssociatedStartInfoToRSS(abilityInfo, type, callerUid, callerPid);
2577 }
2578 
ReportEventToRSS(const AppExecFwk::AbilityInfo & abilityInfo,sptr<IRemoteObject> callerToken)2579 void AbilityManagerService::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo,
2580     sptr<IRemoteObject> callerToken)
2581 {
2582     CHECK_POINTER_LOG(taskHandler_, "taskhandler null");
2583     std::string reason = ResSchedUtil::GetInstance().GetThawReasonByAbilityType(abilityInfo);
2584     const auto uid = abilityInfo.applicationInfo.uid;
2585     const auto bundleName = abilityInfo.applicationInfo.bundleName;
2586     auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2587     const int32_t callerPid = (callerAbility != nullptr) ? callerAbility->GetPid() : IPCSkeleton::GetCallingPid();
2588     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}d_%{public}s reason=%{public}s callerPid=%{public}d", uid,
2589         bundleName.c_str(), reason.c_str(), callerPid);
2590     taskHandler_->SubmitTask([reason, uid, bundleName, callerPid]() {
2591         ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason, -1, callerPid);
2592     });
2593 }
2594 
ReportAppConnectOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want)2595 void AbilityManagerService::ReportAppConnectOtherExtensionEvent(const AppExecFwk::AbilityInfo &abilityInfo,
2596     const Want &want)
2597 {
2598     if (PermissionVerification::GetInstance()->IsSACall()) {
2599         return;
2600     }
2601     const std::unordered_set<AppExecFwk::ExtensionAbilityType> extensionSet {
2602         AppExecFwk::ExtensionAbilityType::FORM,
2603         AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER,
2604         AppExecFwk::ExtensionAbilityType::INPUTMETHOD,
2605         AppExecFwk::ExtensionAbilityType::ACCESSIBILITY,
2606         AppExecFwk::ExtensionAbilityType::STATICSUBSCRIBER,
2607         AppExecFwk::ExtensionAbilityType::WALLPAPER,
2608         AppExecFwk::ExtensionAbilityType::BACKUP,
2609         AppExecFwk::ExtensionAbilityType::ENTERPRISE_ADMIN,
2610         AppExecFwk::ExtensionAbilityType::PRINT,
2611         AppExecFwk::ExtensionAbilityType::VPN,
2612         AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION,
2613         AppExecFwk::ExtensionAbilityType::REMOTE_NOTIFICATION,
2614         AppExecFwk::ExtensionAbilityType::REMOTE_LOCATION,
2615         AppExecFwk::ExtensionAbilityType::PUSH,
2616         AppExecFwk::ExtensionAbilityType::VOIP
2617     };
2618     if (extensionSet.find(abilityInfo.extensionAbilityType) != extensionSet.end()) {
2619         EventInfo eventInfo;
2620         eventInfo.bundleName = abilityInfo.bundleName;
2621         eventInfo.moduleName = abilityInfo.moduleName;
2622         eventInfo.abilityName = abilityInfo.name;
2623         eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
2624         eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
2625         if (eventInfo.callerBundleName.empty()) {
2626             eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
2627         }
2628         // Add prefix to distinguish reporting scenarios
2629         eventInfo.callerBundleName = "Connect:" + eventInfo.callerBundleName;
2630         EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
2631     }
2632 }
2633 
StartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2634 int AbilityManagerService::StartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2635     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2636 {
2637     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2638     if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2639         if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
2640             TAG_LOGE(AAFwkTag::ABILITYMGR, "uiServiceExtensionAbility disable");
2641             return ERR_CAPABILITY_NOT_SUPPORT;
2642         }
2643     }
2644     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2645     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN ||
2646         extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2647         return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false);
2648     }
2649     return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true);
2650 }
2651 
ImplicitStartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2652 int AbilityManagerService::ImplicitStartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2653     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2654 {
2655     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2656     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
2657         return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false, true);
2658     }
2659     return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true, true);
2660 }
2661 
PreloadUIExtensionAbility(const Want & want,std::string & bundleName,int32_t userId)2662 int AbilityManagerService::PreloadUIExtensionAbility(const Want &want, std::string &bundleName, int32_t userId)
2663 {
2664     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
2665     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2666     // check preload ui extension permission.
2667     CHECK_CALLER_IS_SYSTEM_APP;
2668     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
2669         PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
2670         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
2671             PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
2672         return ERR_PERMISSION_DENIED;
2673     }
2674     return PreloadUIExtensionAbilityInner(want, bundleName, userId);
2675 }
2676 
PreloadUIExtensionAbilityInner(const Want & want,std::string & hostBundleName,int32_t userId)2677 int AbilityManagerService::PreloadUIExtensionAbilityInner(const Want &want, std::string &hostBundleName, int32_t userId)
2678 {
2679     TAG_LOGD(AAFwkTag::ABILITYMGR, "Preload ui extension called, elementName: %{public}s.",
2680         want.GetElement().GetURI().c_str());
2681     int32_t validUserId = GetValidUserId(userId);
2682     AbilityRequest abilityRequest;
2683     ErrCode result = ERR_OK;
2684     result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, validUserId);
2685     if (result != ERR_OK) {
2686         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
2687         return result;
2688     }
2689     abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
2690     abilityRequest.want.SetParam(IS_PRELOAD_UIEXTENSION_ABILITY, true);
2691     auto abilityInfo = abilityRequest.abilityInfo;
2692     auto res = JudgeAbilityVisibleControl(abilityInfo);
2693     if (res != ERR_OK) {
2694         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is invisible");
2695         return res;
2696     }
2697     auto connectManager = GetConnectManagerByUserId(validUserId);
2698     if (connectManager == nullptr) {
2699         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", validUserId);
2700         return ERR_INVALID_VALUE;
2701     }
2702     return connectManager->PreloadUIExtensionAbilityLocked(abilityRequest, hostBundleName);
2703 }
2704 
UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> & abilityRecord,std::string & hostBundleName)2705 int AbilityManagerService::UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> &abilityRecord,
2706     std::string &hostBundleName)
2707 {
2708     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call.");
2709     auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
2710     if (connectManager == nullptr) {
2711         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr.");
2712         return ERR_INVALID_VALUE;
2713     }
2714     return connectManager->UnloadUIExtensionAbility(abilityRecord, hostBundleName);
2715 }
2716 
RequestModalUIExtension(const Want & want)2717 int AbilityManagerService::RequestModalUIExtension(const Want &want)
2718 {
2719     CHECK_CALLER_IS_SYSTEM_APP;
2720     return RequestModalUIExtensionInner(want);
2721 }
2722 
RequestModalUIExtensionInner(Want want)2723 int AbilityManagerService::RequestModalUIExtensionInner(Want want)
2724 {
2725     sptr<IRemoteObject> token = nullptr;
2726     int ret = IN_PROCESS_CALL(GetTopAbility(token));
2727     if (ret == ERR_OK && token != nullptr) {
2728         // Gets the record corresponding to the current focus appliaction
2729         auto record = Token::GetAbilityRecordByToken(token);
2730         if (!record) {
2731             TAG_LOGE(AAFwkTag::ABILITYMGR, "Record is nullptr.");
2732             return ERR_INVALID_VALUE;
2733         }
2734 
2735         // Gets the bundleName corresponding to the
2736         // current focus appliaction
2737         std::string focusName = record->GetAbilityInfo().bundleName;
2738 
2739         // Gets the bundleName corresponding to the
2740         // current focus appliaction
2741         std::string callerName = want.GetParams().GetStringParam("bundleName");
2742 
2743         TAG_LOGI(AAFwkTag::ABILITYMGR,
2744                "focusbundlename: %{public}s, callerbundlename: %{public}s.",
2745                focusName.c_str(), callerName.c_str());
2746 
2747         // Compare
2748         if (record->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
2749             focusName == callerName) {
2750             TAG_LOGD(AAFwkTag::ABILITYMGR, "CreateModalUIExtension is called!");
2751             return record->CreateModalUIExtension(want);
2752         }
2753     } else {
2754         TAG_LOGW(AAFwkTag::ABILITYMGR, "token is nullptr.");
2755     }
2756 
2757     TAG_LOGD(AAFwkTag::ABILITYMGR, "Window Modal System Create UIExtension is called!");
2758     want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
2759     auto connection = std::make_shared<Rosen::ModalSystemUiExtension>();
2760     return connection->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR;
2761 }
2762 
ChangeAbilityVisibility(sptr<IRemoteObject> token,bool isShow)2763 int AbilityManagerService::ChangeAbilityVisibility(sptr<IRemoteObject> token, bool isShow)
2764 {
2765     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
2766     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
2767         TAG_LOGE(AAFwkTag::ABILITYMGR, "Capability not support.");
2768         return ERR_CAPABILITY_NOT_SUPPORT;
2769     }
2770     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2771     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2772     return uiAbilityManager->ChangeAbilityVisibility(token, isShow);
2773 }
2774 
ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo,bool isShow)2775 int AbilityManagerService::ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo, bool isShow)
2776 {
2777     if (!IsCallerSceneBoard()) {
2778         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
2779         return ERR_WRONG_INTERFACE_CALL;
2780     }
2781     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2782     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2783     return uiAbilityManager->ChangeUIAbilityVisibilityBySCB(sessionInfo, isShow);
2784 }
2785 
CheckWorkSchedulerPermission(const sptr<IRemoteObject> & callerToken,const uint32_t uid)2786 bool AbilityManagerService::CheckWorkSchedulerPermission(const sptr<IRemoteObject> &callerToken, const uint32_t uid)
2787 {
2788 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2789     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2790     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2791     if (bgtaskObserver_ && abilityRecord) {
2792         auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
2793         if (callerAbilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER) {
2794             return true;
2795         }
2796 
2797         if (!bgtaskObserver_->IsEfficiencyResourcesTaskUid(uid)) {
2798             TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to start extension by WorkScheduler");
2799             return false;
2800         }
2801     }
2802 #endif
2803     return true;
2804 }
2805 
StartExtensionAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType,bool checkSystemCaller,bool isImplicit,bool isDlp,bool isStartAsCaller)2806 int AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
2807     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller, bool isImplicit,
2808     bool isDlp, bool isStartAsCaller)
2809 {
2810     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2811     TAG_LOGI(AAFwkTag::ABILITYMGR,
2812         "Start extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
2813         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
2814     if (checkSystemCaller) {
2815         CHECK_CALLER_IS_SYSTEM_APP;
2816     }
2817     EventInfo eventInfo = BuildEventInfo(want, userId);
2818     eventInfo.extensionType = static_cast<int32_t>(extensionType);
2819 
2820     int result;
2821 #ifdef WITH_DLP
2822     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::START_EXTENSION_ERROR);
2823     if (result != ERR_OK) {
2824         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
2825         return result;
2826     }
2827 #endif // WITH_DLP
2828 
2829     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2830         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
2831         eventInfo.errCode = ERR_INVALID_VALUE;
2832         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2833         return ERR_INVALID_CALLER;
2834     }
2835 
2836     int32_t validUserId = GetValidUserId(userId);
2837     int32_t appIndex = 0;
2838     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
2839         return ERR_APP_CLONE_INDEX_INVALID;
2840     }
2841     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken, true);
2842     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
2843     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2844         interceptorExecuter_->DoProcess(interceptorParam);
2845     if (result != ERR_OK) {
2846         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
2847         eventInfo.errCode = result;
2848         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2849         return result;
2850     }
2851 
2852     if (!JudgeMultiUserConcurrency(validUserId)) {
2853         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
2854         eventInfo.errCode = ERR_INVALID_VALUE;
2855         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2856         return ERR_CROSS_USER;
2857     }
2858 
2859     AbilityRequest abilityRequest;
2860 #ifdef SUPPORT_GRAPHICS
2861     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
2862         abilityRequest.Voluation(want, DEFAULT_INVAL_VALUE, callerToken);
2863         abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
2864         abilityRequest.extensionType = extensionType;
2865         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
2866         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
2867         if (result != ERR_OK) {
2868             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error.");
2869             eventInfo.errCode = result;
2870             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2871         }
2872         return result;
2873     }
2874 #endif
2875     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2876     if (result != ERR_OK) {
2877         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
2878         eventInfo.errCode = result;
2879         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2880         return result;
2881     }
2882 
2883     if (!CheckWorkSchedulerPermission(callerToken, abilityRequest.abilityInfo.applicationInfo.uid)) {
2884         return CHECK_PERMISSION_FAILED;
2885     }
2886     auto abilityInfo = abilityRequest.abilityInfo;
2887     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2888     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
2889         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2890 
2891 #ifdef WITH_DLP
2892     result = isDlp ? IN_PROCESS_CALL(
2893         CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller)) :
2894         CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller);
2895     if (result != ERR_OK) {
2896         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error.");
2897         eventInfo.errCode = result;
2898         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2899         return result;
2900     }
2901 #endif // WITH_DLP
2902 
2903     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
2904         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2905     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2906         afterCheckExecuter_->DoProcess(afterCheckParam);
2907     if (result != ERR_OK) {
2908         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
2909         return result;
2910     }
2911 
2912     auto connectManager = GetConnectManagerByUserId(validUserId);
2913     if (!connectManager) {
2914         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
2915         eventInfo.errCode = ERR_INVALID_VALUE;
2916         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2917         return ERR_INVALID_VALUE;
2918     }
2919     if (!isStartAsCaller) {
2920         UpdateCallerInfo(abilityRequest.want, callerToken);
2921     }
2922     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
2923     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
2924         abilityRequest.abilityInfo.extensionAbilityType);
2925     SetAbilityRequestSessionInfo(abilityRequest, extensionType);
2926     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
2927     if (eventInfo.errCode != ERR_OK) {
2928         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2929     }
2930     ReportAbilityAssociatedStartInfoToRSS(abilityRequest.abilityInfo, RES_TYPE_EXTENSION_START_ABILITY, callerToken);
2931     return eventInfo.errCode;
2932 }
2933 
SetPickerElementName(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)2934 void AbilityManagerService::SetPickerElementName(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
2935 {
2936     CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
2937     std::string targetType = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TARGET_TYPE_KEY);
2938     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
2939         extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
2940         extensionSessionInfo->want.GetElement().GetAbilityName().empty() &&
2941         COMMON_PICKER_TYPE.find(targetType) != COMMON_PICKER_TYPE.end()) {
2942         std::string abilityName = "CommonSelectPickerAbility";
2943         std::string bundleName = "com.ohos.amsdialog";
2944         extensionSessionInfo->want.SetElementName(bundleName, abilityName);
2945         WantParams &parameters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
2946         parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box("sys/commonUI"));
2947         extensionSessionInfo->want.SetParams(parameters);
2948         return;
2949     }
2950     if (extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
2951         extensionSessionInfo->want.GetElement().GetAbilityName().empty() && !targetType.empty()) {
2952         std::string abilityName;
2953         std::string bundleName;
2954         std::string pickerType;
2955         std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
2956         auto pickerMap = AmsConfigurationParameter::GetInstance().GetPickerMap();
2957         auto it = pickerMap.find(targetType);
2958         if (it == pickerMap.end()) {
2959             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not find the targetType: %{public}s", targetType.c_str());
2960             return;
2961         }
2962         pickerType = it->second;
2963         auto bms = GetBundleManager();
2964         CHECK_POINTER(bms);
2965         int32_t validUserId = GetValidUserId(userId);
2966         TAG_LOGI(AAFwkTag::ABILITYMGR, "targetType: %{public}s, pickerType: %{public}s, userId: %{public}d",
2967             targetType.c_str(), pickerType.c_str(), validUserId);
2968         auto flags = static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION) |
2969             static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_BY_TYPE_NAME);
2970         auto ret = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfosOnlyWithTypeName(pickerType,
2971             flags,
2972             validUserId,
2973             extensionInfos));
2974         if (ret != ERR_OK) {
2975             TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryExtensionAbilityInfosOnlyWithTypeName failed");
2976             return;
2977         }
2978         abilityName = extensionInfos[0].name;
2979         bundleName = extensionInfos[0].bundleName;
2980         TAG_LOGI(AAFwkTag::ABILITYMGR,
2981             "abilityName: %{public}s, bundleName: %{public}s", abilityName.c_str(), bundleName.c_str());
2982         extensionSessionInfo->want.SetElementName(bundleName, abilityName);
2983         WantParams &parameters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
2984         parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box(pickerType));
2985         extensionSessionInfo->want.SetParams(parameters);
2986     }
2987 }
2988 
SetAutoFillElementName(const sptr<SessionInfo> & extensionSessionInfo)2989 void AbilityManagerService::SetAutoFillElementName(const sptr<SessionInfo> &extensionSessionInfo)
2990 {
2991     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
2992     CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
2993     std::vector<std::string> argList;
2994     if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_PASSWORD_TPYE) {
2995         SplitStr(KEY_AUTO_FILL_ABILITY, "/", argList);
2996     } else if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_SMART_TPYE) {
2997         SplitStr(KEY_SMART_AUTO_FILL_ABILITY, "/", argList);
2998     } else {
2999         TAG_LOGW(AAFwkTag::ABILITYMGR, "It is not autofill type.");
3000         return;
3001     }
3002 
3003     if (argList.size() != ARGC_THREE) {
3004         TAG_LOGE(AAFwkTag::ABILITYMGR, "Parse auto fill extension element name failed.");
3005         return;
3006     }
3007     extensionSessionInfo->want.SetElementName(argList[INDEX_ZERO], argList[INDEX_TWO]);
3008     extensionSessionInfo->want.SetModuleName(argList[INDEX_ONE]);
3009 }
3010 
CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,AppExecFwk::ExtensionAbilityType extensionType)3011 int AbilityManagerService::CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,
3012     AppExecFwk::ExtensionAbilityType extensionType)
3013 {
3014     if (uiExtensionUsage == UIExtensionUsage::EMBEDDED &&
3015         !AAFwk::UIExtensionUtils::IsPublicForEmbedded(extensionType)) {
3016         CHECK_CALLER_IS_SYSTEM_APP;
3017     }
3018 
3019     if (uiExtensionUsage == UIExtensionUsage::CONSTRAINED_EMBEDDED &&
3020         !AAFwk::UIExtensionUtils::IsPublicForConstrainedEmbedded(extensionType)) {
3021         TAG_LOGE(AAFwkTag::ABILITYMGR, "error extension type %u for SecureConstrainedEmbedded.", extensionType);
3022         return ERR_INVALID_VALUE;
3023     }
3024     return ERR_OK;
3025 }
3026 
StartUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)3027 int AbilityManagerService::StartUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
3028 {
3029     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3030     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ui extension ability come");
3031     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3032     SetPickerElementName(extensionSessionInfo, userId);
3033     SetAutoFillElementName(extensionSessionInfo);
3034 
3035     if (extensionSessionInfo->want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
3036         int32_t screenMode = extensionSessionInfo->want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
3037         if (screenMode != AAFwk::EMBEDDED_FULL_SCREEN_MODE) {
3038             TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support embedded pull-ups");
3039             return ERR_INVALID_VALUE;
3040         }
3041         auto bms = GetBundleManager();
3042         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3043         AppExecFwk::BundleInfo bundleInfo;
3044         if (!IN_PROCESS_CALL(bms->GetBundleInfo(extensionSessionInfo->want.GetBundle(),
3045             AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, GetValidUserId(userId)))) {
3046             TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get application info");
3047             return CHECK_PERMISSION_FAILED;
3048         }
3049         if (bundleInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE) {
3050             TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support atomicService");
3051             return ERR_INVALID_CALLER;
3052         }
3053         if (extensionSessionInfo->want.GetElement().GetAbilityName().empty()) {
3054             if (bundleInfo.abilityInfos.empty()) {
3055                 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get abilityInfos");
3056                 return ERR_INVALID_VALUE;
3057             }
3058             extensionSessionInfo->want.SetElementName(bundleInfo.name, bundleInfo.abilityInfos.begin()->name);
3059         }
3060         extensionSessionInfo->want.SetParam("send_to_erms_embedded", 1);
3061     }
3062     std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY);
3063     AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ?
3064         AppExecFwk::ExtensionAbilityType::UI : AppExecFwk::ConvertToExtensionAbilityType(extensionTypeStr);
3065     if (extensionType == AppExecFwk::ExtensionAbilityType::UNSPECIFIED) {
3066         TAG_LOGE(AAFwkTag::ABILITYMGR, "Input extension ability type is invalid.");
3067         return ERR_INVALID_VALUE;
3068     }
3069     EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, userId);
3070     eventInfo.extensionType = static_cast<int32_t>(extensionType);
3071 
3072     auto ret = CheckUIExtensionUsage(extensionSessionInfo->uiExtensionUsage, extensionType);
3073     if (ret != ERR_OK) {
3074         TAG_LOGE(AAFwkTag::ABILITYMGR, "check usage failed.");
3075         return ret;
3076     }
3077 
3078     if (InsightIntentExecuteParam::IsInsightIntentExecute(extensionSessionInfo->want)) {
3079         int32_t result = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateWant(
3080             extensionSessionInfo->want, AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY);
3081         if (result != ERR_OK) {
3082             return result;
3083         }
3084     }
3085 
3086     sptr<IRemoteObject> callerToken = extensionSessionInfo->callerToken;
3087 
3088 #ifdef WITH_DLP
3089     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, extensionSessionInfo->want) ||
3090         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
3091         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, extensionSessionInfo->want)) {
3092         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIExtensionAbility: Permission verification failed.");
3093         eventInfo.errCode = CHECK_PERMISSION_FAILED;
3094         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3095         return CHECK_PERMISSION_FAILED;
3096     }
3097 #endif // WITH_DLP
3098 
3099     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3100         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIExtensionAbility VerificationAllToken failed.");
3101         eventInfo.errCode = ERR_INVALID_VALUE;
3102         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3103         return ERR_INVALID_CALLER;
3104     }
3105 
3106     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
3107     if (callerRecord == nullptr || !JudgeSelfCalled(callerRecord)) {
3108         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid callerToken.");
3109         eventInfo.errCode = ERR_INVALID_VALUE;
3110         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3111         return ERR_INVALID_CALLER;
3112     }
3113     StartAbilityInfoWrap threadLocalInfo;
3114 
3115     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(extensionSessionInfo->want, 0, GetUserId(),
3116         true, nullptr);
3117     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3118         interceptorExecuter_->DoProcess(interceptorParam);
3119     if (result != ERR_OK) {
3120         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
3121         eventInfo.errCode = result;
3122         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3123         return result;
3124     }
3125 
3126     int32_t validUserId = GetValidUserId(userId);
3127     if (!JudgeMultiUserConcurrency(validUserId)) {
3128         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
3129         eventInfo.errCode = ERR_INVALID_VALUE;
3130         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3131         return ERR_INVALID_VALUE;
3132     }
3133 
3134     if (ImplicitStartProcessor::IsImplicitStartAction(extensionSessionInfo->want)) {
3135         TAG_LOGE(AAFwkTag::ABILITYMGR, "UI extension ability donot support implicit start.");
3136         eventInfo.errCode = ERR_INVALID_VALUE;
3137         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3138         return ERR_INVALID_VALUE;
3139     }
3140 
3141     AbilityRequest abilityRequest;
3142     abilityRequest.Voluation(extensionSessionInfo->want, DEFAULT_INVAL_VALUE, callerToken);
3143     abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
3144     abilityRequest.sessionInfo = extensionSessionInfo;
3145     result = GenerateEmbeddableUIAbilityRequest(extensionSessionInfo->want, abilityRequest, callerToken, validUserId);
3146     CHECK_POINTER_AND_RETURN(abilityRequest.sessionInfo, ERR_INVALID_VALUE);
3147     abilityRequest.sessionInfo->uiExtensionComponentId = (
3148         static_cast<uint64_t>(callerRecord->GetRecordId()) << OFFSET) |
3149         static_cast<uint64_t>(abilityRequest.sessionInfo->persistentId);
3150     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
3151         abilityRequest.sessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3152     if (result != ERR_OK) {
3153         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
3154         eventInfo.errCode = result;
3155         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3156         return result;
3157     }
3158     abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
3159 
3160     auto abilityInfo = abilityRequest.abilityInfo;
3161     threadLocalInfo.SetStartAbilityInfo(abilityInfo);
3162     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3163     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
3164         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3165 
3166     result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType, true);
3167     if (result != ERR_OK) {
3168         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error.");
3169         eventInfo.errCode = result;
3170         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3171         return result;
3172     }
3173 
3174     sptr<IRemoteObject> parentToken = extensionSessionInfo->parentToken;
3175     if (parentToken && parentToken != callerToken) {
3176         UpdateCallerInfoFromToken(abilityRequest.want, parentToken);
3177     }
3178 
3179     result = JudgeAbilityVisibleControl(abilityInfo);
3180     if (result != ERR_OK) {
3181         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3182         eventInfo.errCode = result;
3183         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3184         return result;
3185     }
3186 
3187     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
3188         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
3189     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
3190         afterCheckExecuter_->DoProcess(afterCheckParam);
3191     if (result != ERR_OK) {
3192         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
3193         return result;
3194     }
3195 
3196     auto connectManager = GetConnectManagerByUserId(validUserId);
3197     if (!connectManager) {
3198         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
3199         eventInfo.errCode = ERR_INVALID_VALUE;
3200         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3201         return ERR_INVALID_VALUE;
3202     }
3203     ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
3204     TAG_LOGI(AAFwkTag::ABILITYMGR, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
3205     UriUtils::GetInstance().CheckUriPermissionForUIExtension(abilityRequest.want,
3206         abilityRequest.abilityInfo.extensionAbilityType);
3207     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
3208     if (eventInfo.errCode != ERR_OK) {
3209         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3210     }
3211     return eventInfo.errCode;
3212 }
3213 
StopExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)3214 int AbilityManagerService::StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
3215     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
3216 {
3217     TAG_LOGI(AAFwkTag::ABILITYMGR,
3218         "Stop extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
3219         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3220     if (extensionType != AppExecFwk::ExtensionAbilityType::VPN) {
3221         CHECK_CALLER_IS_SYSTEM_APP;
3222     }
3223     EventInfo eventInfo = BuildEventInfo(want, userId);
3224     eventInfo.extensionType = static_cast<int32_t>(extensionType);
3225 
3226     int result;
3227 #ifdef WITH_DLP
3228     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::STOP_EXTENSION_ERROR);
3229     if (result != ERR_OK) {
3230         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
3231         return result;
3232     }
3233 #endif // WITH_DLP
3234 
3235     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3236         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
3237         if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
3238             TAG_LOGE(AAFwkTag::ABILITYMGR, "VerificationAllToken failed.");
3239             eventInfo.errCode = ERR_INVALID_VALUE;
3240             EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3241             return ERR_INVALID_CALLER;
3242         }
3243         TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller is specific system ability.");
3244     }
3245 
3246     int32_t validUserId = GetValidUserId(userId);
3247     if (!JudgeMultiUserConcurrency(validUserId)) {
3248         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
3249         eventInfo.errCode = ERR_INVALID_VALUE;
3250         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3251         return ERR_CROSS_USER;
3252     }
3253 
3254     if (callerToken != nullptr && CheckIfOperateRemote(want)) {
3255         auto callerUid = IPCSkeleton::GetCallingUid();
3256         uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3257         DistributedClient dmsClient;
3258         return dmsClient.StopRemoteExtensionAbility(want, callerUid, accessToken, eventInfo.extensionType);
3259     }
3260 
3261     AbilityRequest abilityRequest;
3262     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
3263     if (result != ERR_OK) {
3264         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
3265         eventInfo.errCode = result;
3266         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3267         return result;
3268     }
3269 
3270     auto abilityInfo = abilityRequest.abilityInfo;
3271     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3272     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
3273         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3274 
3275     result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
3276     if (result != ERR_OK) {
3277         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error.");
3278         eventInfo.errCode = result;
3279         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3280         return result;
3281     }
3282 
3283     auto connectManager = GetConnectManagerByUserId(validUserId);
3284     if (!connectManager) {
3285         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
3286         eventInfo.errCode = ERR_INVALID_VALUE;
3287         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3288         return ERR_INVALID_VALUE;
3289     }
3290     TAG_LOGI(AAFwkTag::ABILITYMGR, "Stop extension begin, name is %{public}s.", abilityInfo.name.c_str());
3291     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3292     if (eventInfo.errCode != ERR_OK) {
3293         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3294     }
3295     return eventInfo.errCode;
3296 }
3297 
StopSwitchUserDialog()3298 void AbilityManagerService::StopSwitchUserDialog()
3299 {
3300     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog extension ability come");
3301     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3302         TAG_LOGE(AAFwkTag::ABILITYMGR, "Scene board enabled.");
3303         return;
3304     }
3305 
3306     if (userController_ == nullptr || userController_->GetFreezingNewUserId() == DEFAULT_INVAL_VALUE) {
3307         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get last userId error.");
3308         return;
3309     }
3310 
3311     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
3312     if (sysDialog == nullptr) {
3313         TAG_LOGE(AAFwkTag::ABILITYMGR, "System dialog scheduler instance is nullptr.");
3314         return;
3315     }
3316     Want stopWant = sysDialog->GetSwitchUserDialogWant();
3317     StopSwitchUserDialogInner(stopWant, userController_->GetFreezingNewUserId());
3318 
3319     userController_->SetFreezingNewUserId(DEFAULT_INVAL_VALUE);
3320     return;
3321 }
3322 
StopSwitchUserDialogInner(const Want & want,const int32_t lastUserId)3323 void AbilityManagerService::StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)
3324 {
3325     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog inner come");
3326     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
3327     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
3328     AbilityRequest abilityRequest;
3329     auto result =
3330         GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
3331     if (result != ERR_OK) {
3332         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
3333         eventInfo.errCode = result;
3334         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3335         return;
3336     }
3337 
3338     auto abilityInfo = abilityRequest.abilityInfo;
3339     auto stopUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
3340     result = CheckOptExtensionAbility(want, abilityRequest, stopUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
3341     if (result != ERR_OK) {
3342         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check extensionAbility type error.");
3343         eventInfo.errCode = result;
3344         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3345         return;
3346     }
3347 
3348     auto connectManager = GetConnectManagerByUserId(stopUserId);
3349     if (connectManager == nullptr) {
3350         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectManager is nullptr. userId:%{public}d", stopUserId);
3351         eventInfo.errCode = ERR_INVALID_VALUE;
3352         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3353         return;
3354     }
3355 
3356     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3357     if (eventInfo.errCode != ERR_OK) {
3358         TAG_LOGE(AAFwkTag::ABILITYMGR, "EventInfo errCode is %{public}d", eventInfo.errCode);
3359         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3360     }
3361 }
3362 
MoveAbilityToBackground(const sptr<IRemoteObject> & token)3363 int AbilityManagerService::MoveAbilityToBackground(const sptr<IRemoteObject> &token)
3364 {
3365     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3366     TAG_LOGD(AAFwkTag::ABILITYMGR, "Move ability to background begin");
3367     if (!VerificationAllToken(token)) {
3368         return ERR_INVALID_VALUE;
3369     }
3370     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3371     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3372     if (!JudgeSelfCalled(abilityRecord)) {
3373         return CHECK_PERMISSION_FAILED;
3374     }
3375 
3376     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3377         return ERR_WOULD_BLOCK;
3378     }
3379 
3380     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3381     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3382     if (!missionListManager) {
3383         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
3384         return ERR_INVALID_VALUE;
3385     }
3386     return missionListManager->MoveAbilityToBackground(abilityRecord);
3387 }
3388 
MoveUIAbilityToBackground(const sptr<IRemoteObject> token)3389 int32_t AbilityManagerService::MoveUIAbilityToBackground(const sptr<IRemoteObject> token)
3390 {
3391     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3392     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
3393     if (!AppUtils::GetInstance().EnableMoveUIAbilityToBackgroundApi()) {
3394         return ERR_OPERATION_NOT_SUPPORTED_ON_CURRENT_DEVICE;
3395     }
3396     if (!VerificationAllToken(token)) {
3397         return ERR_INVALID_VALUE;
3398     }
3399     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3400     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3401     if (!IsAppSelfCalled(abilityRecord)) {
3402         return CHECK_PERMISSION_FAILED;
3403     }
3404     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3405         TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not move ability to background in Wukong mode.");
3406         return ERR_WUKONG_MODE_CANT_MOVE_STATE;
3407     }
3408     if (!abilityRecord->IsAbilityState(FOREGROUND) && !abilityRecord->IsAbilityState(FOREGROUNDING)) {
3409         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability not in foregorund state.");
3410         return ERR_ABILITY_NOT_FOREGROUND;
3411     }
3412     if (abilityRecord->GetAbilityInfo().type != AppExecFwk::AbilityType::PAGE) {
3413         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot background non UIAbility.");
3414         return RESOLVE_CALL_ABILITY_TYPE_ERR;
3415     }
3416     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3417     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3418         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3419         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3420         return uiAbilityManager->NotifySCBToMinimizeUIAbility(token);
3421     }
3422 
3423     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3424     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3425     return missionListManager->MoveAbilityToBackground(abilityRecord);
3426 }
3427 
TerminateAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3428 int AbilityManagerService::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3429 {
3430     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3431     if (!abilityRecord) {
3432         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
3433         return ERR_INVALID_VALUE;
3434     }
3435     return TerminateAbilityWithFlag(token, resultCode, resultWant, true);
3436 }
3437 
TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> & token)3438 int32_t AbilityManagerService::TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> &token)
3439 {
3440     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3441     if (!VerificationAllToken(token)) {
3442         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
3443         return ERR_INVALID_VALUE;
3444     }
3445 
3446     if (!IsCallerSceneBoard()) {
3447         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3448         return ERR_WRONG_INTERFACE_CALL;
3449     }
3450 
3451     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3452     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3453 
3454     auto type = abilityRecord->GetAbilityInfo().type;
3455     auto extensionAbilityType = abilityRecord->GetAbilityInfo().extensionAbilityType;
3456 
3457     if (type != AppExecFwk::AbilityType::EXTENSION  ||
3458         extensionAbilityType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3459             return ERR_INVALID_VALUE;
3460     }
3461 
3462     auto userId = GetValidUserId(DEFAULT_INVAL_VALUE);
3463     auto connectManager = GetConnectManagerByUserId(userId);
3464     if (!connectManager) {
3465         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
3466         return ERR_INVALID_VALUE;
3467     }
3468     return connectManager->TerminateAbility(token);
3469 }
3470 
BackToCallerAbilityWithResult(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,int64_t callerRequestCode)3471 int AbilityManagerService::BackToCallerAbilityWithResult(const sptr<IRemoteObject> &token, int resultCode,
3472     const Want *resultWant, int64_t callerRequestCode)
3473 {
3474     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3475     if (!abilityRecord) {
3476         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
3477         return ERR_INVALID_VALUE;
3478     }
3479     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3480     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3481         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3482         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3483         return uiAbilityManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant,
3484             callerRequestCode);
3485     }
3486     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3487     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3488     return missionListManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant, callerRequestCode);
3489 }
3490 
CloseAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3491 int AbilityManagerService::CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3492 {
3493     EventInfo eventInfo;
3494     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3495     return TerminateAbilityWithFlag(token, resultCode, resultWant, false);
3496 }
3497 
TerminateAbilityWithFlag(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,bool flag)3498 int AbilityManagerService::TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode,
3499     const Want *resultWant, bool flag)
3500 {
3501     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3502     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ability begin, flag:%{public}d.", flag);
3503     if (!VerificationAllToken(token)) {
3504         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
3505         return ERR_INVALID_VALUE;
3506     }
3507 
3508     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3509     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3510     if (!JudgeSelfCalled(abilityRecord)) {
3511         return CHECK_PERMISSION_FAILED;
3512     }
3513 
3514     if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) {
3515         TAG_LOGE(AAFwkTag::ABILITYMGR, "System ui not allow terminate.");
3516         return ERR_INVALID_VALUE;
3517     }
3518 
3519     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
3520     auto type = abilityRecord->GetAbilityInfo().type;
3521     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
3522         auto connectManager = GetConnectManagerByUserId(userId);
3523         if (!connectManager) {
3524             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
3525             return ERR_INVALID_VALUE;
3526         }
3527         return connectManager->TerminateAbility(token);
3528     }
3529 
3530     if (type == AppExecFwk::AbilityType::DATA) {
3531         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot terminate data ability, use 'ReleaseDataAbility()' instead.");
3532         return ERR_WRONG_INTERFACE_CALL;
3533     }
3534 
3535     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3536         return ERR_WOULD_BLOCK;
3537     }
3538 
3539     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3540     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3541     if (missionListManager) {
3542         return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag);
3543     }
3544     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
3545     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3546         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3547         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3548         return uiAbilityManager->CloseUIAbility(abilityRecord, resultCode, resultWant, false);
3549     }
3550     return ERR_INVALID_VALUE;
3551 }
3552 
TerminateUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int resultCode,const Want * resultWant)3553 int AbilityManagerService::TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode,
3554     const Want *resultWant)
3555 {
3556     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3557     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ui extension ability begin.");
3558     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3559     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3560     std::shared_ptr<AbilityConnectManager> connectManager;
3561     std::shared_ptr<AbilityRecord> targetRecord;
3562     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3563     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3564     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3565 
3566     // self terminate or caller terminate is allowed.
3567     if (!(JudgeSelfCalled(targetRecord) || (abilityRecord != nullptr && JudgeSelfCalled(abilityRecord)))) {
3568         return CHECK_PERMISSION_FAILED;
3569     }
3570 
3571     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3572     if (result != ERR_OK) {
3573         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3574         return result;
3575     }
3576 
3577     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3578         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot terminate except ui extension ability.");
3579         return ERR_WRONG_INTERFACE_CALL;
3580     }
3581 
3582     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension persistentId: %{public}d, element: %{public}s.",
3583         extensionSessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3584     connectManager->TerminateAbilityWindowLocked(targetRecord, extensionSessionInfo);
3585     return ERR_OK;
3586 }
3587 
CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)3588 int AbilityManagerService::CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)
3589 {
3590     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3591     TAG_LOGD(AAFwkTag::ABILITYMGR, "close uiextensionability by scb");
3592     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
3593 
3594     if (!IsCallerSceneBoard()) {
3595         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
3596         return ERR_PERMISSION_DENIED;
3597     }
3598 
3599     if (!VerificationAllToken(token)) {
3600         TAG_LOGE(AAFwkTag::ABILITYMGR, "verificationAllToken failed");
3601         return ERR_INVALID_VALUE;
3602     }
3603 
3604     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3605     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3606     if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
3607         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability %{public}s not an uiextensionability",
3608             abilityRecord->GetURI().c_str());
3609         return ERR_INVALID_VALUE;
3610     }
3611 
3612     auto sessionInfo = abilityRecord->GetSessionInfo();
3613     if (sessionInfo == nullptr) {
3614         TAG_LOGE(AAFwkTag::ABILITYMGR, "target session info is null, ability: %{public}s",
3615             abilityRecord->GetURI().c_str());
3616         return ERR_INVALID_VALUE;
3617     }
3618 
3619     std::shared_ptr<AbilityConnectManager> connectManager;
3620     std::shared_ptr<AbilityRecord> targetRecord;
3621     GetConnectManagerAndUIExtensionBySessionInfo(sessionInfo, connectManager, targetRecord);
3622     if (connectManager == nullptr) {
3623         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null, ability: %{public}s", abilityRecord->GetURI().c_str());
3624         return ERR_INVALID_VALUE;
3625     }
3626 
3627     sptr<Rosen::ISession> sessionProxy = iface_cast<Rosen::ISession>(sessionInfo->sessionToken);
3628     if (sessionProxy == nullptr) {
3629         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get session proxy failed, ability: %{public}s",
3630             abilityRecord->GetURI().c_str());
3631         return ERR_INVALID_VALUE;
3632     }
3633 
3634     // notify caller sync detach
3635     sessionProxy->NotifyExtensionDetachToDisplay();
3636     connectManager->TerminateAbilityWindowLocked(abilityRecord, sessionInfo);
3637     return ERR_OK;
3638 }
3639 
CloseUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)3640 int AbilityManagerService::CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
3641 {
3642     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3643     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3644         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
3645         return ERR_INVALID_VALUE;
3646     }
3647 
3648     if (!IsCallerSceneBoard()) {
3649         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
3650         return ERR_WRONG_INTERFACE_CALL;
3651     }
3652 
3653     SetMinimizedDuringFreeInstall(sessionInfo);
3654 
3655     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3656     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3657     TAG_LOGI(AAFwkTag::ABILITYMGR,
3658         "close session: %{public}d, resultCode: %{public}d", sessionInfo->persistentId, sessionInfo->resultCode);
3659     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3660     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3661     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3662         return ERR_WOULD_BLOCK;
3663     }
3664 
3665     if (sessionInfo->isClearSession) {
3666         const auto &abilityInfo = abilityRecord->GetAbilityInfo();
3667         std::string abilityName = abilityInfo.name;
3668         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
3669             abilityName += std::to_string(sessionInfo->persistentId);
3670         }
3671         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
3672             DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
3673     }
3674     EventInfo eventInfo;
3675     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
3676     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
3677     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3678     eventInfo.errCode = uiAbilityManager->CloseUIAbility(abilityRecord, sessionInfo->resultCode,
3679         &(sessionInfo->want), sessionInfo->isClearSession);
3680     if (eventInfo.errCode != ERR_OK) {
3681         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
3682     }
3683     return eventInfo.errCode;
3684 }
3685 
SendResultToAbility(int32_t requestCode,int32_t resultCode,Want & resultWant)3686 int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)
3687 {
3688     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3689     if (!CheckCallerIsDmsProcess()) {
3690         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check processName failed");
3691         return ERR_INVALID_VALUE;
3692     }
3693     int missionId = resultWant.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
3694     resultWant.RemoveParam(DMS_MISSION_ID);
3695     if (missionId == DEFAULT_DMS_MISSION_ID) {
3696         TAG_LOGE(AAFwkTag::ABILITYMGR, "MissionId is empty");
3697         return ERR_INVALID_VALUE;
3698     }
3699     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
3700     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3701         auto uiAbilityManager = GetCurrentUIAbilityManager();
3702         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3703         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
3704     } else {
3705         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
3706         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3707         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
3708     }
3709     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3710 
3711     abilityRecord->SetResult(std::make_shared<AbilityResult>(requestCode, resultCode, resultWant));
3712     abilityRecord->SendResult(0, 0);
3713     return ERR_OK;
3714 }
3715 
StartRemoteAbility(const Want & want,int requestCode,int32_t validUserId,const sptr<IRemoteObject> & callerToken)3716 int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId,
3717     const sptr<IRemoteObject> &callerToken)
3718 {
3719     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3720     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3721     Want remoteWant = want;
3722     UpdateDmsCallerInfo(remoteWant, callerToken);
3723     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
3724         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
3725         return ERR_INVALID_VALUE;
3726     }
3727     if (AbilityUtil::IsStartFreeInstall(remoteWant)) {
3728         return freeInstallManager_ == nullptr ? ERR_INVALID_VALUE :
3729             freeInstallManager_->StartRemoteFreeInstall(remoteWant, requestCode, validUserId, callerToken);
3730     }
3731     if (remoteWant.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
3732         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: try to StartAbilityForResult", __func__);
3733         int32_t missionId = -1;
3734         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3735             missionId = GetMissionIdByAbilityTokenInner(callerToken);
3736             if (!missionId) {
3737                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
3738                 return ERR_INVALID_VALUE;
3739             }
3740         } else {
3741             missionId = GetMissionIdByAbilityToken(callerToken);
3742         }
3743         if (missionId < 0) {
3744             return ERR_INVALID_VALUE;
3745         }
3746         remoteWant.SetParam(DMS_MISSION_ID, missionId);
3747     }
3748 
3749     int32_t callerUid = IPCSkeleton::GetCallingUid();
3750     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3751     UriUtils::GetInstance().FilterUriWithPermissionDms(remoteWant, accessToken);
3752     DistributedClient dmsClient;
3753     int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken);
3754     if (result != ERR_NONE) {
3755         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartRemoteAbility failed, result = %{public}d", result);
3756     }
3757     return result;
3758 }
3759 
CheckIsRemote(const std::string & deviceId)3760 bool AbilityManagerService::CheckIsRemote(const std::string& deviceId)
3761 {
3762     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3763     if (deviceId.empty()) {
3764         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckIsRemote: deviceId is empty.");
3765         return false;
3766     }
3767     std::string localDeviceId;
3768     if (!GetLocalDeviceId(localDeviceId)) {
3769         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckIsRemote: get local deviceId failed");
3770         return false;
3771     }
3772     if (localDeviceId == deviceId) {
3773         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckIsRemote: deviceId is local.");
3774         return false;
3775     }
3776     TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str());
3777     return true;
3778 }
3779 
CheckIfOperateRemote(const Want & want)3780 bool AbilityManagerService::CheckIfOperateRemote(const Want &want)
3781 {
3782     std::string deviceId = want.GetElement().GetDeviceID();
3783     if (deviceId.empty() || want.GetElement().GetBundleName().empty() ||
3784         want.GetElement().GetAbilityName().empty()) {
3785         TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty");
3786         return false;
3787     }
3788     return CheckIsRemote(deviceId);
3789 }
3790 
GetLocalDeviceId(std::string & localDeviceId)3791 bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId)
3792 {
3793     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3794     auto localNode = std::make_unique<NodeBasicInfo>();
3795     int32_t errCode = GetLocalNodeDeviceInfo(DM_PKG_NAME, localNode.get());
3796     if (errCode != ERR_OK) {
3797         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::GetLocalNodeDeviceInfo errCode = %{public}d", errCode);
3798         return false;
3799     }
3800     if (localNode != nullptr) {
3801         localDeviceId = localNode->networkId;
3802         TAG_LOGD(AAFwkTag::ABILITYMGR, "get local deviceId, deviceId = %{public}s",
3803             AnonymizeDeviceId(localDeviceId).c_str());
3804         return true;
3805     }
3806     TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::GetLocalDeviceId localDeviceId null");
3807     return false;
3808 }
3809 
AnonymizeDeviceId(const std::string & deviceId)3810 std::string AbilityManagerService::AnonymizeDeviceId(const std::string& deviceId)
3811 {
3812     if (deviceId.length() < NON_ANONYMIZE_LENGTH) {
3813         return EMPTY_DEVICE_ID;
3814     }
3815     std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
3816     anonDeviceId.append("******");
3817     return anonDeviceId;
3818 }
3819 
MinimizeAbility(const sptr<IRemoteObject> & token,bool fromUser)3820 int AbilityManagerService::MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)
3821 {
3822     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3823     TAG_LOGI(AAFwkTag::ABILITYMGR, "Minimize ability, fromUser:%{public}d.", fromUser);
3824     if (!VerificationAllToken(token)) {
3825         return ERR_INVALID_VALUE;
3826     }
3827 
3828     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3829     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3830     if (!JudgeSelfCalled(abilityRecord)) {
3831         return CHECK_PERMISSION_FAILED;
3832     }
3833 
3834     auto type = abilityRecord->GetAbilityInfo().type;
3835     if (type != AppExecFwk::AbilityType::PAGE) {
3836         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except page ability.");
3837         return ERR_WRONG_INTERFACE_CALL;
3838     }
3839 
3840     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3841         return ERR_WOULD_BLOCK;
3842     }
3843 
3844     auto missionListManager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
3845     if (!missionListManager) {
3846         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null.");
3847         return ERR_INVALID_VALUE;
3848     }
3849     return missionListManager->MinimizeAbility(token, fromUser);
3850 }
3851 
MinimizeUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,bool fromUser)3852 int AbilityManagerService::MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo,
3853     bool fromUser)
3854 {
3855     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3856     TAG_LOGD(AAFwkTag::ABILITYMGR, "Minimize ui extension ability, fromUser:%{public}d.", fromUser);
3857     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3858     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3859     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3860     if (!JudgeSelfCalled(abilityRecord)) {
3861         return CHECK_PERMISSION_FAILED;
3862     }
3863 
3864     std::shared_ptr<AbilityConnectManager> connectManager;
3865     std::shared_ptr<AbilityRecord> targetRecord;
3866     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3867     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3868     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3869 
3870     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3871     if (result != ERR_OK) {
3872         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3873         return result;
3874     }
3875 
3876     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3877         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except ui extension ability.");
3878         return ERR_WRONG_INTERFACE_CALL;
3879     }
3880     extensionSessionInfo->uiExtensionComponentId = (
3881         static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
3882         static_cast<uint64_t>(extensionSessionInfo->persistentId);
3883     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
3884         extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3885     connectManager->BackgroundAbilityWindowLocked(targetRecord, extensionSessionInfo);
3886     return ERR_OK;
3887 }
3888 
SetMinimizedDuringFreeInstall(const sptr<SessionInfo> & sessionInfo)3889 void AbilityManagerService::SetMinimizedDuringFreeInstall(const sptr<SessionInfo> &sessionInfo)
3890 {
3891     if (sessionInfo == nullptr) {
3892         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
3893         return;
3894     }
3895 
3896     if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
3897         return;
3898     }
3899 
3900     std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
3901     if (sessionId.empty()) {
3902         return;
3903     }
3904 
3905     if (freeInstallManager_ == nullptr) {
3906         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
3907         return;
3908     }
3909     FreeInstallInfo taskInfo;
3910     if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
3911         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task with sessionId=%{public}s does not exist",
3912             sessionId.c_str());
3913         return;
3914     }
3915 
3916     if (taskInfo.isFreeInstallFinished) {
3917         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
3918         return;
3919     }
3920 
3921     {
3922         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
3923         auto it = preStartSessionMap_.find(sessionId);
3924         if (it == preStartSessionMap_.end()) {
3925             TAG_LOGI(AAFwkTag::ABILITYMGR, "session info with sessionId=%{public}s does not exist",
3926                 sessionId.c_str());
3927             return;
3928         }
3929         it->second->isMinimizedDuringFreeInstall = true;
3930     }
3931 }
3932 
MinimizeUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool fromUser,uint32_t sceneFlag)3933 int AbilityManagerService::MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser,
3934     uint32_t sceneFlag)
3935 {
3936     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3937     TAG_LOGI(AAFwkTag::ABILITYMGR, "Called, sceneFlag: %{public}u", sceneFlag);
3938     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3939         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
3940         return ERR_INVALID_VALUE;
3941     }
3942 
3943     if (!IsCallerSceneBoard()) {
3944         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
3945         return ERR_WRONG_INTERFACE_CALL;
3946     }
3947 
3948     SetMinimizedDuringFreeInstall(sessionInfo);
3949 
3950     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3951     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3952     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3953     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3954     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3955         return ERR_WOULD_BLOCK;
3956     }
3957     return uiAbilityManager->MinimizeUIAbility(abilityRecord, fromUser, sceneFlag);
3958 }
3959 
ConnectAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t userId)3960 int AbilityManagerService::ConnectAbility(
3961     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)
3962 {
3963     return ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::SERVICE, userId);
3964 }
3965 
ConnectAbilityCommon(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,AppExecFwk::ExtensionAbilityType extensionType,int32_t userId,bool isQueryExtensionOnly)3966 int AbilityManagerService::ConnectAbilityCommon(
3967     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
3968     AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)
3969 {
3970     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3971     TAG_LOGI(AAFwkTag::ABILITYMGR,
3972         "Connect ability called, element uri: %{public}s.", want.GetElement().GetURI().c_str());
3973     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3974     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3975     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE && want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
3976         TAG_LOGE(AAFwkTag::ABILITYMGR, "error to have UISERVICEHOSTPROXY_KEY");
3977         return ERR_WRONG_INTERFACE_CALL;
3978     }
3979     if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && IsCrossUserCall(userId)) {
3980         CHECK_CALLER_IS_SYSTEM_APP;
3981     }
3982     EventInfo eventInfo = BuildEventInfo(want, userId);
3983 
3984     int result;
3985 #ifdef WITH_DLP
3986     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
3987     if (result != ERR_OK) {
3988         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
3989         eventInfo.errCode = result;
3990         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3991         return result;
3992     }
3993 #endif // WITH_DLP
3994 
3995     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
3996     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3997         interceptorExecuter_->DoProcess(interceptorParam);
3998     if (result != ERR_OK) {
3999         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
4000         eventInfo.errCode = result;
4001         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4002         return result;
4003     }
4004 
4005     int32_t validUserId = GetValidUserId(userId);
4006 
4007     if (AbilityUtil::IsStartFreeInstall(want) && freeInstallManager_ != nullptr) {
4008         std::string localDeviceId;
4009         if (!GetLocalDeviceId(localDeviceId)) {
4010             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Get Local DeviceId failed", __func__);
4011             eventInfo.errCode = ERR_INVALID_VALUE;
4012             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4013             return ERR_INVALID_VALUE;
4014         }
4015         result = freeInstallManager_->ConnectFreeInstall(want, validUserId, callerToken, localDeviceId);
4016         if (result != ERR_OK) {
4017             eventInfo.errCode = result;
4018             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4019             return result;
4020         }
4021     }
4022 
4023     Want abilityWant = want;
4024     AbilityRequest abilityRequest;
4025     std::string uri = abilityWant.GetUri().ToString();
4026     bool isFileUri = (abilityWant.GetUri().GetScheme() == "file");
4027     if (!uri.empty() && !isFileUri) {
4028         // if the want include uri, it may only has uri information. it is probably a datashare extension.
4029         TAG_LOGD(AAFwkTag::ABILITYMGR,
4030             "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
4031         AppExecFwk::ExtensionAbilityInfo extensionInfo;
4032         auto bms = GetBundleManager();
4033         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4034 
4035         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4036         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4037             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid extension ability info.");
4038             eventInfo.errCode = ERR_INVALID_VALUE;
4039             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4040             return ERR_INVALID_VALUE;
4041         }
4042         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4043     }
4044 
4045     if (CheckIfOperateRemote(abilityWant)) {
4046         TAG_LOGD(AAFwkTag::ABILITYMGR, "AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility");
4047         eventInfo.errCode = ConnectRemoteAbility(abilityWant, callerToken, connect->AsObject());
4048         if (eventInfo.errCode != ERR_OK) {
4049             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4050         }
4051         return eventInfo.errCode;
4052     }
4053     UpdateCallerInfo(abilityWant, callerToken);
4054 
4055     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4056         TAG_LOGD(AAFwkTag::ABILITYMGR, "invalid Token.");
4057         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr, extensionType);
4058         if (eventInfo.errCode != ERR_OK) {
4059             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4060         }
4061         return eventInfo.errCode;
4062     }
4063     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken, extensionType, nullptr,
4064         isQueryExtensionOnly);
4065     if (eventInfo.errCode != ERR_OK) {
4066         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4067     }
4068     return eventInfo.errCode;
4069 }
4070 
ConnectUIExtensionAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<SessionInfo> & sessionInfo,int32_t userId,sptr<UIExtensionAbilityConnectInfo> connectInfo)4071 int AbilityManagerService::ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect,
4072     const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4073 {
4074     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4075     TAG_LOGD(AAFwkTag::ABILITYMGR,
4076         "Connect ui extension called, bundlename: %{public}s, ability is %{public}s, userId is %{pravite}d",
4077         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
4078     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4079     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4080     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
4081 
4082     if (IsCrossUserCall(userId)) {
4083         CHECK_CALLER_IS_SYSTEM_APP;
4084     }
4085 
4086     EventInfo eventInfo = BuildEventInfo(want, userId);
4087     sptr<IRemoteObject> callerToken = sessionInfo->callerToken;
4088 
4089     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
4090         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectUIExtensionAbility VerificationAllToken failed.");
4091         eventInfo.errCode = ERR_INVALID_VALUE;
4092         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4093         return ERR_INVALID_CALLER;
4094     }
4095 
4096     int result;
4097 #ifdef WITH_DLP
4098     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
4099     if (result != ERR_OK) {
4100         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
4101         eventInfo.errCode = result;
4102         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4103         return result;
4104     }
4105 #endif // WITH_DLP
4106 
4107     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
4108     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4109         interceptorExecuter_->DoProcess(interceptorParam);
4110     if (result != ERR_OK) {
4111         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
4112         eventInfo.errCode = result;
4113         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4114         return result;
4115     }
4116 
4117     int32_t validUserId = GetValidUserId(userId);
4118 
4119     Want abilityWant = want;
4120     AbilityRequest abilityRequest;
4121     std::string uri = abilityWant.GetUri().ToString();
4122     if (!uri.empty()) {
4123         // if the want include uri, it may only has uri information.
4124         TAG_LOGI(AAFwkTag::ABILITYMGR,
4125             "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
4126         AppExecFwk::ExtensionAbilityInfo extensionInfo;
4127         auto bms = GetBundleManager();
4128         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4129 
4130         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4131         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4132             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid extension ability info.");
4133             eventInfo.errCode = ERR_INVALID_VALUE;
4134             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4135             return ERR_INVALID_VALUE;
4136         }
4137         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4138     }
4139 
4140     UpdateCallerInfo(abilityWant, callerToken);
4141 
4142     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4143         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s invalid Token.", __func__);
4144         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr,
4145             AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4146         if (eventInfo.errCode != ERR_OK) {
4147             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4148         }
4149         return eventInfo.errCode;
4150     }
4151     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken,
4152         AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4153     if (eventInfo.errCode != ERR_OK) {
4154         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4155     }
4156     return eventInfo.errCode;
4157 }
4158 
BuildEventInfo(const Want & want,int32_t userId)4159 EventInfo AbilityManagerService::BuildEventInfo(const Want &want, int32_t userId)
4160 {
4161     EventInfo eventInfo;
4162     eventInfo.userId = userId;
4163     eventInfo.bundleName = want.GetElement().GetBundleName();
4164     eventInfo.moduleName = want.GetElement().GetModuleName();
4165     eventInfo.abilityName = want.GetElement().GetAbilityName();
4166     return eventInfo;
4167 }
4168 
DisconnectAbility(sptr<IAbilityConnection> connect)4169 int AbilityManagerService::DisconnectAbility(sptr<IAbilityConnection> connect)
4170 {
4171     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4172     TAG_LOGD(AAFwkTag::ABILITYMGR, "Disconnect ability begin.");
4173     EventInfo eventInfo;
4174     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4175     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4176 
4177     if (ERR_OK != DisconnectLocalAbility(connect) &&
4178         ERR_OK != DisconnectRemoteAbility(connect->AsObject())) {
4179         eventInfo.errCode = INNER_ERR;
4180         EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4181     }
4182     return ERR_OK;
4183 }
4184 
ConnectLocalAbility(const Want & want,const int32_t userId,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,AppExecFwk::ExtensionAbilityType extensionType,const sptr<SessionInfo> & sessionInfo,bool isQueryExtensionOnly,sptr<UIExtensionAbilityConnectInfo> connectInfo)4185 int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId,
4186     const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
4187     AppExecFwk::ExtensionAbilityType extensionType, const sptr<SessionInfo> &sessionInfo,
4188     bool isQueryExtensionOnly, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4189 {
4190     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4191     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4192     StartAbilityInfoWrap threadLocalInfo;
4193     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
4194     bool isEnterpriseAdmin = AAFwk::UIExtensionUtils::IsEnterpriseAdmin(extensionType);
4195     if (!isEnterpriseAdmin && !JudgeMultiUserConcurrency(userId)) {
4196         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
4197         return ERR_CROSS_USER;
4198     }
4199 
4200     AbilityRequest abilityRequest;
4201     ErrCode result = ERR_OK;
4202     if (isQueryExtensionOnly ||
4203         AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4204         result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, userId);
4205     } else {
4206         result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId);
4207     }
4208     abilityRequest.sessionInfo = sessionInfo;
4209 
4210     Want requestWant = want;
4211     CHECK_POINTER_AND_RETURN_LOG(connect, ERR_INVALID_VALUE, "connect is nullptr");
4212     TAG_LOGD(AAFwkTag::ABILITYMGR, "requestWant SetParam success");
4213 
4214     if (result != ERR_OK) {
4215         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
4216         return result;
4217     }
4218 
4219     result = CheckPermissionForUIService(extensionType, want, abilityRequest);
4220     if (result != ERR_OK) {
4221         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckPermissionForUIService failed");
4222         return result;
4223     }
4224     auto abilityInfo = abilityRequest.abilityInfo;
4225     threadLocalInfo.SetStartAbilityInfo(abilityInfo);
4226     if (abilityInfo.isStageBasedModel) {
4227         bool isService = (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE);
4228         if (isService && extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
4229             TAG_LOGE(AAFwkTag::ABILITYMGR, "Service extension type, please use ConnectAbility.");
4230             return ERR_WRONG_INTERFACE_CALL;
4231         }
4232         // not allow app to connect other extension by using connectServiceExtensionAbility
4233         bool isVpn = abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::VPN;
4234         if (callerToken && extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && !isService && !isVpn) {
4235             TAG_LOGE(AAFwkTag::ABILITYMGR, "ability, type not service");
4236             return TARGET_ABILITY_NOT_SERVICE;
4237         }
4238     }
4239     int32_t validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : userId;
4240     TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
4241         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
4242 
4243     result = CheckStaticCfgPermission(abilityRequest, false, -1);
4244     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
4245         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
4246         return ERR_STATIC_CFG_PERMISSION;
4247     }
4248 
4249     AppExecFwk::ExtensionAbilityType targetExtensionType = abilityInfo.extensionAbilityType;
4250     TAG_LOGD(AAFwkTag::ABILITYMGR, "extension type %{public}d.", targetExtensionType);
4251     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4252         if (!AAFwk::UIExtensionUtils::IsUIExtension(targetExtensionType)
4253             && targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW) {
4254             TAG_LOGE(AAFwkTag::ABILITYMGR, "Try to connect UI extension, but target ability is not UI extension.");
4255             return ERR_WRONG_INTERFACE_CALL;
4256         }
4257 
4258         // Cause window has used this api, don't check it when type is window.
4259         if (targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW &&
4260             !PermissionVerification::GetInstance()->VerifyCallingPermission(
4261                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY)) {
4262             TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
4263                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY);
4264             return ERR_PERMISSION_DENIED;
4265         }
4266     }
4267 
4268     auto type = abilityInfo.type;
4269     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4270         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not Service.");
4271         return TARGET_ABILITY_NOT_SERVICE;
4272     }
4273 
4274     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
4275         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
4276     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
4277         afterCheckExecuter_->DoProcess(afterCheckParam);
4278     if (result != ERR_OK) {
4279         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
4280         return result;
4281     }
4282 
4283     result = CheckCallServicePermission(abilityRequest);
4284     if (result != ERR_OK) {
4285         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallServicePermission error.", __func__);
4286         return result;
4287     }
4288 
4289     ReportAppConnectOtherExtensionEvent(abilityInfo, want);
4290 
4291     if (!ExtensionPermissionsUtil::CheckSAPermission(targetExtensionType)) {
4292         TAG_LOGE(AAFwkTag::ABILITYMGR, "The SA doesn't have permission for target extension.");
4293         return CHECK_PERMISSION_FAILED;
4294     }
4295 
4296     result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
4297     if (result != ERR_OK) {
4298         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectAbility: App data ability preloading failed, '%{public}s', %{public}d",
4299             abilityInfo.bundleName.c_str(),
4300             result);
4301         return result;
4302     }
4303 
4304     auto connectManager = GetConnectManagerByUserId(validUserId);
4305     if (connectManager == nullptr) {
4306         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
4307         return ERR_INVALID_VALUE;
4308     }
4309 
4310     if (targetExtensionType != AppExecFwk::ExtensionAbilityType::REMOTE_NOTIFICATION) {
4311         // this extension type is reported in connectManager instead of here
4312         ReportEventToRSS(abilityInfo, callerToken);
4313     }
4314     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(const_cast<Want &>(abilityRequest.want),
4315         abilityRequest.abilityInfo.extensionAbilityType);
4316     SetAbilityRequestSessionInfo(abilityRequest, targetExtensionType);
4317     return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo);
4318 }
4319 
ConnectRemoteAbility(Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)4320 int AbilityManagerService::ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken,
4321     const sptr<IRemoteObject> &connect)
4322 {
4323     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin ConnectAbilityRemote", __func__);
4324     UpdateDmsCallerInfo(want, callerToken);
4325     if (AddStartControlParam(want, callerToken) != ERR_OK) {
4326         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
4327         return ERR_INVALID_VALUE;
4328     }
4329     DistributedClient dmsClient;
4330     return dmsClient.ConnectRemoteAbility(want, connect);
4331 }
4332 
DisconnectLocalAbility(const sptr<IAbilityConnection> & connect)4333 int AbilityManagerService::DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)
4334 {
4335     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4336     auto currentConnectManager = GetCurrentConnectManager();
4337     CHECK_POINTER_AND_RETURN(currentConnectManager, ERR_NO_INIT);
4338     if (currentConnectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4339         return ERR_OK;
4340     }
4341     // If current connectManager does not exist connect, then try connectManagerU0
4342     auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
4343     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4344     if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4345         return ERR_OK;
4346     }
4347 
4348     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
4349     if (userId == U0_USER_ID) {
4350         auto connectManagers = GetConnectManagers();
4351         for (auto& item : connectManagers) {
4352             if (item.second && item.second->DisconnectAbilityLocked(connect) == ERR_OK) {
4353                 return ERR_OK;
4354             }
4355         }
4356     }
4357 
4358     // EnterpriseAdminExtensionAbility Scene
4359     connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT);
4360     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4361     return connectManager->DisconnectAbilityLocked(connect);
4362 }
4363 
DisconnectRemoteAbility(const sptr<IRemoteObject> & connect)4364 int AbilityManagerService::DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)
4365 {
4366     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin DisconnectAbilityRemote", __func__);
4367     int32_t callerUid = IPCSkeleton::GetCallingUid();
4368     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4369     DistributedClient dmsClient;
4370     return dmsClient.DisconnectRemoteAbility(connect, callerUid, accessToken);
4371 }
4372 
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callBack,AAFwk::WantParams & wantParams)4373 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
4374     int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
4375 {
4376     CHECK_CALLER_IS_SYSTEM_APP;
4377     TAG_LOGI(AAFwkTag::ABILITYMGR, "ContinueMission missionId: %{public}d", missionId);
4378     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4379         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4380         return CHECK_PERMISSION_FAILED;
4381     }
4382 
4383     DistributedClient dmsClient;
4384     return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams);
4385 }
4386 
ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,const sptr<IRemoteObject> & callback)4387 int AbilityManagerService::ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,
4388     const sptr<IRemoteObject> &callback)
4389 {
4390     CHECK_CALLER_IS_SYSTEM_APP;
4391     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
4392     AAFWK::ContinueRadar::GetInstance().ClickIconContinue("ContinueMission");
4393     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4394         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4395         return CHECK_PERMISSION_FAILED;
4396     }
4397 
4398     DistributedClient dmsClient;
4399     return dmsClient.ContinueMission(continueMissionInfo, callback);
4400 }
4401 
ContinueAbility(const std::string & deviceId,int32_t missionId,uint32_t versionCode)4402 int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)
4403 {
4404     TAG_LOGI(AAFwkTag::ABILITYMGR,
4405         "ContinueAbility missionId = %{public}d, version = %{public}u.", missionId, versionCode);
4406     if (!CheckCallerIsDmsProcess()) {
4407         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check processName failed");
4408         return ERR_INVALID_VALUE;
4409     }
4410 
4411     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4412     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4413         auto uiAbilityManager = GetCurrentUIAbilityManager();
4414         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4415         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4416     } else {
4417         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4418         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4419         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4420     }
4421     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4422 
4423     abilityRecord->ContinueAbility(deviceId, versionCode);
4424     return ERR_OK;
4425 }
4426 
StartContinuation(const Want & want,const sptr<IRemoteObject> & abilityToken,int32_t status)4427 int AbilityManagerService::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)
4428 {
4429     TAG_LOGI(AAFwkTag::ABILITYMGR, "Start Continuation.");
4430     if (!CheckIfOperateRemote(want)) {
4431         TAG_LOGE(AAFwkTag::ABILITYMGR, "deviceId or bundle name or abilityName empty");
4432         return ERR_INVALID_VALUE;
4433     }
4434     CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4435 
4436     int32_t appUid = IPCSkeleton::GetCallingUid();
4437     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4438         TAG_LOGI(AAFwkTag::ABILITYMGR,
4439             "AbilityManagerService::Try to StartContinuation");
4440     int32_t missionId = -1;
4441     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4442         missionId = GetMissionIdByAbilityTokenInner(abilityToken);
4443         if (!missionId) {
4444             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
4445             return ERR_INVALID_VALUE;
4446         }
4447     } else {
4448         missionId = GetMissionIdByAbilityToken(abilityToken);
4449     }
4450     if (missionId < 0) {
4451         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartContinuation failed to get missionId.");
4452         return ERR_INVALID_VALUE;
4453     }
4454     AAFWK::ContinueRadar::GetInstance().SaveDataRemoteWant("StartContinuation");
4455     DistributedClient dmsClient;
4456     auto result =  dmsClient.StartContinuation(want, missionId, appUid, status, accessToken);
4457     if (result != ERR_OK) {
4458         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartContinuation failed, result = %{public}d, notify caller", result);
4459         NotifyContinuationResult(missionId, result);
4460     }
4461     return result;
4462 }
4463 
NotifyCompleteContinuation(const std::string & deviceId,int32_t sessionId,bool isSuccess)4464 void AbilityManagerService::NotifyCompleteContinuation(const std::string &deviceId,
4465     int32_t sessionId, bool isSuccess)
4466 {
4467     TAG_LOGI(AAFwkTag::ABILITYMGR, "NotifyCompleteContinuation.");
4468     AAFWK::ContinueRadar::GetInstance().ClickIconRecvOver("NotifyCompleteContinuation");
4469     sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4470     if (samgrProxy == nullptr) {
4471         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get samgrProxy");
4472         return;
4473     }
4474     sptr<IRemoteObject> bmsProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
4475     if (bmsProxy == nullptr) {
4476         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms from samgr");
4477         return;
4478     }
4479     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bmsProxy);
4480     if (bundleMgr == nullptr) {
4481         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms");
4482         return;
4483     }
4484     int32_t callerUid = IPCSkeleton::GetCallingUid();
4485     std::string callerBundleName;
4486     // reset ipc identity
4487     auto identity = IPCSkeleton::ResetCallingIdentity();
4488     bool result = bundleMgr->GetBundleNameForUid(callerUid, callerBundleName);
4489     // set ipc identity to raw
4490     IPCSkeleton::SetCallingIdentity(identity);
4491     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName: %{public}s", callerBundleName.c_str());
4492     DistributedClient dmsClient;
4493     dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess, callerBundleName);
4494 }
4495 
NotifyContinuationResult(int32_t missionId,int32_t result)4496 int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result)
4497 {
4498     TAG_LOGI(AAFwkTag::ABILITYMGR, "Notify Continuation Result : %{public}d.", result);
4499 
4500     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4501     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4502         auto uiAbilityManager = GetCurrentUIAbilityManager();
4503         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4504         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4505     } else {
4506         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4507         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4508         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4509     }
4510     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4511 
4512     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
4513         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
4514         return ERR_INVALID_VALUE;
4515     }
4516     abilityRecord->NotifyContinuationResult(result);
4517     return ERR_OK;
4518 }
4519 
StartSyncRemoteMissions(const std::string & devId,bool fixConflict,int64_t tag)4520 int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
4521 {
4522     CHECK_CALLER_IS_SYSTEM_APP;
4523     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4524         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4525         return CHECK_PERMISSION_FAILED;
4526     }
4527     DistributedClient dmsClient;
4528     return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag);
4529 }
4530 
StopSyncRemoteMissions(const std::string & devId)4531 int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId)
4532 {
4533     CHECK_CALLER_IS_SYSTEM_APP;
4534     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4535         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4536         return CHECK_PERMISSION_FAILED;
4537     }
4538     DistributedClient dmsClient;
4539     return dmsClient.StopSyncRemoteMissions(devId);
4540 }
4541 
RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4542 int AbilityManagerService::RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4543 {
4544     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4545         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
4546         return CHECK_PERMISSION_FAILED;
4547     }
4548     return DelayedSingleton<ConnectionStateManager>::GetInstance()->RegisterObserver(observer);
4549 }
4550 
UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4551 int AbilityManagerService::UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4552 {
4553     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4554         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
4555         return CHECK_PERMISSION_FAILED;
4556     }
4557     return DelayedSingleton<ConnectionStateManager>::GetInstance()->UnregisterObserver(observer);
4558 }
4559 
4560 #ifdef WITH_DLP
GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> & infos)4561 int AbilityManagerService::GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)
4562 {
4563     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4564         TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get dlp connection infos if caller is not sa.");
4565         return CHECK_PERMISSION_FAILED;
4566     }
4567     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetDlpConnectionInfos(infos);
4568 
4569     return ERR_OK;
4570 }
4571 #endif // WITH_DLP
4572 
GetConnectionData(std::vector<AbilityRuntime::ConnectionData> & connectionData)4573 int AbilityManagerService::GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)
4574 {
4575     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4576         TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get connection data if caller is not sa.");
4577         return CHECK_PERMISSION_FAILED;
4578     }
4579     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetConnectionData(connectionData);
4580 
4581     return ERR_OK;
4582 }
4583 
RegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4584 int AbilityManagerService::RegisterMissionListener(const std::string &deviceId,
4585     const sptr<IRemoteMissionListener> &listener)
4586 {
4587     CHECK_CALLER_IS_SYSTEM_APP;
4588     std::string localDeviceId;
4589     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4590         TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterMissionListener: Check DeviceId failed");
4591         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4592     }
4593     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4594     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4595         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4596         return CHECK_PERMISSION_FAILED;
4597     }
4598     DistributedClient dmsClient;
4599     return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4600 }
4601 
RegisterOnListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4602 int AbilityManagerService::RegisterOnListener(const std::string &type,
4603     const sptr<IRemoteOnListener> &listener)
4604 {
4605     CHECK_CALLER_IS_SYSTEM_APP;
4606     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4607     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4608         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4609         return CHECK_PERMISSION_FAILED;
4610     }
4611     DistributedClient dmsClient;
4612     return dmsClient.RegisterOnListener(type, listener->AsObject());
4613 }
4614 
RegisterOffListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4615 int AbilityManagerService::RegisterOffListener(const std::string &type,
4616     const sptr<IRemoteOnListener> &listener)
4617 {
4618     CHECK_CALLER_IS_SYSTEM_APP;
4619     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4620     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4621         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4622         return CHECK_PERMISSION_FAILED;
4623     }
4624     DistributedClient dmsClient;
4625     return dmsClient.RegisterOffListener(type, listener->AsObject());
4626 }
4627 
UnRegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4628 int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId,
4629     const sptr<IRemoteMissionListener> &listener)
4630 {
4631     CHECK_CALLER_IS_SYSTEM_APP;
4632     std::string localDeviceId;
4633     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4634         TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterMissionListener: Check DeviceId failed");
4635         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4636     }
4637     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4638     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4639         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4640         return CHECK_PERMISSION_FAILED;
4641     }
4642     DistributedClient dmsClient;
4643     return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4644 }
4645 
GetWantSender(const WantSenderInfo & wantSenderInfo,const sptr<IRemoteObject> & callerToken,int32_t uid)4646 sptr<IWantSender> AbilityManagerService::GetWantSender(
4647     const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken,
4648     int32_t uid)
4649 {
4650     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4651     auto pendingWantManager = GetCurrentPendingWantManager();
4652     CHECK_POINTER_AND_RETURN(pendingWantManager, nullptr);
4653 
4654     auto bms = GetBundleManager();
4655     CHECK_POINTER_AND_RETURN(bms, nullptr);
4656 
4657     int32_t callerUid = IPCSkeleton::GetCallingUid();
4658     int32_t userId = wantSenderInfo.userId;
4659     int32_t bundleMgrResult = 0;
4660 
4661     if (userId < 0) {
4662         if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4663             GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4664             TAG_LOGE(AAFwkTag::ABILITYMGR, "GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
4665             return nullptr;
4666         }
4667     }
4668     //sa caller and has uid,no need find from bms.
4669     bool isSpecifyUidBySa = (uid != -1) && (AAFwk::PermissionVerification::GetInstance()->IsSACall());
4670 
4671     int32_t appUid = 0;
4672     int32_t appIndex = 0;
4673     if (!wantSenderInfo.allWants.empty()) {
4674         AppExecFwk::BundleInfo bundleInfo;
4675         std::string bundleName = wantSenderInfo.allWants.back().want.GetElement().GetBundleName();
4676         GetRunningMultiAppIndex(bundleName, callerUid, appIndex);
4677         if (!isSpecifyUidBySa) {
4678             bundleMgrResult = IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName,
4679                 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
4680                 appIndex, bundleInfo, userId));
4681             if (bundleMgrResult == ERR_OK) {
4682                 appUid = bundleInfo.uid;
4683             }
4684         } else {
4685             appUid = uid;
4686         }
4687         TAG_LOGD(AAFwkTag::ABILITYMGR, "App bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), appUid);
4688     }
4689     if (!CheckSenderWantInfo(callerUid, wantSenderInfo)) {
4690         TAG_LOGE(AAFwkTag::ABILITYMGR, "check bundleName failed");
4691         return nullptr;
4692     }
4693 
4694     bool isSystemApp = false;
4695     if (!wantSenderInfo.bundleName.empty() && !isSpecifyUidBySa) {
4696         AppExecFwk::BundleInfo bundleInfo;
4697         bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(wantSenderInfo.bundleName,
4698             AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
4699         if (bundleMgrResult) {
4700             isSystemApp = bundleInfo.applicationInfo.isSystemApp;
4701         }
4702     }
4703 
4704     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName = %{public}s, appIndex:%{public}d",
4705         wantSenderInfo.bundleName.c_str(), appIndex);
4706     return pendingWantManager->GetWantSender(callerUid, appUid, isSystemApp, wantSenderInfo, callerToken, appIndex);
4707 }
4708 
SendWantSender(sptr<IWantSender> target,const SenderInfo & senderInfo)4709 int AbilityManagerService::SendWantSender(sptr<IWantSender> target, const SenderInfo &senderInfo)
4710 {
4711     TAG_LOGI(AAFwkTag::ABILITYMGR, "Send want sender.");
4712     auto pendingWantManager = GetCurrentPendingWantManager();
4713     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4714     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4715     return pendingWantManager->SendWantSender(target, senderInfo);
4716 }
4717 
CancelWantSender(const sptr<IWantSender> & sender)4718 void AbilityManagerService::CancelWantSender(const sptr<IWantSender> &sender)
4719 {
4720     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4721     auto pendingWantManager = GetCurrentPendingWantManager();
4722     CHECK_POINTER(pendingWantManager);
4723     CHECK_POINTER(sender);
4724 
4725     sptr<IRemoteObject> obj = sender->AsObject();
4726     if (!obj || obj->IsProxyObject()) {
4727         TAG_LOGE(AAFwkTag::ABILITYMGR, "obj is nullptr or obj is a proxy obj.");
4728         return;
4729     }
4730 
4731     auto bms = GetBundleManager();
4732     CHECK_POINTER(bms);
4733 
4734     int32_t callerUid = IPCSkeleton::GetCallingUid();
4735     sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
4736 
4737     int userId = -1;
4738     if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4739         GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4740         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
4741         return;
4742     }
4743 
4744     bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
4745     pendingWantManager->CancelWantSender(isSystemAppCall, sender);
4746 }
4747 
CancelWantSenderByFlags(const sptr<IWantSender> & sender,uint32_t flags)4748 void AbilityManagerService::CancelWantSenderByFlags(const sptr<IWantSender> &sender, uint32_t flags)
4749 {
4750     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4751     auto pendingWantManager = GetCurrentPendingWantManager();
4752     CHECK_POINTER(pendingWantManager);
4753     CHECK_POINTER(sender);
4754 
4755     sptr<IRemoteObject> obj = sender->AsObject();
4756     if (!obj || obj->IsProxyObject()) {
4757         TAG_LOGE(AAFwkTag::ABILITYMGR, "obj is nullptr or obj is a proxy obj.");
4758         return;
4759     }
4760 
4761     auto bms = GetBundleManager();
4762     CHECK_POINTER(bms);
4763 
4764     sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
4765 
4766     if (flags != 0 && record->GetKey() != nullptr &&
4767         (static_cast<uint32_t>(record->GetKey()->GetFlags()) & flags) == 0) {
4768         TAG_LOGI(AAFwkTag::ABILITYMGR, "flags=%{public}u not match wantAgent flags=%{public}d",
4769                 flags, record->GetKey()->GetFlags());
4770         return;
4771     }
4772 
4773     TAG_LOGI(AAFwkTag::ABILITYMGR, "code=%{public}d cancel by flags=%{public}u",
4774         record->GetKey() != nullptr ? record->GetKey()->GetCode() : -1, flags);
4775     bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
4776     pendingWantManager->CancelWantSender(isSystemAppCall, sender);
4777 }
4778 
GetPendingWantUid(const sptr<IWantSender> & target)4779 int AbilityManagerService::GetPendingWantUid(const sptr<IWantSender> &target)
4780 {
4781     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4782     auto pendingWantManager = GetCurrentPendingWantManager();
4783     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4784     if (target == nullptr) {
4785         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4786         return -1;
4787     }
4788     return pendingWantManager->GetPendingWantUid(target);
4789 }
4790 
GetPendingWantUserId(const sptr<IWantSender> & target)4791 int AbilityManagerService::GetPendingWantUserId(const sptr<IWantSender> &target)
4792 {
4793     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4794     auto pendingWantManager = GetCurrentPendingWantManager();
4795     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4796     if (target == nullptr) {
4797         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4798         return -1;
4799     }
4800     return pendingWantManager->GetPendingWantUserId(target);
4801 }
4802 
GetPendingWantBundleName(const sptr<IWantSender> & target)4803 std::string AbilityManagerService::GetPendingWantBundleName(const sptr<IWantSender> &target)
4804 {
4805     TAG_LOGI(AAFwkTag::ABILITYMGR, "Get pending want bundle name.");
4806     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantBundleName");
4807     auto pendingWantManager = GetCurrentPendingWantManager();
4808     CHECK_POINTER_AND_RETURN(pendingWantManager, "");
4809     CHECK_POINTER_AND_RETURN(target, "");
4810     return pendingWantManager->GetPendingWantBundleName(target);
4811 }
4812 
GetPendingWantCode(const sptr<IWantSender> & target)4813 int AbilityManagerService::GetPendingWantCode(const sptr<IWantSender> &target)
4814 {
4815     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4816     auto pendingWantManager = GetCurrentPendingWantManager();
4817     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4818     if (target == nullptr) {
4819         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4820         return -1;
4821     }
4822     return pendingWantManager->GetPendingWantCode(target);
4823 }
4824 
GetPendingWantType(const sptr<IWantSender> & target)4825 int AbilityManagerService::GetPendingWantType(const sptr<IWantSender> &target)
4826 {
4827     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4828     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantType");
4829     auto pendingWantManager = GetCurrentPendingWantManager();
4830     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4831     if (target == nullptr) {
4832         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4833         return -1;
4834     }
4835     return pendingWantManager->GetPendingWantType(target);
4836 }
4837 
RegisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)4838 void AbilityManagerService::RegisterCancelListener(const sptr<IWantSender> &sender,
4839     const sptr<IWantReceiver> &receiver)
4840 {
4841     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register cancel listener.");
4842     auto pendingWantManager = GetCurrentPendingWantManager();
4843     CHECK_POINTER(pendingWantManager);
4844     CHECK_POINTER(sender);
4845     CHECK_POINTER(receiver);
4846     pendingWantManager->RegisterCancelListener(sender, receiver);
4847 }
4848 
UnregisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)4849 void AbilityManagerService::UnregisterCancelListener(
4850     const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)
4851 {
4852     TAG_LOGI(AAFwkTag::ABILITYMGR, "Unregister cancel listener.");
4853     auto pendingWantManager = GetCurrentPendingWantManager();
4854     CHECK_POINTER(pendingWantManager);
4855     CHECK_POINTER(sender);
4856     CHECK_POINTER(receiver);
4857     pendingWantManager->UnregisterCancelListener(sender, receiver);
4858 }
4859 
GetPendingRequestWant(const sptr<IWantSender> & target,std::shared_ptr<Want> & want)4860 int AbilityManagerService::GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)
4861 {
4862     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4863     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get pending request want.");
4864     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingRequestWant");
4865     auto pendingWantManager = GetCurrentPendingWantManager();
4866     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4867     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4868     CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE);
4869     CHECK_CALLER_IS_SYSTEM_APP;
4870     return pendingWantManager->GetPendingRequestWant(target, want);
4871 }
4872 
LockMissionForCleanup(int32_t missionId)4873 int AbilityManagerService::LockMissionForCleanup(int32_t missionId)
4874 {
4875     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock mission for clean up all, id :%{public}d", missionId);
4876     auto missionListManager = GetCurrentMissionListManager();
4877     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4878     CHECK_CALLER_IS_SYSTEM_APP;
4879 
4880     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4881         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4882         return CHECK_PERMISSION_FAILED;
4883     }
4884     return missionListManager->SetMissionLockedState(missionId, true);
4885 }
4886 
UnlockMissionForCleanup(int32_t missionId)4887 int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId)
4888 {
4889     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4890     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock mission for clean up all, id :%{public}d", missionId);
4891     auto missionListManager = GetCurrentMissionListManager();
4892     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4893     CHECK_CALLER_IS_SYSTEM_APP;
4894 
4895     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4896         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4897         return CHECK_PERMISSION_FAILED;
4898     }
4899     return missionListManager->SetMissionLockedState(missionId, false);
4900 }
4901 
SetLockedState(int32_t sessionId,bool lockedState)4902 void AbilityManagerService::SetLockedState(int32_t sessionId, bool lockedState)
4903 {
4904     TAG_LOGI(AAFwkTag::ABILITYMGR, "request lock abilityRecord, sessionId :%{public}d", sessionId);
4905     if (!IsCallerSceneBoard()) {
4906         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
4907         return;
4908     }
4909     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4910     CHECK_POINTER(uiAbilityManager);
4911     auto abilityRecord = uiAbilityManager->GetAbilityRecordsById(sessionId);
4912     if (!abilityRecord) {
4913         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
4914         return;
4915     }
4916     abilityRecord->SetLockedState(lockedState);
4917 }
4918 
RegisterMissionListener(const sptr<IMissionListener> & listener)4919 int AbilityManagerService::RegisterMissionListener(const sptr<IMissionListener> &listener)
4920 {
4921     TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
4922     auto missionListManager = GetCurrentMissionListManager();
4923     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4924     CHECK_CALLER_IS_SYSTEM_APP;
4925 
4926     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4927         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4928         return CHECK_PERMISSION_FAILED;
4929     }
4930     return missionListManager->RegisterMissionListener(listener);
4931 }
4932 
UnRegisterMissionListener(const sptr<IMissionListener> & listener)4933 int AbilityManagerService::UnRegisterMissionListener(const sptr<IMissionListener> &listener)
4934 {
4935     TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
4936     auto missionListManager = GetCurrentMissionListManager();
4937     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4938     CHECK_CALLER_IS_SYSTEM_APP;
4939 
4940     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4941         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4942         return CHECK_PERMISSION_FAILED;
4943     }
4944     return missionListManager->UnRegisterMissionListener(listener);
4945 }
4946 
GetMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)4947 int AbilityManagerService::GetMissionInfos(const std::string& deviceId, int32_t numMax,
4948     std::vector<MissionInfo> &missionInfos)
4949 {
4950     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4951     TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfos.");
4952     auto missionListManager = GetCurrentMissionListManager();
4953     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4954     CHECK_CALLER_IS_SYSTEM_APP;
4955 
4956     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4957         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4958         return CHECK_PERMISSION_FAILED;
4959     }
4960 
4961     if (CheckIsRemote(deviceId)) {
4962         return GetRemoteMissionInfos(deviceId, numMax, missionInfos);
4963     }
4964 
4965     return missionListManager->GetMissionInfos(numMax, missionInfos);
4966 }
4967 
GetRemoteMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)4968 int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax,
4969     std::vector<MissionInfo> &missionInfos)
4970 {
4971     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetRemoteMissionInfos begin");
4972     DistributedClient dmsClient;
4973     int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos);
4974     if (result != ERR_OK) {
4975         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetRemoteMissionInfos failed, result = %{public}d", result);
4976         return result;
4977     }
4978     return ERR_OK;
4979 }
4980 
GetMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)4981 int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId,
4982     MissionInfo &missionInfo)
4983 {
4984     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4985     TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfo, missionId:%{public}d", missionId);
4986     auto missionListManager = GetCurrentMissionListManager();
4987     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4988     CHECK_CALLER_IS_SYSTEM_APP;
4989 
4990     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4991         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4992         return CHECK_PERMISSION_FAILED;
4993     }
4994 
4995     if (CheckIsRemote(deviceId)) {
4996         return GetRemoteMissionInfo(deviceId, missionId, missionInfo);
4997     }
4998 
4999     return missionListManager->GetMissionInfo(missionId, missionInfo);
5000 }
5001 
GetRemoteMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)5002 int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId,
5003     MissionInfo &missionInfo)
5004 {
5005     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5006     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetMissionInfoFromDms begin");
5007     std::vector<MissionInfo> missionVector;
5008     int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector);
5009     if (result != ERR_OK) {
5010         return result;
5011     }
5012     for (auto iter = missionVector.begin(); iter != missionVector.end(); iter++) {
5013         if (iter->id == missionId) {
5014             missionInfo = *iter;
5015             return ERR_OK;
5016         }
5017     }
5018     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionId not found");
5019     return ERR_INVALID_VALUE;
5020 }
5021 
CleanMission(int32_t missionId)5022 int AbilityManagerService::CleanMission(int32_t missionId)
5023 {
5024     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5025     TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanMission, missionId:%{public}d", missionId);
5026     auto missionListManager = GetCurrentMissionListManager();
5027     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5028     CHECK_CALLER_IS_SYSTEM_APP;
5029 
5030     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5031         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5032         return CHECK_PERMISSION_FAILED;
5033     }
5034 
5035     return missionListManager->ClearMission(missionId);
5036 }
5037 
CleanAllMissions()5038 int AbilityManagerService::CleanAllMissions()
5039 {
5040     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5041     TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanAllMissions ");
5042     auto missionListManager = GetCurrentMissionListManager();
5043     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5044     CHECK_CALLER_IS_SYSTEM_APP;
5045 
5046     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5047         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5048         return CHECK_PERMISSION_FAILED;
5049     }
5050 
5051     Want want;
5052     want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME);
5053     if (!IsAbilityControllerStart(want, AbilityConfig::LAUNCHER_BUNDLE_NAME)) {
5054         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
5055         return ERR_WOULD_BLOCK;
5056     }
5057 
5058     return missionListManager->ClearAllMissions();
5059 }
5060 
MoveMissionToFront(int32_t missionId)5061 int AbilityManagerService::MoveMissionToFront(int32_t missionId)
5062 {
5063     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5064     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5065     CHECK_CALLER_IS_SYSTEM_APP;
5066     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5067         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5068         return CHECK_PERMISSION_FAILED;
5069     }
5070 
5071     if (!IsAbilityControllerStartById(missionId)) {
5072         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
5073         return ERR_WOULD_BLOCK;
5074     }
5075 
5076     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5077         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5078         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5079         return uiAbilityManager->MoveMissionToFront(missionId);
5080     }
5081 
5082     auto missionListManager = GetCurrentMissionListManager();
5083     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5084     return missionListManager->MoveMissionToFront(missionId);
5085 }
5086 
MoveMissionToFront(int32_t missionId,const StartOptions & startOptions)5087 int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)
5088 {
5089     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5090     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5091     CHECK_CALLER_IS_SYSTEM_APP;
5092     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5093         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5094         return CHECK_PERMISSION_FAILED;
5095     }
5096 
5097     if (!IsAbilityControllerStartById(missionId)) {
5098         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
5099         return ERR_WOULD_BLOCK;
5100     }
5101 
5102     auto options = std::make_shared<StartOptions>(startOptions);
5103     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5104         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5105         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5106         return uiAbilityManager->MoveMissionToFront(missionId, options);
5107     }
5108 
5109     auto missionListManager = GetCurrentMissionListManager();
5110     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5111     return missionListManager->MoveMissionToFront(missionId, options);
5112 }
5113 
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)5114 int AbilityManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
5115 {
5116     CHECK_CALLER_IS_SYSTEM_APP;
5117     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5118         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5119         return CHECK_PERMISSION_FAILED;
5120     }
5121     if (wmsHandler_) {
5122         auto ret = wmsHandler_->MoveMissionsToForeground(missionIds, topMissionId);
5123         if (ret) {
5124             TAG_LOGE(AAFwkTag::ABILITYMGR, "MoveMissionsToForeground failed, missiondIds may be invalid");
5125             return ERR_INVALID_VALUE;
5126         } else {
5127             return NO_ERROR;
5128         }
5129     }
5130     return ERR_NO_INIT;
5131 }
5132 
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)5133 int AbilityManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
5134     std::vector<int32_t>& result)
5135 {
5136     CHECK_CALLER_IS_SYSTEM_APP;
5137     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5138         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5139         return CHECK_PERMISSION_FAILED;
5140     }
5141     if (wmsHandler_) {
5142         auto ret = wmsHandler_->MoveMissionsToBackground(missionIds, result);
5143         if (ret) {
5144             TAG_LOGE(AAFwkTag::ABILITYMGR, "MoveMissionsToBackground failed, missiondIds may be invalid");
5145             return ERR_INVALID_VALUE;
5146         } else {
5147             return NO_ERROR;
5148         }
5149     }
5150     return ERR_NO_INIT;
5151 }
5152 
GetMissionIdByToken(const sptr<IRemoteObject> & token)5153 int32_t AbilityManagerService::GetMissionIdByToken(const sptr<IRemoteObject> &token)
5154 {
5155     TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken.");
5156     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5157     if (!abilityRecord) {
5158         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
5159         return ERR_INVALID_VALUE;
5160     }
5161     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
5162         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5163         return ERR_INVALID_VALUE;
5164     }
5165     return GetMissionIdByAbilityTokenInner(token);
5166 }
5167 
IsAbilityControllerStartById(int32_t missionId)5168 bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId)
5169 {
5170     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5171     auto missionListWrap = GetMissionListWrap();
5172     if (missionListWrap == nullptr) {
5173         TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null.");
5174         return true;
5175     }
5176     InnerMissionInfo innerMissionInfo;
5177     int getMission = missionListWrap->GetInnerMissionInfoById(missionId, innerMissionInfo);
5178     if (getMission != ERR_OK) {
5179         TAG_LOGE(AAFwkTag::ABILITYMGR,
5180             "cannot find mission info from MissionInfoList by missionId: %{public}d", missionId);
5181         return true;
5182     }
5183     if (!IsAbilityControllerStart(innerMissionInfo.missionInfo.want, innerMissionInfo.missionInfo.want.GetBundle())) {
5184         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s",
5185             innerMissionInfo.missionInfo.want.GetBundle().c_str());
5186         return false;
5187     }
5188     return true;
5189 }
5190 
GetConnectRecordListByCallback(sptr<IAbilityConnection> callback)5191 std::list<std::shared_ptr<ConnectionRecord>> AbilityManagerService::GetConnectRecordListByCallback(
5192     sptr<IAbilityConnection> callback)
5193 {
5194     auto connectManager = GetCurrentConnectManager();
5195     CHECK_POINTER_AND_RETURN(connectManager, std::list<std::shared_ptr<ConnectionRecord>>());
5196     return connectManager->GetConnectRecordListByCallback(callback);
5197 }
5198 
GenerateDataAbilityRequestByUri(const std::string & dataAbilityUri,AbilityRequest & abilityRequest,sptr<IRemoteObject> callerToken,int32_t userId)5199 bool AbilityManagerService::GenerateDataAbilityRequestByUri(const std::string& dataAbilityUri,
5200     AbilityRequest &abilityRequest, sptr<IRemoteObject> callerToken, int32_t userId)
5201 {
5202     auto bms = GetBundleManager();
5203     CHECK_POINTER_AND_RETURN(bms, false);
5204     TAG_LOGI(AAFwkTag::ABILITYMGR, "called. userId %{public}d", userId);
5205     bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo));
5206     if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) {
5207         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ability info for data ability acquiring.");
5208         return false;
5209     }
5210     abilityRequest.callerToken = callerToken;
5211     return true;
5212 }
5213 
AcquireDataAbility(const Uri & uri,bool tryBind,const sptr<IRemoteObject> & callerToken)5214 sptr<IAbilityScheduler> AbilityManagerService::AcquireDataAbility(
5215     const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
5216 {
5217     auto localUri(uri);
5218     if (localUri.GetScheme() != AbilityConfig::SCHEME_DATA_ABILITY) {
5219         TAG_LOGE(AAFwkTag::ABILITYMGR, "Acquire data ability with invalid uri scheme.");
5220         return nullptr;
5221     }
5222     std::vector<std::string> pathSegments;
5223     localUri.GetPathSegments(pathSegments);
5224     if (pathSegments.empty()) {
5225         TAG_LOGE(AAFwkTag::ABILITYMGR, "Acquire data ability with invalid uri path.");
5226         return nullptr;
5227     }
5228 
5229     auto userId = GetValidUserId(INVALID_USER_ID);
5230     AbilityRequest abilityRequest;
5231     if (!GenerateDataAbilityRequestByUri(localUri.ToString(), abilityRequest, callerToken, userId)) {
5232         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate data ability request by uri failed.");
5233         return nullptr;
5234     }
5235 
5236     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5237     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5238     if (!isSaCall && CheckCallDataAbilityPermission(abilityRequest, isShellCall, isSaCall) != ERR_OK) {
5239         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ability request info for data ability acquiring.");
5240         return nullptr;
5241     }
5242 
5243     TAG_LOGD(AAFwkTag::ABILITYMGR, "Query data ability info: %{public}s|%{public}s|%{public}s",
5244         abilityRequest.appInfo.name.c_str(), abilityRequest.appInfo.bundleName.c_str(),
5245         abilityRequest.abilityInfo.name.c_str());
5246 
5247     if (CheckStaticCfgPermission(abilityRequest, false, -1, true, isSaCall) !=
5248         AppExecFwk::Constants::PERMISSION_GRANTED) {
5249         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission fail");
5250         return nullptr;
5251     }
5252 
5253     if (!VerificationAllToken(callerToken)) {
5254         TAG_LOGI(AAFwkTag::ABILITYMGR, "VerificationAllToken fail");
5255         return nullptr;
5256     }
5257 
5258     if (abilityRequest.abilityInfo.applicationInfo.singleton) {
5259         userId = U0_USER_ID;
5260     }
5261 
5262     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5263     CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr);
5264     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
5265     bool isNotHap = isSaCall || isShellCall;
5266     UpdateCallerInfo(abilityRequest.want, callerToken);
5267     return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap);
5268 }
5269 
ReleaseDataAbility(sptr<IAbilityScheduler> dataAbilityScheduler,const sptr<IRemoteObject> & callerToken)5270 int AbilityManagerService::ReleaseDataAbility(
5271     sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
5272 {
5273     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
5274     if (!dataAbilityScheduler || !callerToken) {
5275         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilitySchedule or callerToken is nullptr");
5276         return ERR_INVALID_VALUE;
5277     }
5278 
5279     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler);
5280     if (!dataAbilityManager) {
5281         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityScheduler is not exists");
5282         return ERR_INVALID_VALUE;
5283     }
5284 
5285     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5286     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5287     bool isNotHap = isSaCall || isShellCall;
5288     return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isNotHap);
5289 }
5290 
AttachAbilityThread(const sptr<IAbilityScheduler> & scheduler,const sptr<IRemoteObject> & token)5291 int AbilityManagerService::AttachAbilityThread(
5292     const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
5293 {
5294     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5295     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called", __func__);
5296     CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE);
5297     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5298         return ERR_INVALID_VALUE;
5299     }
5300     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5301     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5302     if (!JudgeSelfCalled(abilityRecord)) {
5303         return CHECK_PERMISSION_FAILED;
5304     }
5305 
5306     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5307     auto abilityInfo = abilityRecord->GetAbilityInfo();
5308     auto type = abilityInfo.type;
5309     // force timeout ability for test
5310     if (IsNeedTimeoutForTest(abilityInfo.name, AbilityRecord::ConvertAbilityState(AbilityState::INITIAL))) {
5311         TAG_LOGW(AAFwkTag::ABILITYMGR,
5312             "force timeout ability for test, state:INITIAL, ability: %{public}s", abilityInfo.name.c_str());
5313         return ERR_OK;
5314     }
5315     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5316         auto connectManager = GetConnectManagerByUserId(userId);
5317         if (!connectManager) {
5318             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5319             return ERR_INVALID_VALUE;
5320         }
5321         return connectManager->AttachAbilityThreadLocked(scheduler, token);
5322     } else if (type == AppExecFwk::AbilityType::DATA) {
5323         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5324         if (!dataAbilityManager) {
5325             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
5326             return ERR_INVALID_VALUE;
5327         }
5328         return dataAbilityManager->AttachAbilityThread(scheduler, token);
5329     } else {
5330         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::LOAD };
5331         std::string entry = "AbilityManagerService::AttachAbilityThread; the end of load lifecycle.";
5332         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5333         int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5334         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5335             auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5336             CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5337             return uiAbilityManager->AttachAbilityThread(scheduler, token);
5338         }
5339         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5340         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
5341         return missionListManager->AttachAbilityThread(scheduler, token);
5342     }
5343 }
5344 
DumpSysInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5345 void AbilityManagerService::DumpSysInner(
5346     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5347 {
5348     std::vector<std::string> argList;
5349     SplitStr(args, " ", argList);
5350     if (argList.empty()) {
5351         return;
5352     }
5353 
5354     DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5355     DumpSysStateInner(args, info, isClient, isUserID, userId);
5356     DumpSysPendingInner(args, info, isClient, isUserID, userId);
5357     DumpSysProcess(args, info, isClient, isUserID, userId);
5358 }
5359 
DumpSysMissionListInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5360 void AbilityManagerService::DumpSysMissionListInner(
5361     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5362 {
5363     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5364         DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId);
5365         return;
5366     }
5367     std::shared_ptr<MissionListManagerInterface> targetManager;
5368     if (isUserID) {
5369         auto missionListManager = GetMissionListManagerByUserId(userId);
5370         if (missionListManager == nullptr) {
5371             info.push_back("error: No user found.");
5372             return;
5373         }
5374         targetManager = missionListManager;
5375     } else {
5376         targetManager = GetCurrentMissionListManager();
5377     }
5378 
5379     CHECK_POINTER(targetManager);
5380 
5381     std::vector<std::string> argList;
5382     SplitStr(args, " ", argList);
5383     if (argList.empty()) {
5384         return;
5385     }
5386 
5387     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5388         targetManager->DumpMissionList(info, isClient, argList[1]);
5389     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5390         targetManager->DumpMissionList(info, isClient);
5391     } else {
5392         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5393     }
5394 }
5395 
DumpSysMissionListInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5396 void AbilityManagerService::DumpSysMissionListInnerBySCB(
5397     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5398 {
5399     if (!isUserID) {
5400         userId = GetUserId();
5401     }
5402 
5403     std::vector<std::string> argList;
5404     SplitStr(args, " ", argList);
5405     if (argList.empty()) {
5406         return;
5407     }
5408 
5409     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5410     CHECK_POINTER(uiAbilityManager);
5411     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5412         uiAbilityManager->DumpMissionList(info, isClient, argList[1]);
5413     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5414         uiAbilityManager->DumpMissionList(info, isClient);
5415     } else {
5416         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5417     }
5418 }
5419 
DumpSysAbilityInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5420 void AbilityManagerService::DumpSysAbilityInner(
5421     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5422 {
5423     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5424         DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId);
5425         return;
5426     }
5427     std::shared_ptr<MissionListManagerInterface> targetManager;
5428     if (isUserID) {
5429         auto missionListManager = GetMissionListManagerByUserId(userId);
5430         if (missionListManager == nullptr) {
5431             info.push_back("error: No user found.");
5432             return;
5433         }
5434         targetManager = missionListManager;
5435     } else {
5436         targetManager = GetCurrentMissionListManager();
5437     }
5438 
5439     CHECK_POINTER(targetManager);
5440 
5441     std::vector<std::string> argList;
5442     SplitStr(args, " ", argList);
5443     if (argList.empty()) {
5444         return;
5445     }
5446     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5447         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList = %{public}s", argList[1].c_str());
5448         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5449         try {
5450             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5451             targetManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5452         } catch (...) {
5453             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5454             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5455         }
5456     } else {
5457         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5458     }
5459 }
5460 
DumpSysAbilityInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5461 void AbilityManagerService::DumpSysAbilityInnerBySCB(
5462     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5463 {
5464     if (!isUserID) {
5465         userId = GetUserId();
5466     }
5467 
5468     std::vector<std::string> argList;
5469     SplitStr(args, " ", argList);
5470     if (argList.empty()) {
5471         return;
5472     }
5473     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5474         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList = %{public}s", argList[1].c_str());
5475         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5476         try {
5477             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5478             auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5479             CHECK_POINTER(uiAbilityManager);
5480             uiAbilityManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5481         } catch (...) {
5482             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5483             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5484         }
5485     } else {
5486         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5487     }
5488 }
5489 
DumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5490 void AbilityManagerService::DumpSysStateInner(
5491     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5492 {
5493     TAG_LOGI(AAFwkTag::ABILITYMGR, "DumpSysStateInner begin:%{public}s", args.c_str());
5494     std::shared_ptr<AbilityConnectManager> targetManager;
5495 
5496     if (isUserID) {
5497         auto connectManager = GetConnectManagerByUserId(userId);
5498         if (connectManager == nullptr) {
5499             info.push_back("error: No user found.");
5500             return;
5501         }
5502         targetManager = connectManager;
5503     } else {
5504         targetManager = GetCurrentConnectManager();
5505     }
5506 
5507     CHECK_POINTER(targetManager);
5508 
5509     std::vector<std::string> argList;
5510     SplitStr(args, " ", argList);
5511     if (argList.empty()) {
5512         return;
5513     }
5514 
5515     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5516         targetManager->DumpState(info, isClient, argList[1]);
5517     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5518         targetManager->DumpState(info, isClient);
5519     } else {
5520         TAG_LOGI(AAFwkTag::ABILITYMGR, "uri = %{public}s", argList[1].c_str());
5521         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5522         targetManager->DumpStateByUri(info, isClient, argList[1], params);
5523     }
5524 }
5525 
DumpSysPendingInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5526 void AbilityManagerService::DumpSysPendingInner(
5527     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5528 {
5529     std::shared_ptr<PendingWantManager> targetManager;
5530     if (isUserID) {
5531         auto pendingWantManager = GetPendingWantManagerByUserId(userId);
5532         if (pendingWantManager == nullptr) {
5533             info.push_back("error: No user found.");
5534             return;
5535         }
5536         targetManager = pendingWantManager;
5537     } else {
5538         targetManager = GetCurrentPendingWantManager();
5539     }
5540 
5541     CHECK_POINTER(targetManager);
5542 
5543     std::vector<std::string> argList;
5544     SplitStr(args, " ", argList);
5545     if (argList.empty()) {
5546         return;
5547     }
5548 
5549     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5550         targetManager->DumpByRecordId(info, argList[1]);
5551     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5552         targetManager->Dump(info);
5553     } else {
5554         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5555     }
5556 }
5557 
DumpSysProcess(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5558 void AbilityManagerService::DumpSysProcess(
5559     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5560 {
5561     std::vector<std::string> argList;
5562     SplitStr(args, " ", argList);
5563     if (argList.empty()) {
5564         return;
5565     }
5566     std::vector<AppExecFwk::RunningProcessInfo> processInfos;
5567     int ret = 0;
5568     if (isUserID) {
5569         ret = GetProcessRunningInfosByUserId(processInfos, userId);
5570     } else {
5571         ret = GetProcessRunningInfos(processInfos);
5572     }
5573 
5574     if (ret != ERR_OK || processInfos.size() == 0) {
5575         return;
5576     }
5577 
5578     std::string dumpInfo = "  AppRunningRecords:";
5579     info.push_back(dumpInfo);
5580     auto processInfoID = 0;
5581     auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false);
5582     for (const auto& processInfo : processInfos) {
5583         if (hasProcessName && argList[1] != processInfo.processName_) {
5584             continue;
5585         }
5586 
5587         dumpInfo = "    AppRunningRecord ID #" + std::to_string(processInfoID);
5588         processInfoID++;
5589         info.push_back(dumpInfo);
5590         dumpInfo = "      process name [" + processInfo.processName_ + "]";
5591         info.push_back(dumpInfo);
5592         dumpInfo = "      pid #" + std::to_string(processInfo.pid_) +
5593             "  uid #" + std::to_string(processInfo.uid_);
5594         info.push_back(dumpInfo);
5595         auto appState = static_cast<AppState>(processInfo.state_);
5596         dumpInfo = "      state #" + DelayedSingleton<AppScheduler>::GetInstance()->ConvertAppState(appState);
5597         info.push_back(dumpInfo);
5598         DumpUIExtensionRootHostRunningInfos(processInfo.pid_, info);
5599         DumpUIExtensionProviderRunningInfos(processInfo.pid_, info);
5600     }
5601 }
5602 
DumpUIExtensionRootHostRunningInfos(pid_t pid,std::vector<std::string> & info)5603 void AbilityManagerService::DumpUIExtensionRootHostRunningInfos(pid_t pid, std::vector<std::string> &info)
5604 {
5605     auto appMgr = GetAppMgr();
5606     if (appMgr == nullptr) {
5607         TAG_LOGW(AAFwkTag::ABILITYMGR, "Get AppMgr failed.");
5608         return;
5609     }
5610 
5611     std::vector<pid_t> hostPids;
5612     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionRootHostPid(pid, hostPids));
5613     if (ret != ERR_OK) {
5614         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get root host process info faild.");
5615         return;
5616     }
5617 
5618     if (hostPids.size() == 0) {
5619         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extenson root host of pid %{public}d.", pid);
5620         return;
5621     }
5622 
5623     std::string temp;
5624     for (size_t i = 0; i < hostPids.size(); i++) {
5625         temp = "      root caller #" + std::to_string(i);
5626         info.push_back(temp);
5627         temp = "        pid #" + std::to_string(hostPids[i]);
5628         info.push_back(temp);
5629     }
5630 }
5631 
DumpUIExtensionProviderRunningInfos(pid_t hostPid,std::vector<std::string> & info)5632 void AbilityManagerService::DumpUIExtensionProviderRunningInfos(pid_t hostPid, std::vector<std::string> &info)
5633 {
5634     auto appMgr = GetAppMgr();
5635     if (appMgr == nullptr) {
5636         TAG_LOGW(AAFwkTag::ABILITYMGR, "Get AppMgr failed.");
5637         return;
5638     }
5639 
5640     std::vector<pid_t> providerPids;
5641     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionProviderPid(hostPid, providerPids));
5642     if (ret != ERR_OK) {
5643         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get provider process info faild.");
5644         return;
5645     }
5646 
5647     if (providerPids.size() == 0) {
5648         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extension provider of pid %{public}d.", hostPid);
5649         return;
5650     }
5651 
5652     std::string temp;
5653     for (size_t i = 0; i < providerPids.size(); i++) {
5654         temp = "      uiextension provider #" + std::to_string(i);
5655         info.push_back(temp);
5656         temp = "        pid #" + std::to_string(providerPids[i]);
5657         info.push_back(temp);
5658     }
5659 }
5660 
DataDumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5661 void AbilityManagerService::DataDumpSysStateInner(
5662     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5663 {
5664     std::shared_ptr<DataAbilityManager> targetManager;
5665     if (isUserID) {
5666         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5667         if (dataAbilityManager == nullptr) {
5668             info.push_back("error: No user found.");
5669             return;
5670         }
5671         targetManager = dataAbilityManager;
5672     } else {
5673         targetManager = GetCurrentDataAbilityManager();
5674     }
5675 
5676     CHECK_POINTER(targetManager);
5677 
5678     std::vector<std::string> argList;
5679     SplitStr(args, " ", argList);
5680     if (argList.empty()) {
5681         return;
5682     }
5683     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5684         targetManager->DumpSysState(info, isClient, argList[1]);
5685     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5686         targetManager->DumpSysState(info, isClient);
5687     } else {
5688         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5689     }
5690 }
5691 
DumpInner(const std::string & args,std::vector<std::string> & info)5692 void AbilityManagerService::DumpInner(const std::string &args, std::vector<std::string> &info)
5693 {
5694     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5695         auto uiAbilityManager = GetCurrentUIAbilityManager();
5696         CHECK_POINTER(uiAbilityManager);
5697         uiAbilityManager->Dump(info);
5698         return;
5699     }
5700 
5701     auto missionListManager = GetCurrentMissionListManager();
5702     if (missionListManager) {
5703         missionListManager->Dump(info);
5704     }
5705 }
5706 
DumpMissionListInner(const std::string & args,std::vector<std::string> & info)5707 void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector<std::string> &info)
5708 {
5709     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5710         auto uiAbilityManager = GetCurrentUIAbilityManager();
5711         CHECK_POINTER(uiAbilityManager);
5712         uiAbilityManager->DumpMissionList(info, false, " ");
5713         return;
5714     }
5715     auto missionListManager = GetCurrentMissionListManager();
5716     if (missionListManager) {
5717         missionListManager->DumpMissionList(info, false, "");
5718     }
5719 }
5720 
DumpMissionInfosInner(const std::string & args,std::vector<std::string> & info)5721 void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)
5722 {
5723     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5724         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5725         Rosen::WindowManager::GetInstance().DumpSessionAll(info);
5726         return;
5727     }
5728     auto missionListManager = GetCurrentMissionListManager();
5729     if (missionListManager) {
5730         missionListManager->DumpMissionInfos(info);
5731     }
5732 }
5733 
DumpMissionInner(const std::string & args,std::vector<std::string> & info)5734 void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector<std::string> &info)
5735 {
5736     std::vector<std::string> argList;
5737     SplitStr(args, " ", argList);
5738     if (argList.empty()) {
5739         return;
5740     }
5741     if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5742         info.push_back("error: invalid argument, please see 'ability dump -h'.");
5743         return;
5744     }
5745     int missionId = DEFAULT_INVAL_VALUE;
5746     (void)StrToInt(argList[1], missionId);
5747 
5748     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5749         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5750         Rosen::WindowManager::GetInstance().DumpSessionWithId(missionId, info);
5751         return;
5752     }
5753 
5754     auto missionListManager = GetCurrentMissionListManager();
5755     CHECK_POINTER_LOG(missionListManager, "Current mission manager not init.");
5756     missionListManager->DumpMission(missionId, info);
5757 }
5758 
DumpStateInner(const std::string & args,std::vector<std::string> & info)5759 void AbilityManagerService::DumpStateInner(const std::string &args, std::vector<std::string> &info)
5760 {
5761     auto connectManager = GetCurrentConnectManager();
5762     CHECK_POINTER_LOG(connectManager, "Current mission manager not init.");
5763     std::vector<std::string> argList;
5764     SplitStr(args, " ", argList);
5765     if (argList.empty()) {
5766         return;
5767     }
5768     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5769         connectManager->DumpState(info, false, argList[1]);
5770     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5771         connectManager->DumpState(info, false);
5772     } else {
5773         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5774     }
5775 }
5776 
DataDumpStateInner(const std::string & args,std::vector<std::string> & info)5777 void AbilityManagerService::DataDumpStateInner(const std::string &args, std::vector<std::string> &info)
5778 {
5779     auto dataAbilityManager = GetCurrentDataAbilityManager();
5780     CHECK_POINTER(dataAbilityManager);
5781     std::vector<std::string> argList;
5782     SplitStr(args, " ", argList);
5783     if (argList.empty()) {
5784         return;
5785     }
5786     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5787         dataAbilityManager->DumpState(info, argList[1]);
5788     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5789         dataAbilityManager->DumpState(info);
5790     } else {
5791         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5792     }
5793 }
5794 
DumpState(const std::string & args,std::vector<std::string> & info)5795 void AbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
5796 {
5797     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5798     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5799     if (!isShellCall && !isHidumperServiceCall) {
5800         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5801         return;
5802     }
5803     std::vector<std::string> argList;
5804     SplitStr(args, " ", argList);
5805     if (argList.empty()) {
5806         return;
5807     }
5808     auto key = DumpUtils::DumpMap(argList[0]);
5809     if (!key.first) {
5810         return;
5811     }
5812     switch (key.second) {
5813         case DumpUtils::KEY_DUMP_SERVICE:
5814             DumpStateInner(args, info);
5815             break;
5816         case DumpUtils::KEY_DUMP_DATA:
5817             DataDumpStateInner(args, info);
5818             break;
5819         case DumpUtils::KEY_DUMP_ALL:
5820             DumpInner(args, info);
5821             break;
5822         case DumpUtils::KEY_DUMP_MISSION:
5823             DumpMissionInner(args, info);
5824             break;
5825         case DumpUtils::KEY_DUMP_MISSION_LIST:
5826             DumpMissionListInner(args, info);
5827             break;
5828         case DumpUtils::KEY_DUMP_MISSION_INFOS:
5829             DumpMissionInfosInner(args, info);
5830             break;
5831         default:
5832             info.push_back("error: invalid argument, please see 'ability dump -h'.");
5833             break;
5834     }
5835 }
5836 
DumpSysState(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5837 void AbilityManagerService::DumpSysState(
5838     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5839 {
5840     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
5841     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5842     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5843     if (!isShellCall && !isHidumperServiceCall) {
5844         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5845         return;
5846     }
5847     std::vector<std::string> argList;
5848     SplitStr(args, " ", argList);
5849     if (argList.empty()) {
5850         return;
5851     }
5852     auto key = DumpUtils::DumpsysMap(argList[0]);
5853     if (!key.first) {
5854         return;
5855     }
5856     switch (key.second) {
5857         case DumpUtils::KEY_DUMP_SYS_ALL:
5858             DumpSysInner(args, info, isClient, isUserID, userId);
5859             break;
5860         case DumpUtils::KEY_DUMP_SYS_SERVICE:
5861             DumpSysStateInner(args, info, isClient, isUserID, userId);
5862             break;
5863         case DumpUtils::KEY_DUMP_SYS_PENDING:
5864             DumpSysPendingInner(args, info, isClient, isUserID, userId);
5865             break;
5866         case DumpUtils::KEY_DUMP_SYS_PROCESS:
5867             DumpSysProcess(args, info, isClient, isUserID, userId);
5868             break;
5869         case DumpUtils::KEY_DUMP_SYS_DATA:
5870             DataDumpSysStateInner(args, info, isClient, isUserID, userId);
5871             break;
5872         case DumpUtils::KEY_DUMP_SYS_MISSION_LIST:
5873             DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5874             break;
5875         case DumpUtils::KEY_DUMP_SYS_ABILITY:
5876             DumpSysAbilityInner(args, info, isClient, isUserID, userId);
5877             break;
5878         default:
5879             info.push_back("error: invalid argument, please see 'ability dump -h'.");
5880             break;
5881     }
5882 }
5883 
AbilityTransitionDone(const sptr<IRemoteObject> & token,int state,const PacMap & saveData)5884 int AbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
5885 {
5886     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5887     TAG_LOGD(AAFwkTag::ABILITYMGR, "Lifecycle: state:%{public}d.", state);
5888     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5889         return ERR_INVALID_VALUE;
5890     }
5891     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5892     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
5893     if (!JudgeSelfCalled(abilityRecord)) {
5894         return CHECK_PERMISSION_FAILED;
5895     }
5896 
5897     auto abilityInfo = abilityRecord->GetAbilityInfo();
5898     TAG_LOGI(AAFwkTag::ABILITYMGR, "Lifecycle: ability: %{public}s.", abilityRecord->GetURI().c_str());
5899     auto type = abilityInfo.type;
5900     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5901     // force timeout ability for test
5902     int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast<AbilityLifeCycleState>(state));
5903     bool isTerminate = abilityRecord->IsAbilityState(AbilityState::TERMINATING) && targetState == AbilityState::INITIAL;
5904     std::string tempState = isTerminate ? AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) :
5905         AbilityRecord::ConvertAbilityState(static_cast<AbilityState>(targetState));
5906     if (IsNeedTimeoutForTest(abilityInfo.name, tempState)) {
5907         TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability for test, state:%{public}s, ability: %{public}s",
5908             tempState.c_str(),
5909             abilityInfo.name.c_str());
5910         return ERR_OK;
5911     }
5912     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5913         auto connectManager = GetConnectManagerByUserId(userId);
5914         if (!connectManager) {
5915             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5916             return ERR_INVALID_VALUE;
5917         }
5918         return connectManager->AbilityTransitionDone(token, state);
5919     }
5920     if (type == AppExecFwk::AbilityType::DATA) {
5921         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5922         if (!dataAbilityManager) {
5923             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
5924             return ERR_INVALID_VALUE;
5925         }
5926         return dataAbilityManager->AbilityTransitionDone(token, state);
5927     }
5928 
5929     if (targetState == AbilityState::BACKGROUND) {
5930         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::BACKGROUND };
5931         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of background lifecycle.";
5932         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5933     } else if (targetState != AbilityState::INITIAL) {
5934         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::FOREGROUND };
5935         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of foreground lifecycle."
5936             " the end of foreground lifecycle.";
5937         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5938     }
5939 
5940     int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5941     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5942         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5943         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5944         return uiAbilityManager->AbilityTransactionDone(token, state, saveData);
5945     } else {
5946         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5947         if (!missionListManager) {
5948             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", ownerMissionUserId);
5949             return ERR_INVALID_VALUE;
5950         }
5951         return missionListManager->AbilityTransactionDone(token, state, saveData);
5952     }
5953 }
5954 
AbilityWindowConfigTransitionDone(const sptr<IRemoteObject> & token,const WindowConfig & windowConfig)5955 int AbilityManagerService::AbilityWindowConfigTransitionDone(
5956     const sptr<IRemoteObject> &token, const WindowConfig &windowConfig)
5957 {
5958     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5959     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5960         return ERR_INVALID_VALUE;
5961     }
5962     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5963     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
5964     if (!JudgeSelfCalled(abilityRecord)) {
5965         return CHECK_PERMISSION_FAILED;
5966     }
5967 
5968     TAG_LOGI(AAFwkTag::ABILITYMGR, "Lifecycle: ability: %{public}s.", abilityRecord->GetURI().c_str());
5969     auto abilityInfo = abilityRecord->GetAbilityInfo();
5970     auto type = abilityInfo.extensionAbilityType;
5971     if (type != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
5972         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid type");
5973         return ERR_INVALID_VALUE;
5974     }
5975     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5976     auto connectManager = GetConnectManagerByUserId(userId);
5977     if(!connectManager) {
5978         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5979         return ERR_INVALID_VALUE;
5980     }
5981     return connectManager->AbilityWindowConfigTransactionDone(token, windowConfig);
5982 }
5983 
ScheduleConnectAbilityDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & remoteObject)5984 int AbilityManagerService::ScheduleConnectAbilityDone(
5985     const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
5986 {
5987     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5988     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5989     if (!VerificationAllToken(token)) {
5990         return ERR_INVALID_VALUE;
5991     }
5992 
5993     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5994     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5995     if (!JudgeSelfCalled(abilityRecord)) {
5996         return CHECK_PERMISSION_FAILED;
5997     }
5998 
5999     auto type = abilityRecord->GetAbilityInfo().type;
6000     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6001         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not service.");
6002         return TARGET_ABILITY_NOT_SERVICE;
6003     }
6004     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6005     auto connectManager = GetConnectManagerByUserId(userId);
6006     if (!connectManager) {
6007         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
6008         return ERR_INVALID_VALUE;
6009     }
6010     return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject);
6011 }
6012 
ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> & token)6013 int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
6014 {
6015     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6016     TAG_LOGI(AAFwkTag::ABILITYMGR, "Schedule disconnect ability done.");
6017     if (!VerificationAllToken(token)) {
6018         return ERR_INVALID_VALUE;
6019     }
6020 
6021     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6022     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6023     if (!JudgeSelfCalled(abilityRecord)) {
6024         return CHECK_PERMISSION_FAILED;
6025     }
6026 
6027     auto type = abilityRecord->GetAbilityInfo().type;
6028     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6029         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not service.");
6030         return TARGET_ABILITY_NOT_SERVICE;
6031     }
6032     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6033     auto connectManager = GetConnectManagerByUserId(userId);
6034     if (!connectManager) {
6035         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
6036         return ERR_INVALID_VALUE;
6037     }
6038     return connectManager->ScheduleDisconnectAbilityDoneLocked(token);
6039 }
6040 
ScheduleCommandAbilityDone(const sptr<IRemoteObject> & token)6041 int AbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
6042 {
6043     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6044     TAG_LOGD(AAFwkTag::ABILITYMGR, "Schedule command ability done.");
6045     if (!VerificationAllToken(token)) {
6046         return ERR_INVALID_VALUE;
6047     }
6048 
6049     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6050     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6051     if (!JudgeSelfCalled(abilityRecord)) {
6052         return CHECK_PERMISSION_FAILED;
6053     }
6054     // force timeout ability for test
6055     if (IsNeedTimeoutForTest(abilityRecord->GetAbilityInfo().name, std::string("COMMAND"))) {
6056         TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability for test, state:COMMAND, ability: %{public}s",
6057             abilityRecord->GetAbilityInfo().name.c_str());
6058         return ERR_OK;
6059     }
6060     auto type = abilityRecord->GetAbilityInfo().type;
6061     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6062         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not service.");
6063         return TARGET_ABILITY_NOT_SERVICE;
6064     }
6065     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6066     auto connectManager = GetConnectManagerByUserId(userId);
6067     if (!connectManager) {
6068         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
6069         return ERR_INVALID_VALUE;
6070     }
6071     return connectManager->ScheduleCommandAbilityDoneLocked(token);
6072 }
6073 
ScheduleCommandAbilityWindowDone(const sptr<IRemoteObject> & token,const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd,AbilityCommand abilityCmd)6074 int AbilityManagerService::ScheduleCommandAbilityWindowDone(
6075     const sptr<IRemoteObject> &token,
6076     const sptr<SessionInfo> &sessionInfo,
6077     WindowCommand winCmd,
6078     AbilityCommand abilityCmd)
6079 {
6080     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6081     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter.");
6082     if (!VerificationAllToken(token)) {
6083         return ERR_INVALID_VALUE;
6084     }
6085 
6086     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6087     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6088     if (!JudgeSelfCalled(abilityRecord)) {
6089         return CHECK_PERMISSION_FAILED;
6090     }
6091 
6092     if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)
6093         && !UIExtensionUtils::IsWindowExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
6094         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability is not ui or window extension.");
6095         return ERR_INVALID_VALUE;
6096     }
6097     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6098     auto connectManager = GetConnectManagerByUserId(userId);
6099     if (!connectManager) {
6100         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
6101         return ERR_INVALID_VALUE;
6102     }
6103     return connectManager->ScheduleCommandAbilityWindowDone(token, sessionInfo, winCmd, abilityCmd);
6104 }
6105 
OnAbilityRequestDone(const sptr<IRemoteObject> & token,const int32_t state)6106 void AbilityManagerService::OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)
6107 {
6108     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6109     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6110     CHECK_POINTER(abilityRecord);
6111     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnAbilityRequestDone, bundleName: %{public}s, abilityName: %{public}s",
6112         abilityRecord->GetAbilityInfo().bundleName.c_str(), abilityRecord->GetAbilityInfo().name.c_str());
6113     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6114 
6115     auto type = abilityRecord->GetAbilityInfo().type;
6116     switch (type) {
6117         case AppExecFwk::AbilityType::DATA: {
6118             auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6119             if (!dataAbilityManager) {
6120                 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
6121                 return;
6122             }
6123             dataAbilityManager->OnAbilityRequestDone(token, state);
6124             break;
6125         }
6126         case AppExecFwk::AbilityType::SERVICE:
6127         case AppExecFwk::AbilityType::EXTENSION: {
6128             auto connectManager = GetConnectManagerByUserId(userId);
6129             if (!connectManager) {
6130                 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
6131                 return;
6132             }
6133             connectManager->OnAbilityRequestDone(token, state);
6134             break;
6135         }
6136         default: {
6137             int32_t ownerUserId = abilityRecord->GetOwnerMissionUserId();
6138             if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6139                 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
6140                 CHECK_POINTER(uiAbilityManager);
6141                 uiAbilityManager->OnAbilityRequestDone(token, state);
6142             } else {
6143                 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
6144                 if (!missionListManager) {
6145                     TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", ownerUserId);
6146                     return;
6147                 }
6148                 missionListManager->OnAbilityRequestDone(token, state);
6149             }
6150             break;
6151         }
6152     }
6153 }
6154 
OnAppStateChanged(const AppInfo & info)6155 void AbilityManagerService::OnAppStateChanged(const AppInfo &info)
6156 {
6157     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6158     auto connectManager = GetCurrentConnectManager();
6159     CHECK_POINTER_LOG(connectManager, "Connect manager not init.");
6160     connectManager->OnAppStateChanged(info);
6161     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6162         auto uiAbilityManager = GetCurrentUIAbilityManager();
6163         CHECK_POINTER(uiAbilityManager);
6164         uiAbilityManager->OnAppStateChanged(info);
6165     } else {
6166         auto missionListManager = GetCurrentMissionListManager();
6167         CHECK_POINTER_LOG(missionListManager, "Current mission list manager not init.");
6168         missionListManager->OnAppStateChanged(info);
6169     }
6170     auto dataAbilityManager = GetCurrentDataAbilityManager();
6171     CHECK_POINTER(dataAbilityManager);
6172     dataAbilityManager->OnAppStateChanged(info);
6173 
6174     auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
6175     CHECK_POINTER(residentProcessMgr);
6176     residentProcessMgr->OnAppStateChanged(info);
6177 }
6178 
GetEventHandler()6179 std::shared_ptr<AbilityEventHandler> AbilityManagerService::GetEventHandler()
6180 {
6181     return eventHandler_;
6182 }
6183 
6184 // multi user scene
GetUserId() const6185 int32_t AbilityManagerService::GetUserId() const
6186 {
6187     if (userController_) {
6188         auto userId = userController_->GetCurrentUserId();
6189         TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is %{public}d", userId);
6190         return userId;
6191     }
6192     return U0_USER_ID;
6193 }
6194 
StartHighestPriorityAbility(int32_t userId,bool isBoot)6195 void AbilityManagerService::StartHighestPriorityAbility(int32_t userId, bool isBoot)
6196 {
6197     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
6198     auto bms = GetBundleManager();
6199     CHECK_POINTER(bms);
6200 
6201     /* Query the highest priority ability or extension ability, and start it. usually, it is OOBE or launcher */
6202     Want want;
6203     want.AddEntity(HIGHEST_PRIORITY_ABILITY_ENTITY);
6204     AppExecFwk::AbilityInfo abilityInfo;
6205     AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
6206     int attemptNums = 0;
6207     while (!IN_PROCESS_CALL(bms->ImplicitQueryInfoByPriority(want,
6208         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId,
6209         abilityInfo, extensionAbilityInfo))) {
6210         TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting query highest priority ability info completed.");
6211         ++attemptNums;
6212         if (!isBoot && attemptNums > SWITCH_ACCOUNT_TRY) {
6213             TAG_LOGE(AAFwkTag::ABILITYMGR, "Query highest priority ability failed.");
6214             return;
6215         }
6216         AbilityRequest abilityRequest;
6217         usleep(REPOLL_TIME_MICRO_SECONDS);
6218     }
6219 
6220     if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
6221         TAG_LOGE(AAFwkTag::ABILITYMGR, "Query highest priority ability failed");
6222         return;
6223     }
6224 
6225     Want abilityWant; // donot use 'want' here, because the entity of 'want' is not empty
6226     if (!abilityInfo.name.empty()) {
6227         /* highest priority ability */
6228         TAG_LOGI(AAFwkTag::ABILITYMGR, "Start the highest priority ability. bundleName: %{public}s, ability:%{public}s",
6229             abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
6230         abilityWant.SetElementName(abilityInfo.bundleName, abilityInfo.name);
6231     } else {
6232         /* highest priority extension ability */
6233         TAG_LOGI(AAFwkTag::ABILITYMGR,
6234             "Start the highest priority extension ability. bundleName: %{public}s, ability:%{public}s",
6235             extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str());
6236         abilityWant.SetElementName(extensionAbilityInfo.bundleName, extensionAbilityInfo.name);
6237     }
6238 
6239 #ifdef SUPPORT_GRAPHICS
6240     abilityWant.SetParam(NEED_STARTINGWINDOW, false);
6241     // wait BOOT_ANIMATION_STARTED to start LAUNCHER
6242     WaitBootAnimationStart();
6243 #endif
6244 
6245     /* note: OOBE APP need disable itself, otherwise, it will be started when restart system everytime */
6246     (void)StartAbility(abilityWant, userId, DEFAULT_INVAL_VALUE);
6247 }
6248 
GenerateAbilityRequest(const Want & want,int requestCode,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)6249 int AbilityManagerService::GenerateAbilityRequest(const Want &want, int requestCode, AbilityRequest &request,
6250     const sptr<IRemoteObject> &callerToken, int32_t userId)
6251 {
6252     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6253     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6254     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6255         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6256         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6257         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6258     }
6259 
6260     int32_t appIndex = 0;
6261     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
6262     if (abilityRecord != nullptr &&
6263         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName() &&
6264         abilityRecord->GetAppIndex() == appIndex) {
6265         (const_cast<Want &>(want)).SetParam(DEBUG_APP, abilityRecord->IsDebugApp());
6266     }
6267 
6268     request.want = want;
6269     request.requestCode = requestCode;
6270     request.callerToken = callerToken;
6271     auto setting = AbilityStartSetting::GetEmptySetting();
6272     if (setting != nullptr) {
6273         setting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "false"); // default is false
6274         request.startSetting = std::make_shared<AbilityStartSetting>(*(setting.get()));
6275     }
6276 
6277     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6278     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6279         int32_t appIndex = 0;
6280         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6281             return ERR_APP_CLONE_INDEX_INVALID;
6282         }
6283         Want localWant = want;
6284         if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
6285             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
6286             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
6287         }
6288         abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(localWant, userId, appIndex);
6289     }
6290     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6291     if (abilityInfo->status != ERR_OK) {
6292         return abilityInfo->status;
6293     }
6294     request.abilityInfo = abilityInfo->abilityInfo;
6295     request.extensionProcessMode = abilityInfo->extensionProcessMode;
6296 
6297     if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
6298         request.collaboratorType = CollaboratorType::RESERVE_TYPE;
6299     } else if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::OTHERS_TYPE)) {
6300         request.collaboratorType = CollaboratorType::OTHERS_TYPE;
6301     }
6302 
6303     if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) {
6304         TAG_LOGI(AAFwkTag::ABILITYMGR, "Stage mode, abilityInfo SERVICE type reset EXTENSION.");
6305         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
6306     }
6307 
6308     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6309         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app info failed.");
6310         return RESOLVE_APP_ERR;
6311     }
6312     if (want.GetIntParam(AAFwk::SCREEN_MODE_KEY, ScreenMode::IDLE_SCREEN_MODE) == ScreenMode::JUMP_SCREEN_MODE &&
6313         (request.abilityInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE ||
6314         request.abilityInfo.launchMode != AppExecFwk::LaunchMode::SINGLETON)) {
6315         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface of starting atomicService can start only atomicService.");
6316         return TARGET_ABILITY_NOT_SERVICE;
6317     }
6318     request.appInfo = request.abilityInfo.applicationInfo;
6319     request.uid = request.appInfo.uid;
6320     TAG_LOGD(AAFwkTag::ABILITYMGR,
6321         "GenerateAbilityRequest end, app name: %{public}s, moduleName name: %{public}s, uid: %{public}d.",
6322         request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid);
6323 
6324     request.want.SetModuleName(request.abilityInfo.moduleName);
6325 
6326     if (want.GetBoolParam(Want::PARAM_RESV_START_RECENT, false) &&
6327         AAFwk::PermissionVerification::GetInstance()->VerifyStartRecentAbilityPermission()) {
6328         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set start recent.");
6329         request.startRecent = true;
6330     }
6331 
6332     return ERR_OK;
6333 }
6334 
GenerateExtensionAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)6335 int AbilityManagerService::GenerateExtensionAbilityRequest(
6336     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
6337 {
6338     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6339     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6340         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6341         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6342         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6343     }
6344     request.want = want;
6345     request.callerToken = callerToken;
6346     request.startSetting = nullptr;
6347 
6348     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6349     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6350         int32_t appIndex = 0;
6351         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6352             return ERR_APP_CLONE_INDEX_INVALID;
6353         }
6354         abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, appIndex);
6355     }
6356     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6357     if (abilityInfo->status != ERR_OK) {
6358         return abilityInfo->status;
6359     }
6360 
6361     auto result = InitialAbilityRequest(request, *abilityInfo);
6362     return result;
6363 }
6364 
InitialAbilityRequest(AbilityRequest & request,const StartAbilityInfo & abilityInfo) const6365 int32_t AbilityManagerService::InitialAbilityRequest(AbilityRequest &request,
6366     const StartAbilityInfo &abilityInfo) const
6367 {
6368     request.abilityInfo = abilityInfo.abilityInfo;
6369     request.extensionProcessMode = abilityInfo.extensionProcessMode;
6370     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6371         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app info failed.");
6372         return RESOLVE_APP_ERR;
6373     }
6374     request.appInfo = request.abilityInfo.applicationInfo;
6375     request.uid = request.appInfo.uid;
6376     TAG_LOGD(AAFwkTag::ABILITYMGR,
6377         "GenerateAbilityRequest end, app name: %{public}s, bundle name: %{public}s, uid: %{public}d.",
6378         request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid);
6379 
6380     TAG_LOGD(AAFwkTag::ABILITYMGR,
6381         "GenerateExtensionAbilityRequest, moduleName: %{public}s.", request.abilityInfo.moduleName.c_str());
6382     request.want.SetModuleName(request.abilityInfo.moduleName);
6383 
6384     return ERR_OK;
6385 }
6386 
StopServiceAbility(const Want & want,int32_t userId,const sptr<IRemoteObject> & token)6387 int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)
6388 {
6389     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6390     TAG_LOGD(AAFwkTag::ABILITYMGR, "call.");
6391 
6392     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6393     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6394     if (!isSaCall && !isShellCall) {
6395         auto abilityRecord = Token::GetAbilityRecordByToken(token);
6396         if (abilityRecord == nullptr) {
6397             TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord is nullptr");
6398             return ERR_INVALID_VALUE;
6399         }
6400     }
6401 
6402     int32_t validUserId = GetValidUserId(userId);
6403     if (!JudgeMultiUserConcurrency(validUserId)) {
6404         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
6405         return ERR_CROSS_USER;
6406     }
6407 
6408     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
6409     AbilityRequest abilityRequest;
6410     auto result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId);
6411     if (result != ERR_OK) {
6412         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
6413         return result;
6414     }
6415 
6416     auto abilityInfo = abilityRequest.abilityInfo;
6417     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
6418     TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
6419         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
6420 
6421     auto type = abilityInfo.type;
6422     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6423         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is not service type.");
6424         return TARGET_ABILITY_NOT_SERVICE;
6425     }
6426 
6427     auto res = JudgeAbilityVisibleControl(abilityInfo);
6428     if (res != ERR_OK) {
6429         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is invisible");
6430         return res;
6431     }
6432 
6433     auto connectManager = GetConnectManagerByUserId(validUserId);
6434     if (connectManager == nullptr) {
6435         return ERR_INVALID_VALUE;
6436     }
6437 
6438     return connectManager->StopServiceAbility(abilityRequest);
6439 }
6440 
OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)6441 void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)
6442 {
6443     CHECK_POINTER(abilityRecord);
6444     if (abilityRecord->GetToken()) {
6445         FreezeUtil::GetInstance().DeleteLifecycleEvent(abilityRecord->GetToken()->AsObject());
6446     }
6447     FreezeUtil::GetInstance().DeleteAppLifecycleEvent(abilityRecord->GetPid());
6448     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6449         if (abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6450             auto uiAbilityManager = GetUIAbilityManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6451             CHECK_POINTER(uiAbilityManager);
6452             uiAbilityManager->OnAbilityDied(abilityRecord);
6453             return;
6454         }
6455     } else {
6456         auto manager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6457         if (manager && abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6458             ReleaseAbilityTokenMap(abilityRecord->GetToken());
6459             manager->OnAbilityDied(abilityRecord, GetUserId());
6460             return;
6461         }
6462     }
6463 
6464     auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
6465     if (connectManager) {
6466         connectManager->OnAbilityDied(abilityRecord, GetUserId());
6467         return;
6468     }
6469 
6470     auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken());
6471     if (dataAbilityManager) {
6472         dataAbilityManager->OnAbilityDied(abilityRecord);
6473     }
6474 }
6475 
OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)6476 void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
6477 {
6478     CHECK_POINTER(callRecord);
6479     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6480         auto uiAbilityManager = GetCurrentUIAbilityManager();
6481         CHECK_POINTER(uiAbilityManager);
6482         uiAbilityManager->OnCallConnectDied(callRecord);
6483         return;
6484     }
6485     auto missionListManager = GetCurrentMissionListManager();
6486     if (missionListManager) {
6487         missionListManager->OnCallConnectDied(callRecord);
6488     }
6489 }
6490 
ReleaseAbilityTokenMap(const sptr<IRemoteObject> & token)6491 void AbilityManagerService::ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)
6492 {
6493     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
6494     for (auto iter = callStubTokenMap_.begin(); iter != callStubTokenMap_.end(); iter++) {
6495         if (iter->second == token) {
6496             callStubTokenMap_.erase(iter);
6497             break;
6498         }
6499     }
6500 }
6501 
KillProcess(const std::string & bundleName,const bool clearPageStack)6502 int AbilityManagerService::KillProcess(const std::string &bundleName, const bool clearPageStack)
6503 {
6504     TAG_LOGI(AAFwkTag::ABILITYMGR, "Kill process, bundleName: %{public}s", bundleName.c_str());
6505     auto bms = GetBundleManager();
6506     CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED);
6507     int32_t userId = GetUserId();
6508     AppExecFwk::BundleInfo bundleInfo;
6509     if (!IN_PROCESS_CALL(
6510         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
6511         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info when kill process.");
6512         return GET_BUNDLE_INFO_FAILED;
6513     }
6514 
6515     bool keepAliveEnable = bundleInfo.isKeepAlive;
6516     AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleName, keepAliveEnable);
6517     if (keepAliveEnable && DelayedSingleton<AppScheduler>::GetInstance()->IsMemorySizeSufficent()) {
6518         TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not kill keep alive process.");
6519         return KILL_PROCESS_KEEP_ALIVE;
6520     }
6521 
6522     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName, clearPageStack);
6523     if (ret != ERR_OK) {
6524         return KILL_PROCESS_FAILED;
6525     }
6526 
6527     return ERR_OK;
6528 }
6529 
UninstallApp(const std::string & bundleName,int32_t uid)6530 int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid)
6531 {
6532     return UninstallApp(bundleName, uid, 0);
6533 }
6534 
UninstallApp(const std::string & bundleName,int32_t uid,int32_t appIndex)6535 int32_t AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex)
6536 {
6537     TAG_LOGI(AAFwkTag::ABILITYMGR, "Uninstall app, bundleName: %{public}s, uid=%{public}d, appIndex:%{public}d",
6538         bundleName.c_str(), uid, appIndex);
6539     return UninstallAppInner(bundleName, uid, appIndex, false, "");
6540 }
6541 
UpgradeApp(const std::string & bundleName,const int32_t uid,const std::string & exitMsg,int32_t appIndex)6542 int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg,
6543     int32_t appIndex)
6544 {
6545     TAG_LOGI(AAFwkTag::ABILITYMGR,
6546         "UpgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg: %{public}s, appIndex:%{public}d",
6547         bundleName.c_str(), uid, exitMsg.c_str(), appIndex);
6548     return UninstallAppInner(bundleName, uid, appIndex, true, exitMsg);
6549 }
6550 
UninstallAppInner(const std::string & bundleName,const int32_t uid,int32_t appIndex,const bool isUpgrade,const std::string & exitMsg)6551 int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex,
6552     const bool isUpgrade, const std::string &exitMsg)
6553 {
6554     pid_t callingPid = IPCSkeleton::GetCallingPid();
6555     pid_t pid = getprocpid();
6556     if (callingPid != pid) {
6557         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Not bundleMgr call.", __func__);
6558         return CHECK_PERMISSION_FAILED;
6559     }
6560 
6561     auto userId = uid / BASE_USER_RANGE;
6562     if (isUpgrade) {
6563         CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
6564         AAFwk::ExitReason exitReason = { REASON_UPGRADE, exitMsg };
6565         appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
6566     }
6567     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppExecFwk::AppMgrClient>::
6568         GetInstance()->SetKeepAliveEnableState(bundleName, false, uid));
6569     auto connectManager = GetConnectManagerByUserId(userId);
6570     if (connectManager) {
6571         connectManager->UninstallApp(bundleName, uid);
6572     }
6573 
6574     CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT);
6575     subManagersHelper_->UninstallApp(bundleName, uid);
6576     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplicationByUid(bundleName, uid, "UninstallApp");
6577     if (ret != ERR_OK) {
6578         return UNINSTALL_APP_FAILED;
6579     }
6580     if (!isUpgrade) {
6581         DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->DeleteAppExitReason(bundleName, uid,
6582             appIndex);
6583     }
6584     return ERR_OK;
6585 }
6586 
GetBundleManager()6587 std::shared_ptr<AppExecFwk::BundleMgrHelper> AbilityManagerService::GetBundleManager()
6588 {
6589     if (bundleMgrHelper_ == nullptr) {
6590         bundleMgrHelper_ = AbilityUtil::GetBundleManagerHelper();
6591     }
6592     return bundleMgrHelper_;
6593 }
6594 
PreLoadAppDataAbilities(const std::string & bundleName,const int32_t userId)6595 int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)
6596 {
6597     if (bundleName.empty()) {
6598         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name when app data abilities preloading.");
6599         return ERR_INVALID_VALUE;
6600     }
6601 
6602     if (taskHandler_ == nullptr) {
6603         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler nullptr.");
6604         return ERR_INVALID_STATE;
6605     }
6606 
6607     taskHandler_->SubmitTask([weak = weak_from_this(), bundleName, userId]() {
6608         auto pthis = weak.lock();
6609         if (pthis == nullptr) {
6610             TAG_LOGE(AAFwkTag::ABILITYMGR, "pthis nullptr.");
6611             return;
6612         }
6613         pthis->PreLoadAppDataAbilitiesTask(bundleName, userId);
6614         });
6615 
6616     return ERR_OK;
6617 }
6618 
PreLoadAppDataAbilitiesTask(const std::string & bundleName,const int32_t userId)6619 void AbilityManagerService::PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId)
6620 {
6621     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6622     auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6623     if (dataAbilityManager == nullptr) {
6624         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid data ability manager when app data abilities preloading.");
6625         return;
6626     }
6627 
6628     auto bms = GetBundleManager();
6629     CHECK_POINTER(bms);
6630 
6631     AppExecFwk::BundleInfo bundleInfo;
6632     bool ret = IN_PROCESS_CALL(
6633         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
6634     if (!ret) {
6635         TAG_LOGE(AAFwkTag::ABILITYMGR,
6636             "Failed to get bundle info when app data abilities preloading, userId is %{public}d", userId);
6637         return;
6638     }
6639 
6640     auto begin = system_clock::now();
6641     AbilityRequest dataAbilityRequest;
6642     UpdateCallerInfo(dataAbilityRequest.want, nullptr);
6643     dataAbilityRequest.appInfo = bundleInfo.applicationInfo;
6644     for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
6645         if (it->type != AppExecFwk::AbilityType::DATA) {
6646             continue;
6647         }
6648         if ((system_clock::now() - begin) >= DATA_ABILITY_START_TIMEOUT) {
6649             TAG_LOGE(AAFwkTag::ABILITYMGR, "App data ability preloading for '%{public}s' timeout.", bundleName.c_str());
6650             return;
6651         }
6652         dataAbilityRequest.abilityInfo = *it;
6653         dataAbilityRequest.uid = bundleInfo.uid;
6654         TAG_LOGD(AAFwkTag::ABILITYMGR, "App data ability preloading: '%{public}s.%{public}s'...",
6655             it->bundleName.c_str(), it->name.c_str());
6656 
6657         auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false);
6658         if (dataAbility == nullptr) {
6659             TAG_LOGE(AAFwkTag::ABILITYMGR,
6660                 "Failed to preload data ability '%{public}s.%{public}s'.", it->bundleName.c_str(), it->name.c_str());
6661             return;
6662         }
6663     }
6664 }
6665 
IsSystemUiApp(const AppExecFwk::AbilityInfo & info) const6666 bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const
6667 {
6668     if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) {
6669         return false;
6670     }
6671     return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR ||
6672         info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR ||
6673         info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME);
6674 }
6675 
IsSystemUI(const std::string & bundleName) const6676 bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const
6677 {
6678     return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME;
6679 }
6680 
HandleLoadTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)6681 void AbilityManagerService::HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6682 {
6683     TAG_LOGD(AAFwkTag::ABILITYMGR, "load timeout %{public}" PRId64, abilityRecordId);
6684     if (isExtension) {
6685         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6686         if (connectManager != nullptr) {
6687             connectManager->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6688         }
6689         return;
6690     }
6691 
6692     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6693         auto uiAbilityManagers = GetUIAbilityManagers();
6694         for (auto& item : uiAbilityManagers) {
6695             if (item.second) {
6696                 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6697             }
6698         }
6699         return;
6700     }
6701     auto missionListManagers = GetMissionListManagers();
6702     for (auto& item : missionListManagers) {
6703         if (item.second) {
6704             item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6705         }
6706     }
6707 }
6708 
HandleActiveTimeOut(int64_t abilityRecordId)6709 void AbilityManagerService::HandleActiveTimeOut(int64_t abilityRecordId)
6710 {
6711     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle active timeout.");
6712     auto missionListManagers = GetMissionListManagers();
6713     for (auto& item : missionListManagers) {
6714         if (item.second) {
6715             item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecordId);
6716         }
6717     }
6718 }
6719 
HandleInactiveTimeOut(int64_t abilityRecordId)6720 void AbilityManagerService::HandleInactiveTimeOut(int64_t abilityRecordId)
6721 {
6722     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle inactive timeout.");
6723     auto missionListManagers = GetMissionListManagers();
6724     for (auto& item : missionListManagers) {
6725         if (item.second) {
6726             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6727         }
6728     }
6729     auto connectManagers = GetConnectManagers();
6730     for (auto& item : connectManagers) {
6731         if (item.second) {
6732             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6733         }
6734     }
6735 }
6736 
HandleForegroundTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)6737 void AbilityManagerService::HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6738 {
6739     TAG_LOGD(AAFwkTag::ABILITYMGR, "foreground timeout %{public}" PRId64, abilityRecordId);
6740     if (isExtension) {
6741         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6742         if (connectManager != nullptr) {
6743             connectManager->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6744         }
6745         return;
6746     }
6747 
6748     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6749         auto uiAbilityManagers = GetUIAbilityManagers();
6750         for (auto& item : uiAbilityManagers) {
6751             if (item.second) {
6752                 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6753             }
6754         }
6755         return;
6756     }
6757     auto missionListManagers = GetMissionListManagers();
6758     for (auto& item : missionListManagers) {
6759         if (item.second) {
6760             item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6761         }
6762     }
6763 }
6764 
HandleShareDataTimeOut(int64_t uniqueId)6765 void AbilityManagerService::HandleShareDataTimeOut(int64_t uniqueId)
6766 {
6767     WantParams wantParam;
6768     int32_t ret = GetShareDataPairAndReturnData(nullptr, ERR_TIMED_OUT, uniqueId, wantParam);
6769     if (ret) {
6770         TAG_LOGE(AAFwkTag::ABILITYMGR, "acqurieShareData failed.");
6771     }
6772 }
6773 
GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)6774 int32_t AbilityManagerService::GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,
6775     const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
6776 {
6777     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d, wantParam size:%{public}d.",
6778         resultCode, uniqueId, wantParam.Size());
6779     {
6780         std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
6781         auto it = iAcquireShareDataMap_.find(uniqueId);
6782         if (it != iAcquireShareDataMap_.end()) {
6783             auto shareDataPair = it->second;
6784             if (abilityRecord && shareDataPair.first != abilityRecord->GetAbilityRecordId()) {
6785                 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is not the abilityRecord from request.");
6786                 return ERR_INVALID_VALUE;
6787             }
6788             auto callback = shareDataPair.second;
6789             if (!callback) {
6790                 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback object is nullptr.");
6791                 return ERR_INVALID_VALUE;
6792             }
6793             auto ret = callback->AcquireShareDataDone(resultCode, wantParam);
6794             iAcquireShareDataMap_.erase(it);
6795             return ret;
6796         }
6797     }
6798     TAG_LOGE(AAFwkTag::ABILITYMGR, "iAcquireShareData is null.");
6799     return ERR_INVALID_VALUE;
6800 }
6801 
VerificationToken(const sptr<IRemoteObject> & token)6802 bool AbilityManagerService::VerificationToken(const sptr<IRemoteObject> &token)
6803 {
6804     TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token.");
6805     auto dataAbilityManager = GetCurrentDataAbilityManager();
6806     CHECK_POINTER_RETURN_BOOL(dataAbilityManager);
6807     auto connectManager = GetCurrentConnectManager();
6808     CHECK_POINTER_RETURN_BOOL(connectManager);
6809     auto missionListManager = GetCurrentMissionListManager();
6810     CHECK_POINTER_RETURN_BOOL(missionListManager);
6811 
6812     if (missionListManager->GetAbilityRecordByToken(token)) {
6813         return true;
6814     }
6815     if (missionListManager->GetAbilityFromTerminateList(token)) {
6816         return true;
6817     }
6818 
6819     if (dataAbilityManager->GetAbilityRecordByToken(token)) {
6820         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token4.");
6821         return true;
6822     }
6823 
6824     if (connectManager->GetExtensionByTokenFromServiceMap(token)) {
6825         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6826         return true;
6827     }
6828 
6829     if (connectManager->GetExtensionByTokenFromAbilityCache(token)) {
6830         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6831         return true;
6832     }
6833 
6834     if (connectManager->GetExtensionByTokenFromTerminatingMap(token)) {
6835         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6836         return true;
6837     }
6838 
6839     TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to verify token.");
6840     return false;
6841 }
6842 
VerificationAllToken(const sptr<IRemoteObject> & token)6843 bool AbilityManagerService::VerificationAllToken(const sptr<IRemoteObject> &token)
6844 {
6845     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6846     CHECK_POINTER_AND_RETURN(subManagersHelper_, false);
6847     return subManagersHelper_->VerificationAllToken(token);
6848 }
6849 
GetCurrentDataAbilityManager()6850 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetCurrentDataAbilityManager()
6851 {
6852     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6853     return subManagersHelper_->GetCurrentDataAbilityManager();
6854 }
6855 
GetDataAbilityManager(const sptr<IAbilityScheduler> & scheduler)6856 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManager(
6857     const sptr<IAbilityScheduler> &scheduler)
6858 {
6859     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6860     return subManagersHelper_->GetDataAbilityManager(scheduler);
6861 }
6862 
GetDataAbilityManagerByUserId(int32_t userId)6863 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId)
6864 {
6865     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6866     return subManagersHelper_->GetDataAbilityManagerByUserId(userId);
6867 }
6868 
GetDataAbilityManagerByToken(const sptr<IRemoteObject> & token)6869 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByToken(
6870     const sptr<IRemoteObject> &token)
6871 {
6872     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6873     return subManagersHelper_->GetDataAbilityManagerByToken(token);
6874 }
6875 
GetConnectManagers()6876 std::unordered_map<int, std::shared_ptr<AbilityConnectManager>> AbilityManagerService::GetConnectManagers()
6877 {
6878     if (subManagersHelper_ == nullptr) {
6879         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6880         return std::unordered_map<int, std::shared_ptr<AbilityConnectManager>>();
6881     }
6882     return subManagersHelper_->GetConnectManagers();
6883 }
6884 
GetCurrentConnectManager()6885 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetCurrentConnectManager()
6886 {
6887     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6888     return subManagersHelper_->GetCurrentConnectManager();
6889 }
6890 
GetConnectManagerByUserId(int32_t userId)6891 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByUserId(int32_t userId)
6892 {
6893     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6894     return subManagersHelper_->GetConnectManagerByUserId(userId);
6895 }
6896 
GetConnectManagerByToken(const sptr<IRemoteObject> & token)6897 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByToken(
6898     const sptr<IRemoteObject> &token)
6899 {
6900     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6901     return subManagersHelper_->GetConnectManagerByToken(token);
6902 }
6903 
GetConnectManagerByAbilityRecordId(const int64_t & abilityRecordId)6904 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByAbilityRecordId(
6905     const int64_t &abilityRecordId)
6906 {
6907     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6908     return subManagersHelper_->GetConnectManagerByAbilityRecordId(abilityRecordId);
6909 }
6910 
GetCurrentPendingWantManager()6911 std::shared_ptr<PendingWantManager> AbilityManagerService::GetCurrentPendingWantManager()
6912 {
6913     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6914     return subManagersHelper_->GetCurrentPendingWantManager();
6915 }
6916 
GetPendingWantManagerByUserId(int32_t userId)6917 std::shared_ptr<PendingWantManager> AbilityManagerService::GetPendingWantManagerByUserId(int32_t userId)
6918 {
6919     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6920     return subManagersHelper_->GetPendingWantManagerByUserId(userId);
6921 }
6922 
GetMissionListManagers()6923 std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>> AbilityManagerService::GetMissionListManagers()
6924 {
6925     if (subManagersHelper_ == nullptr) {
6926         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6927         return std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>>();
6928     }
6929     return subManagersHelper_->GetMissionListManagers();
6930 }
6931 
GetCurrentMissionListManager()6932 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetCurrentMissionListManager()
6933 {
6934     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6935     return subManagersHelper_->GetCurrentMissionListManager();
6936 }
6937 
GetMissionListManagerByUserId(int32_t userId)6938 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetMissionListManagerByUserId(int32_t userId)
6939 {
6940     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6941     return subManagersHelper_->GetMissionListManagerByUserId(userId);
6942 }
6943 
GetMissionListWrap()6944 std::shared_ptr<MissionListWrap> AbilityManagerService::GetMissionListWrap()
6945 {
6946     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6947     return subManagersHelper_->GetMissionListWrap();
6948 }
6949 
GetUIAbilityManagers()6950 std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>> AbilityManagerService::GetUIAbilityManagers()
6951 {
6952     if (subManagersHelper_ == nullptr) {
6953         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6954         return std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>>();
6955     }
6956     return subManagersHelper_->GetUIAbilityManagers();
6957 }
6958 
GetCurrentUIAbilityManager()6959 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetCurrentUIAbilityManager()
6960 {
6961     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6962     return subManagersHelper_->GetCurrentUIAbilityManager();
6963 }
6964 
GetUIAbilityManagerByUserId(int32_t userId) const6965 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUserId(int32_t userId) const
6966 {
6967     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6968     return subManagersHelper_->GetUIAbilityManagerByUserId(userId);
6969 }
6970 
GetUIAbilityManagerByUid(int32_t uid)6971 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUid(int32_t uid)
6972 {
6973     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6974     return subManagersHelper_->GetUIAbilityManagerByUid(uid);
6975 }
6976 
StartResidentApps(int32_t userId)6977 void AbilityManagerService::StartResidentApps(int32_t userId)
6978 {
6979     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps %{public}d", userId);
6980     ConnectBmsService();
6981     auto bms = GetBundleManager();
6982     CHECK_POINTER_IS_NULLPTR(bms);
6983     std::vector<AppExecFwk::BundleInfo> bundleInfos;
6984     if (!DelayedSingleton<ResidentProcessManager>::GetInstance()->GetResidentBundleInfosForUser(bundleInfos, userId)) {
6985         TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident bundleinfos failed");
6986         return;
6987     }
6988     DelayedSingleton<ResidentProcessManager>::GetInstance()->Init();
6989     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps GetBundleInfos size: %{public}zu", bundleInfos.size());
6990 
6991     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId);
6992     if (!bundleInfos.empty()) {
6993 #ifdef SUPPORT_GRAPHICS
6994         if (userId == U0_USER_ID) {
6995             WaitBootAnimationStart();
6996         }
6997 #endif
6998         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
6999     }
7000 }
7001 
StartAutoStartupApps()7002 void AbilityManagerService::StartAutoStartupApps()
7003 {
7004     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7005     if (abilityAutoStartupService_ == nullptr) {
7006         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
7007         return;
7008     }
7009     std::vector<AutoStartupInfo> infoList;
7010     int32_t result = abilityAutoStartupService_->QueryAllAutoStartupApplicationsWithoutPermission(infoList,
7011         GetUserId());
7012     if (result != ERR_OK) {
7013         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to query data.");
7014         return;
7015     }
7016 
7017     constexpr int retryCount = 5;
7018     RetryStartAutoStartupApps(infoList, retryCount);
7019 }
7020 
RetryStartAutoStartupApps(const std::vector<AutoStartupInfo> & infoList,int32_t retryCount)7021 void AbilityManagerService::RetryStartAutoStartupApps(
7022     const std::vector<AutoStartupInfo> &infoList, int32_t retryCount)
7023 {
7024     TAG_LOGD(AAFwkTag::ABILITYMGR,
7025         "Called, retryCount: %{public}d, infoList.size:%{public}zu", retryCount, infoList.size());
7026     std::vector<AutoStartupInfo> failedList;
7027     for (auto info : infoList) {
7028         AppExecFwk::ElementName element;
7029         element.SetBundleName(info.bundleName);
7030         element.SetAbilityName(info.abilityName);
7031         element.SetModuleName(info.moduleName);
7032         Want want;
7033         want.SetElement(element);
7034         want.SetParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, true);
7035         if (info.appCloneIndex > 0 && info.appCloneIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
7036             want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, info.appCloneIndex);
7037         }
7038         if (StartAbility(want) != ERR_OK) {
7039             failedList.push_back(info);
7040         }
7041     }
7042 
7043     TAG_LOGD(AAFwkTag::ABILITYMGR,
7044         "RetryCount: %{public}d, failedList.size:%{public}zu", retryCount, failedList.size());
7045     if (!failedList.empty() && retryCount > 0) {
7046         auto retryStartAutoStartupAppsTask = [aams = weak_from_this(), list = failedList, retryCount]() {
7047             auto obj = aams.lock();
7048             if (obj == nullptr) {
7049                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Retry start auto startup app error, obj is nullptr");
7050                 return;
7051             }
7052             obj->RetryStartAutoStartupApps(list, retryCount - 1);
7053         };
7054         constexpr int delaytime = 2000;
7055         taskHandler_->SubmitTask(retryStartAutoStartupAppsTask, "RetryStartAutoStartupApps", delaytime);
7056     }
7057 }
7058 
SubscribeScreenUnlockedEvent()7059 void AbilityManagerService::SubscribeScreenUnlockedEvent()
7060 {
7061     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7062     // add listen screen unlocked.
7063     EventFwk::MatchingSkills matchingSkills;
7064     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
7065     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
7066     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
7067     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
7068     auto callback = [abilityManager = weak_from_this()]() {
7069         TAG_LOGD(AAFwkTag::ABILITYMGR, "On screen unlocked.");
7070         auto abilityMgr = abilityManager.lock();
7071         if (abilityMgr == nullptr) {
7072             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
7073             return;
7074         }
7075         auto taskHandler = abilityMgr->GetTaskHandler();
7076         if (taskHandler == nullptr) {
7077             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid taskHandler pointer.");
7078             return;
7079         }
7080         auto startAutoStartupAppsTask = [abilityManager]() {
7081             auto abilityMgr = abilityManager.lock();
7082             if (abilityMgr == nullptr) {
7083                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
7084                 return;
7085             }
7086             abilityMgr->RemoveScreenUnlockInterceptor();
7087             abilityMgr->StartAutoStartupApps();
7088             abilityMgr->UnSubscribeScreenUnlockedEvent();
7089         };
7090         taskHandler->SubmitTask(startAutoStartupAppsTask, "StartAutoStartupApps");
7091     };
7092     auto userScreenUnlockCallback = [abilityManager = weak_from_this()]() {
7093         TAG_LOGD(AAFwkTag::ABILITYMGR, "On user screen unlocked.");
7094         auto abilityMgr = abilityManager.lock();
7095         if (abilityMgr == nullptr) {
7096             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
7097             return;
7098         }
7099         abilityMgr->RemoveScreenUnlockInterceptor();
7100     };
7101     screenSubscriber_ = std::make_shared<AbilityRuntime::AbilityManagerEventSubscriber>(subscribeInfo, callback,
7102         userScreenUnlockCallback);
7103     bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber_);
7104     if (!subResult) {
7105         constexpr int retryCount = 20;
7106         RetrySubscribeScreenUnlockedEvent(retryCount);
7107     }
7108 }
7109 
UnSubscribeScreenUnlockedEvent()7110 void AbilityManagerService::UnSubscribeScreenUnlockedEvent()
7111 {
7112     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7113     bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_);
7114     TAG_LOGD(AAFwkTag::ABILITYMGR, "Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult);
7115 }
7116 
RetrySubscribeScreenUnlockedEvent(int32_t retryCount)7117 void AbilityManagerService::RetrySubscribeScreenUnlockedEvent(int32_t retryCount)
7118 {
7119     TAG_LOGD(AAFwkTag::ABILITYMGR, "RetryCount: %{public}d.", retryCount);
7120     auto retrySubscribeScreenUnlockedEventTask = [aams = weak_from_this(), screenSubscriber = screenSubscriber_,
7121                                                      retryCount]() {
7122         bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber);
7123         auto obj = aams.lock();
7124         if (obj == nullptr) {
7125             TAG_LOGE(AAFwkTag::ABILITYMGR, "Retry subscribe screen unlocked event, obj is nullptr.");
7126             return;
7127         }
7128         if (!subResult && retryCount > 0) {
7129             obj->RetrySubscribeScreenUnlockedEvent(retryCount - 1);
7130         }
7131     };
7132     constexpr int delaytime = 200;
7133     taskHandler_->SubmitTask(retrySubscribeScreenUnlockedEventTask, "RetrySubscribeScreenUnlockedEvent", delaytime);
7134 }
7135 
RemoveScreenUnlockInterceptor()7136 void AbilityManagerService::RemoveScreenUnlockInterceptor()
7137 {
7138     interceptorExecuter_->RemoveInterceptor("ScreenUnlock");
7139 }
7140 
ConnectBmsService()7141 void AbilityManagerService::ConnectBmsService()
7142 {
7143     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7144     TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting AppMgr Service run completed.");
7145     while (!DelayedSingleton<AppScheduler>::GetInstance()->Init(shared_from_this())) {
7146         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to init AppScheduler");
7147         usleep(REPOLL_TIME_MICRO_SECONDS);
7148     }
7149 
7150     TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting BundleMgr Service run completed.");
7151     /* wait until connected to bundle manager service */
7152     std::lock_guard<ffrt::mutex> guard(globalLock_);
7153     while (iBundleManager_ == nullptr) {
7154         sptr<IRemoteObject> bundle_obj =
7155             OHOS::DelayedSingleton<SaMgrClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
7156         if (bundle_obj == nullptr) {
7157             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bundle manager service");
7158             usleep(REPOLL_TIME_MICRO_SECONDS);
7159             continue;
7160         }
7161         iBundleManager_ = iface_cast<AppExecFwk::IBundleMgr>(bundle_obj);
7162     }
7163 
7164     TAG_LOGI(AAFwkTag::ABILITYMGR, "Connect bms success!");
7165 }
7166 
GetWantSenderInfo(const sptr<IWantSender> & target,std::shared_ptr<WantSenderInfo> & info)7167 int AbilityManagerService::GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)
7168 {
7169     TAG_LOGI(AAFwkTag::ABILITYMGR, "Get pending request info.");
7170     auto pendingWantManager = GetCurrentPendingWantManager();
7171     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
7172     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
7173     CHECK_POINTER_AND_RETURN(info, ERR_INVALID_VALUE);
7174     return pendingWantManager->GetWantSenderInfo(target, info);
7175 }
7176 
GetAppMemorySize()7177 int AbilityManagerService::GetAppMemorySize()
7178 {
7179     TAG_LOGI(AAFwkTag::ABILITYMGR, "service GetAppMemorySize start");
7180     const char *key = "const.product.arkheaplimit";
7181     const char *def = "512m";
7182     char *valueGet = nullptr;
7183     unsigned int len = 128;
7184     int ret = GetParameter(key, def, valueGet, len);
7185     int resultInt = 0;
7186     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7187         if (valueGet == nullptr) {
7188             TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, valueGet is nullptr", __func__);
7189             return APP_MEMORY_SIZE;
7190         }
7191         int len = strlen(valueGet);
7192         for (int i = 0; i < len; i++) {
7193             if (valueGet[i] >= '0' && valueGet[i] <= '9') {
7194                 resultInt *= SIZE_10;
7195                 resultInt += valueGet[i] - '0';
7196             }
7197         }
7198         if (resultInt == 0) {
7199             return APP_MEMORY_SIZE;
7200         }
7201         return resultInt;
7202     }
7203     return APP_MEMORY_SIZE;
7204 }
7205 
IsRamConstrainedDevice()7206 bool AbilityManagerService::IsRamConstrainedDevice()
7207 {
7208     TAG_LOGI(AAFwkTag::ABILITYMGR, "service IsRamConstrainedDevice start");
7209     const char *key = "const.product.islowram";
7210     const char *def = "0";
7211     char *valueGet = nullptr;
7212     unsigned int len = 128;
7213     int ret = GetParameter(key, def, valueGet, len);
7214     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7215         int value = atoi(valueGet);
7216         if (value) {
7217             return true;
7218         }
7219         return false;
7220     }
7221     return false;
7222 }
7223 
GetMissionIdByAbilityToken(const sptr<IRemoteObject> & token)7224 int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)
7225 {
7226     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7227     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7228     if (!abilityRecord) {
7229         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
7230         return -1;
7231     }
7232     if (!JudgeSelfCalled(abilityRecord)) {
7233         return -1;
7234     }
7235     return GetMissionIdByAbilityTokenInner(token);
7236 }
7237 
GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> & token)7238 int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)
7239 {
7240     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7241     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7242     if (!abilityRecord) {
7243         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
7244         return -1;
7245     }
7246     auto userId = abilityRecord->GetOwnerMissionUserId();
7247     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7248         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7249         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7250         return uiAbilityManager->GetSessionIdByAbilityToken(token);
7251     }
7252     auto missionListManager = GetMissionListManagerByUserId(userId);
7253     if (!missionListManager) {
7254         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. owner mission userId=%{public}d", userId);
7255         return -1;
7256     }
7257     return missionListManager->GetMissionIdByAbilityToken(token);
7258 }
7259 
GetAbilityTokenByMissionId(int32_t missionId)7260 sptr<IRemoteObject> AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId)
7261 {
7262     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7263     auto missionListManager = GetCurrentMissionListManager();
7264     if (!missionListManager) {
7265         return nullptr;
7266     }
7267     return missionListManager->GetAbilityTokenByMissionId(missionId);
7268 }
7269 
StartRemoteAbilityByCall(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)7270 int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken,
7271     const sptr<IRemoteObject> &connect)
7272 {
7273     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin StartRemoteAbilityByCall", __func__);
7274     Want remoteWant = want;
7275     UpdateDmsCallerInfo(remoteWant, callerToken);
7276     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
7277         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
7278         return ERR_INVALID_VALUE;
7279     }
7280     int32_t missionId = -1;
7281     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7282         missionId = GetMissionIdByAbilityTokenInner(callerToken);
7283         if (!missionId) {
7284             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
7285             return ERR_INVALID_VALUE;
7286         }
7287     } else {
7288         missionId = GetMissionIdByAbilityToken(callerToken);
7289 }
7290     if (missionId < 0) {
7291         return ERR_INVALID_VALUE;
7292     }
7293     remoteWant.SetParam(DMS_MISSION_ID, missionId);
7294     DistributedClient dmsClient;
7295     return dmsClient.StartRemoteAbilityByCall(remoteWant, connect);
7296 }
7297 
ReleaseRemoteAbility(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element)7298 int AbilityManagerService::ReleaseRemoteAbility(const sptr<IRemoteObject> &connect,
7299     const AppExecFwk::ElementName &element)
7300 {
7301     DistributedClient dmsClient;
7302     return dmsClient.ReleaseRemoteAbility(connect, element);
7303 }
7304 
StartAbilityByCall(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId)7305 int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect,
7306     const sptr<IRemoteObject> &callerToken, int32_t accountId)
7307 {
7308     TAG_LOGI(AAFwkTag::ABILITYMGR, "call ability.");
7309     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7310     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7311     if (IsCrossUserCall(accountId)) {
7312         CHECK_CALLER_IS_SYSTEM_APP;
7313     }
7314 
7315     if (VerifyAccountPermission(accountId) == CHECK_PERMISSION_FAILED) {
7316         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed.", __func__);
7317         return CHECK_PERMISSION_FAILED;
7318     }
7319 
7320     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7321     if (abilityRecord && !JudgeSelfCalled(abilityRecord)) {
7322         return CHECK_PERMISSION_FAILED;
7323     }
7324 
7325     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
7326     int32_t appIndex = 0;
7327     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
7328         return ERR_APP_CLONE_INDEX_INVALID;
7329     }
7330     auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
7331         GetUserId(), appIndex, callerToken);
7332     if (checkRet != ERR_OK) {
7333         return checkRet;
7334     }
7335     StartAbilityInfoWrap threadLocalInfo(want, GetUserId(), appIndex, callerToken);
7336     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), true, nullptr);
7337     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
7338         interceptorExecuter_->DoProcess(interceptorParam);
7339     if (result != ERR_OK) {
7340         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
7341         return result;
7342     }
7343 
7344     if (CheckIfOperateRemote(want)) {
7345         TAG_LOGI(AAFwkTag::ABILITYMGR, "start remote ability by call");
7346         return StartRemoteAbilityByCall(want, callerToken, connect->AsObject());
7347     }
7348 
7349     if (accountId == U0_USER_ID) {
7350         accountId = DEFAULT_INVAL_VALUE;
7351     }
7352     int32_t oriValidUserId = GetValidUserId(accountId);
7353     if (!JudgeMultiUserConcurrency(oriValidUserId)) {
7354         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
7355         return ERR_CROSS_USER;
7356     }
7357 
7358     AbilityRequest abilityRequest;
7359     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
7360     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
7361     abilityRequest.callerToken = callerToken;
7362     abilityRequest.startSetting = nullptr;
7363     abilityRequest.want = want;
7364     abilityRequest.connect = connect;
7365     result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
7366     if (result != ERR_OK) {
7367         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
7368         return result;
7369     }
7370 
7371     if (!abilityRequest.abilityInfo.isStageBasedModel) {
7372         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability is not stage base model.");
7373         return RESOLVE_CALL_ABILITY_VERSION_ERR;
7374     }
7375 
7376     result = CheckStartByCallPermission(abilityRequest);
7377     if (result != ERR_OK) {
7378         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStartByCallPermission fail, result: %{public}d", result);
7379         return result;
7380     }
7381 
7382     TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityInfo.applicationInfo.singleton is %{public}s",
7383         abilityRequest.abilityInfo.applicationInfo.singleton ? "true" : "false");
7384     UpdateCallerInfo(abilityRequest.want, callerToken);
7385     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
7386         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityRequest.abilityInfo), false, appIndex);
7387     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
7388         afterCheckExecuter_->DoProcess(afterCheckParam);
7389     if (result != ERR_OK) {
7390         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
7391         return result;
7392     }
7393     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7394         ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7395         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
7396         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
7397         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7398         return uiAbilityManager->ResolveLocked(abilityRequest);
7399     }
7400 
7401     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
7402     if (missionListMgr == nullptr) {
7403         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is Null. Designated User Id=%{public}d", oriValidUserId);
7404         return ERR_INVALID_VALUE;
7405     }
7406     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7407 
7408     return missionListMgr->ResolveLocked(abilityRequest);
7409 }
7410 
StartAbilityJust(AbilityRequest & abilityRequest,int32_t validUserId)7411 int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)
7412 {
7413     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7414     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
7415     UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
7416     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7417         ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7418         auto uiAbilityManager = GetUIAbilityManagerByUserId(validUserId);
7419         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7420         return uiAbilityManager->ResolveLocked(abilityRequest);
7421     }
7422 
7423     auto missionListMgr = GetMissionListManagerByUserId(validUserId);
7424     if (missionListMgr == nullptr) {
7425         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is Null. Designated User Id=%{public}d", validUserId);
7426         return ERR_INVALID_VALUE;
7427     }
7428     ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7429 
7430     return missionListMgr->ResolveLocked(abilityRequest);
7431 }
7432 
ReleaseCall(const sptr<IAbilityConnection> & connect,const AppExecFwk::ElementName & element)7433 int AbilityManagerService::ReleaseCall(
7434     const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
7435 {
7436     TAG_LOGD(AAFwkTag::ABILITYMGR, "Release called ability.");
7437 
7438     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7439     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7440 
7441     std::string elementName = element.GetURI();
7442     TAG_LOGD(AAFwkTag::ABILITYMGR, "try to release called ability, name: %{public}s.", elementName.c_str());
7443 
7444     if (CheckIsRemote(element.GetDeviceID())) {
7445         TAG_LOGI(AAFwkTag::ABILITYMGR, "release remote ability");
7446         return ReleaseRemoteAbility(connect->AsObject(), element);
7447     }
7448 
7449     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7450         auto uiAbilityManager = GetCurrentUIAbilityManager();
7451         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7452         return uiAbilityManager->ReleaseCallLocked(connect, element);
7453     }
7454     auto missionListManager = GetCurrentMissionListManager();
7455     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
7456     return missionListManager->ReleaseCallLocked(connect, element);
7457 }
7458 
JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo & abilityInfo)7459 int AbilityManagerService::JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)
7460 {
7461     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
7462     if (abilityInfo.visible) {
7463         return ERR_OK;
7464     }
7465     auto callerTokenId = IPCSkeleton::GetCallingTokenID();
7466     if (callerTokenId == abilityInfo.applicationInfo.accessTokenId ||
7467         callerTokenId == static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID())) {  // foundation call is allowed
7468         return ERR_OK;
7469     }
7470     if (AccessTokenKit::VerifyAccessToken(callerTokenId,
7471         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == AppExecFwk::Constants::PERMISSION_GRANTED) {
7472         return ERR_OK;
7473     }
7474     TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken: %{private}u, targetToken: %{private}u, caller doesn's have permission",
7475         callerTokenId, abilityInfo.applicationInfo.accessTokenId);
7476     return ABILITY_VISIBLE_FALSE_DENY_REQUEST;
7477 }
7478 
StartUser(int userId,sptr<IUserCallback> callback)7479 int AbilityManagerService::StartUser(int userId, sptr<IUserCallback> callback)
7480 {
7481     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartUser in service:%{public}d.", userId);
7482     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7483         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUser permission verification failed, not account process.");
7484         if (callback != nullptr) {
7485             callback->OnStartUserDone(userId, CHECK_PERMISSION_FAILED);
7486         }
7487         return CHECK_PERMISSION_FAILED;
7488     }
7489 
7490     if (userController_) {
7491         userController_->StartUser(userId, callback);
7492     }
7493     return 0;
7494 }
7495 
StopUser(int userId,const sptr<IUserCallback> & callback)7496 int AbilityManagerService::StopUser(int userId, const sptr<IUserCallback> &callback)
7497 {
7498     TAG_LOGI(AAFwkTag::ABILITYMGR, "StopUser in service:%{public}d", userId);
7499     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7500         TAG_LOGE(AAFwkTag::ABILITYMGR, "StopUser permission verification failed, not account process");
7501         if (callback != nullptr) {
7502             callback->OnStopUserDone(userId, CHECK_PERMISSION_FAILED);
7503         }
7504         return CHECK_PERMISSION_FAILED;
7505     }
7506 
7507     auto ret = -1;
7508     if (userController_) {
7509         ret = userController_->StopUser(userId);
7510         TAG_LOGD(AAFwkTag::ABILITYMGR, "ret = %{public}d", ret);
7511     }
7512     if (callback) {
7513         callback->OnStopUserDone(userId, ret);
7514     }
7515     return 0;
7516 }
7517 
LogoutUser(int32_t userId)7518 int AbilityManagerService::LogoutUser(int32_t userId)
7519 {
7520     TAG_LOGI(AAFwkTag::ABILITYMGR, "LogoutUser in service:%{public}d", userId);
7521     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7522         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed, not account process");
7523         return CHECK_PERMISSION_FAILED;
7524     }
7525 
7526     // Lister screen unlock for auto startup apps.
7527     if (system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) {
7528         InitInterceptorForScreenUnlock();
7529         SubscribeScreenUnlockedEvent();
7530     }
7531 
7532     if (userController_) {
7533         auto ret = userController_->LogoutUser(userId);
7534         TAG_LOGD(AAFwkTag::ABILITYMGR, "logout user return = %{public}d", ret);
7535         return ret;
7536     }
7537     return ERR_OK;
7538 }
7539 
OnAcceptWantResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)7540 void AbilityManagerService::OnAcceptWantResponse(
7541     const AAFwk::Want &want, const std::string &flag, int32_t requestId)
7542 {
7543     TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
7544     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7545         auto uiAbilityManager = GetCurrentUIAbilityManager();
7546         CHECK_POINTER(uiAbilityManager);
7547         uiAbilityManager->OnAcceptWantResponse(want, flag, requestId);
7548         return;
7549     }
7550     auto missionListManager = GetCurrentMissionListManager();
7551     if (!missionListManager) {
7552         return;
7553     }
7554     missionListManager->OnAcceptWantResponse(want, flag);
7555 }
7556 
OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want & want,int32_t requestId)7557 void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7558 {
7559     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str());
7560     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7561         auto uiAbilityManager = GetCurrentUIAbilityManager();
7562         CHECK_POINTER(uiAbilityManager);
7563         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7564         return;
7565     }
7566     auto missionListManager = GetCurrentMissionListManager();
7567     if (!missionListManager) {
7568         return;
7569     }
7570     missionListManager->OnStartSpecifiedAbilityTimeoutResponse(want);
7571 }
7572 
OnStartSpecifiedProcessResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)7573 void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag,
7574     int32_t requestId)
7575 {
7576     TAG_LOGD(AAFwkTag::ABILITYMGR, "flag = %{public}s", flag.c_str());
7577     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7578         auto uiAbilityManager = GetCurrentUIAbilityManager();
7579         CHECK_POINTER(uiAbilityManager);
7580         uiAbilityManager->OnStartSpecifiedProcessResponse(want, flag, requestId);
7581         return;
7582     }
7583 }
7584 
OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want & want,int32_t requestId)7585 void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7586 {
7587     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str());
7588     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7589         auto uiAbilityManager = GetCurrentUIAbilityManager();
7590         CHECK_POINTER(uiAbilityManager);
7591         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7592         return;
7593     }
7594 }
7595 
GetAbilityRunningInfos(std::vector<AbilityRunningInfo> & info)7596 int AbilityManagerService::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
7597 {
7598     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7599     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get running ability infos.");
7600     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7601     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7602         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
7603         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7604         uiAbilityManager->GetAbilityRunningInfos(info, isPerm);
7605     } else {
7606         auto missionListManager = GetCurrentMissionListManager();
7607         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
7608         missionListManager->GetAbilityRunningInfos(info, isPerm);
7609     }
7610 
7611     UpdateFocusState(info);
7612 
7613     return ERR_OK;
7614 }
7615 
UpdateFocusState(std::vector<AbilityRunningInfo> & info)7616 void AbilityManagerService::UpdateFocusState(std::vector<AbilityRunningInfo> &info)
7617 {
7618     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7619     if (info.empty()) {
7620         return;
7621     }
7622 
7623 #ifdef SUPPORT_GRAPHICS
7624     sptr<IRemoteObject> token;
7625     int ret = IN_PROCESS_CALL(GetTopAbility(token));
7626     if (ret != ERR_OK || token == nullptr) {
7627         return;
7628     }
7629 
7630     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7631     if (abilityRecord == nullptr) {
7632         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
7633         return;
7634     }
7635 
7636     for (auto &item : info) {
7637         if (item.uid == abilityRecord->GetUid() && item.pid == abilityRecord->GetPid() &&
7638             item.ability == abilityRecord->GetElementName()) {
7639             item.abilityState = static_cast<int>(AbilityState::ACTIVE);
7640             break;
7641         }
7642     }
7643 #endif
7644 }
7645 
GetExtensionRunningInfos(int upperLimit,std::vector<ExtensionRunningInfo> & info)7646 int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)
7647 {
7648     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7649     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension infos, upperLimit : %{public}d", upperLimit);
7650     CHECK_CALLER_IS_SYSTEM_APP;
7651     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7652     auto connectManager = GetCurrentConnectManager();
7653     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
7654     connectManager->GetExtensionRunningInfos(upperLimit, info, GetUserId(), isPerm);
7655     return ERR_OK;
7656 }
7657 
GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> & info)7658 int AbilityManagerService::GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)
7659 {
7660     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfos(info);
7661 }
7662 
GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> & info,int32_t userId)7663 int AbilityManagerService::GetProcessRunningInfosByUserId(
7664     std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)
7665 {
7666     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfosByUserId(info, userId);
7667 }
7668 
ClearUserData(int32_t userId)7669 void AbilityManagerService::ClearUserData(int32_t userId)
7670 {
7671     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7672     CHECK_POINTER(subManagersHelper_);
7673     subManagersHelper_->ClearSubManagers(userId);
7674 }
7675 
RegisterSnapshotHandler(const sptr<ISnapshotHandler> & handler)7676 int AbilityManagerService::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
7677 {
7678     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7679     if (!isSaCall) {
7680         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
7681         return 0;
7682     }
7683 
7684     auto missionListManager = GetCurrentMissionListManager();
7685     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7686     missionListManager->RegisterSnapshotHandler(handler);
7687     TAG_LOGI(AAFwkTag::ABILITYMGR, "snapshot: AbilityManagerService register snapshot handler success.");
7688     return ERR_OK;
7689 }
7690 
GetMissionSnapshot(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot,bool isLowResolution)7691 int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId,
7692     MissionSnapshot& missionSnapshot, bool isLowResolution)
7693 {
7694     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7695     CHECK_CALLER_IS_SYSTEM_APP;
7696     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
7697         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
7698         return CHECK_PERMISSION_FAILED;
7699     }
7700 
7701     if (CheckIsRemote(deviceId)) {
7702         TAG_LOGI(AAFwkTag::ABILITYMGR, "get remote mission snapshot.");
7703         return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot);
7704     }
7705     TAG_LOGI(AAFwkTag::ABILITYMGR, "get local mission snapshot.");
7706     auto missionListManager = GetCurrentMissionListManager();
7707     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7708     auto token = GetAbilityTokenByMissionId(missionId);
7709     bool result = missionListManager->GetMissionSnapshot(missionId, token, missionSnapshot, isLowResolution);
7710     if (!result) {
7711         return INNER_ERR;
7712     }
7713     return ERR_OK;
7714 }
7715 
UpdateMissionSnapShot(const sptr<IRemoteObject> & token,const std::shared_ptr<Media::PixelMap> & pixelMap)7716 void AbilityManagerService::UpdateMissionSnapShot(const sptr<IRemoteObject> &token,
7717     const std::shared_ptr<Media::PixelMap> &pixelMap)
7718 {
7719     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)) {
7720         return;
7721     }
7722     auto missionListManager = GetCurrentMissionListManager();
7723     if (missionListManager) {
7724         missionListManager->UpdateSnapShot(token, pixelMap);
7725     }
7726 }
7727 
EnableRecoverAbility(const sptr<IRemoteObject> & token)7728 void AbilityManagerService::EnableRecoverAbility(const sptr<IRemoteObject>& token)
7729 {
7730     TAG_LOGD(AAFwkTag::ABILITYMGR, "Enable recovery ability.");
7731     if (token == nullptr) {
7732         return;
7733     }
7734     auto record = Token::GetAbilityRecordByToken(token);
7735     if (record == nullptr) {
7736         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
7737         return;
7738     }
7739     if (record->IsClearMissionFlag()) {
7740         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::not allow EnableRecoverAbility before clearMission.",
7741             __func__);
7742         return;
7743     }
7744 
7745     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7746     auto tokenID = record->GetApplicationInfo().accessTokenId;
7747     if (callingTokenId != tokenID) {
7748         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery ScheduleRecoverAbility not self, not enabled");
7749         return;
7750     }
7751     {
7752         std::lock_guard<ffrt::mutex> guard(globalLock_);
7753         auto it = appRecoveryHistory_.find(record->GetUid());
7754         if (it == appRecoveryHistory_.end()) {
7755             appRecoveryHistory_.emplace(record->GetUid(), 0);
7756         }
7757     }
7758     auto userId = record->GetOwnerMissionUserId();
7759     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7760         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7761         CHECK_POINTER(uiAbilityManager);
7762         const auto& abilityInfo = record->GetAbilityInfo();
7763         std::string abilityName = abilityInfo.name;
7764         auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
7765         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
7766             abilityName += std::to_string(sessionId);
7767         }
7768         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->AddAbilityRecoverInfo(
7769             abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName, sessionId);
7770     } else {
7771         auto missionListMgr = GetMissionListManagerByUserId(userId);
7772         if (missionListMgr == nullptr) {
7773             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is nullptr");
7774             return;
7775         }
7776         missionListMgr->EnableRecoverAbility(record->GetMissionId());
7777     }
7778 }
7779 
ScheduleClearRecoveryPageStack()7780 void AbilityManagerService::ScheduleClearRecoveryPageStack()
7781 {
7782     int32_t callerUid = IPCSkeleton::GetCallingUid();
7783     std::string bundleName;
7784     auto bms = GetBundleManager();
7785     if (bms == nullptr) {
7786         TAG_LOGE(AAFwkTag::ABILITYMGR, "ScheduleClearRecoveryPageStack failed to get bms");
7787         return;
7788     }
7789 
7790     if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
7791         TAG_LOGE(AAFwkTag::ABILITYMGR, "ScheduleClearRecoveryPageStack failed to get bundleName by uid");
7792         return;
7793     }
7794 
7795     auto tokenId = IPCSkeleton::GetCallingTokenID();
7796 
7797     TAG_LOGI(AAFwkTag::ABILITYMGR,
7798         "ScheduleClearRecoveryPageStack bundleName = %{public}s, callerUid = %{public}d, tokenId = %{public}d",
7799         bundleName.c_str(), callerUid, tokenId);
7800     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
7801         DeleteAppExitReason(bundleName, tokenId);
7802     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
7803         DeleteAllRecoverInfoByTokenId(tokenId);
7804 }
7805 
ReportAppRecoverResult(const int32_t appId,const AppExecFwk::ApplicationInfo & appInfo,const std::string & abilityName,const std::string & result)7806 void AbilityManagerService::ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo,
7807     const std::string& abilityName, const std::string& result)
7808 {
7809     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
7810         "APP_UID", appId,
7811         "VERSION_CODE", std::to_string(appInfo.versionCode),
7812         "VERSION_NAME", appInfo.versionName,
7813         "BUNDLE_NAME", appInfo.bundleName,
7814         "ABILITY_NAME", abilityName,
7815         "RECOVERY_RESULT", result);
7816 }
7817 
SubmitSaveRecoveryInfo(const sptr<IRemoteObject> & token)7818 void AbilityManagerService::SubmitSaveRecoveryInfo(const sptr<IRemoteObject>& token)
7819 {
7820     if (token == nullptr) {
7821         TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo token is nullptr");
7822         return;
7823     }
7824     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7825     if (abilityRecord == nullptr) {
7826         TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo abilityRecord is nullptr");
7827         return;
7828     }
7829     auto abilityInfo = abilityRecord->GetAbilityInfo();
7830     auto userId = abilityRecord->GetOwnerMissionUserId();
7831     auto tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
7832     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7833     if (callingTokenId != tokenId) {
7834         TAG_LOGE(AAFwkTag::ABILITYMGR, "SubmitSaveRecoveryInfo not self, not enabled");
7835         return;
7836     }
7837     std::string abilityName = abilityInfo.name;
7838     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7839         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7840         CHECK_POINTER(uiAbilityManager);
7841         auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
7842         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
7843             abilityName += std::to_string(sessionId);
7844         }
7845     } else {
7846         auto missionListMgr = GetMissionListManagerByUserId(userId);
7847         if (missionListMgr == nullptr) {
7848             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is nullptr");
7849             return;
7850         }
7851         abilityName += std::to_string(abilityRecord->GetMissionId());
7852     }
7853     TAG_LOGI(AAFwkTag::ABILITYMGR,
7854         "submitInfo bundleName = %{public}s, moduleName = %{public}s, abilityName = %{public}s, tokenId = %{public}d",
7855         abilityInfo.bundleName.c_str(),  abilityInfo.moduleName.c_str(), abilityName.c_str(), tokenId);
7856     RecoveryInfo recoveryInfo;
7857     recoveryInfo.bundleName = abilityInfo.bundleName;
7858     recoveryInfo.moduleName = abilityInfo.moduleName;
7859     recoveryInfo.abilityName = abilityName;
7860     recoveryInfo.time = time(nullptr);
7861     OHOS::AAFwk::RecoveryInfoTimer::GetInstance().SubmitSaveRecoveryInfo(recoveryInfo);
7862 }
7863 
AppRecoverKill(pid_t pid,int32_t reason)7864 void AbilityManagerService::AppRecoverKill(pid_t pid, int32_t reason)
7865 {
7866     AppExecFwk::AppFaultDataBySA faultDataSA;
7867     faultDataSA.errorObject.name = "appRecovery";
7868     switch (reason) {
7869         case AppExecFwk::StateReason::CPP_CRASH:
7870             faultDataSA.faultType = AppExecFwk::FaultDataType::CPP_CRASH;
7871             break;
7872         case AppExecFwk::StateReason::JS_ERROR:
7873             faultDataSA.faultType = AppExecFwk::FaultDataType::JS_ERROR;
7874             break;
7875         case AppExecFwk::StateReason::LIFECYCLE:
7876         case AppExecFwk::StateReason::APP_FREEZE:
7877             faultDataSA.faultType = AppExecFwk::FaultDataType::APP_FREEZE;
7878             break;
7879         default:
7880             faultDataSA.faultType = AppExecFwk::FaultDataType::UNKNOWN;
7881     }
7882     faultDataSA.pid = pid;
7883     IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFaultBySA(faultDataSA));
7884 }
7885 
ScheduleRecoverAbility(const sptr<IRemoteObject> & token,int32_t reason,const Want * want)7886 void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)
7887 {
7888     if (token == nullptr) {
7889         return;
7890     }
7891     auto record = Token::GetAbilityRecordByToken(token);
7892     if (record == nullptr) {
7893         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
7894         return;
7895     }
7896     if (!record->IsForeground() && !record->GetAbilityForegroundingFlag()) {
7897         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed to recoveryAbility."
7898             "due to it is background", __func__);
7899         return;
7900     }
7901 
7902     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7903     auto tokenID = record->GetApplicationInfo().accessTokenId;
7904     if (callingTokenId != tokenID) {
7905         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery ScheduleRecoverAbility not self, not enabled");
7906         return;
7907     }
7908 
7909     AAFwk::Want curWant;
7910     {
7911         std::lock_guard<ffrt::mutex> guard(globalLock_);
7912         auto type = record->GetAbilityInfo().type;
7913         if (type != AppExecFwk::AbilityType::PAGE) {
7914             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::only do recover for page ability.", __func__);
7915             return;
7916         }
7917 
7918         constexpr int64_t MIN_RECOVERY_TIME = 60;
7919         int64_t now = time(nullptr);
7920         auto it = appRecoveryHistory_.find(record->GetUid());
7921         auto appInfo = record->GetApplicationInfo();
7922         auto abilityInfo = record->GetAbilityInfo();
7923 
7924         if ((it != appRecoveryHistory_.end()) &&
7925             (it->second + MIN_RECOVERY_TIME > now)) {
7926             TAG_LOGE(AAFwkTag::ABILITYMGR,
7927                 "%{public}s AppRecovery recover app more than once in one minute, just kill app(%{public}d).",
7928                 __func__, record->GetPid());
7929             ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_WITHIN_ONE_MINUTE");
7930             AppRecoverKill(record->GetPid(), reason);
7931             return;
7932         }
7933 
7934         if (want != nullptr) {
7935             TAG_LOGD(AAFwkTag::ABILITYMGR, "BundleName:%{public}s targetBundleName:%{public}s.",
7936                 appInfo.bundleName.c_str(), want->GetElement().GetBundleName().c_str());
7937             if (want->GetElement().GetBundleName().empty() ||
7938                 (appInfo.bundleName.compare(want->GetElement().GetBundleName()) != 0)) {
7939                 TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery BundleName not match, Not recovery ability!");
7940                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_BUNDLE_NAME_NOT_MATCH");
7941                 return;
7942             } else if (want->GetElement().GetAbilityName().empty()) {
7943                 TAG_LOGD(AAFwkTag::ABILITYMGR, "AppRecovery recovery target ability is empty");
7944                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_TARGET_ABILITY_EMPTY");
7945                 return;
7946             } else {
7947                 auto bms = GetBundleManager();
7948                 if (bms == nullptr) {
7949                     TAG_LOGE(AAFwkTag::ABILITYMGR, "bms is nullptr");
7950                     return;
7951                 }
7952                 AppExecFwk::BundleInfo bundleInfo;
7953                 auto bundleName = want->GetElement().GetBundleName();
7954                 int32_t userId = GetUserId();
7955                 bool ret = IN_PROCESS_CALL(
7956                     bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo,
7957                     userId));
7958                 if (!ret) {
7959                     TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery Failed to get bundle info, not do recovery!");
7960                     return;
7961                 }
7962                 bool isRestartPage = false;
7963                 auto abilityName = want->GetElement().GetAbilityName();
7964                 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
7965                     if ((abilityName.compare(it->name) == 0) && it->type == AppExecFwk::AbilityType::PAGE) {
7966                         isRestartPage = true;
7967                         break;
7968                     }
7969                 }
7970                 if (!isRestartPage) {
7971                     TAG_LOGI(AAFwkTag::ABILITYMGR, "AppRecovery the target ability type is not PAGE!");
7972                     ReportAppRecoverResult(record->GetUid(), appInfo, abilityName, "FAIL_TARGET_ABILITY_NOT_PAGE");
7973                     return;
7974                 }
7975             }
7976         }
7977 
7978         appRecoveryHistory_[record->GetUid()] = now;
7979         curWant = (want == nullptr) ? record->GetWant() : *want;
7980         curWant.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
7981 
7982         ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "SUCCESS");
7983     }
7984     RestartApp(curWant, true);
7985 }
7986 
GetRemoteMissionSnapshotInfo(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot)7987 int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId,
7988     MissionSnapshot& missionSnapshot)
7989 {
7990     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7991     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetRemoteMissionSnapshotInfo begin");
7992     std::unique_ptr<MissionSnapshot> missionSnapshotPtr = std::make_unique<MissionSnapshot>();
7993     DistributedClient dmsClient;
7994     int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr);
7995     if (result != ERR_OK) {
7996         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetRemoteMissionSnapshotInfo failed, result = %{public}d", result);
7997         return result;
7998     }
7999     missionSnapshot = *missionSnapshotPtr;
8000     return ERR_OK;
8001 }
8002 
StartSwitchUserDialog()8003 void AbilityManagerService::StartSwitchUserDialog()
8004 {
8005     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog extension ability come");
8006     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8007         TAG_LOGE(AAFwkTag::ABILITYMGR, "Scene board enabled, dialog not show.");
8008         return;
8009     }
8010 
8011     if (userController_ == nullptr) {
8012         TAG_LOGE(AAFwkTag::ABILITYMGR, "User Controller instance is nullptr.");
8013         return;
8014     }
8015 
8016     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
8017     if (sysDialog == nullptr) {
8018         TAG_LOGE(AAFwkTag::ABILITYMGR, "System dialog scheduler instance is nullptr.");
8019         return;
8020     }
8021 
8022     Want dialogWant = sysDialog->GetSwitchUserDialogWant();
8023     StartSwitchUserDialogInner(dialogWant, userController_->GetFreezingNewUserId());
8024 }
8025 
8026 
StartSwitchUserDialogInner(const Want & want,int32_t lastUserId)8027 void AbilityManagerService::StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)
8028 {
8029     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog inner come");
8030     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
8031     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
8032     AbilityRequest abilityRequest;
8033     auto result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
8034     if (result != ERR_OK) {
8035         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
8036         eventInfo.errCode = result;
8037         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8038         return;
8039     }
8040 
8041     auto abilityInfo = abilityRequest.abilityInfo;
8042     auto startUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
8043     result = CheckOptExtensionAbility(want, abilityRequest, startUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
8044     if (result != ERR_OK) {
8045         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check extensionAbility type error.");
8046         eventInfo.errCode = result;
8047         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8048         return;
8049     }
8050 
8051     auto connectManager = GetConnectManagerByUserId(startUserId);
8052     if (connectManager == nullptr) {
8053         CHECK_POINTER(subManagersHelper_);
8054         subManagersHelper_->InitConnectManager(startUserId, false);
8055         connectManager = GetConnectManagerByUserId(startUserId);
8056         if (connectManager == nullptr) {
8057             TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectManager is nullptr. userId=%{public}d", startUserId);
8058             eventInfo.errCode = ERR_INVALID_VALUE;
8059             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8060             return;
8061         }
8062     }
8063 
8064     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
8065         abilityRequest.abilityInfo.extensionAbilityType);
8066     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
8067     if (eventInfo.errCode != ERR_OK) {
8068         TAG_LOGE(AAFwkTag::ABILITYMGR, "EventInfo errCode is %{public}d", eventInfo.errCode);
8069         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8070     }
8071 }
8072 
StartFreezingScreen()8073 void AbilityManagerService::StartFreezingScreen()
8074 {
8075     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8076 #ifdef SUPPORT_GRAPHICS
8077     StartSwitchUserDialog();
8078     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8079     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Freeze(displayIds));
8080 #endif
8081 }
8082 
StopFreezingScreen()8083 void AbilityManagerService::StopFreezingScreen()
8084 {
8085     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8086 #ifdef SUPPORT_GRAPHICS
8087     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8088     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Unfreeze(displayIds));
8089     StopSwitchUserDialog();
8090 #endif
8091 }
8092 
UserStarted(int32_t userId)8093 void AbilityManagerService::UserStarted(int32_t userId)
8094 {
8095     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8096     CHECK_POINTER(subManagersHelper_);
8097     subManagersHelper_->InitSubManagers(userId, false);
8098 }
8099 
SwitchToUser(int32_t oldUserId,int32_t userId,sptr<IUserCallback> callback)8100 void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId, sptr<IUserCallback> callback)
8101 {
8102     TAG_LOGI(AAFwkTag::ABILITYMGR,
8103         "%{public}s, oldUserId:%{public}d, newUserId:%{public}d", __func__, oldUserId, userId);
8104     SwitchManagers(userId);
8105     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8106         PauseOldUser(oldUserId);
8107         ConnectBmsService();
8108         StartUserApps();
8109     }
8110     callback->OnStartUserDone(userId, ERR_OK);
8111     bool isBoot = oldUserId == U0_USER_ID ? true : false;
8112     StartHighestPriorityAbility(userId, isBoot);
8113      if (taskHandler_) {
8114         taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() {
8115             TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps userId:%{public}d", userId);
8116             abilityMs->StartResidentApps(userId);
8117             });
8118     }
8119     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
8120         AmsConfigurationParameter::GetInstance().MultiUserType() != 0) {
8121         TAG_LOGI(AAFwkTag::ABILITYMGR, "no need to terminate old scb.");
8122         return;
8123     }
8124     PauseOldConnectManager(oldUserId);
8125 }
8126 
SwitchManagers(int32_t userId,bool switchUser)8127 void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser)
8128 {
8129     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId);
8130     CHECK_POINTER(subManagersHelper_);
8131     subManagersHelper_->InitSubManagers(userId, switchUser);
8132     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----end", __func__, userId);
8133 }
8134 
PauseOldUser(int32_t userId)8135 void AbilityManagerService::PauseOldUser(int32_t userId)
8136 {
8137     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId);
8138     PauseOldMissionListManager(userId);
8139     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----end", __func__, userId);
8140 }
8141 
PauseOldMissionListManager(int32_t userId)8142 void AbilityManagerService::PauseOldMissionListManager(int32_t userId)
8143 {
8144     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId);
8145     auto manager = GetMissionListManagerByUserId(userId);
8146     CHECK_POINTER(manager);
8147     manager->PauseManager();
8148     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId);
8149 }
8150 
PauseOldConnectManager(int32_t userId)8151 void AbilityManagerService::PauseOldConnectManager(int32_t userId)
8152 {
8153     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----begin", __func__, userId);
8154     if (userId == U0_USER_ID) {
8155         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, u0 not stop, id:%{public}d-----nullptr", __func__, userId);
8156         return;
8157     }
8158 
8159     auto manager = GetConnectManagerByUserId(userId);
8160     CHECK_POINTER(manager);
8161     manager->PauseExtensions();
8162     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----end", __func__, userId);
8163 }
8164 
StartUserApps()8165 void AbilityManagerService::StartUserApps()
8166 {
8167     auto missionListManager = GetCurrentMissionListManager();
8168     if (missionListManager && missionListManager->IsStarted()) {
8169         TAG_LOGI(AAFwkTag::ABILITYMGR, "missionListManager ResumeManager");
8170         missionListManager->ResumeManager();
8171     }
8172 }
8173 
GetValidUserId(const int32_t userId)8174 int32_t AbilityManagerService::GetValidUserId(const int32_t userId)
8175 {
8176     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId = %{public}d.", userId);
8177     int32_t validUserId = userId;
8178 
8179     if (DEFAULT_INVAL_VALUE == userId) {
8180         validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
8181         TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId = %{public}d, CallingUid = %{public}d.", validUserId,
8182             IPCSkeleton::GetCallingUid());
8183         if (validUserId == U0_USER_ID) {
8184             validUserId = GetUserId();
8185         }
8186     }
8187     return validUserId;
8188 }
8189 
SetAbilityController(const sptr<IAbilityController> & abilityController,bool imAStabilityTest)8190 int AbilityManagerService::SetAbilityController(const sptr<IAbilityController> &abilityController,
8191     bool imAStabilityTest)
8192 {
8193     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest);
8194     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyControllerPerm();
8195     if (!isPerm) {
8196         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
8197         return CHECK_PERMISSION_FAILED;
8198     }
8199 
8200     std::lock_guard<ffrt::mutex> guard(globalLock_);
8201     abilityController_ = abilityController;
8202     controllerIsAStabilityTest_ = imAStabilityTest;
8203     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, end", __func__);
8204     return ERR_OK;
8205 }
8206 
IsRunningInStabilityTest()8207 bool AbilityManagerService::IsRunningInStabilityTest()
8208 {
8209     std::lock_guard<ffrt::mutex> guard(globalLock_);
8210     bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_;
8211     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret);
8212     return ret;
8213 }
8214 
IsAbilityControllerStart(const Want & want,const std::string & bundleName)8215 bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName)
8216 {
8217     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8218     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8219     if (abilityController_ == nullptr) {
8220         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8221         return true;
8222     }
8223 
8224     if (controllerIsAStabilityTest_) {
8225         bool isStart = abilityController_->AllowAbilityStart(want, bundleName);
8226         if (!isStart) {
8227             TAG_LOGI(AAFwkTag::ABILITYMGR,
8228                 "Not finishing start ability because controller starting: %{public}s", bundleName.c_str());
8229             return false;
8230         }
8231     }
8232     return true;
8233 }
8234 
IsAbilityControllerForeground(const std::string & bundleName)8235 bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName)
8236 {
8237     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8238     if (abilityController_ == nullptr) {
8239         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8240         return true;
8241     }
8242 
8243     if (controllerIsAStabilityTest_) {
8244         bool isResume = abilityController_->AllowAbilityBackground(bundleName);
8245         if (!isResume) {
8246             TAG_LOGI(AAFwkTag::ABILITYMGR,
8247                 "Not finishing terminate ability because controller resuming: %{public}s", bundleName.c_str());
8248             return false;
8249         }
8250     }
8251     return true;
8252 }
8253 
StartUserTest(const Want & want,const sptr<IRemoteObject> & observer)8254 int AbilityManagerService::StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)
8255 {
8256     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8257     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
8258         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
8259         return ERR_NOT_DEVELOPER_MODE;
8260     }
8261 
8262     if (observer == nullptr) {
8263         TAG_LOGE(AAFwkTag::ABILITYMGR, "observer is nullptr");
8264         return ERR_INVALID_VALUE;
8265     }
8266 
8267     std::string bundleName = want.GetStringParam("-b");
8268     if (bundleName.empty()) {
8269         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name");
8270         return ERR_INVALID_VALUE;
8271     }
8272 
8273     auto checkResult = AbilityUtil::CheckInstanceKey(want);
8274     if (checkResult != ERR_OK) {
8275         return checkResult;
8276     }
8277     int32_t appIndex = 0;
8278     if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex) || appIndex != 0) {
8279         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support app clone");
8280         return ERR_NOT_SUPPORT_APP_CLONE;
8281     }
8282 
8283     auto bms = GetBundleManager();
8284     CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL);
8285     AppExecFwk::BundleInfo bundleInfo;
8286     if (!IN_PROCESS_CALL(
8287         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID))) {
8288         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info by U0_USER_ID %{public}d.", U0_USER_ID);
8289         int32_t userId = GetUserId();
8290         if (!IN_PROCESS_CALL(
8291             bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
8292             TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info by userId %{public}d.", userId);
8293             return GET_BUNDLE_INFO_FAILED;
8294         }
8295     }
8296 
8297     return DelayedSingleton<AppScheduler>::GetInstance()->StartUserTest(want, observer, bundleInfo, GetUserId());
8298 }
8299 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName)8300 int AbilityManagerService::FinishUserTest(
8301     const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
8302 {
8303     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8304     if (bundleName.empty()) {
8305         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name.");
8306         return ERR_INVALID_VALUE;
8307     }
8308 
8309     return DelayedSingleton<AppScheduler>::GetInstance()->FinishUserTest(msg, resultCode, bundleName);
8310 }
8311 
GetTopAbility(sptr<IRemoteObject> & token)8312 int AbilityManagerService::GetTopAbility(sptr<IRemoteObject> &token)
8313 {
8314     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8315     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8316     if (!isSaCall) {
8317         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
8318         return CHECK_PERMISSION_FAILED;
8319     }
8320 #ifdef SUPPORT_GRAPHICS
8321     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8322         Rosen::FocusChangeInfo focusChangeInfo;
8323         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
8324         token = focusChangeInfo.abilityToken_;
8325     } else {
8326         if (!wmsHandler_) {
8327             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
8328             return ERR_INVALID_VALUE;
8329         }
8330         wmsHandler_->GetFocusWindow(token);
8331     }
8332 
8333     if (!token) {
8334         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
8335         return ERR_INVALID_VALUE;
8336     }
8337 #endif
8338     return ERR_OK;
8339 }
8340 
DelegatorDoAbilityForeground(const sptr<IRemoteObject> & token)8341 int AbilityManagerService::DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)
8342 {
8343     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8344     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8345     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8346     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8347     int32_t callerPid = IPCSkeleton::GetCallingPid();
8348     int32_t appPid = abilityRecord->GetPid();
8349     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8350     if (callerPid != appPid) {
8351         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not the application itself");
8352         return ERR_INVALID_VALUE;
8353     }
8354     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8355         auto sessionId = GetMissionIdByAbilityTokenInner(token);
8356         if (!sessionId) {
8357             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid session id.");
8358             return ERR_INVALID_VALUE;
8359         }
8360         auto want = abilityRecord->GetWant();
8361         if (!IsAbilityControllerStart(want, want.GetBundle())) {
8362             TAG_LOGE(AAFwkTag::ABILITYMGR,
8363                 "SceneBoard IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
8364             return ERR_WOULD_BLOCK;
8365         }
8366         return ERR_OK;
8367     }
8368     auto missionId = GetMissionIdByAbilityToken(token);
8369     if (missionId < 0) {
8370         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid mission id.");
8371         return ERR_INVALID_VALUE;
8372     }
8373     return DelegatorMoveMissionToFront(missionId);
8374 }
8375 
DelegatorDoAbilityBackground(const sptr<IRemoteObject> & token)8376 int AbilityManagerService::DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)
8377 {
8378     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8379     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8380     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8381     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8382     int32_t appPid = abilityRecord->GetPid();
8383     int32_t callerPid = IPCSkeleton::GetCallingPid();
8384     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8385     if (callerPid != appPid) {
8386         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not the application itself");
8387         return ERR_INVALID_VALUE;
8388     }
8389     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8390         return ERR_OK;
8391     }
8392     return MinimizeAbility(token, true);
8393 }
8394 
DoAbilityForeground(const sptr<IRemoteObject> & token,uint32_t flag)8395 int AbilityManagerService::DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)
8396 {
8397     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityForeground, sceneFlag:%{public}u", flag);
8398     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8399     if (!VerificationToken(token) && !VerificationAllToken(token)) {
8400         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s token error.", __func__);
8401         return ERR_INVALID_VALUE;
8402     }
8403 
8404     std::lock_guard<ffrt::mutex> guard(globalLock_);
8405     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8406     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8407     if (!JudgeSelfCalled(abilityRecord)) {
8408         return CHECK_PERMISSION_FAILED;
8409     }
8410 
8411     auto type = abilityRecord->GetAbilityInfo().type;
8412     if (type != AppExecFwk::AbilityType::PAGE) {
8413         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except page ability.");
8414         return ERR_WRONG_INTERFACE_CALL;
8415     }
8416 
8417     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
8418         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerForeground false.");
8419         return ERR_WOULD_BLOCK;
8420     }
8421 
8422     auto missionListManager = GetCurrentMissionListManager();
8423     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8424     return missionListManager->DoAbilityForeground(abilityRecord, flag);
8425 }
8426 
DoAbilityBackground(const sptr<IRemoteObject> & token,uint32_t flag)8427 int AbilityManagerService::DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)
8428 {
8429     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityBackground, sceneFlag:%{public}u", flag);
8430     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8431 
8432     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8433     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8434 
8435     abilityRecord->lifeCycleStateInfo_.sceneFlag = flag;
8436     int ret = MinimizeAbility(token);
8437     abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL;
8438     return ret;
8439 }
8440 
DelegatorMoveMissionToFront(int32_t missionId)8441 int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId)
8442 {
8443     TAG_LOGI(AAFwkTag::ABILITYMGR, "enter missionId : %{public}d", missionId);
8444     auto missionListManager = GetCurrentMissionListManager();
8445     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8446 
8447     if (!IsAbilityControllerStartById(missionId)) {
8448         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
8449         return ERR_WOULD_BLOCK;
8450     }
8451 
8452     return missionListManager->MoveMissionToFront(missionId);
8453 }
8454 
UpdateCallerInfo(Want & want,const sptr<IRemoteObject> & callerToken)8455 void AbilityManagerService::UpdateCallerInfo(Want& want, const sptr<IRemoteObject> &callerToken)
8456 {
8457     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8458     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
8459         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8460         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8461         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8462     }
8463     int32_t tokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
8464     int32_t callerUid = IPCSkeleton::GetCallingUid();
8465     int32_t callerPid = IPCSkeleton::GetCallingPid();
8466     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8467     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8468     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8469     want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
8470     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8471     want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
8472     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8473     want.RemoveParam(IS_SHELL_CALL);
8474     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8475     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8476     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8477 
8478     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8479     if (!abilityRecord) {
8480         std::string bundleName;
8481         auto bundleMgr = GetBundleManager();
8482         if (bundleMgr != nullptr) {
8483             IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, bundleName));
8484         }
8485         if (bundleName == "") {
8486             std::string nativeName;
8487             Security::AccessToken::NativeTokenInfo nativeTokenInfo;
8488             int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
8489             if (result == ERR_OK) {
8490                 nativeName = "_" + nativeTokenInfo.processName;
8491             }
8492             want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8493             want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME, nativeName);
8494         }
8495         want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, bundleName);
8496         want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, std::string(""));
8497         want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, 0);
8498         return;
8499     }
8500     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8501     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8502     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8503     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8504     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, abilityRecord->GetAppIndex());
8505     UpdateSignatureInfo(callerBundleName, want);
8506 }
8507 
UpdateCallerInfoFromToken(Want & want,const sptr<IRemoteObject> & token)8508 void AbilityManagerService::UpdateCallerInfoFromToken(Want& want, const sptr<IRemoteObject> &token)
8509 {
8510     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8511     if (!abilityRecord) {
8512         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller abilityRecord is null.");
8513         return;
8514     }
8515 
8516     int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
8517     int32_t callerUid = abilityRecord->GetUid();
8518     int32_t callerPid = abilityRecord->GetPid();
8519     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8520     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8521     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8522     want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
8523     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8524     want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
8525     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8526     want.RemoveParam(IS_SHELL_CALL);
8527 
8528     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8529     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8530     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8531     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8532     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8533     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8534     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8535     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, abilityRecord->GetAppIndex());
8536     UpdateSignatureInfo(callerBundleName, want);
8537 }
8538 
UpdateSignatureInfo(std::string bundleName,Want & want,bool isRemote)8539 void AbilityManagerService::UpdateSignatureInfo(std::string bundleName, Want& want, bool isRemote)
8540 {
8541     auto bundleMgr = GetBundleManager();
8542     if (bundleMgr != nullptr) {
8543         AppExecFwk::SignatureInfo signatureInfo;
8544         IN_PROCESS_CALL(bundleMgr->GetSignatureInfoByBundleName(bundleName, signatureInfo));
8545         std::string callerAppId = isRemote ? DMS_CALLER_APP_ID : Want::PARAM_RESV_CALLER_APP_ID;
8546         std::string callerAppIdentifier = isRemote ? DMS_CALLER_APP_IDENTIFIER : Want::PARAM_RESV_CALLER_APP_IDENTIFIER;
8547         want.RemoveParam(callerAppId);
8548         want.SetParam(callerAppId, signatureInfo.appId);
8549         want.RemoveParam(callerAppIdentifier);
8550         want.SetParam(callerAppIdentifier, signatureInfo.appIdentifier);
8551     }
8552 }
8553 
UpdateDmsCallerInfo(Want & want,const sptr<IRemoteObject> & callerToken)8554 void AbilityManagerService::UpdateDmsCallerInfo(Want& want, const sptr<IRemoteObject> &callerToken)
8555 {
8556     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8557     int32_t tokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
8558     int32_t callerUid = IPCSkeleton::GetCallingUid();
8559 
8560     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8561     if (!abilityRecord) {
8562         std::string bundleName;
8563         auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
8564         if (bundleMgr != nullptr) {
8565             IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, bundleName));
8566         }
8567         if (bundleName == "") {
8568             std::string nativeName;
8569             Security::AccessToken::NativeTokenInfo nativeTokenInfo;
8570             int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
8571             if (result == ERR_OK) {
8572                 nativeName = "_" + nativeTokenInfo.processName;
8573             }
8574             want.RemoveParam(DMS_CALLER_NATIVE_NAME);
8575             want.SetParam(DMS_CALLER_NATIVE_NAME, nativeName);
8576         }
8577         want.RemoveParam(DMS_CALLER_BUNDLE_NAME);
8578         want.SetParam(DMS_CALLER_BUNDLE_NAME, bundleName);
8579         want.RemoveParam(DMS_CALLER_ABILITY_NAME);
8580         want.SetParam(DMS_CALLER_ABILITY_NAME, std::string(""));
8581         return;
8582     }
8583     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8584     want.RemoveParam(DMS_CALLER_BUNDLE_NAME);
8585     want.SetParam(DMS_CALLER_BUNDLE_NAME, callerBundleName);
8586     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8587     want.RemoveParam(DMS_CALLER_ABILITY_NAME);
8588     want.SetParam(DMS_CALLER_ABILITY_NAME, callerAbilityName);
8589     UpdateSignatureInfo(callerBundleName, want, true);
8590 }
8591 
JudgeMultiUserConcurrency(const int32_t userId)8592 bool AbilityManagerService::JudgeMultiUserConcurrency(const int32_t userId)
8593 {
8594     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8595     if (userId == U0_USER_ID) {
8596         TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, userId is 0.", __func__);
8597         return true;
8598     }
8599 
8600     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, current userId : %{public}d", userId, GetUserId());
8601 
8602     // Only non-concurrent mode is supported
8603     bool concurrencyMode = CONCURRENCY_MODE_FALSE;
8604     if (!concurrencyMode) {
8605         return (userId == GetUserId());
8606     }
8607 
8608     return true;
8609 }
8610 
8611 #ifdef ABILITY_COMMAND_FOR_TEST
ForceTimeoutForTest(const std::string & abilityName,const std::string & state)8612 int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, const std::string &state)
8613 {
8614     if (abilityName.empty()) {
8615         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityName is empty.");
8616         return INVALID_DATA;
8617     }
8618     if (abilityName == "clean") {
8619         timeoutMap_.clear();
8620         return ERR_OK;
8621     }
8622     if (state != AbilityRecord::ConvertAbilityState(AbilityState::INITIAL) &&
8623         state != AbilityRecord::ConvertAbilityState(AbilityState::INACTIVE) &&
8624         state != AbilityRecord::ConvertAbilityState(AbilityState::FOREGROUND) &&
8625         state != AbilityRecord::ConvertAbilityState(AbilityState::BACKGROUND) &&
8626         state != AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) &&
8627         state != std::string("COMMAND")) {
8628         TAG_LOGE(AAFwkTag::ABILITYMGR, "lifecycle state is invalid.");
8629         return INVALID_DATA;
8630     }
8631     timeoutMap_.insert(std::make_pair(state, abilityName));
8632     return ERR_OK;
8633 }
8634 #endif
8635 
UpdateAsCallerSourceInfo(Want & want,sptr<IRemoteObject> asCallerSourceToken,sptr<IRemoteObject> callerToken)8636 void AbilityManagerService::UpdateAsCallerSourceInfo(Want& want, sptr<IRemoteObject> asCallerSourceToken,
8637     sptr<IRemoteObject> callerToken)
8638 {
8639 #ifdef SUPPORT_SCREEN
8640     if (UpdateAsCallerInfoFromDialog(want)) {
8641         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from dialog.");
8642         return;
8643     }
8644 #endif // SUPPORT_SCREEN
8645     if (asCallerSourceToken != nullptr) {
8646         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from token.");
8647         UpdateAsCallerInfoFromToken(want, asCallerSourceToken);
8648     } else if (callerToken != nullptr) {
8649         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from callerRecord.");
8650         UpdateAsCallerInfoFromCallerRecord(want, callerToken);
8651     }
8652 }
8653 
UpdateAsCallerInfoFromToken(Want & want,sptr<IRemoteObject> asCallerSourceToken)8654 void AbilityManagerService::UpdateAsCallerInfoFromToken(Want& want, sptr<IRemoteObject> asCallerSourceToken)
8655 {
8656     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(asCallerSourceToken)) {
8657         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8658         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8659         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8660     }
8661     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8662     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8663     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8664     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8665     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8666     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8667     want.RemoveParam(IS_SHELL_CALL);
8668 
8669     auto abilityRecord = Token::GetAbilityRecordByToken(asCallerSourceToken);
8670     if (abilityRecord == nullptr) {
8671         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to update as caller info from token");
8672         return;
8673     }
8674     AppExecFwk::RunningProcessInfo processInfo = {};
8675     DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByToken(asCallerSourceToken, processInfo);
8676     int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
8677     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8678     want.SetParam(Want::PARAM_RESV_CALLER_UID, processInfo.uid_);
8679     want.SetParam(Want::PARAM_RESV_CALLER_PID, processInfo.pid_);
8680 
8681     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8682     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8683     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8684     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8685     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8686     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, abilityRecord->GetAppIndex());
8687     UpdateSignatureInfo(callerBundleName, want);
8688 }
8689 
UpdateAsCallerInfoFromCallerRecord(Want & want,sptr<IRemoteObject> callerToken)8690 void AbilityManagerService::UpdateAsCallerInfoFromCallerRecord(Want& want, sptr<IRemoteObject> callerToken)
8691 {
8692     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
8693         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8694         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8695         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8696     }
8697     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8698     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8699     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8700     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8701     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8702     want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8703     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8704     want.RemoveParam(IS_SHELL_CALL);
8705     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
8706     CHECK_POINTER(callerRecord);
8707     auto sourceInfo = callerRecord->GetCallerInfo();
8708     CHECK_POINTER(sourceInfo);
8709     std::string callerBundleName = sourceInfo->callerBundleName;
8710     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, sourceInfo->callerTokenId);
8711     want.SetParam(Want::PARAM_RESV_CALLER_UID, sourceInfo->callerUid);
8712     want.SetParam(Want::PARAM_RESV_CALLER_PID, sourceInfo->callerPid);
8713     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8714     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, sourceInfo->callerAbilityName);
8715     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8716     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, sourceInfo->callerAppCloneIndex);
8717     if (callerBundleName == "") {
8718         want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME, sourceInfo->callerNativeName);
8719         return;
8720     }
8721     UpdateSignatureInfo(callerBundleName, want);
8722 }
8723 
UpdateAsCallerInfoFromDialog(Want & want)8724 bool AbilityManagerService::UpdateAsCallerInfoFromDialog(Want& want)
8725 {
8726     std::string dialogSessionId = want.GetStringParam("dialogSessionId");
8727     auto dialogCallerInfo = DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId);
8728     if (dialogCallerInfo == nullptr) {
8729         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed to get dialog caller info.");
8730         return false;
8731     }
8732     Want dialogCallerWant = dialogCallerInfo->targetWant;
8733     int32_t tokenId = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0);
8734     int32_t uid = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_UID, 0);
8735     int32_t pid = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_PID, 0);
8736     std::string callerBundleName = dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8737     std::string callerAbilityName = dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8738     int32_t callerAppCloneIndex = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, 0);
8739     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8740     want.SetParam(Want::PARAM_RESV_CALLER_UID, uid);
8741     want.SetParam(Want::PARAM_RESV_CALLER_PID, pid);
8742     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8743     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8744     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, callerAppCloneIndex);
8745     want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8746     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8747     want.RemoveParam(IS_SHELL_CALL);
8748     if (callerBundleName == "") {
8749         want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME,
8750             dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME));
8751         return true;
8752     }
8753     UpdateSignatureInfo(callerBundleName, want);
8754     return true;
8755 }
8756 
UpdateBackToCallerFlag(const sptr<IRemoteObject> & callerToken,Want & want,int32_t requestCode,bool backFlag)8757 void AbilityManagerService::UpdateBackToCallerFlag(const sptr<IRemoteObject> &callerToken, Want &want,
8758     int32_t requestCode, bool backFlag)
8759 {
8760     if (want.HasParameter(CALLER_REQUEST_CODE)) {
8761         want.RemoveParam(CALLER_REQUEST_CODE);
8762     }
8763     auto callerAbilityRecord = Token::GetAbilityRecordByToken(callerToken);
8764     if (requestCode > 0 && callerAbilityRecord != nullptr) {
8765         // default return true on oh
8766         if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8767             backFlag = AmsConfigurationParameter::GetInstance().IsSupportBackToCaller();
8768         }
8769         auto fullRequestCode = StartupUtil::GenerateFullRequestCode(
8770             callerAbilityRecord->GetPid(), backFlag, requestCode);
8771         want.SetParam(CALLER_REQUEST_CODE, std::to_string(fullRequestCode));
8772         TAG_LOGI(AAFwkTag::ABILITYMGR,
8773             "pid: %{public}d, backFlag:%{private}d, requestCode: %{private}d, fullRequestCode: %{private}s",
8774             callerAbilityRecord->GetPid(), backFlag, requestCode, std::to_string(fullRequestCode).c_str());
8775     }
8776 }
8777 
CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo & abilityInfo,uint32_t tokenId)8778 int AbilityManagerService::CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo,
8779     uint32_t tokenId)
8780 {
8781     if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId,
8782         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) {
8783         return AppExecFwk::Constants::PERMISSION_GRANTED;
8784     }
8785 
8786     for (auto permission : abilityInfo.permissions) {
8787         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8788             AppExecFwk::Constants::PERMISSION_GRANTED) {
8789             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Ability permission: %{public}s",
8790                 permission.c_str());
8791             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8792         }
8793     }
8794 
8795     return AppExecFwk::Constants::PERMISSION_GRANTED;
8796 }
8797 
CheckOneSkillPermission(const AppExecFwk::Skill & skill,uint32_t tokenId)8798 bool AbilityManagerService::CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId)
8799 {
8800     for (auto permission : skill.permissions) {
8801         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8802             AppExecFwk::Constants::PERMISSION_GRANTED) {
8803             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Skill permission: %{public}s",
8804                 permission.c_str());
8805             return false;
8806         }
8807     }
8808 
8809     return true;
8810 }
8811 
CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest & abilityRequest,uint32_t tokenId)8812 int AbilityManagerService::CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest,
8813     uint32_t tokenId)
8814 {
8815     auto abilityInfo = abilityRequest.abilityInfo;
8816     auto resultAbilityPermission = CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8817     if (resultAbilityPermission != AppExecFwk::Constants::PERMISSION_GRANTED) {
8818         return resultAbilityPermission;
8819     }
8820 
8821     if (abilityInfo.skills.empty()) {
8822         return AppExecFwk::Constants::PERMISSION_GRANTED;
8823     }
8824     int32_t result = AppExecFwk::Constants::PERMISSION_GRANTED;
8825     for (auto skill : abilityInfo.skills) {
8826         if (skill.Match(abilityRequest.want)) {
8827             if (CheckOneSkillPermission(skill, tokenId)) {
8828                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8829             } else {
8830                 result = AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8831             }
8832         }
8833     }
8834     return result;
8835 }
8836 
CheckStaticCfgPermission(const AppExecFwk::AbilityRequest & abilityRequest,bool isStartAsCaller,uint32_t callerTokenId,bool isData,bool isSaCall,bool isImplicit)8837 int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest,
8838     bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit)
8839 {
8840     auto abilityInfo = abilityRequest.abilityInfo;
8841     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8842     if (AppUtils::GetInstance().IsSupportAncoApp() &&
8843         StartAbilityUtils::IsCallFromAncoShellOrBroker(abilityRequest.callerToken)) {
8844         TAG_LOGD(AAFwkTag::ABILITYMGR,
8845             "Check static permission, name is %{public}s.", abilityInfo.name.c_str());
8846         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
8847         if (collaborator == nullptr) {
8848             TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator is nullptr.");
8849             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8850         }
8851         int result = collaborator->CheckStaticCfgPermission(abilityRequest.want, isImplicit);
8852         if (result != ERR_OK) {
8853             TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker.");
8854             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8855         }
8856     }
8857     if (!isData) {
8858         isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8859     }
8860     if (isSaCall) {
8861         // do not need check static config permission when start ability by SA
8862         return AppExecFwk::Constants::PERMISSION_GRANTED;
8863     }
8864 
8865     uint32_t tokenId;
8866     if (isStartAsCaller) {
8867         tokenId = callerTokenId;
8868     } else {
8869         tokenId = IPCSkeleton::GetCallingTokenID();
8870     }
8871 
8872     if (abilityInfo.applicationInfo.accessTokenId == tokenId) {
8873         return ERR_OK;
8874     }
8875 
8876     if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
8877         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) ||
8878         (abilityInfo.type == AppExecFwk::AbilityType::DATA)) {
8879         // just need check the read permission and write permission of extension ability or data ability
8880         if (!abilityInfo.readPermission.empty()) {
8881             int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission, false);
8882             if (checkReadPermission == ERR_OK) {
8883                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8884             }
8885             TAG_LOGW(AAFwkTag::ABILITYMGR,
8886                 "verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str());
8887         }
8888         if (!abilityInfo.writePermission.empty()) {
8889             int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission, false);
8890             if (checkWritePermission == ERR_OK) {
8891                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8892             }
8893             TAG_LOGW(AAFwkTag::ABILITYMGR,
8894                 "verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str());
8895         }
8896 
8897         if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) {
8898             // 'readPermission' and 'writePermission' take precedence over 'permission'
8899             // when 'readPermission' or 'writePermission' is not empty, no need check 'permission'
8900             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8901         }
8902     }
8903 
8904     if (!isImplicit) {
8905         return CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8906     }
8907     return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId);
8908 }
8909 
CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,const Want & want,const AbilityRequest & abilityRequest)8910 int AbilityManagerService::CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,
8911     const Want &want, const AbilityRequest &abilityRequest)
8912 {
8913     AppExecFwk::ExtensionAbilityType targetExtType = abilityRequest.abilityInfo.extensionAbilityType;
8914     if (targetExtType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
8915         return ERR_OK;
8916     }
8917     if (!want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
8918         TAG_LOGE(AAFwkTag::ABILITYMGR, "need UISERVICEHOSTPROXY_KEY to connect UI_SERVICE");
8919         return ERR_WRONG_INTERFACE_CALL;
8920     }
8921     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
8922         TAG_LOGE(AAFwkTag::ABILITYMGR, "interface not support connect UI_SERVICE");
8923         return ERR_WRONG_INTERFACE_CALL;
8924     }
8925     if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
8926         TAG_LOGE(AAFwkTag::ABILITYMGR, "ABILITYMS_ENABLE_UISERVICE false");
8927         return ERR_CAPABILITY_NOT_SUPPORT;
8928     }
8929 
8930     return ERR_OK;
8931 }
8932 
IsNeedTimeoutForTest(const std::string & abilityName,const std::string & state) const8933 bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const
8934 {
8935     for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) {
8936         if (iter->first == state && iter->second == abilityName) {
8937             return true;
8938         }
8939     }
8940     return false;
8941 }
8942 
GetValidDataAbilityUri(const std::string & abilityInfoUri,std::string & adjustUri)8943 bool AbilityManagerService::GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)
8944 {
8945     // note: do not use abilityInfo.uri directly, need check uri first.
8946     size_t firstSeparator = abilityInfoUri.find_first_of('/');
8947     size_t lastSeparator = abilityInfoUri.find_last_of('/');
8948     if (lastSeparator - firstSeparator != 1) {
8949         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability info uri error, uri: %{public}s", abilityInfoUri.c_str());
8950         return false;
8951     }
8952 
8953     adjustUri = abilityInfoUri;
8954     adjustUri.insert(lastSeparator, "/");
8955     return true;
8956 }
8957 
GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> & abilityInfos,const std::string & mainAbility,std::string & uri)8958 bool AbilityManagerService::GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos,
8959     const std::string &mainAbility, std::string &uri)
8960 {
8961     if (abilityInfos.empty() || mainAbility.empty()) {
8962         TAG_LOGE(AAFwkTag::ABILITYMGR,
8963             "abilityInfos or mainAbility is empty. mainAbility: %{public}s", mainAbility.c_str());
8964         return false;
8965     }
8966 
8967     std::string dataAbilityUri;
8968     for (auto abilityInfo : abilityInfos) {
8969         if (abilityInfo.type == AppExecFwk::AbilityType::DATA &&
8970             abilityInfo.name == mainAbility) {
8971             dataAbilityUri = abilityInfo.uri;
8972             TAG_LOGI(AAFwkTag::ABILITYMGR, "get data ability uri: %{public}s", dataAbilityUri.c_str());
8973             break;
8974         }
8975     }
8976 
8977     return GetValidDataAbilityUri(dataAbilityUri, uri);
8978 }
8979 
GetAbilityRunningInfo(std::vector<AbilityRunningInfo> & info,std::shared_ptr<AbilityRecord> & abilityRecord)8980 void AbilityManagerService::GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info,
8981     std::shared_ptr<AbilityRecord> &abilityRecord)
8982 {
8983     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8984     AbilityRunningInfo runningInfo;
8985     AppExecFwk::RunningProcessInfo processInfo;
8986 
8987     runningInfo.ability = abilityRecord->GetElementName();
8988     runningInfo.startTime = abilityRecord->GetStartTime();
8989     runningInfo.abilityState = static_cast<int>(abilityRecord->GetAbilityState());
8990 
8991     DelayedSingleton<AppScheduler>::GetInstance()->
8992         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
8993     runningInfo.pid = processInfo.pid_;
8994     runningInfo.uid = processInfo.uid_;
8995     runningInfo.processName = processInfo.processName_;
8996     runningInfo.appCloneIndex = processInfo.appCloneIndex;
8997     info.emplace_back(runningInfo);
8998 }
8999 
VerifyAccountPermission(int32_t userId)9000 int AbilityManagerService::VerifyAccountPermission(int32_t userId)
9001 {
9002     if ((userId < 0) || (userController_ && (userController_->GetCurrentUserId() == userId))) {
9003         return ERR_OK;
9004     }
9005     return AAFwk::PermissionVerification::GetInstance()->VerifyAccountPermission();
9006 }
9007 
FreeInstallAbilityFromRemote(const Want & want,const sptr<IRemoteObject> & callback,int32_t userId,int requestCode)9008 int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
9009     int32_t userId, int requestCode)
9010 {
9011     auto callingUid = IPCSkeleton::GetCallingUid();
9012     if (callingUid != DMS_UID) {
9013         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for DMS");
9014         return CHECK_PERMISSION_FAILED;
9015     }
9016     int32_t validUserId = GetValidUserId(userId);
9017     if (freeInstallManager_ == nullptr) {
9018         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr");
9019         return ERR_INVALID_VALUE;
9020     }
9021     return freeInstallManager_->FreeInstallAbilityFromRemote(want, callback, validUserId, requestCode);
9022 }
9023 
GetTopAbility(bool isNeedLocalDeviceId)9024 AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId)
9025 {
9026     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9027     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
9028     AppExecFwk::ElementName elementName = {};
9029     if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
9030         auto callerPid = IPCSkeleton::GetCallingPid();
9031         AppExecFwk::RunningProcessInfo processInfo;
9032         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
9033         if (!processInfo.isTestProcess) {
9034             TAG_LOGE(AAFwkTag::ABILITYMGR, "caller can not use system-api or not test process.");
9035             return elementName;
9036         }
9037     }
9038 #ifdef SUPPORT_GRAPHICS
9039     sptr<IRemoteObject> token;
9040     int ret = IN_PROCESS_CALL(GetTopAbility(token));
9041     if (ret) {
9042         return elementName;
9043     }
9044     if (!token) {
9045         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
9046         return elementName;
9047     }
9048     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9049     if (abilityRecord == nullptr) {
9050         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
9051         return elementName;
9052     }
9053     elementName = abilityRecord->GetElementName();
9054     bool isDeviceEmpty = elementName.GetDeviceID().empty();
9055     std::string localDeviceId;
9056     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
9057         elementName.SetDeviceID(localDeviceId);
9058     }
9059 #endif
9060     return elementName;
9061 }
9062 
GetElementNameByToken(sptr<IRemoteObject> token,bool isNeedLocalDeviceId)9063 AppExecFwk::ElementName AbilityManagerService::GetElementNameByToken(sptr<IRemoteObject> token,
9064     bool isNeedLocalDeviceId)
9065 {
9066     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9067     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
9068     AppExecFwk::ElementName elementName = {};
9069 #ifdef SUPPORT_GRAPHICS
9070     if (!token) {
9071         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
9072         return elementName;
9073     }
9074     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9075     if (abilityRecord == nullptr) {
9076         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
9077         return elementName;
9078     }
9079     elementName = abilityRecord->GetElementName();
9080     bool isDeviceEmpty = elementName.GetDeviceID().empty();
9081     std::string localDeviceId;
9082     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
9083         elementName.SetDeviceID(localDeviceId);
9084     }
9085 #endif
9086     return elementName;
9087 }
9088 
Dump(int fd,const std::vector<std::u16string> & args)9089 int AbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
9090 {
9091     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump begin fd: %{public}d", fd);
9092     std::string result;
9093     auto errCode = Dump(args, result);
9094     int ret = dprintf(fd, "%s\n", result.c_str());
9095     if (ret < 0) {
9096         TAG_LOGE(AAFwkTag::ABILITYMGR, "dprintf error");
9097         return ERR_AAFWK_HIDUMP_ERROR;
9098     }
9099     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump end");
9100     return errCode;
9101 }
9102 
Dump(const std::vector<std::u16string> & args,std::string & result)9103 int AbilityManagerService::Dump(const std::vector<std::u16string>& args, std::string& result)
9104 {
9105     ErrCode errCode = ERR_OK;
9106     auto size = args.size();
9107     if (size == 0) {
9108         ShowHelp(result);
9109         return errCode;
9110     }
9111 
9112     std::vector<std::string> argsStr;
9113     for (auto arg : args) {
9114         argsStr.emplace_back(Str16ToStr8(arg));
9115     }
9116 
9117     if (argsStr[0] == "-h") {
9118         ShowHelp(result);
9119     } else {
9120         errCode = ProcessMultiParam(argsStr, result);
9121         if (errCode == ERR_AAFWK_HIDUMP_INVALID_ARGS) {
9122             ShowIllegalInfomation(result);
9123         }
9124     }
9125     return errCode;
9126 }
9127 
ProcessMultiParam(std::vector<std::string> & argsStr,std::string & result)9128 ErrCode AbilityManagerService::ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)
9129 {
9130     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
9131     bool isClient = false;
9132     bool isUser = false;
9133     int userID = DEFAULT_INVAL_VALUE;
9134     std::vector<std::string>::iterator it;
9135     for (it = argsStr.begin(); it != argsStr.end();) {
9136         if (*it == ARGS_CLIENT) {
9137             isClient = true;
9138             it = argsStr.erase(it);
9139             continue;
9140         }
9141         if (*it == ARGS_USER_ID) {
9142             it = argsStr.erase(it);
9143             if (it == argsStr.end()) {
9144                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
9145                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
9146             }
9147             (void)StrToInt(*it, userID);
9148             if (userID < 0) {
9149                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
9150                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
9151             }
9152             isUser = true;
9153             it = argsStr.erase(it);
9154             continue;
9155         }
9156         it++;
9157     }
9158     std::string cmd;
9159     for (unsigned int i = 0; i < argsStr.size(); i++) {
9160         cmd.append(argsStr[i]);
9161         if (i != argsStr.size() - 1) {
9162             cmd.append(" ");
9163         }
9164     }
9165     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, isClient:%{public}d, userID is : %{public}d, cmd is : %{public}s",
9166         __func__, isClient, userID, cmd.c_str());
9167 
9168     std::vector<std::string> dumpResults;
9169     DumpSysState(cmd, dumpResults, isClient, isUser, userID);
9170     for (auto it : dumpResults) {
9171         result += it + "\n";
9172     }
9173     return ERR_OK;
9174 }
9175 
ShowHelp(std::string & result)9176 void AbilityManagerService::ShowHelp(std::string& result)
9177 {
9178     result.append("Usage:\n")
9179         .append("-h                          ")
9180         .append("help text for the tool\n")
9181         .append("-a [-c | -u {UserId}]       ")
9182         .append("dump all ability infomation in the system or all ability infomation of client/UserId\n")
9183         .append("-l                          ")
9184         .append("dump all mission list information in the system\n")
9185         .append("-i {AbilityRecordId}        ")
9186         .append("dump an ability infomation by ability record id\n")
9187         .append("-e                          ")
9188         .append("dump all extension infomation in the system(FA: ServiceAbilityRecords, Stage: ExtensionRecords)\n")
9189         .append("-p [PendingWantRecordId]    ")
9190         .append("dump all pendingwant record infomation in the system\n")
9191         .append("-r                          ")
9192         .append("dump all process in the system\n")
9193         .append("-d                          ")
9194         .append("dump all data ability infomation in the system");
9195 }
9196 
ShowIllegalInfomation(std::string & result)9197 void AbilityManagerService::ShowIllegalInfomation(std::string& result)
9198 {
9199     result.append(ILLEGAL_INFOMATION);
9200 }
9201 
DumpAbilityInfoDone(std::vector<std::string> & infos,const sptr<IRemoteObject> & callerToken)9202 int AbilityManagerService::DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)
9203 {
9204     TAG_LOGD(AAFwkTag::ABILITYMGR, "DumpAbilityInfoDone begin");
9205     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
9206     if (abilityRecord == nullptr) {
9207         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord nullptr");
9208         return ERR_INVALID_VALUE;
9209     }
9210     if (!JudgeSelfCalled(abilityRecord)) {
9211         return CHECK_PERMISSION_FAILED;
9212     }
9213     abilityRecord->DumpAbilityInfoDone(infos);
9214     return ERR_OK;
9215 }
9216 
SetMissionContinueState(const sptr<IRemoteObject> & token,const AAFwk::ContinueState & state)9217 int AbilityManagerService::SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)
9218 {
9219     TAG_LOGD(AAFwkTag::ABILITYMGR, "SetMissionContinueState begin. State: %{public}d", state);
9220 
9221     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
9222 
9223     int32_t missionId = GetMissionIdByAbilityToken(token);
9224     if (missionId == -1) {
9225         TAG_LOGE(AAFwkTag::ABILITYMGR, "SetMissionContinueState failed to get missionId. State: %{public}d", state);
9226         return ERR_INVALID_VALUE;
9227     }
9228 
9229     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9230     if (!abilityRecord) {
9231         TAG_LOGE(AAFwkTag::ABILITYMGR,
9232             "SetMissionContinueState: No such ability record. Mission id: %{public}d, state: %{public}d",
9233             missionId, state);
9234         return -1;
9235     }
9236 
9237     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9238     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9239     if (callingTokenId != tokenID) {
9240         TAG_LOGE(AAFwkTag::ABILITYMGR,
9241             "SetMissionContinueState not self, not enabled. Mission id: %{public}d, state: %{public}d",
9242             missionId, state);
9243         return -1;
9244     }
9245 
9246     auto userId = abilityRecord->GetOwnerMissionUserId();
9247     auto missionListManager = GetMissionListManagerByUserId(userId);
9248     if (!missionListManager) {
9249         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager. Mission id: %{public}d, state: %{public}d",
9250             missionId, state);
9251         return -1;
9252     }
9253 
9254     auto setResult = missionListManager->SetMissionContinueState(token, missionId, state);
9255     if (setResult != ERR_OK) {
9256         TAG_LOGE(AAFwkTag::ABILITYMGR,
9257             "missionListManager set failed, result: %{public}d, mission id: %{public}d, state: %{public}d",
9258             setResult, missionId, state);
9259         return setResult;
9260     }
9261 
9262     DistributedClient dmsClient;
9263     auto result =  dmsClient.SetMissionContinueState(missionId, state);
9264     if (result != ERR_OK) {
9265         TAG_LOGE(AAFwkTag::ABILITYMGR,
9266             "Notify DMS client failed, result: %{public}d. Mission id: %{public}d, state: %{public}d",
9267             result, missionId, state);
9268     }
9269 
9270     TAG_LOGD(AAFwkTag::ABILITYMGR,
9271         "SetMissionContinueState end. Mission id: %{public}d, state: %{public}d", missionId, state);
9272     return ERR_OK;
9273 }
9274 
9275 #ifdef SUPPORT_GRAPHICS
SetMissionLabel(const sptr<IRemoteObject> & token,const std::string & label)9276 int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
9277 {
9278     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9279     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9280     if (!abilityRecord) {
9281         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
9282         return -1;
9283     }
9284 
9285     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9286     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9287     if (callingTokenId != tokenID) {
9288         TAG_LOGE(AAFwkTag::ABILITYMGR, "SetMissionLabel not self, not enabled");
9289         return -1;
9290     }
9291 
9292     auto userId = abilityRecord->GetOwnerMissionUserId();
9293     auto missionListManager = GetMissionListManagerByUserId(userId);
9294     if (!missionListManager) {
9295         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager when set mission label.");
9296         return -1;
9297     }
9298 
9299     return missionListManager->SetMissionLabel(token, label);
9300 }
9301 
SetMissionIcon(const sptr<IRemoteObject> & token,const std::shared_ptr<OHOS::Media::PixelMap> & icon)9302 int AbilityManagerService::SetMissionIcon(const sptr<IRemoteObject> &token,
9303     const std::shared_ptr<OHOS::Media::PixelMap> &icon)
9304 {
9305     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9306     CHECK_CALLER_IS_SYSTEM_APP;
9307     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9308     if (!abilityRecord) {
9309         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
9310         return -1;
9311     }
9312 
9313     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9314     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9315     if (callingTokenId != tokenID) {
9316         TAG_LOGE(AAFwkTag::ABILITYMGR, "not self, not enable to set mission icon");
9317         return -1;
9318     }
9319 
9320     auto userId = abilityRecord->GetOwnerMissionUserId();
9321     auto missionListManager = GetMissionListManagerByUserId(userId);
9322     if (!missionListManager) {
9323         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager.");
9324         return -1;
9325     }
9326 
9327     return missionListManager->SetMissionIcon(token, icon);
9328 }
9329 
RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> & handler,bool animationEnabled)9330 int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler,
9331     bool animationEnabled)
9332 {
9333     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9334     if (!isSaCall) {
9335         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
9336         return CHECK_PERMISSION_FAILED;
9337     }
9338     wmsHandler_ = handler;
9339     isAnimationEnabled_ = animationEnabled;
9340     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s: WMS handler registered successfully.", __func__);
9341     return ERR_OK;
9342 }
9343 
GetWMSHandler() const9344 sptr<IWindowManagerServiceHandler> AbilityManagerService::GetWMSHandler() const
9345 {
9346     return wmsHandler_;
9347 }
9348 
CompleteFirstFrameDrawing(const sptr<IRemoteObject> & abilityToken)9349 void AbilityManagerService::CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)
9350 {
9351     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9352     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
9353         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not foundation call.");
9354         return;
9355     }
9356     auto abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
9357     CHECK_POINTER(abilityRecord);
9358 
9359     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
9360     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
9361     CHECK_POINTER(missionListManager);
9362     missionListManager->CompleteFirstFrameDrawing(abilityToken);
9363 }
9364 
CompleteFirstFrameDrawing(int32_t sessionId)9365 void AbilityManagerService::CompleteFirstFrameDrawing(int32_t sessionId)
9366 {
9367     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9368     if (!IsCallerSceneBoard()) {
9369         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
9370         return;
9371     }
9372     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
9373     CHECK_POINTER(uiAbilityManager);
9374     uiAbilityManager->CompleteFirstFrameDrawing(sessionId);
9375 }
9376 
ShowPickerDialog(const Want & want,int32_t userId,const sptr<IRemoteObject> & callerToken)9377 int32_t AbilityManagerService::ShowPickerDialog(
9378     const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)
9379 {
9380     AAFwk::Want newWant = want;
9381     std::string sharePickerBundleName =
9382         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME);
9383     std::string sharePickerAbilityName =
9384         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_ABILITY_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME);
9385     newWant.SetElementName(sharePickerBundleName, sharePickerAbilityName);
9386     newWant.SetParam(TOKEN_KEY, callerToken);
9387     // note: clear actions
9388     newWant.SetAction("");
9389     return IN_PROCESS_CALL(StartAbility(newWant, DEFAULT_INVAL_VALUE, userId));
9390 }
9391 
CheckWindowMode(int32_t windowMode,const std::vector<AppExecFwk::SupportWindowMode> & windowModes) const9392 bool AbilityManagerService::CheckWindowMode(int32_t windowMode,
9393     const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const
9394 {
9395     TAG_LOGI(AAFwkTag::ABILITYMGR, "Window mode is %{public}d.", windowMode);
9396     if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED) {
9397         return true;
9398     }
9399 
9400     auto bmsWindowMode = WindowOptionsUtils::WindowModeMap(windowMode);
9401     if (bmsWindowMode.first) {
9402         for (const auto& mode : windowModes) {
9403             if (mode == bmsWindowMode.second) {
9404                 return true;
9405             }
9406         }
9407     }
9408     return false;
9409 }
9410 
PrepareTerminateAbility(const sptr<IRemoteObject> & token,sptr<IPrepareTerminateCallback> & callback)9411 int AbilityManagerService::PrepareTerminateAbility(const sptr<IRemoteObject> &token,
9412     sptr<IPrepareTerminateCallback> &callback)
9413 {
9414     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
9415     if (callback == nullptr) {
9416         TAG_LOGE(AAFwkTag::ABILITYMGR, "callback is nullptr.");
9417         return ERR_INVALID_VALUE;
9418     }
9419     if (!CheckPrepareTerminateEnable()) {
9420         callback->DoPrepareTerminate();
9421         return ERR_INVALID_VALUE;
9422     }
9423 
9424     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9425     if (abilityRecord == nullptr) {
9426         TAG_LOGE(AAFwkTag::ABILITYMGR, "record is nullptr.");
9427         callback->DoPrepareTerminate();
9428         return ERR_INVALID_VALUE;
9429     }
9430 
9431     if (!JudgeSelfCalled(abilityRecord)) {
9432         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not self call.");
9433         callback->DoPrepareTerminate();
9434         return CHECK_PERMISSION_FAILED;
9435     }
9436 
9437     auto type = abilityRecord->GetAbilityInfo().type;
9438     if (type != AppExecFwk::AbilityType::PAGE) {
9439         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support PAGE.");
9440         callback->DoPrepareTerminate();
9441         return RESOLVE_CALL_ABILITY_TYPE_ERR;
9442     }
9443 
9444     auto timeoutTask = [&callback]() {
9445         callback->DoPrepareTerminate();
9446     };
9447     int prepareTerminateTimeout =
9448         AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * PREPARE_TERMINATE_TIMEOUT_MULTIPLE;
9449     if (taskHandler_) {
9450         taskHandler_->SubmitTask(timeoutTask, "PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()),
9451             prepareTerminateTimeout);
9452     }
9453 
9454     bool res = abilityRecord->PrepareTerminateAbility();
9455     if (!res) {
9456         callback->DoPrepareTerminate();
9457     }
9458     if (taskHandler_) {
9459         taskHandler_->CancelTask("PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()));
9460     }
9461     return ERR_OK;
9462 }
9463 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9464 void AbilityManagerService::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9465 {
9466     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle focused event");
9467     auto missionListManager = GetCurrentMissionListManager();
9468     CHECK_POINTER(missionListManager);
9469 
9470     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9471     missionListManager->NotifyMissionFocused(missionId);
9472 }
9473 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9474 void AbilityManagerService::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9475 {
9476     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle unfocused event");
9477     auto missionListManager = GetCurrentMissionListManager();
9478     CHECK_POINTER(missionListManager);
9479 
9480     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9481     missionListManager->NotifyMissionUnfocused(missionId);
9482 }
9483 
InitFocusListener()9484 void AbilityManagerService::InitFocusListener()
9485 {
9486     TAG_LOGI(AAFwkTag::ABILITYMGR, "Init ability focus listener");
9487     if (focusListener_) {
9488         return;
9489     }
9490 
9491     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
9492     auto registerTask = [innerService = shared_from_this()]() {
9493         if (innerService) {
9494             TAG_LOGI(AAFwkTag::ABILITYMGR, "RegisterFocusListener task");
9495             innerService->RegisterFocusListener();
9496         }
9497     };
9498     if (taskHandler_) {
9499         taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
9500     }
9501 }
9502 
RegisterFocusListener()9503 void AbilityManagerService::RegisterFocusListener()
9504 {
9505     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register focus listener");
9506     if (!focusListener_) {
9507         TAG_LOGE(AAFwkTag::ABILITYMGR, "no listener obj");
9508         return;
9509     }
9510     Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
9511     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register focus listener success");
9512 }
9513 
InitPrepareTerminateConfig()9514 void AbilityManagerService::InitPrepareTerminateConfig()
9515 {
9516     char value[PREPARE_TERMINATE_ENABLE_SIZE] = "false";
9517     int retSysParam = GetParameter(PREPARE_TERMINATE_ENABLE_PARAMETER, "false", value, PREPARE_TERMINATE_ENABLE_SIZE);
9518     TAG_LOGI(AAFwkTag::ABILITYMGR,
9519         "CheckPrepareTerminateEnable, %{public}s value is %{public}s.", PREPARE_TERMINATE_ENABLE_PARAMETER,
9520         value);
9521     if (retSysParam > 0 && !std::strcmp(value, "true")) {
9522         isPrepareTerminateEnable_ = true;
9523     }
9524 }
9525 
RegisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer,const std::string & targetBundleName)9526 int AbilityManagerService::RegisterAbilityFirstFrameStateObserver(
9527     const sptr<IAbilityFirstFrameStateObserver> &observer, const std::string &targetBundleName)
9528 {
9529     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9530         RegisterAbilityFirstFrameStateObserver(observer, targetBundleName);
9531 }
9532 
UnregisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer)9533 int AbilityManagerService::UnregisterAbilityFirstFrameStateObserver(
9534     const sptr<IAbilityFirstFrameStateObserver> &observer)
9535 {
9536     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9537         UnregisterAbilityFirstFrameStateObserver(observer);
9538 }
9539 
GetAnimationFlag()9540 bool AbilityManagerService::GetAnimationFlag()
9541 {
9542     return isAnimationEnabled_;
9543 }
9544 
9545 #endif
9546 
CheckCallServicePermission(const AbilityRequest & abilityRequest)9547 int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest)
9548 {
9549     if (abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()) == BROKER_UID &&
9550         abilityRequest.want.GetElement().GetBundleName() == SHELL_ASSISTANT_BUNDLENAME) {
9551         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9552         if (collaborator != nullptr) {
9553             TAG_LOGI(AAFwkTag::ABILITYMGR, "Collaborator CheckCallAbilityPermission.");
9554             return collaborator->CheckCallAbilityPermission(abilityRequest.want);
9555         }
9556     }
9557     if (abilityRequest.abilityInfo.isStageBasedModel) {
9558         auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9559         TAG_LOGD(AAFwkTag::ABILITYMGR, "extensionType is %{public}d.", static_cast<int>(extensionType));
9560         if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE ||
9561             extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
9562             extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9563             return CheckCallServiceExtensionPermission(abilityRequest);
9564         } else {
9565             return CheckCallOtherExtensionPermission(abilityRequest);
9566         }
9567     } else {
9568         return CheckCallServiceAbilityPermission(abilityRequest);
9569     }
9570 }
9571 
CheckCallDataAbilityPermission(AbilityRequest & abilityRequest,bool isShell,bool isSACall)9572 int AbilityManagerService::CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)
9573 {
9574     abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo;
9575     abilityRequest.uid = abilityRequest.appInfo.uid;
9576     if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) {
9577         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid app info for data ability acquiring.");
9578         return ERR_INVALID_VALUE;
9579     }
9580     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) {
9581         TAG_LOGE(AAFwkTag::ABILITYMGR, "BMS query result is not a data ability.");
9582         return ERR_WRONG_INTERFACE_CALL;
9583     }
9584 
9585     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest,
9586         true, isShell, isSACall);
9587     if (isShell) {
9588         verificationInfo.isBackgroundCall = true;
9589     }
9590     if (!isShell && IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall, true) != ERR_OK) {
9591         return ERR_INVALID_VALUE;
9592     }
9593     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallDataAbilityPermission(verificationInfo,
9594         isShell);
9595     if (result != ERR_OK) {
9596         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start DataAbility");
9597         return result;
9598     }
9599 
9600     return ERR_OK;
9601 }
9602 
CreateVerificationInfo(const AbilityRequest & abilityRequest,bool isData,bool isShell,bool isSA)9603 AAFwk::PermissionVerification::VerificationInfo AbilityManagerService::CreateVerificationInfo(
9604     const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)
9605 {
9606     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9607     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9608     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9609     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9610     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call ServiceAbility or DataAbility, target bundleName: %{public}s.",
9611         abilityRequest.appInfo.bundleName.c_str());
9612     if (whiteListassociatedWakeUpFlag_ &&
9613         abilityRequest.appInfo.bundleName == BUNDLE_NAME_SETTINGSDATA) {
9614         TAG_LOGD(AAFwkTag::ABILITYMGR,
9615             "Call ServiceAbility or DataAbility, target bundle in white-list, allow associatedWakeUp.");
9616         verificationInfo.associatedWakeUp = true;
9617     } else {
9618         verificationInfo.associatedWakeUp = abilityRequest.appInfo.associatedWakeUp;
9619     }
9620     if (!isData) {
9621         isSA = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9622         isShell = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
9623     }
9624     if (isSA || isShell) {
9625         return verificationInfo;
9626     }
9627     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9628     if (callerAbility) {
9629         verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9630     }
9631 
9632     return verificationInfo;
9633 }
9634 
CheckCallServiceExtensionPermission(const AbilityRequest & abilityRequest)9635 int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)
9636 {
9637     TAG_LOGD(AAFwkTag::ABILITYMGR, "begin");
9638 
9639     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9640     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9641     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9642     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9643     verificationInfo.isBackgroundCall = false;
9644     if (isParamStartAbilityEnable_) {
9645         bool stopContinuousTaskFlag = ShouldPreventStartAbility(abilityRequest);
9646         if (stopContinuousTaskFlag) {
9647             TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension");
9648             return CHECK_PERMISSION_FAILED;
9649         }
9650     }
9651 
9652     if (abilityRequest.abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9653         TAG_LOGE(AAFwkTag::ABILITYMGR, "background startup UI_SERVICE");
9654         verificationInfo.isBackgroundCall = true;
9655         std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9656         if (callerAbility) {
9657             verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9658         }
9659         if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9660             TAG_LOGE(AAFwkTag::ABILITYMGR, "not background startup UI_SERVICE");
9661             return ERR_INVALID_VALUE;
9662         }
9663     }
9664 
9665     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo);
9666     if (result != ERR_OK) {
9667         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension or DataShareExtension");
9668     }
9669     return result;
9670 }
CheckCallAutoFillExtensionPermission(const AbilityRequest & abilityRequest)9671 int AbilityManagerService::CheckCallAutoFillExtensionPermission(const AbilityRequest &abilityRequest)
9672 {
9673     if (!abilityRequest.appInfo.isSystemApp) {
9674         TAG_LOGE(AAFwkTag::ABILITYMGR, "application requesting call isn't system application");
9675         return CHECK_PERMISSION_FAILED;
9676     }
9677     std::string jsonDataStr = abilityRequest.want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY);
9678     AbilityBase::ViewData viewData;
9679     viewData.FromJsonString(jsonDataStr.c_str());
9680     std::string callerName;
9681     int32_t uid = 0;
9682     auto callerPid = IPCSkeleton::GetCallingPid();
9683     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
9684     if (viewData.bundleName != callerName) {
9685         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not %{public}s called, no allowed", viewData.bundleName.c_str());
9686         return ERR_WRONG_INTERFACE_CALL;
9687     }
9688     return ERR_OK;
9689 }
9690 
CheckCallOtherExtensionPermission(const AbilityRequest & abilityRequest)9691 int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)
9692 {
9693     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9694     if (IPCSkeleton::GetCallingUid() != BROKER_UID && AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9695         return ERR_OK;
9696     }
9697     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9698     TAG_LOGD(AAFwkTag::ABILITYMGR, "OtherExtension type: %{public}d.", static_cast<int32_t>(extensionType));
9699     if (system::GetBoolParameter(DEVELOPER_MODE_STATE, false) &&
9700         PermissionVerification::GetInstance()->VerifyShellStartExtensionType(static_cast<int32_t>(extensionType))) {
9701         return ERR_OK;
9702     }
9703     if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) {
9704         CHECK_CALLER_IS_SYSTEM_APP;
9705         return ERR_OK;
9706     }
9707     if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) {
9708         return ERR_OK;
9709     }
9710     if (extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD ||
9711         extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART) {
9712         return CheckCallAutoFillExtensionPermission(abilityRequest);
9713     }
9714     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
9715         return CheckUIExtensionPermission(abilityRequest);
9716     }
9717     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
9718         return ERR_OK;
9719     }
9720     if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION) {
9721         return CheckFileAccessExtensionPermission(abilityRequest);
9722     }
9723     if (extensionType == AppExecFwk::ExtensionAbilityType::CALLER_INFO_QUERY) {
9724         return CheckCallerInfoQueryExtensionPermission(abilityRequest);
9725     }
9726     TAG_LOGE(AAFwkTag::ABILITYMGR, "not SA, can't start other extension");
9727     return CHECK_PERMISSION_FAILED;
9728 }
9729 
CheckCallerInfoQueryExtensionPermission(const AbilityRequest & abilityRequest)9730 int AbilityManagerService::CheckCallerInfoQueryExtensionPermission(const AbilityRequest &abilityRequest)
9731 {
9732     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9733         PermissionConstants::PERMISSION_GET_TELEPHONY_STATE);
9734     if (!ret) {
9735         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny for callerInfoQueryExtension");
9736         return CHECK_PERMISSION_FAILED;
9737     }
9738     TAG_LOGI(AAFwkTag::ABILITYMGR, "check permission success");
9739     return ERR_OK;
9740 }
9741 
CheckFileAccessExtensionPermission(const AbilityRequest & abilityRequest)9742 int AbilityManagerService::CheckFileAccessExtensionPermission(const AbilityRequest &abilityRequest)
9743 {
9744     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9745         PermissionConstants::PERMISSION_FILE_ACCESS_MANAGER);
9746     if (!ret) {
9747         return CHECK_PERMISSION_FAILED;
9748     }
9749     TAG_LOGD(AAFwkTag::ABILITYMGR, "Temporary, FILEACCESS_EXTENSION use serviceExtension start-up rule.");
9750     return CheckCallServiceExtensionPermission(abilityRequest);
9751 }
9752 
CheckUIExtensionPermission(const AbilityRequest & abilityRequest)9753 int AbilityManagerService::CheckUIExtensionPermission(const AbilityRequest &abilityRequest)
9754 {
9755     if (abilityRequest.want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
9756         // If started by embedded atomic service, allow it.
9757         return ERR_OK;
9758     }
9759 
9760     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9761     if (AAFwk::UIExtensionUtils::IsSystemUIExtension(extensionType)) {
9762         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9763         if (callerRecord == nullptr) {
9764             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid caller.");
9765             return NO_FOUND_ABILITY_BY_CALLER;
9766         }
9767 
9768         if (!abilityRequest.appInfo.isSystemApp) {
9769             TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle %{public}s wanna to start or caller bundle %{public}s "
9770                 "isn't system app, type %{public}d not allowed.", abilityRequest.appInfo.bundleName.c_str(),
9771                 callerRecord->GetApplicationInfo().bundleName.c_str(), extensionType);
9772             return CHECK_PERMISSION_FAILED;
9773         }
9774     }
9775 
9776     if (AAFwk::UIExtensionUtils::IsSystemCallerNeeded(extensionType)) {
9777         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9778         if (callerRecord == nullptr) {
9779             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid caller.");
9780             return NO_FOUND_ABILITY_BY_CALLER;
9781         }
9782 
9783         if (!callerRecord->GetApplicationInfo().isSystemApp
9784             && !AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9785             TAG_LOGE(AAFwkTag::ABILITYMGR,
9786                      "Bundle %{public}s wanna to start but caller bundle %{public}s "
9787                      "isn't system app, type %{public}d not allowed.",
9788                      abilityRequest.appInfo.bundleName.c_str(), callerRecord->GetApplicationInfo().bundleName.c_str(),
9789                      extensionType);
9790             return CHECK_PERMISSION_FAILED;
9791         }
9792     }
9793 
9794     if (!CheckUIExtensionCallerIsForeground(abilityRequest)) {
9795         return CHECK_PERMISSION_FAILED;
9796     }
9797 
9798     if (!CheckUIExtensionCallerPidByHostWindowId(abilityRequest)) {
9799         return ERR_INVALID_CALLER;
9800     }
9801 
9802     return ERR_OK;
9803 }
9804 
CheckUIExtensionCallerIsForeground(const AbilityRequest & abilityRequest)9805 bool AbilityManagerService::CheckUIExtensionCallerIsForeground(const AbilityRequest &abilityRequest)
9806 {
9807     if (!CheckUIExtensionCallerIsUIAbility(abilityRequest)) {
9808         // Check only if the caller is uiability, if caller is not a uiability, don't check.
9809         return true;
9810     }
9811 
9812     bool isBackgroundCall = true;
9813     auto ret = IsCallFromBackground(abilityRequest, isBackgroundCall);
9814     if (ret != ERR_OK) {
9815         TAG_LOGE(AAFwkTag::UI_EXT, "start uea when background");
9816         return false;
9817     }
9818 
9819     if (!isBackgroundCall) {
9820         return true;
9821     }
9822 
9823     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9824     if (callerAbility != nullptr) {
9825         if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9826             auto tokenId = callerAbility->GetApplicationInfo().accessTokenId;
9827             bool isFocused = false;
9828             if (CheckUIExtensionIsFocused(tokenId, isFocused) == ERR_OK && isFocused) {
9829                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Root caller is foreground");
9830                 return true;
9831             }
9832         }
9833 
9834         if (callerAbility->IsSceneBoard()) {
9835             return true;
9836         }
9837     }
9838 
9839     if (PermissionVerification::GetInstance()->VerifyCallingPermission(
9840         PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
9841         return true;
9842     }
9843 
9844     TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller app is not foreground, can't start %{public}s",
9845         abilityRequest.want.GetElement().GetURI().c_str());
9846     return false;
9847 }
9848 
CheckUIExtensionCallerIsUIAbility(const AbilityRequest & abilityRequest)9849 bool AbilityManagerService::CheckUIExtensionCallerIsUIAbility(const AbilityRequest &abilityRequest)
9850 {
9851     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9852     if (callerAbility == nullptr) {
9853         TAG_LOGE(AAFwkTag::UI_EXT, "caller ability invalid");
9854         return false;
9855     }
9856 
9857     if (callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9858         return true;
9859     }
9860 
9861     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9862         callerAbility = GetUIExtensionRootCaller(abilityRequest.callerToken, abilityRequest.userId);
9863         if (callerAbility != nullptr && callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9864             return true;
9865         }
9866     }
9867 
9868     return false;
9869 }
9870 
CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest & abilityRequest)9871 bool AbilityManagerService::CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest &abilityRequest)
9872 {
9873 #ifdef SUPPORT_SCREEN
9874     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9875         return true;
9876     }
9877 
9878     auto sessionInfo = abilityRequest.sessionInfo;
9879     CHECK_POINTER_AND_RETURN(sessionInfo, false);
9880     auto hostWindowId = sessionInfo->hostWindowId;
9881     auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
9882     CHECK_POINTER_AND_RETURN(sceneSessionManager, false);
9883     pid_t hostPid = 0;
9884     // If host window id is scb, it will return with error.
9885     auto tokenId = abilityRequest.appInfo.accessTokenId;
9886     auto element = abilityRequest.want.GetElement();
9887     auto extType = abilityRequest.abilityInfo.extensionAbilityType;
9888     {
9889         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "Rosen::SceneSessionManager::CheckUIExtensionCreation");
9890         auto ret = sceneSessionManager->CheckUIExtensionCreation(hostWindowId, tokenId, element, extType, hostPid);
9891         if (ret == Rosen::WMError::WM_ERROR_INVALID_PERMISSION) {
9892             // If check permission failed, means target ability can't show on lock screen.
9893             TAG_LOGE(AAFwkTag::UI_EXT, "Check fail, tokenId: %{public}d, element: %{public}s, ret: %{public}d",
9894                 tokenId, element.GetURI().c_str(), ret);
9895             return false;
9896         }
9897     }
9898 
9899     TAG_LOGD(AAFwkTag::UI_EXT, "get pid %{public}d by windowId %{public}d", hostPid, hostWindowId);
9900     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9901     CHECK_POINTER_AND_RETURN(callerAbility, false);
9902     if (callerAbility->IsSceneBoard()) {
9903         return true;
9904     }
9905     if (hostPid != 0 && callerAbility->GetPid() == hostPid) {
9906         return true;
9907     }
9908 
9909     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9910         TAG_LOGD(AAFwkTag::UI_EXT, "caller is nested uiextability");
9911         auto connectManager = GetCurrentConnectManager();
9912         CHECK_POINTER_AND_RETURN(connectManager, false);
9913         bool matched = false;
9914         std::list<sptr<IRemoteObject>> callerList;
9915         connectManager->GetUIExtensionCallerTokenList(callerAbility, callerList);
9916         for (auto &item : callerList) {
9917             auto ability = AAFwk::Token::GetAbilityRecordByToken(item);
9918             if (ability == nullptr) {
9919                 TAG_LOGW(AAFwkTag::UI_EXT, "wrong ability");
9920                 continue;
9921             }
9922 
9923             if ((hostPid != 0 && ability->GetPid() == hostPid) || ability->IsSceneBoard()) {
9924                 matched = true;
9925                 return true;
9926             }
9927         }
9928         if (!matched) {
9929             TAG_LOGE(AAFwkTag::UI_EXT, "Check nested uiextability failed");
9930         }
9931     }
9932 
9933     TAG_LOGE(AAFwkTag::UI_EXT, "Check pid by windowId %{public}d failed, got %{public}d but actual is %{public}d",
9934         hostWindowId, hostPid, callerAbility->GetPid());
9935     return false;
9936 #else
9937     return true;
9938 #endif // SUPPORT_SCREEN
9939 }
9940 
CheckCallServiceAbilityPermission(const AbilityRequest & abilityRequest)9941 int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)
9942 {
9943     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9944     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest);
9945     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9946         return ERR_INVALID_VALUE;
9947     }
9948 
9949     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceAbilityPermission(verificationInfo);
9950     if (result != ERR_OK) {
9951         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceAbility");
9952     }
9953     return result;
9954 }
9955 
CheckCallAbilityPermission(const AbilityRequest & abilityRequest,uint32_t specifyTokenId,bool isCallByShortcut)9956 int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId,
9957     bool isCallByShortcut)
9958 {
9959     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9960     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9961 
9962     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9963     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9964     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9965     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9966     verificationInfo.specifyTokenId = specifyTokenId;
9967     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9968         return ERR_INVALID_VALUE;
9969     }
9970 
9971     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission(
9972         verificationInfo, isCallByShortcut);
9973     if (result != ERR_OK) {
9974         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start PageAbility(FA) or Ability(Stage)");
9975     }
9976     return result;
9977 }
9978 
CheckStartByCallPermission(const AbilityRequest & abilityRequest)9979 int AbilityManagerService::CheckStartByCallPermission(const AbilityRequest &abilityRequest)
9980 {
9981     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call");
9982     // check whether the target ability is page type and not specified mode.
9983     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::PAGE ||
9984         abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
9985         TAG_LOGE(AAFwkTag::ABILITYMGR, "Called ability is not common ability.");
9986         return RESOLVE_CALL_ABILITY_TYPE_ERR;
9987     }
9988 
9989     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9990     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9991     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9992     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9993     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9994         return ERR_INVALID_VALUE;
9995     }
9996 
9997     if (AAFwk::PermissionVerification::GetInstance()->CheckStartByCallPermission(verificationInfo) != ERR_OK) {
9998         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to StartAbilityByCall.");
9999         return RESOLVE_CALL_NO_PERMISSIONS;
10000     }
10001     TAG_LOGD(AAFwkTag::ABILITYMGR, "The caller has permission to resolve the call proxy of common ability.");
10002     return ERR_OK;
10003 }
10004 
IsCallFromBackground(const AbilityRequest & abilityRequest,bool & isBackgroundCall,bool isData)10005 int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall,
10006     bool isData)
10007 {
10008     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10009     if (!isData && AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10010         isBackgroundCall = true;
10011         return ERR_OK;
10012     }
10013 
10014     if (!isData && (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
10015         AbilityUtil::IsStartFreeInstall(abilityRequest.want))) {
10016         isBackgroundCall = false;
10017         return ERR_OK;
10018     }
10019 
10020     AppExecFwk::RunningProcessInfo processInfo;
10021     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10022     if (callerAbility && callerAbility->GetAbilityInfo().bundleName == BUNDLE_NAME_DIALOG) {
10023         callerAbility = callerAbility->GetCallerRecord();
10024     }
10025     if (callerAbility) {
10026         if (callerAbility->IsForeground() || callerAbility->GetAbilityForegroundingFlag()) {
10027             isBackgroundCall = false;
10028             return ERR_OK;
10029         }
10030         // CallerAbility is not foreground, so check process state
10031         DelayedSingleton<AppScheduler>::GetInstance()->
10032             GetRunningProcessInfoByToken(callerAbility->GetToken(), processInfo);
10033         if (IsDelegatorCall(processInfo, abilityRequest)) {
10034             TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
10035             isBackgroundCall = false;
10036             return ERR_OK;
10037         }
10038         auto abilityState = callerAbility->GetAbilityState();
10039         if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING ||
10040             // If uiability or uiextensionability ability state is foreground when terminate,
10041             // it will move to background firstly. So if startAbility in onBackground() lifecycle,
10042             // the actual ability state may be had changed to terminating from background or backgrounding.
10043             abilityState == AbilityState::TERMINATING) {
10044             return ERR_OK;
10045         }
10046     } else {
10047         auto callerPid = IPCSkeleton::GetCallingPid();
10048         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
10049         if (processInfo.processName_.empty()) {
10050             TAG_LOGD(AAFwkTag::ABILITYMGR, "Can not find caller application by callerPid: %{private}d.", callerPid);
10051             if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
10052                 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
10053                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller has PERMISSION_START_ABILITIES_FROM_BACKGROUND, PASS.");
10054                 isBackgroundCall = false;
10055                 return ERR_OK;
10056             }
10057             TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller does not have PERMISSION_START_ABILITIES_FROM_BACKGROUND, REJECT.");
10058             return ERR_INVALID_VALUE;
10059         }
10060     }
10061     return SetBackgroundCall(processInfo, abilityRequest, isBackgroundCall);
10062 }
10063 
SetBackgroundCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest,bool & isBackgroundCall) const10064 int32_t AbilityManagerService::SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo,
10065     const AbilityRequest &abilityRequest, bool &isBackgroundCall) const
10066 {
10067     if (IsDelegatorCall(processInfo, abilityRequest)) {
10068         TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
10069         isBackgroundCall = false;
10070         return ERR_OK;
10071     }
10072 
10073     if (backgroundJudgeFlag_) {
10074         isBackgroundCall = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND &&
10075             !processInfo.isFocused && !processInfo.isAbilityForegrounding;
10076     } else {
10077         isBackgroundCall = !processInfo.isFocused;
10078         if (!processInfo.isFocused && processInfo.state_ == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) {
10079             // Allow background startup within 1 second after application startup if state is FOREGROUND
10080             int64_t aliveTime = AbilityUtil::SystemTimeMillis() - processInfo.startTimeMillis_;
10081             isBackgroundCall = aliveTime > APP_ALIVE_TIME_MS;
10082             TAG_LOGD(AAFwkTag::ABILITYMGR, "Process %{public}s is alive %{public}s ms.",
10083                 processInfo.processName_.c_str(), std::to_string(aliveTime).c_str());
10084         }
10085     }
10086     TAG_LOGD(AAFwkTag::ABILITYMGR,
10087         "backgroundJudgeFlag: %{public}d, isBackgroundCall: %{public}d, callerAppState: %{public}d.",
10088         static_cast<int32_t>(backgroundJudgeFlag_),
10089         static_cast<int32_t>(isBackgroundCall),
10090         static_cast<int32_t>(processInfo.state_));
10091 
10092     return ERR_OK;
10093 }
10094 
IsTargetPermission(const Want & want) const10095 bool AbilityManagerService::IsTargetPermission(const Want &want) const
10096 {
10097     if (want.GetElement().GetBundleName() == PERMISSIONMGR_BUNDLE_NAME &&
10098         want.GetElement().GetAbilityName() == PERMISSIONMGR_ABILITY_NAME) {
10099         return true;
10100     }
10101 
10102     return false;
10103 }
10104 
IsDelegatorCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest) const10105 inline bool AbilityManagerService::IsDelegatorCall(
10106     const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest) const
10107 {
10108     /*  To make sure the AbilityDelegator is not counterfeited
10109      *   1. The caller-process must be test-process
10110      *   2. The callerToken must be nullptr
10111      */
10112     if (processInfo.isTestProcess &&
10113         !abilityRequest.callerToken && abilityRequest.want.GetBoolParam(IS_DELEGATOR_CALL, false)) {
10114         return true;
10115     }
10116     return false;
10117 }
10118 
CheckNewRuleSwitchState(const std::string & param)10119 bool AbilityManagerService::CheckNewRuleSwitchState(const std::string &param)
10120 {
10121     char value[NEW_RULE_VALUE_SIZE] = "false";
10122     int retSysParam = GetParameter(param.c_str(), "false", value, NEW_RULE_VALUE_SIZE);
10123     TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckNewRuleSwitchState, %{public}s value is %{public}s.", param.c_str(), value);
10124     if (retSysParam > 0 && !std::strcmp(value, "true")) {
10125         return true;
10126     }
10127     return false;
10128 }
10129 
GetStartUpNewRuleFlag() const10130 bool AbilityManagerService::GetStartUpNewRuleFlag() const
10131 {
10132     return startUpNewRule_;
10133 }
10134 
CallRequestDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callStub)10135 void AbilityManagerService::CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)
10136 {
10137     {
10138         std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
10139         callStubTokenMap_[callStub] = token;
10140     }
10141     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10142     CHECK_POINTER(abilityRecord);
10143     if (!JudgeSelfCalled(abilityRecord)) {
10144         return;
10145     }
10146 
10147     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10148         auto uiAbilityManager = GetCurrentUIAbilityManager();
10149         CHECK_POINTER(uiAbilityManager);
10150         uiAbilityManager->CallRequestDone(abilityRecord, callStub);
10151         return;
10152     }
10153 
10154     auto missionListManager = GetCurrentMissionListManager();
10155     CHECK_POINTER(missionListManager);
10156     missionListManager->CallRequestDone(abilityRecord, callStub);
10157 }
10158 
GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> & callStub,sptr<IRemoteObject> & token)10159 void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)
10160 {
10161     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
10162     auto it = callStubTokenMap_.find(callStub);
10163     if (it == callStubTokenMap_.end()) {
10164         token = nullptr;
10165         return;
10166     }
10167     token = callStubTokenMap_[callStub];
10168 }
10169 
AddStartControlParam(Want & want,const sptr<IRemoteObject> & callerToken)10170 int AbilityManagerService::AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)
10171 {
10172     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10173     if (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
10174         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10175         return ERR_OK;
10176     }
10177     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
10178     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
10179     int32_t apiVersion = abilityRecord->GetApplicationInfo().apiTargetVersion;
10180     want.SetParam(DMS_API_VERSION, apiVersion);
10181     bool isCallerBackground = true;
10182     AppExecFwk::RunningProcessInfo processInfo;
10183     DelayedSingleton<AppScheduler>::GetInstance()->
10184         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
10185     if (backgroundJudgeFlag_) {
10186         isCallerBackground = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND;
10187     } else {
10188         isCallerBackground = !processInfo.isFocused;
10189     }
10190     want.SetParam(DMS_IS_CALLER_BACKGROUND, isCallerBackground);
10191     return ERR_OK;
10192 }
10193 
10194 #ifdef WITH_DLP
CheckDlpForExtension(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,EventInfo & eventInfo,const EventName & eventName)10195 int AbilityManagerService::CheckDlpForExtension(
10196     const Want &want, const sptr<IRemoteObject> &callerToken,
10197     int32_t userId, EventInfo &eventInfo, const EventName &eventName)
10198 {
10199     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10200     // check if form frs
10201     auto callingUid = IPCSkeleton::GetCallingUid();
10202     std::string bundleName = want.GetBundle();
10203     if (callingUid == FOUNDATION_UID && FRS_BUNDLE_NAME == bundleName) {
10204         return ERR_OK;
10205     }
10206 
10207     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
10208         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
10209         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
10210         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
10211         eventInfo.errCode = CHECK_PERMISSION_FAILED;
10212         EventReport::SendExtensionEvent(eventName, HiSysEventType::FAULT, eventInfo);
10213         return CHECK_PERMISSION_FAILED;
10214     }
10215     return ERR_OK;
10216 }
10217 #endif // WITH_DLP
10218 
JudgeSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)10219 bool AbilityManagerService::JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
10220 {
10221     if (IPCSkeleton::GetCallingPid() == getprocpid()) {
10222         return true;
10223     }
10224 
10225     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10226     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10227     if (callingTokenId != tokenID) {
10228         TAG_LOGE(AAFwkTag::ABILITYMGR, "Is not self, not enabled");
10229         return false;
10230     }
10231 
10232     return true;
10233 }
10234 
IsAppSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)10235 bool AbilityManagerService::IsAppSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
10236 {
10237     CHECK_POINTER_RETURN_BOOL(abilityRecord);
10238     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10239     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10240     if (callingTokenId != tokenID) {
10241         TAG_LOGE(AAFwkTag::ABILITYMGR, "not app self called");
10242         return false;
10243     }
10244     return true;
10245 }
10246 
GetFocusAbility()10247 std::shared_ptr<AbilityRecord> AbilityManagerService::GetFocusAbility()
10248 {
10249 #ifdef SUPPORT_GRAPHICS
10250     sptr<IRemoteObject> token;
10251     if (!wmsHandler_) {
10252         TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
10253         return nullptr;
10254     }
10255 
10256     wmsHandler_->GetFocusWindow(token);
10257     if (!token) {
10258         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
10259         return nullptr;
10260     }
10261 
10262     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10263     if (!abilityRecord) {
10264         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr.");
10265     }
10266     return abilityRecord;
10267 #endif
10268 
10269     return nullptr;
10270 }
10271 
CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId,bool & isFocused)10272 int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)
10273 {
10274     sptr<IRemoteObject> token;
10275     auto ret = GetTopAbility(token);
10276     if (ret != ERR_OK) {
10277         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetTopAbility failed");
10278         return ret;
10279     }
10280 
10281     auto topAbility = Token::GetAbilityRecordByToken(token);
10282     if (topAbility != nullptr) {
10283         TAG_LOGD(AAFwkTag::ABILITYMGR, "top ability: %{public}s, pid: %{public}d, tokenId: %{public}d",
10284             topAbility->GetWant().GetElement().GetURI().c_str(), topAbility->GetPid(),
10285             topAbility->GetApplicationInfo().accessTokenId);
10286     }
10287 
10288     bool focused = false;
10289     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10290     auto connectManager = GetConnectManagerByUserId(userId);
10291     if (connectManager) {
10292         focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
10293             || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
10294     } else {
10295         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", userId);
10296     }
10297     if (!focused && userId != U0_USER_ID) {
10298         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check connectManager in user0");
10299         connectManager = GetConnectManagerByUserId(U0_USER_ID);
10300         if (connectManager) {
10301             focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
10302                 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
10303         } else {
10304             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: 0");
10305         }
10306     }
10307     isFocused = focused;
10308     TAG_LOGD(AAFwkTag::ABILITYMGR, "isFocused: %{public}d", isFocused);
10309     return ERR_OK;
10310 }
10311 
AddFreeInstallObserver(const sptr<IRemoteObject> & callerToken,const sptr<AbilityRuntime::IFreeInstallObserver> & observer)10312 int AbilityManagerService::AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken,
10313     const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
10314 {
10315     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10316     if (freeInstallManager_ == nullptr) {
10317         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
10318         return ERR_INVALID_VALUE;
10319     }
10320     return freeInstallManager_->AddFreeInstallObserver(callerToken, observer);
10321 }
10322 
IsValidMissionIds(const std::vector<int32_t> & missionIds,std::vector<MissionValidResult> & results)10323 int32_t AbilityManagerService::IsValidMissionIds(
10324     const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)
10325 {
10326     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
10327     auto missionlistMgr = GetMissionListManagerByUserId(userId);
10328     if (missionlistMgr == nullptr) {
10329         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionlistMgr is nullptr.");
10330         return ERR_INVALID_VALUE;
10331     }
10332 
10333     return missionlistMgr->IsValidMissionIds(missionIds, results);
10334 }
10335 
VerifyPermission(const std::string & permission,int pid,int uid)10336 int AbilityManagerService::VerifyPermission(const std::string &permission, int pid, int uid)
10337 {
10338     TAG_LOGI(AAFwkTag::ABILITYMGR, "permission=%{public}s, pid=%{public}d, uid=%{public}d",
10339         permission.c_str(),
10340         pid,
10341         uid);
10342     if (permission.empty()) {
10343         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission permission invalid");
10344         return CHECK_PERMISSION_FAILED;
10345     }
10346 
10347     auto bms = GetBundleManager();
10348     CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
10349 
10350     std::string bundleName;
10351     if (IN_PROCESS_CALL(bms->GetNameForUid(uid, bundleName)) != ERR_OK) {
10352         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get bundle name by uid");
10353         return CHECK_PERMISSION_FAILED;
10354     }
10355 
10356     int account = -1;
10357     DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, account);
10358     AppExecFwk::ApplicationInfo appInfo;
10359     if (!IN_PROCESS_CALL(bms->GetApplicationInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
10360         account, appInfo))) {
10361         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get application info");
10362         return CHECK_PERMISSION_FAILED;
10363     }
10364 
10365     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false);
10366     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
10367         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission %{public}d: PERMISSION_DENIED", appInfo.accessTokenId);
10368         return CHECK_PERMISSION_FAILED;
10369     }
10370 
10371     return ERR_OK;
10372 }
10373 
AcquireShareData(const int32_t & missionId,const sptr<IAcquireShareDataCallback> & shareData)10374 int32_t AbilityManagerService::AcquireShareData(
10375     const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)
10376 {
10377     TAG_LOGD(AAFwkTag::ABILITYMGR, "missionId is %{public}d.", missionId);
10378     CHECK_CALLER_IS_SYSTEM_APP;
10379     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
10380     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10381         auto uiAbilityManager = GetCurrentUIAbilityManager();
10382         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10383         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
10384     } else {
10385         auto missionListManager = GetCurrentMissionListManager();
10386         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
10387         abilityRecord = missionListManager->GetAbilityRecordByMissionId(missionId);
10388     }
10389     if (!abilityRecord) {
10390         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
10391         return ERR_INVALID_VALUE;
10392     }
10393     std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
10394     uniqueId_ = (uniqueId_ == INT_MAX) ? 0 : (uniqueId_ + 1);
10395     std::pair<int64_t, const sptr<IAcquireShareDataCallback>> shareDataPair =
10396         std::make_pair(abilityRecord->GetAbilityRecordId(), shareData);
10397     iAcquireShareDataMap_.emplace(uniqueId_, shareDataPair);
10398     abilityRecord->ShareData(uniqueId_);
10399     return ERR_OK;
10400 }
10401 
ShareDataDone(const sptr<IRemoteObject> & token,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)10402 int32_t AbilityManagerService::ShareDataDone(
10403     const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
10404 {
10405     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d.", resultCode, uniqueId);
10406     if (!VerificationAllToken(token)) {
10407         return ERR_INVALID_VALUE;
10408     }
10409     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10410     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record is nullptr.");
10411     if (!JudgeSelfCalled(abilityRecord)) {
10412         return CHECK_PERMISSION_FAILED;
10413     }
10414     CHECK_POINTER_AND_RETURN_LOG(eventHandler_, ERR_INVALID_VALUE, "fail to get abilityEventHandler.");
10415     eventHandler_->RemoveEvent(SHAREDATA_TIMEOUT_MSG, uniqueId);
10416     return GetShareDataPairAndReturnData(abilityRecord, resultCode, uniqueId, wantParam);
10417 }
10418 
NotifySaveAsResult(const Want & want,int resultCode,int requestCode)10419 int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCode, int requestCode)
10420 {
10421     TAG_LOGD(AAFwkTag::ABILITYMGR, "requestCode is %{public}d.", requestCode);
10422     CHECK_CALLER_IS_SYSTEM_APP;
10423 #ifdef WITH_DLP
10424     //caller check
10425     if (!DlpUtils::CheckCallerIsDlpManager(GetBundleManager())) {
10426         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller check failed");
10427         return CHECK_PERMISSION_FAILED;
10428     }
10429 #endif // WITH_DLP
10430     auto checkResult = AbilityUtil::CheckInstanceKey(want);
10431     if (checkResult != ERR_OK) {
10432         return checkResult;
10433     }
10434 
10435     for (const auto &item : startAbilityChain_) {
10436         if (item.second->GetHandlerName() == StartAbilitySandboxSavefile::handlerName_) {
10437             auto savefileHandler = (StartAbilitySandboxSavefile*)(item.second.get());
10438             savefileHandler->HandleResult(want, resultCode, requestCode);
10439             break;
10440         }
10441     }
10442     return ERR_OK;
10443 }
10444 
SetRootSceneSession(const sptr<IRemoteObject> & rootSceneSession)10445 void AbilityManagerService::SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)
10446 {
10447     if (!IsCallerSceneBoard()) {
10448         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10449         return;
10450     }
10451     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10452     CHECK_POINTER(uiAbilityManager);
10453     uiAbilityManager->SetRootSceneSession(rootSceneSession);
10454 }
10455 
CallUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isColdStart)10456 void AbilityManagerService::CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isColdStart)
10457 {
10458     if (!IsCallerSceneBoard()) {
10459         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10460         return;
10461     }
10462     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10463     CHECK_POINTER(uiAbilityManager);
10464     uiAbilityManager->CallUIAbilityBySCB(sessionInfo, isColdStart);
10465 }
10466 
SetSessionManagerService(const sptr<IRemoteObject> & sessionManagerService)10467 int32_t AbilityManagerService::SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)
10468 {
10469     if (!IsCallerSceneBoard()) {
10470         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10471         return ERR_WRONG_INTERFACE_CALL;
10472     }
10473 
10474     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10475     auto ret = Rosen::MockSessionManagerService::GetInstance().SetSessionManagerService(sessionManagerService);
10476     if (ret) {
10477         TAG_LOGD(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10478         return ERR_OK;
10479     }
10480     TAG_LOGE(AAFwkTag::ABILITYMGR, "SMS SetSessionManagerService return false.");
10481     return ERR_OK;
10482 }
10483 
CheckPrepareTerminateEnable()10484 bool AbilityManagerService::CheckPrepareTerminateEnable()
10485 {
10486     if (!isPrepareTerminateEnable_) {
10487         TAG_LOGD(AAFwkTag::ABILITYMGR, "Only support PC.");
10488         return false;
10489     }
10490     if (!AAFwk::PermissionVerification::GetInstance()->VerifyPrepareTerminatePermission()) {
10491         TAG_LOGD(AAFwkTag::ABILITYMGR, "failed, please apply permission ohos.permission.PREPARE_APP_TERMINATE");
10492         return false;
10493     }
10494     return true;
10495 }
10496 
StartSpecifiedAbilityBySCB(const Want & want)10497 void AbilityManagerService::StartSpecifiedAbilityBySCB(const Want &want)
10498 {
10499     if (!IsCallerSceneBoard()) {
10500         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10501         return;
10502     }
10503     int32_t appIndex = 0;
10504     if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex)) {
10505         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app clone index");
10506     }
10507     (void)AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
10508         GetUserId(), appIndex, nullptr);
10509     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10510     CHECK_POINTER(uiAbilityManager);
10511     uiAbilityManager->StartSpecifiedAbilityBySCB(want);
10512 }
10513 
RegisterIAbilityManagerCollaborator(int32_t type,const sptr<IAbilityManagerCollaborator> & impl)10514 int32_t AbilityManagerService::RegisterIAbilityManagerCollaborator(
10515     int32_t type, const sptr<IAbilityManagerCollaborator> &impl)
10516 {
10517     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10518     auto callingUid = IPCSkeleton::GetCallingUid();
10519     if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
10520         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
10521         return CHECK_PERMISSION_FAILED;
10522     }
10523     if (!CheckCollaboratorType(type)) {
10524         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator register failed, invalid type.");
10525         return ERR_INVALID_VALUE;
10526     }
10527     {
10528         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10529         collaboratorMap_[type] = impl;
10530     }
10531     return ERR_OK;
10532 }
10533 
UnregisterIAbilityManagerCollaborator(int32_t type)10534 int32_t AbilityManagerService::UnregisterIAbilityManagerCollaborator(int32_t type)
10535 {
10536     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10537     auto callingUid = IPCSkeleton::GetCallingUid();
10538     if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
10539         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
10540         return CHECK_PERMISSION_FAILED;
10541     }
10542     if (!CheckCollaboratorType(type)) {
10543         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator unregister failed, invalid type.");
10544         return ERR_INVALID_VALUE;
10545     }
10546     {
10547         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10548         collaboratorMap_.erase(type);
10549     }
10550     return ERR_OK;
10551 }
10552 
GetCollaborator(int32_t type)10553 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetCollaborator(int32_t type)
10554 {
10555     if (!CheckCollaboratorType(type)) {
10556         return nullptr;
10557     }
10558     {
10559         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10560         auto it = collaboratorMap_.find(type);
10561         if (it != collaboratorMap_.end()) {
10562             return it->second;
10563         }
10564     }
10565     return nullptr;
10566 }
10567 
CheckCollaboratorType(int32_t type)10568 bool AbilityManagerService::CheckCollaboratorType(int32_t type)
10569 {
10570     if (type != CollaboratorType::RESERVE_TYPE && type != CollaboratorType::OTHERS_TYPE) {
10571         return false;
10572     }
10573     return true;
10574 }
10575 
GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> & sessionInfo,std::shared_ptr<AbilityConnectManager> & connectManager,std::shared_ptr<AbilityRecord> & targetAbility)10576 void AbilityManagerService::GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo,
10577     std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility)
10578 {
10579     targetAbility = nullptr;
10580     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10581     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId=%{public}d", userId);
10582     connectManager = GetConnectManagerByUserId(userId);
10583     if (connectManager) {
10584         targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
10585     } else {
10586         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", userId);
10587     }
10588     if (targetAbility == nullptr && userId != U0_USER_ID) {
10589         TAG_LOGD(AAFwkTag::ABILITYMGR, "try to find UIExtension in user0");
10590         connectManager = GetConnectManagerByUserId(U0_USER_ID);
10591         if (connectManager) {
10592             targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
10593         } else {
10594             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: 0");
10595         }
10596     }
10597 }
10598 
RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)10599 int32_t AbilityManagerService::RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)
10600 {
10601     if (!IsCallerSceneBoard()) {
10602         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10603         return ERR_WRONG_INTERFACE_CALL;
10604     }
10605     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10606     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10607     return uiAbilityManager->RegisterStatusBarDelegate(delegate);
10608 }
10609 
KillProcessWithPrepareTerminate(const std::vector<int32_t> & pids)10610 int32_t AbilityManagerService::KillProcessWithPrepareTerminate(const std::vector<int32_t>& pids)
10611 {
10612     if (!IsCallerSceneBoard()) {
10613         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10614         return ERR_WRONG_INTERFACE_CALL;
10615     }
10616     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10617     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10618     return uiAbilityManager->TryPrepareTerminateByPids(pids);
10619 }
10620 
RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10621 int32_t AbilityManagerService::RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10622 {
10623     if (abilityAutoStartupService_ == nullptr) {
10624         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10625         return ERR_NO_INIT;
10626     }
10627     return abilityAutoStartupService_->RegisterAutoStartupSystemCallback(callback);
10628 }
10629 
UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10630 int32_t AbilityManagerService::UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10631 {
10632     if (abilityAutoStartupService_ == nullptr) {
10633         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10634         return ERR_NO_INIT;
10635     }
10636     return abilityAutoStartupService_->UnregisterAutoStartupSystemCallback(callback);
10637 }
10638 
SetApplicationAutoStartup(const AutoStartupInfo & info)10639 int32_t AbilityManagerService::SetApplicationAutoStartup(const AutoStartupInfo &info)
10640 {
10641     if (abilityAutoStartupService_ == nullptr) {
10642         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10643         return ERR_NO_INIT;
10644     }
10645     return abilityAutoStartupService_->SetApplicationAutoStartup(info);
10646 }
10647 
CancelApplicationAutoStartup(const AutoStartupInfo & info)10648 int32_t AbilityManagerService::CancelApplicationAutoStartup(const AutoStartupInfo &info)
10649 {
10650     if (abilityAutoStartupService_ == nullptr) {
10651         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10652         return ERR_NO_INIT;
10653     }
10654     return abilityAutoStartupService_->CancelApplicationAutoStartup(info);
10655 }
10656 
QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> & infoList)10657 int32_t AbilityManagerService::QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)
10658 {
10659     if (abilityAutoStartupService_ == nullptr) {
10660         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10661         return ERR_NO_INIT;
10662     }
10663     return abilityAutoStartupService_->QueryAllAutoStartupApplications(infoList, GetUserId());
10664 }
10665 
PrepareTerminateAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isTerminate)10666 int AbilityManagerService::PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)
10667 {
10668     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10669     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
10670     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
10671         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
10672         return ERR_INVALID_VALUE;
10673     }
10674 
10675     if (!IsCallerSceneBoard()) {
10676         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10677         return ERR_WRONG_INTERFACE_CALL;
10678     }
10679 
10680     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10681     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10682     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
10683     isTerminate = uiAbilityManager->PrepareTerminateAbility(abilityRecord);
10684 
10685     return ERR_OK;
10686 }
10687 
RegisterSessionHandler(const sptr<IRemoteObject> & object)10688 int AbilityManagerService::RegisterSessionHandler(const sptr<IRemoteObject> &object)
10689 {
10690     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
10691     if (!IsCallerSceneBoard()) {
10692         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10693         return ERR_WRONG_INTERFACE_CALL;
10694     }
10695     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10696     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10697     sptr<ISessionHandler> handler = iface_cast<ISessionHandler>(object);
10698     uiAbilityManager->SetSessionHandler(handler);
10699     return ERR_OK;
10700 }
10701 
CheckUserIdActive(int32_t userId)10702 bool AbilityManagerService::CheckUserIdActive(int32_t userId)
10703 {
10704     std::vector<int32_t> osActiveAccountIds;
10705     auto ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
10706         QueryActiveOsAccountIds(osActiveAccountIds);
10707     if (ret != ERR_OK) {
10708         TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryActiveOsAccountIds failed");
10709         return false;
10710     }
10711     if (osActiveAccountIds.empty()) {
10712         TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryActiveOsAccountIds empty");
10713         return false;
10714     }
10715     auto iter = std::find(osActiveAccountIds.begin(), osActiveAccountIds.end(), userId);
10716     if (iter == osActiveAccountIds.end()) {
10717         return false;
10718     }
10719     return true;
10720 }
10721 
CheckProcessOptions(const Want & want,const StartOptions & startOptions,int32_t userId)10722 int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const StartOptions &startOptions, int32_t userId)
10723 {
10724     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10725     if (startOptions.processOptions == nullptr ||
10726         !ProcessOptions::IsValidProcessMode(startOptions.processOptions->processMode)) {
10727         return ERR_OK;
10728     }
10729 
10730     TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability with process options.");
10731     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
10732     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
10733         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support process options.");
10734         return ERR_CAPABILITY_NOT_SUPPORT;
10735     }
10736 
10737     auto element = want.GetElement();
10738     if (element.GetAbilityName().empty() || want.GetAction().compare(ACTION_CHOOSE) == 0) {
10739         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not allow implicit start.");
10740         return ERR_NOT_ALLOW_IMPLICIT_START;
10741     }
10742 
10743     int32_t appIndex = 0;
10744     appIndex = !AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex) ? 0 : appIndex;
10745     if (!CheckCallingTokenId(element.GetBundleName(), userId, appIndex)) {
10746         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not self application.");
10747         return ERR_NOT_SELF_APPLICATION;
10748     }
10749 
10750     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10751     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10752 
10753     if (ProcessOptions::IsAttachToStatusBarMode(startOptions.processOptions->processMode) &&
10754         !uiAbilityManager->IsCallerInStatusBar()) {
10755         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not in status bar in attch to status bar mode.");
10756         return ERR_START_OPTIONS_CHECK_FAILED;
10757     }
10758 
10759     auto abilityRecords = uiAbilityManager->GetAbilityRecordsByName(element);
10760     if (!abilityRecords.empty() && abilityRecords[0] &&
10761         abilityRecords[0]->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::STANDARD) {
10762         TAG_LOGE(AAFwkTag::ABILITYMGR, "If it is not in STANDARD mode, repeated starts are not allowed");
10763         return ERR_ABILITY_ALREADY_RUNNING;
10764     }
10765 
10766     return ERR_OK;
10767 }
10768 
RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10769 int32_t AbilityManagerService::RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10770 {
10771     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10772     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10773         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10774         return CHECK_PERMISSION_FAILED;
10775     }
10776     return DelayedSingleton<AppScheduler>::GetInstance()->RegisterAppDebugListener(listener);
10777 }
10778 
UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10779 int32_t AbilityManagerService::UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10780 {
10781     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10782     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10783         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10784         return CHECK_PERMISSION_FAILED;
10785     }
10786     return DelayedSingleton<AppScheduler>::GetInstance()->UnregisterAppDebugListener(listener);
10787 }
10788 
ConnectInitAbilityDebugDeal()10789 std::shared_ptr<AbilityDebugDeal> AbilityManagerService::ConnectInitAbilityDebugDeal()
10790 {
10791     if (abilityDebugDeal_ != nullptr) {
10792         return abilityDebugDeal_;
10793     }
10794 
10795     std::unique_lock<ffrt::mutex> lock(abilityDebugDealLock_);
10796     if (abilityDebugDeal_ != nullptr) {
10797         return abilityDebugDeal_;
10798     }
10799 
10800     TAG_LOGD(AAFwkTag::ABILITYMGR, "Creat ability debug deal object.");
10801     abilityDebugDeal_ = std::make_shared<AbilityDebugDeal>();
10802     if (abilityDebugDeal_ == nullptr) {
10803         TAG_LOGE(AAFwkTag::ABILITYMGR, "Creat ability debug deal object failed.");
10804         return nullptr;
10805     }
10806 
10807     abilityDebugDeal_->RegisterAbilityDebugResponse();
10808     return abilityDebugDeal_;
10809 }
10810 
AttachAppDebug(const std::string & bundleName)10811 int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName)
10812 {
10813     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10814     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10815         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
10816         return ERR_NOT_DEVELOPER_MODE;
10817     }
10818 
10819     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10820         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10821         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10822         return CHECK_PERMISSION_FAILED;
10823     }
10824 
10825     ConnectInitAbilityDebugDeal();
10826     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->AttachAppDebug(bundleName));
10827 }
10828 
DetachAppDebug(const std::string & bundleName)10829 int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName)
10830 {
10831     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10832     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10833         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
10834         return ERR_NOT_DEVELOPER_MODE;
10835     }
10836 
10837     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10838         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10839         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10840         return CHECK_PERMISSION_FAILED;
10841     }
10842 
10843     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->DetachAppDebug(bundleName));
10844 }
10845 
ExecuteIntent(uint64_t key,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)10846 int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken,
10847     const InsightIntentExecuteParam &param)
10848 {
10849     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10850     auto paramPtr = std::make_shared<InsightIntentExecuteParam>(param);
10851     int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateParam(key, callerToken,
10852         paramPtr);
10853     if (ret != ERR_OK) {
10854         return ret;
10855     }
10856 
10857     Want want;
10858     ret = InsightIntentExecuteManager::GenerateWant(paramPtr, want);
10859     if (ret != ERR_OK) {
10860         return ret;
10861     }
10862 
10863     switch (param.executeMode_) {
10864         case AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND:
10865             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_FOREGROUND.");
10866             ret = StartAbilityWithInsightIntent(want);
10867             break;
10868         case AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND: {
10869             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_BACKGROUND.");
10870             ret = StartAbilityByCallWithInsightIntent(want, callerToken, param);
10871             break;
10872         }
10873         case AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY:
10874             TAG_LOGW(AAFwkTag::ABILITYMGR, "ExecuteMode UI_EXTENSION_ABILITY not supported.");
10875             ret = ERR_INVALID_OPERATION;
10876             break;
10877         case AppExecFwk::ExecuteMode::SERVICE_EXTENSION_ABILITY:
10878             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode SERVICE_EXTENSION_ABILITY.");
10879             ret = StartExtensionAbilityWithInsightIntent(want, AppExecFwk::ExtensionAbilityType::SERVICE);
10880             break;
10881         default:
10882             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ExecuteMode.");
10883             ret = ERR_INVALID_OPERATION;
10884             break;
10885     }
10886     if (ret == START_ABILITY_WAITING) {
10887         TAG_LOGD(AAFwkTag::ABILITYMGR, "Top ability is foregrounding. The intent will be queued for execution");
10888         ret = ERR_OK;
10889     }
10890     if (ret != ERR_OK) {
10891         DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->RemoveExecuteIntent(paramPtr->insightIntentId_);
10892     }
10893 
10894     TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteIntent done, ret: %{public}d.", ret);
10895     return ret;
10896 }
10897 
IsAbilityStarted(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord,const int32_t oriValidUserId)10898 bool AbilityManagerService::IsAbilityStarted(AbilityRequest &abilityRequest,
10899     std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)
10900 {
10901     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10902         TAG_LOGI(AAFwkTag::ABILITYMGR, "scene board is enable");
10903         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
10904         CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
10905         return uiAbilityManager->IsAbilityStarted(abilityRequest, targetRecord);
10906     }
10907 
10908     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10909     if (missionListMgr == nullptr) {
10910         return false;
10911     }
10912     return missionListMgr->IsAbilityStarted(abilityRequest, targetRecord);
10913 }
10914 
OnExecuteIntent(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord)10915 int32_t AbilityManagerService::OnExecuteIntent(AbilityRequest &abilityRequest,
10916     std::shared_ptr<AbilityRecord> &targetRecord)
10917 {
10918     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnExecuteIntent");
10919     if (targetRecord == nullptr || targetRecord->GetScheduler() == nullptr) {
10920         return ERR_INVALID_VALUE;
10921     }
10922     targetRecord->GetScheduler()->OnExecuteIntent(abilityRequest.want);
10923 
10924     return ERR_OK;
10925 }
10926 
StartAbilityWithInsightIntent(const Want & want,int32_t userId,int requestCode)10927 int32_t AbilityManagerService::StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)
10928 {
10929     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10930     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
10931     if (startWithAccount || IsCrossUserCall(userId)) {
10932         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
10933         CHECK_CALLER_IS_SYSTEM_APP;
10934     }
10935     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
10936     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
10937     EventInfo eventInfo = BuildEventInfo(want, userId);
10938     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
10939     int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
10940     if (ret != ERR_OK) {
10941         eventInfo.errCode = ret;
10942         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
10943     }
10944     return ret;
10945 }
10946 
StartExtensionAbilityWithInsightIntent(const Want & want,AppExecFwk::ExtensionAbilityType extensionType)10947 int32_t AbilityManagerService::StartExtensionAbilityWithInsightIntent(const Want &want,
10948     AppExecFwk::ExtensionAbilityType extensionType)
10949 {
10950     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10951     return StartExtensionAbilityInner(want, nullptr, DEFAULT_INVAL_VALUE, extensionType, true);
10952 }
10953 
StartAbilityByCallWithInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)10954 int32_t AbilityManagerService::StartAbilityByCallWithInsightIntent(const Want &want,
10955     const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam &param)
10956 {
10957     TAG_LOGI(AAFwkTag::ABILITYMGR, "call StartAbilityByCallWithInsightIntent.");
10958     sptr<IAbilityConnection> connect = sptr<AbilityBackgroundConnection>::MakeSptr();
10959     if (connect == nullptr) {
10960         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid connect.");
10961         return ERR_INVALID_VALUE;
10962     }
10963 
10964     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
10965     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
10966     AbilityRequest abilityRequest;
10967     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
10968     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
10969     abilityRequest.callerToken = callerToken;
10970     abilityRequest.startSetting = nullptr;
10971     abilityRequest.want = want;
10972     abilityRequest.connect = connect;
10973     int32_t result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
10974     if (result != ERR_OK) {
10975         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
10976         return result;
10977     }
10978     std::shared_ptr<AbilityRecord> targetRecord;
10979     int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
10980     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10981     if (IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId)) {
10982         TAG_LOGI(AAFwkTag::ABILITYMGR, "ability has already started");
10983         UpdateCallerInfo(abilityRequest.want, callerToken);
10984         result = OnExecuteIntent(abilityRequest, targetRecord);
10985     }  else {
10986         result = StartAbilityByCall(want, connect, callerToken);
10987     }
10988 
10989     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartAbilityByCallWithInsightIntent %{public}d", result);
10990     return result;
10991 }
10992 
IsAbilityControllerStart(const Want & want)10993 bool AbilityManagerService::IsAbilityControllerStart(const Want &want)
10994 {
10995     auto callingUid = IPCSkeleton::GetCallingUid();
10996     bool isBrokerCall = (callingUid == BROKER_UID || callingUid == BROKER_RESERVE_UID);
10997     if (isBrokerCall) {
10998         return IsAbilityControllerStart(want, want.GetBundle());
10999     }
11000     TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
11001     return true;
11002 }
11003 
ExecuteInsightIntentDone(const sptr<IRemoteObject> & token,uint64_t intentId,const InsightIntentExecuteResult & result)11004 int32_t AbilityManagerService::ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId,
11005     const InsightIntentExecuteResult &result)
11006 {
11007     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11008     auto abilityRecord = Token::GetAbilityRecordByToken(token);
11009     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
11010     if (!JudgeSelfCalled(abilityRecord)) {
11011         return CHECK_PERMISSION_FAILED;
11012     }
11013 
11014     // check send by same bundleName.
11015     std::string bundleNameStored = "";
11016     auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetBundleName(intentId, bundleNameStored);
11017     if (ret != ERR_OK) {
11018         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get matched bundleName failed, intentId: %{public}" PRIu64"", intentId);
11019         return ERR_INVALID_VALUE;
11020     }
11021 
11022     std::string bundleName = abilityRecord->GetAbilityInfo().bundleName;
11023     if (bundleNameStored != bundleName) {
11024         TAG_LOGE(AAFwkTag::ABILITYMGR,
11025             "BundleName %{public}s and %{public}s mismatch.", bundleName.c_str(), bundleNameStored.c_str());
11026         return ERR_INVALID_VALUE;
11027     }
11028 
11029     return DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
11030         intentId, result.innerErr, result);
11031 }
11032 
SetApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)11033 int32_t AbilityManagerService::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
11034 {
11035     if (abilityAutoStartupService_ == nullptr) {
11036         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
11037         return ERR_NO_INIT;
11038     }
11039     return abilityAutoStartupService_->SetApplicationAutoStartupByEDM(info, flag);
11040 }
11041 
CancelApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)11042 int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
11043 {
11044     if (abilityAutoStartupService_ == nullptr) {
11045         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
11046         return ERR_NO_INIT;
11047     }
11048     return abilityAutoStartupService_->CancelApplicationAutoStartupByEDM(info, flag);
11049 }
11050 
GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> & list)11051 int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)
11052 {
11053     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11054     CHECK_CALLER_IS_SYSTEM_APP;
11055     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
11056     if (!isPerm) {
11057         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
11058         return CHECK_PERMISSION_FAILED;
11059     }
11060 
11061     std::vector<AbilityRunningInfo> abilityRunningInfos;
11062     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11063         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11064         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11065         uiAbilityManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
11066     } else {
11067         auto missionListManager = GetCurrentMissionListManager();
11068         CHECK_POINTER_AND_RETURN(missionListManager, ERR_NULL_OBJECT);
11069         missionListManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
11070     }
11071 
11072     for (auto &info : abilityRunningInfos) {
11073         if (info.abilityState != AbilityState::FOREGROUND) {
11074             continue;
11075         }
11076 
11077         AppExecFwk::AbilityStateData abilityData;
11078         abilityData.bundleName = info.ability.GetBundleName();
11079         abilityData.moduleName = info.ability.GetModuleName();
11080         abilityData.abilityName = info.ability.GetAbilityName();
11081         abilityData.abilityState = info.abilityState;
11082         abilityData.pid = info.pid;
11083         abilityData.uid = info.uid;
11084         abilityData.abilityType = static_cast<int32_t>(AppExecFwk::AbilityType::PAGE);
11085         abilityData.appCloneIndex = info.appCloneIndex;
11086         AppExecFwk::ApplicationInfo appInfo;
11087         if (!StartAbilityUtils::GetApplicationInfo(abilityData.bundleName, GetUserId(), appInfo)) {
11088             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get applicationInfo through bundleName");
11089         } else if (appInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
11090             abilityData.isAtomicService = true;
11091         }
11092         list.push_back(abilityData);
11093     }
11094     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get foreground ui abilities end, list.size = %{public}zu.", list.size());
11095     return ERR_OK;
11096 }
11097 
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)11098 void AbilityManagerService::NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)
11099 {
11100     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
11101     if (collaborator == nullptr) {
11102         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator GetCollaborator is nullptr.");
11103         return;
11104     }
11105     collaborator->UpdateConfiguration(config, userId);
11106 }
11107 
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)11108 void AbilityManagerService::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
11109 {
11110     if (userController_ == nullptr) {
11111         TAG_LOGE(AAFwkTag::ABILITYMGR, "userController_ null");
11112         return;
11113     }
11114     auto currentUser = userController_->GetCurrentUserId();
11115     std::vector<AppExecFwk::BundleInfo> bundleInfosForU0;
11116     std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
11117     for (const auto &item: bundleInfos) {
11118         auto user = item.uid / BASE_USER_RANGE;
11119         if (user == U0_USER_ID) {
11120             bundleInfosForU0.push_back(item);
11121         } else if (user == currentUser) {
11122             bundleInfosForCurrentUser.push_back(item);
11123         }
11124     }
11125 
11126     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
11127         bundleInfosForU0, U0_USER_ID);
11128     if (!bundleInfosForU0.empty()) {
11129         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForU0);
11130     }
11131 
11132     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
11133         bundleInfosForCurrentUser, currentUser);
11134     if (!bundleInfosForCurrentUser.empty()) {
11135         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForCurrentUser);
11136     }
11137 }
11138 
NotifyAppPreCache(int32_t pid,int32_t userId)11139 void AbilityManagerService::NotifyAppPreCache(int32_t pid, int32_t userId)
11140 {
11141     ForceTerminateSerivceExtensionByPid(pid, userId);
11142 }
11143 
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> & abilityTokens)11144 void AbilityManagerService::OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens)
11145 {
11146     std::shared_ptr<AbilityRecord> abilityRecord;
11147     for (auto &token : abilityTokens) {
11148         abilityRecord = Token::GetAbilityRecordByToken(token);
11149         if (abilityRecord == nullptr) {
11150             continue;
11151         }
11152         TAG_LOGI(AAFwkTag::ABILITYMGR, "App OnRemoteDied, ability is %{public}s, app is %{public}s",
11153             abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
11154         abilityRecord->OnProcessDied();
11155     }
11156 }
11157 
OpenFile(const Uri & uri,uint32_t flag)11158 int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag)
11159 {
11160     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
11161     if (!IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission(
11162         uri, flag, accessTokenId))) {
11163         TAG_LOGE(AAFwkTag::ABILITYMGR, "premission check failed");
11164         return -1;
11165     }
11166     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
11167     if (collaborator == nullptr) {
11168         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator GetCollaborator is nullptr.");
11169         return ERR_COLLABORATOR_NOT_REGISTER;
11170     }
11171     return collaborator->OpenFile(uri, flag);
11172 }
11173 
GetDialogSessionInfo(const std::string & dialogSessionId,sptr<DialogSessionInfo> & dialogSessionInfo)11174 int AbilityManagerService::GetDialogSessionInfo(const std::string &dialogSessionId,
11175     sptr<DialogSessionInfo> &dialogSessionInfo)
11176 {
11177     CHECK_CALLER_IS_SYSTEM_APP;
11178     dialogSessionInfo = DialogSessionManager::GetInstance().GetDialogSessionInfo(dialogSessionId);
11179     if (dialogSessionInfo) {
11180         TAG_LOGD(AAFwkTag::ABILITYMGR, "success");
11181         return ERR_OK;
11182     }
11183     TAG_LOGD(AAFwkTag::ABILITYMGR, "fail");
11184     return INNER_ERR;
11185 }
11186 
SendDialogResult(const Want & want,const std::string & dialogSessionId,bool isAllowed)11187 int AbilityManagerService::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed)
11188 {
11189     CHECK_CALLER_IS_SYSTEM_APP;
11190     return DialogSessionManager::GetInstance().SendDialogResult(want, dialogSessionId, isAllowed);
11191 }
11192 
CreateCloneSelectorDialog(AbilityRequest & request,int32_t userId,const std::string & replaceWantString)11193 int AbilityManagerService::CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId,
11194     const std::string &replaceWantString)
11195 {
11196     CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
11197     return implicitStartProcessor_->ImplicitStartAbility(request, userId, 0, replaceWantString, true);
11198 }
11199 
RemoveSelectorIdentity(int32_t tokenId)11200 void AbilityManagerService::RemoveSelectorIdentity(int32_t tokenId)
11201 {
11202     CHECK_POINTER(implicitStartProcessor_);
11203     implicitStartProcessor_->RemoveIdentity(tokenId);
11204 }
11205 
SetTargetCloneIndexInSameBundle(const Want & want,sptr<IRemoteObject> callerToken)11206 void AbilityManagerService::SetTargetCloneIndexInSameBundle(const Want &want, sptr<IRemoteObject> callerToken)
11207 {
11208     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
11209     CHECK_POINTER(callerRecord);
11210     if (callerRecord->GetAbilityInfo().bundleName != want.GetElement().GetBundleName()) {
11211         TAG_LOGD(AAFwkTag::ABILITYMGR, "not the same bundle");
11212         return;
11213     }
11214     if (want.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY)) {
11215         TAG_LOGD(AAFwkTag::ABILITYMGR, "want with app clone index.");
11216         return;
11217     }
11218     int32_t appIndex = callerRecord->GetApplicationInfo().appIndex;
11219     if (appIndex >= 0 && appIndex < AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
11220         (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
11221     }
11222 }
11223 
RemoveLauncherDeathRecipient(int32_t userId)11224 void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId)
11225 {
11226     auto connectManager = GetConnectManagerByUserId(userId);
11227     if (connectManager == nullptr) {
11228         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
11229         return;
11230     }
11231     connectManager->RemoveLauncherDeathRecipient();
11232 }
11233 
CheckDebugAssertPermission()11234 int32_t AbilityManagerService::CheckDebugAssertPermission()
11235 {
11236     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11237     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11238     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
11239         TAG_LOGE(AAFwkTag::ABILITYMGR, "Product of assert fault dialog is not enabled.");
11240         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11241     }
11242     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
11243         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
11244         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11245     }
11246 
11247     auto bundleMgr = GetBundleManager();
11248     if (bundleMgr == nullptr) {
11249         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle manager instance is nullptr.");
11250         return ERR_INVALID_VALUE;
11251     }
11252     int32_t flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
11253     AppExecFwk::BundleInfo bundleInfo;
11254     auto ret = bundleMgr->GetBundleInfoForSelf(flags, bundleInfo);
11255     if (ret != ERR_OK) {
11256         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle Info failed.");
11257         return ret;
11258     }
11259     if (!bundleInfo.applicationInfo.debug) {
11260         TAG_LOGE(AAFwkTag::ABILITYMGR, "Non-debug version application.");
11261         return ERR_INVALID_VALUE;
11262     }
11263     return ERR_OK;
11264 }
11265 
SetResidentProcessEnabled(const std::string & bundleName,bool enable)11266 int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable)
11267 {
11268     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11269     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) {
11270         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
11271         return ERR_NOT_SYSTEM_APP;
11272     }
11273 
11274     auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
11275     if (residentProcessManager == nullptr) {
11276         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get resident proces mgr is nullptr");
11277         return INNER_ERR;
11278     }
11279 
11280     std::string callerName;
11281     int32_t uid = 0;
11282     auto callerPid = IPCSkeleton::GetCallingPid();
11283     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
11284     if (callerName.empty()) {
11285         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to obtain caller name.");
11286         return INNER_ERR;
11287     }
11288 
11289     return residentProcessManager->SetResidentProcessEnabled(bundleName, callerName, enable);
11290 }
11291 
CloseAssertDialog(const std::string & assertSessionId)11292 void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId)
11293 {
11294     TAG_LOGD(AAFwkTag::ABILITYMGR, "Close assert fault dialog begin.");
11295     auto validUserId = GetUserId();
11296     auto connectManager = GetConnectManagerByUserId(validUserId);
11297     if (connectManager == nullptr) {
11298         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11299         return;
11300     }
11301 
11302     connectManager->CloseAssertDialog(assertSessionId);
11303 }
11304 
RequestAssertFaultDialog(const sptr<IRemoteObject> & callback,const AAFwk::WantParams & wantParams)11305 int32_t AbilityManagerService::RequestAssertFaultDialog(
11306     const sptr<IRemoteObject> &callback, const AAFwk::WantParams &wantParams)
11307 {
11308     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog begin.");
11309     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11310     auto checkRet = CheckDebugAssertPermission();
11311     if (checkRet != ERR_OK) {
11312         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check debug assert permission error.");
11313         return checkRet;
11314     }
11315     sptr<IRemoteObject> remoteCallback = callback;
11316     if (remoteCallback == nullptr) {
11317         TAG_LOGE(AAFwkTag::ABILITYMGR, "Params remote callback is nullptr");
11318         return ERR_INVALID_VALUE;
11319     }
11320     auto debugDeal = ConnectInitAbilityDebugDeal();
11321     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
11322     if (sysDialog == nullptr || debugDeal == nullptr) {
11323         TAG_LOGE(AAFwkTag::ABILITYMGR, "sysDialog or debugDeal is nullptr.");
11324         return ERR_INVALID_VALUE;
11325     }
11326     Want want;
11327     if (!sysDialog->GetAssertFaultDialogWant(want)) {
11328         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get assert fault dialog want failed.");
11329         return ERR_INVALID_VALUE;
11330     }
11331     uint64_t assertFaultSessionId = reinterpret_cast<uint64_t>(remoteCallback.GetRefPtr());
11332     want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, std::to_string(assertFaultSessionId));
11333     want.SetParam(ASSERT_FAULT_DETAIL, wantParams.GetStringParam(ASSERT_FAULT_DETAIL));
11334     auto &connection = AbilityRuntime::ModalSystemAssertUIExtension::GetInstance();
11335     want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
11336     if (!IN_PROCESS_CALL(connection.CreateModalUIExtension(want))) {
11337         TAG_LOGE(AAFwkTag::ABILITYMGR, "Create modal ui extension failed.");
11338         return ERR_INVALID_VALUE;
11339     }
11340     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11341     if (callbackDeathMgr == nullptr) {
11342         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callback death manager instance is nullptr.");
11343         return ERR_INVALID_VALUE;
11344     }
11345     auto callbackTask = [weak = weak_from_this()] (const std::string &assertSessionId) {
11346         auto abilityMgr = weak.lock();
11347         if (abilityMgr == nullptr) {
11348             TAG_LOGE(AAFwkTag::ABILITYMGR, "ability manager instance is nullptr.");
11349             return;
11350         }
11351         abilityMgr->CloseAssertDialog(assertSessionId);
11352     };
11353     callbackDeathMgr->AddAssertFaultCallback(remoteCallback, callbackTask);
11354     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog end.");
11355     return ERR_OK;
11356 }
11357 
NotifyDebugAssertResult(uint64_t assertFaultSessionId,AAFwk::UserStatus userStatus)11358 int32_t AbilityManagerService::NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus)
11359 {
11360     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11361     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
11362         TAG_LOGE(AAFwkTag::ABILITYMGR, "Product of assert fault dialog is not enabled.");
11363         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11364     }
11365 
11366     CHECK_CALLER_IS_SYSTEM_APP;
11367     auto permissionSA = PermissionVerification::GetInstance();
11368     if (permissionSA == nullptr) {
11369         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification instance is nullptr.");
11370         return ERR_INVALID_VALUE;
11371     }
11372     if (!permissionSA->VerifyCallingPermission(PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT)) {
11373         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
11374             PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT);
11375         return ERR_PERMISSION_DENIED;
11376     }
11377 
11378     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11379     if (callbackDeathMgr == nullptr) {
11380         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callback death manager instance is nullptr.");
11381         return ERR_INVALID_VALUE;
11382     }
11383     callbackDeathMgr->CallAssertFaultCallback(assertFaultSessionId, userStatus);
11384     return ERR_OK;
11385 }
11386 
UpdateSessionInfoBySCB(std::list<SessionInfo> & sessionInfos,int32_t userId,std::vector<int32_t> & sessionIds)11387 int32_t AbilityManagerService::UpdateSessionInfoBySCB(std::list<SessionInfo> &sessionInfos, int32_t userId,
11388     std::vector<int32_t> &sessionIds)
11389 {
11390     if (!IsCallerSceneBoard()) {
11391         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
11392         return ERR_WRONG_INTERFACE_CALL;
11393     }
11394     TAG_LOGI(AAFwkTag::ABILITYMGR, "The sceneboard is being restored.");
11395     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11396     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11397     return uiAbilityManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds);
11398 }
11399 
CheckSenderWantInfo(int32_t callerUid,const WantSenderInfo & wantSenderInfo)11400 bool AbilityManagerService::CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)
11401 {
11402     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
11403         auto bms = GetBundleManager();
11404         CHECK_POINTER_AND_RETURN(bms, false);
11405 
11406         std::string bundleName;
11407         if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
11408             TAG_LOGE(AAFwkTag::ABILITYMGR, "Get Bundle Name failed.");
11409             return false;
11410         }
11411         if (wantSenderInfo.bundleName != bundleName) {
11412             TAG_LOGE(AAFwkTag::ABILITYMGR, "wantSender bundleName check failed");
11413             return false;
11414         }
11415     }
11416     return true;
11417 }
11418 
CheckCallerIsDmsProcess()11419 bool AbilityManagerService::CheckCallerIsDmsProcess()
11420 {
11421     Security::AccessToken::NativeTokenInfo nativeTokenInfo;
11422     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
11423     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
11424     int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
11425     if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
11426         result != ERR_OK || nativeTokenInfo.processName != DMS_PROCESS_NAME) {
11427         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not dms");
11428         return false;
11429     }
11430     return true;
11431 }
11432 
GenerateEmbeddableUIAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)11433 int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest(
11434     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
11435 {
11436     int32_t screenMode = want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
11437     int32_t result = ERR_OK;
11438     if (screenMode == AAFwk::EMBEDDED_FULL_SCREEN_MODE) {
11439         result = GenerateAbilityRequest(want, -1, request, callerToken, userId);
11440         request.abilityInfo.isModuleJson = true;
11441         request.abilityInfo.isStageBasedModel = true;
11442         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
11443         request.abilityInfo.extensionAbilityType = AppExecFwk::ExtensionAbilityType::UI;
11444         struct timespec time = {0, 0};
11445         clock_gettime(CLOCK_MONOTONIC, &time);
11446         int64_t times = static_cast<int64_t>(time.tv_sec);
11447         request.abilityInfo.process = request.abilityInfo.bundleName + PROCESS_SUFFIX + std::to_string(times);
11448     } else {
11449         result = GenerateExtensionAbilityRequest(want, request, callerToken, userId);
11450     }
11451     return result;
11452 }
11453 
WaitBootAnimationStart()11454 void AbilityManagerService::WaitBootAnimationStart()
11455 {
11456     char value[BOOTEVENT_BOOT_ANIMATION_READY_SIZE] = "";
11457     int32_t ret = GetParameter(BOOTEVENT_BOOT_ANIMATION_READY, "", value,
11458         BOOTEVENT_BOOT_ANIMATION_READY_SIZE);
11459     if (ret > 0 && !std::strcmp(value, "false")) {
11460         // Get new param success and new param is not ready, wait the new param.
11461         WaitParameter(BOOTEVENT_BOOT_ANIMATION_READY, "true",
11462             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11463     } else if (ret <= 0 || !std::strcmp(value, "")) {
11464         // Get new param failed or new param is not set, wait the old param.
11465         WaitParameter(BOOTEVENT_BOOT_ANIMATION_STARTED, "true",
11466             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11467     }
11468     // other, the animation is ready, not wait.
11469 }
11470 
GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,UIExtensionSessionInfo & uiExtensionSessionInfo,int32_t userId)11471 int32_t AbilityManagerService::GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,
11472     UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId)
11473 {
11474     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11475     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11476     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11477 
11478     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11479         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
11480         return ERR_PERMISSION_DENIED;
11481     }
11482 
11483     auto validUserId = GetValidUserId(userId);
11484     auto connectManager = GetConnectManagerByUserId(validUserId);
11485     if (connectManager == nullptr) {
11486         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11487         return ERR_INVALID_VALUE;
11488     }
11489 
11490     auto ret = connectManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo);
11491     if (ret != ERR_OK) {
11492         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get ui extension session info failed.");
11493         return ret;
11494     }
11495 
11496     return ERR_OK;
11497 }
11498 
RestartApp(const AAFwk::Want & want,bool isAppRecovery)11499 int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want, bool isAppRecovery)
11500 {
11501     TAG_LOGI(AAFwkTag::ABILITYMGR, "RestartApp, isAppRecovery: %{public}d", isAppRecovery);
11502     auto appIndex = GetAppIndex(want);
11503     int result = CheckRestartAppWant(want, appIndex);
11504     if (result != ERR_OK) {
11505         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckRestartAppWant error.");
11506         return result;
11507     }
11508 
11509     int32_t callerUid = IPCSkeleton::GetCallingUid();
11510     int64_t now = time(nullptr);
11511     if (!isAppRecovery && RestartAppManager::GetInstance().IsRestartAppFrequent(callerUid, now)) {
11512         return AAFwk::ERR_RESTART_APP_FREQUENT;
11513     }
11514 
11515     bool isForegroundToRestartApp = RestartAppManager::GetInstance().IsForegroundToRestartApp();
11516     if (!isForegroundToRestartApp) {
11517         TAG_LOGE(AAFwkTag::ABILITYMGR, "RestartApp, IsForegroundToRestartApp failed.");
11518         return AAFwk::NOT_TOP_ABILITY;
11519     }
11520 
11521     int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11522     result = SignRestartAppFlag(userId, callerUid, isAppRecovery);
11523     if (result != ERR_OK) {
11524         TAG_LOGE(AAFwkTag::ABILITYMGR, "SignRestartAppFlag error.");
11525         return result;
11526     }
11527     result = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->KillApplicationSelf(false, "RestartApp");
11528     if (result != ERR_OK) {
11529         TAG_LOGE(AAFwkTag::ABILITYMGR, "KillApplicationSelf error.");
11530         return result;
11531     }
11532 
11533     TAG_LOGD(AAFwkTag::ABILITYMGR, "RestartApp, start ability without CheckCallAbilityPermission.");
11534     (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
11535     result = StartAbilityWrap(want, nullptr,
11536         DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, 0, isForegroundToRestartApp);
11537     if (result != ERR_OK) {
11538         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility error.");
11539         return result;
11540     }
11541     if (!isAppRecovery) {
11542         RestartAppManager::GetInstance().AddRestartAppHistory(callerUid, now);
11543     }
11544     return result;
11545 }
11546 
GetAppIndex(const Want & want)11547 int32_t AbilityManagerService::GetAppIndex(const Want& want)
11548 {
11549     int32_t appIndex = want.GetIntParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, -1);
11550     if (appIndex == -1) {
11551         auto appMgr = AppMgrUtil::GetAppMgr();
11552         if (appMgr == nullptr) {
11553             TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
11554             return appIndex;
11555         }
11556         auto callingPid = IPCSkeleton::GetCallingPid();
11557         auto ret = IN_PROCESS_CALL(appMgr->GetAppIndexByPid(callingPid, appIndex));
11558         if (ret != ERR_OK) {
11559             TAG_LOGE(AAFwkTag::ABILITYMGR, "appMgr GetAppIndexByPid error");
11560         }
11561     }
11562     return appIndex;
11563 }
11564 
CheckRestartAppWant(const AAFwk::Want & want,int32_t appIndex)11565 int32_t AbilityManagerService::CheckRestartAppWant(const AAFwk::Want &want, int32_t appIndex)
11566 {
11567     std::string bundleName = want.GetElement().GetBundleName();
11568     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11569     if (!CheckCallingTokenId(bundleName, userId, appIndex)) {
11570         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not itself called, not allowed.");
11571         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11572     }
11573 
11574     auto bms = GetBundleManager();
11575     CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
11576     auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
11577     AppExecFwk::AbilityInfo abilityInfo;
11578     auto queryResult = IN_PROCESS_CALL(
11579         bms->QueryCloneAbilityInfo(want.GetElement(), abilityInfoFlag, appIndex, abilityInfo, userId));
11580     if (queryResult != ERR_OK || abilityInfo.name.empty() || abilityInfo.bundleName.empty() ||
11581         abilityInfo.type != AbilityType::PAGE) {
11582         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability is invalid or not UIAbility.");
11583         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11584     }
11585     return ERR_OK;
11586 }
11587 
SignRestartAppFlag(int32_t userId,int32_t uid,bool isAppRecovery)11588 int32_t AbilityManagerService::SignRestartAppFlag(int32_t userId, int32_t uid, bool isAppRecovery)
11589 {
11590     auto appMgr = GetAppMgr();
11591     if (appMgr == nullptr) {
11592         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
11593         return ERR_INVALID_VALUE;
11594     }
11595     auto ret = IN_PROCESS_CALL(appMgr->SignRestartAppFlag(uid));
11596     if (ret != ERR_OK) {
11597         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppMgr SignRestartAppFlag error");
11598         return ret;
11599     }
11600 
11601     auto connectManager = GetConnectManagerByUserId(userId);
11602     connectManager->SignRestartAppFlag(uid);
11603     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11604         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
11605         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11606         uiAbilityManager->SignRestartAppFlag(uid, isAppRecovery);
11607         return ERR_OK;
11608     }
11609     auto missionListManager = GetMissionListManagerByUserId(userId);
11610     if (missionListManager == nullptr) {
11611         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is nullptr. userId:%{public}d", userId);
11612         return ERR_INVALID_VALUE;
11613     }
11614     missionListManager->SignRestartAppFlag(uid);
11615     return ERR_OK;
11616 }
11617 
GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,UIExtensionHostInfo & hostInfo,int32_t userId)11618 int32_t AbilityManagerService::GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,
11619     UIExtensionHostInfo &hostInfo, int32_t userId)
11620 {
11621     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11622     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11623     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11624 
11625     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11626         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
11627         return ERR_PERMISSION_DENIED;
11628     }
11629 
11630     auto callerRecord = GetUIExtensionRootCaller(token, userId);
11631     if (callerRecord == nullptr) {
11632         TAG_LOGE(AAFwkTag::UI_EXT, "Get root host info failed.");
11633         return ERR_INVALID_VALUE;
11634     }
11635 
11636     hostInfo.elementName_ = callerRecord->GetElementName();
11637     TAG_LOGD(AAFwkTag::UI_EXT, "Root host uri: %{public}s.", hostInfo.elementName_.GetURI().c_str());
11638     return ERR_OK;
11639 }
11640 
GetUIExtensionRootCaller(const sptr<IRemoteObject> token,int32_t userId)11641 std::shared_ptr<AbilityRecord> AbilityManagerService::GetUIExtensionRootCaller(const sptr<IRemoteObject> token,
11642     int32_t userId)
11643 {
11644     auto validUserId = GetValidUserId(userId);
11645     auto connectManager = GetConnectManagerByUserId(validUserId);
11646     if (connectManager == nullptr) {
11647         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11648         return nullptr;
11649     }
11650 
11651     auto callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11652     if (callerRecord == nullptr && validUserId != U0_USER_ID) {
11653         connectManager = GetConnectManagerByUserId(U0_USER_ID);
11654         if (connectManager == nullptr) {
11655             TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", U0_USER_ID);
11656             return nullptr;
11657         }
11658         callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11659     }
11660 
11661     return callerRecord;
11662 }
11663 
IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken,const std::string & appId)11664 bool AbilityManagerService::IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken, const std::string &appId)
11665 {
11666     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11667     if (!AppUtils::GetInstance().IsLaunchEmbededUIAbility()) {
11668         TAG_LOGE(AAFwkTag::ABILITYMGR, "device type is not allowd.");
11669         return false;
11670     }
11671     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
11672     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
11673     if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
11674         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is not hap.");
11675         return false;
11676     }
11677     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11678     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11679     auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
11680     if (callerAbility == nullptr) {
11681         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is invalid.");
11682         return false;
11683     }
11684     if (callerAbility->GetApplicationInfo().accessTokenId != accessTokenId) {
11685         TAG_LOGE(AAFwkTag::ABILITYMGR, "The callerToken does not belong to the caller.");
11686         return false;
11687     }
11688     if (!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag()) {
11689         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller not foreground.");
11690         return false;
11691     }
11692     std::string bundleName = ATOMIC_SERVICE_PREFIX + appId;
11693     Want want;
11694     want.SetBundle(bundleName);
11695     want.SetParam("send_to_erms_embedded", 1);
11696     int32_t ret = freeInstallManager_->StartFreeInstall(want, GetUserId(), 0, callerToken, false);
11697     if (ret != ERR_OK) {
11698         TAG_LOGE(AAFwkTag::ABILITYMGR, "The target is not allowed to free install.");
11699         return false;
11700     }
11701     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
11702     auto erms = std::make_shared<EcologicalRuleInterceptor>();
11703     return erms->DoProcess(want, GetUserId());
11704 }
11705 
ShouldPreventStartAbility(const AbilityRequest & abilityRequest)11706 bool AbilityManagerService::ShouldPreventStartAbility(const AbilityRequest &abilityRequest)
11707 {
11708     std::shared_ptr<AbilityRecord> abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11709     if (abilityRecord == nullptr) {
11710         TAG_LOGD(AAFwkTag::ABILITYMGR, "No matched token pass");
11711         return false;
11712     }
11713     auto abilityInfo = abilityRequest.abilityInfo;
11714     auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
11715     PrintStartAbilityInfo(callerAbilityInfo, abilityInfo);
11716     if (abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD < API12) {
11717         TAG_LOGD(AAFwkTag::ABILITYMGR, "API version %{public}d pass",
11718             abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD);
11719         return false;
11720     }
11721     bool continuousFlag = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
11722     if (abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::DATASHARE &&
11723         abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
11724         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process did not call service or datashare extension Pass");
11725         return false;
11726     }
11727     if (abilityInfo.applicationInfo.uid == IPCSkeleton::GetCallingUid()) {
11728         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in same bundle Pass");
11729         return false;
11730     }
11731     if (callerAbilityInfo.type != AppExecFwk::AbilityType::PAGE) {
11732         TAG_LOGD(AAFwkTag::ABILITYMGR, "Is not UI Ability Pass");
11733         return false;
11734     }
11735     if (abilityRecord->GetAbilityState() != AAFwk::AbilityState::BACKGROUND) {
11736         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is not on background Pass");
11737         return false;
11738     }
11739     if (continuousFlag) {
11740         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has continuous task Pass");
11741         return false;
11742     }
11743     if (IsInWhiteList(callerAbilityInfo.bundleName, abilityInfo.bundleName, abilityInfo.name)) {
11744         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in white list Pass");
11745         return false;
11746     }
11747     if(!IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->
11748         IsProcessContainsOnlyUIAbility(abilityRecord->GetPid()))) {
11749         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has other extension except UIAbility, pass");
11750         return false;
11751     }
11752     TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension %{public}s.",
11753         abilityRecord->GetURI().c_str());
11754     ReportPreventStartAbilityResult(callerAbilityInfo, abilityInfo);
11755     return true;
11756 }
11757 
PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo,AppExecFwk::AbilityInfo calledInfo)11758 void AbilityManagerService::PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo, AppExecFwk::AbilityInfo calledInfo)
11759 {
11760     TAG_LOGD(AAFwkTag::ABILITYMGR, "calledAbilityInfo toString: "
11761         "calledUid is: %{public}d, "
11762         "name is: %{public}s, "
11763         "bundleName is: %{public}s, "
11764         "type is: %{public}d, "
11765         "extensionAbilityType is: %{public}d, "
11766         "moduleName is: %{public}s, "
11767         "applicationName is: %{public}s",
11768         calledInfo.applicationInfo.uid,
11769         calledInfo.name.c_str(),
11770         calledInfo.bundleName.c_str(),
11771         static_cast<int32_t>(calledInfo.type),
11772         static_cast<int32_t>(calledInfo.extensionAbilityType),
11773         calledInfo.moduleName.c_str(),
11774         calledInfo.applicationName.c_str());
11775 
11776 
11777     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerAbilityInfo toString: "
11778         "callerUid is: %{public}d, "
11779         "callerPid is: %{public}d, "
11780         "name is: %{public}s, "
11781         "bundleName is: %{public}s, "
11782         "type is: %{public}d, "
11783         "extensionAbilityType is: %{public}d, "
11784         "moduleName is: %{public}s, "
11785         "applicationName is: %{public}s",
11786         IPCSkeleton::GetCallingUid(),
11787         IPCSkeleton::GetCallingPid(),
11788         callerInfo.name.c_str(),
11789         callerInfo.bundleName.c_str(),
11790         static_cast<int32_t>(callerInfo.type),
11791         static_cast<int32_t>(callerInfo.extensionAbilityType),
11792         callerInfo.moduleName.c_str(),
11793         callerInfo.applicationName.c_str());
11794 }
11795 
ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo & callerAbilityInfo,const AppExecFwk::AbilityInfo & abilityInfo)11796 void AbilityManagerService::ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo,
11797     const AppExecFwk::AbilityInfo &abilityInfo)
11798 {
11799     int32_t callerUid = IPCSkeleton::GetCallingUid();
11800     int32_t callerPid = IPCSkeleton::GetCallingPid();
11801     int32_t extensionAbilityType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
11802     TAG_LOGD(AAFwkTag::ABILITYMGR,
11803         "Prevent start ability debug log CALLER_BUNDLE_NAME %{public}s CALLEE_BUNDLE_NAME"
11804         "%{public}s ABILITY_NAME %{public}s",
11805         callerAbilityInfo.bundleName.c_str(), abilityInfo.name.c_str(), abilityInfo.name.c_str());
11806     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "PREVENT_START_ABILITY", HiSysEvent::EventType::BEHAVIOR,
11807         "CALLER_UID", callerUid,
11808         "CALLER_PID", callerPid,
11809         "CALLER_PROCESS_NAME", callerAbilityInfo.process,
11810         "CALLER_BUNDLE_NAME", callerAbilityInfo.bundleName,
11811         "CALLEE_BUNDLE_NAME", abilityInfo.bundleName,
11812         "CALLEE_PROCESS_NAME", abilityInfo.process,
11813         "EXTENSION_ABILITY_TYPE", extensionAbilityType,
11814         "ABILITY_NAME", abilityInfo.name);
11815 }
11816 
IsInWhiteList(const std::string & callerBundleName,const std::string & calleeBundleName,const std::string & calleeAbilityName)11817 bool AbilityManagerService::IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName,
11818     const std::string &calleeAbilityName)
11819 {
11820     std::lock_guard<std::mutex> locker(whiteListMutex_);
11821     std::map<std::string, std::list<std::string>>::iterator iter = whiteListMap_.find(callerBundleName);
11822     std::string uri = calleeBundleName + "/" + calleeAbilityName;
11823     if (iter != whiteListMap_.end()) {
11824         if (std::find(std::begin(iter->second), std::end(iter->second), uri) != std::end(iter->second)) {
11825             return true;
11826         }
11827     }
11828     std::list<std::string>::iterator it = std::find(exportWhiteList_.begin(), exportWhiteList_.end(), uri);
11829     if (it != exportWhiteList_.end()) {
11830         return true;
11831     }
11832     return false;
11833 }
11834 
ParseJsonFromBoot(const std::string & relativePath)11835 bool AbilityManagerService::ParseJsonFromBoot(const std::string &relativePath)
11836 {
11837     nlohmann::json jsonObj;
11838     std::string absolutePath = GetConfigFileAbsolutePath(relativePath);
11839     if (ParseJsonValueFromFile(jsonObj, absolutePath) != ERR_OK) {
11840         return false;
11841     }
11842     std::lock_guard<std::mutex> locker(whiteListMutex_);
11843     nlohmann::json whiteListJsonList = jsonObj[WHITE_LIST];
11844     for (const auto& [key, value] : whiteListJsonList.items()) {
11845         if (!value.is_array()) {
11846             continue;
11847         }
11848         whiteListMap_.emplace(key, std::list<std::string>());
11849         for (const auto& it : value) {
11850             if (it.is_string()) {
11851                 whiteListMap_[key].push_back(it);
11852             }
11853         }
11854     }
11855     if (!jsonObj.contains("exposed_white_list")) {
11856         return false;
11857     }
11858     nlohmann::json exportWhiteJsonList = jsonObj["exposed_white_list"];
11859     for (const auto& it : exportWhiteJsonList) {
11860         if (it.is_string()) {
11861             exportWhiteList_.push_back(it);
11862         }
11863     }
11864     return true;
11865 }
11866 
GetConfigFileAbsolutePath(const std::string & relativePath)11867 std::string AbilityManagerService::GetConfigFileAbsolutePath(const std::string &relativePath)
11868 {
11869     if (relativePath.empty()) {
11870         TAG_LOGE(AAFwkTag::ABILITYMGR, "relativePath is empty");
11871         return "";
11872     }
11873     char buf[PATH_MAX];
11874     char *tmpPath = GetOneCfgFile(relativePath.c_str(), buf, PATH_MAX);
11875     char absolutePath[PATH_MAX] = {0};
11876     if (!tmpPath || strlen(tmpPath) > PATH_MAX || !realpath(tmpPath, absolutePath)) {
11877         TAG_LOGE(AAFwkTag::ABILITYMGR, "get file fail.");
11878         return "";
11879     }
11880     return std::string(absolutePath);
11881 }
11882 
ParseJsonValueFromFile(nlohmann::json & value,const std::string & filePath)11883 int32_t AbilityManagerService::ParseJsonValueFromFile(nlohmann::json &value, const std::string &filePath)
11884 {
11885     std::ifstream fin;
11886     std::string realPath;
11887     if (!ConvertFullPath(filePath, realPath)) {
11888         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get real path failed");
11889         return ERR_INVALID_VALUE;
11890     }
11891     fin.open(realPath, std::ios::in);
11892     if (!fin.is_open()) {
11893         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot open file %{private}s", realPath.c_str());
11894         return ERR_INVALID_VALUE;
11895     }
11896     char buffer[MAX_BUFFER];
11897     std::ostringstream os;
11898     while (fin.getline(buffer, MAX_BUFFER)) {
11899         os << buffer;
11900     }
11901     const std::string data = os.str();
11902     value = nlohmann::json::parse(data, nullptr, false);
11903     if (value.is_discarded()) {
11904         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed due to data is discarded");
11905         return ERR_INVALID_VALUE;
11906     }
11907     return ERR_OK;
11908 }
11909 
ConvertFullPath(const std::string & partialPath,std::string & fullPath)11910 bool AbilityManagerService::ConvertFullPath(const std::string& partialPath, std::string& fullPath)
11911 {
11912     if (partialPath.empty() || partialPath.length() >= PATH_MAX) {
11913         return false;
11914     }
11915     char tmpPath[PATH_MAX] = {0};
11916     if (realpath(partialPath.c_str(), tmpPath) == nullptr) {
11917         return false;
11918     }
11919     fullPath = tmpPath;
11920     return true;
11921 }
11922 
StartShortcut(const Want & want,const StartOptions & startOptions)11923 int32_t AbilityManagerService::StartShortcut(const Want &want, const StartOptions &startOptions)
11924 {
11925     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11926     if (!PermissionVerification::GetInstance()->IsSystemAppCall()) {
11927         TAG_LOGE(AAFwkTag::ABILITYMGR, "non-system app calling system api.");
11928         return ERR_NOT_SYSTEM_APP;
11929     }
11930     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
11931         PermissionConstants::PERMISSION_START_SHORTCUT)) {
11932         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
11933             PermissionConstants::PERMISSION_START_SHORTCUT);
11934         return ERR_PERMISSION_DENIED;
11935     }
11936     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
11937     return StartUIAbilityForOptionWrap(want, startOptions, nullptr, false, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE,
11938         0, false, true);
11939 }
11940 
GetAbilityStateByPersistentId(int32_t persistentId,bool & state)11941 int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentId, bool &state)
11942 {
11943     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11944     if (!CheckCallerIsDmsProcess()) {
11945         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetAbilityStateByPersistentId, caller is not dms.");
11946         return ERR_PERMISSION_DENIED;
11947     }
11948 
11949     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11950         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11951         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11952         return uiAbilityManager->GetAbilityStateByPersistentId(persistentId, state);
11953     }
11954     TAG_LOGE(AAFwkTag::ABILITYMGR, "GetAbilityStateByPersistentId, mission not have persistent id.");
11955     return INNER_ERR;
11956 }
11957 
TransferAbilityResultForExtension(const sptr<IRemoteObject> & callerToken,int32_t resultCode,const Want & want)11958 int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptr<IRemoteObject> &callerToken,
11959     int32_t resultCode, const Want &want)
11960 {
11961     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11962     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
11963     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
11964     if (!JudgeSelfCalled(abilityRecord)) {
11965         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller mismatch.");
11966         return ERR_INVALID_VALUE;
11967     }
11968     auto type = abilityRecord->GetAbilityInfo().type;
11969     if (type != AppExecFwk::AbilityType::EXTENSION) {
11970         TAG_LOGE(AAFwkTag::ABILITYMGR, "type is not uiextension.");
11971         return ERR_INVALID_VALUE;
11972     }
11973     // save result to caller AbilityRecord.
11974     Want* newWant = const_cast<Want*>(&want);
11975     newWant->RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
11976     abilityRecord->SaveResultToCallers(resultCode, newWant);
11977     abilityRecord->SendResultToCallers();
11978     return ERR_OK;
11979 }
11980 
GetRunningMultiAppIndex(const std::string & bundleName,int32_t uid,int32_t & appIndex)11981 void AbilityManagerService::GetRunningMultiAppIndex(const std::string &bundleName, int32_t uid, int32_t &appIndex)
11982 {
11983     AppExecFwk::RunningMultiAppInfo runningMultiAppInfo;
11984     auto appMgr = GetAppMgr();
11985     if (appMgr == nullptr) {
11986         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
11987         return;
11988     }
11989     auto ret = IN_PROCESS_CALL(appMgr->GetRunningMultiAppInfoByBundleName(bundleName, runningMultiAppInfo));
11990     if (ret != ERR_OK) {
11991         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetRunningMultiAppInfo failed bundleName = %{public}s",
11992             bundleName.c_str());
11993     }
11994     for (auto &item : runningMultiAppInfo.runningAppClones) {
11995         if (item.uid == uid) {
11996             appIndex = item.appCloneIndex;
11997             break;
11998         }
11999     }
12000 }
12001 
NotifyFrozenProcessByRSS(const std::vector<int32_t> & pidList,int32_t uid)12002 void AbilityManagerService::NotifyFrozenProcessByRSS(const std::vector<int32_t> &pidList, int32_t uid)
12003 {
12004     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(RSS_PROCESS_NAME)) {
12005         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not RSS.");
12006         return;
12007     }
12008     auto userId = uid / BASE_USER_RANGE;
12009     auto connectManager = GetConnectManagerByUserId(userId);
12010     CHECK_POINTER_LOG(connectManager, "can not find user connect manager");
12011     connectManager->HandleProcessFrozen(pidList, uid);
12012 }
12013 
HandleRestartResidentProcessDependedOnWeb()12014 void AbilityManagerService::HandleRestartResidentProcessDependedOnWeb()
12015 {
12016     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
12017     auto appMgr = GetAppMgr();
12018     CHECK_POINTER_LOG(appMgr, "get appMgr fail");
12019     appMgr->RestartResidentProcessDependedOnWeb();
12020 }
12021 
PreStartMission(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & startTime)12022 int32_t AbilityManagerService::PreStartMission(const std::string& bundleName, const std::string& moduleName,
12023     const std::string& abilityName, const std::string& startTime)
12024 {
12025     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12026     CHECK_CALLER_IS_SYSTEM_APP;
12027 
12028     if (!PermissionVerification::GetInstance()->VerifyPreStartAtomicServicePermission()) {
12029         TAG_LOGE(AAFwkTag::ABILITYMGR, "calling user is not ag.");
12030         return ERR_PERMISSION_DENIED;
12031     }
12032 
12033     if (!freeInstallManager_) {
12034         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
12035         return ERR_INVALID_VALUE;
12036     }
12037 
12038     FreeInstallInfo taskInfo;
12039     if (!freeInstallManager_->GetFreeInstallTaskInfo(bundleName, abilityName, startTime, taskInfo)) {
12040         TAG_LOGE(AAFwkTag::ABILITYMGR,
12041             "failed to find free install task info:bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
12042             bundleName.c_str(), abilityName.c_str(), startTime.c_str());
12043         return ERR_FREE_INSTALL_TASK_NOT_EXIST;
12044     }
12045 
12046     if (taskInfo.isFreeInstallFinished) {
12047         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install is finished.");
12048         if (!taskInfo.isInstalled) {
12049             TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
12050                 taskInfo.resultCode);
12051         } else {
12052             TAG_LOGI(AAFwkTag::ABILITYMGR, "free install has succeeded.");
12053         }
12054         // if free install is already finished then either the window is opened (on success)
12055         // or the user is informed of the error (on failure).
12056         return taskInfo.resultCode;
12057     }
12058 
12059     return PreStartInner(taskInfo);
12060 }
12061 
PreStartInner(const FreeInstallInfo & taskInfo)12062 int32_t AbilityManagerService::PreStartInner(const FreeInstallInfo& taskInfo)
12063 {
12064     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12065 
12066     const Want& want = taskInfo.want;
12067     sptr<IRemoteObject> callerToken = taskInfo.callerToken;
12068 
12069     EventInfo eventInfo = BuildEventInfo(want, taskInfo.userId);
12070     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12071 
12072     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
12073         eventInfo.errCode = ERR_INVALID_VALUE;
12074         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
12075         return ERR_INVALID_CALLER;
12076     }
12077 
12078     int32_t oriValidUserId = GetValidUserId(taskInfo.userId);
12079 
12080     int32_t appIndex = 0;
12081     StartAbilityInfoWrap threadLocalInfo(want, oriValidUserId,
12082         StartAbilityUtils::GetAppIndex(want, callerToken, appIndex), callerToken);
12083 
12084     AbilityRequest abilityRequest = {
12085         .want = want,
12086         .requestCode = taskInfo.requestCode,
12087         .callerToken = callerToken,
12088         .startSetting = nullptr
12089     };
12090 
12091     TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
12092     UpdateCallerInfo(abilityRequest.want, callerToken);
12093 
12094     // sceneboard
12095     abilityRequest.userId = oriValidUserId;
12096     abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
12097     std::string sessionId = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
12098         std::chrono::system_clock::now().time_since_epoch()).count());
12099     abilityRequest.want.SetParam(KEY_SESSION_ID, sessionId);
12100     auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
12101     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12102     sptr<SessionInfo> sessionInfo = nullptr;
12103     auto errCode = uiAbilityManager->NotifySCBToPreStartUIAbility(abilityRequest, sessionInfo);
12104     if (errCode != ERR_OK) {
12105         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to notify sceneboard to pre-start uiability.");
12106         return errCode;
12107     }
12108     freeInstallManager_->SetFreeInstallTaskSessionId(taskInfo.want.GetElement().GetBundleName(),
12109         taskInfo.want.GetElement().GetAbilityName(),
12110         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), sessionId);
12111 
12112     freeInstallManager_->SetPreStartMissionCallStatus(taskInfo.want.GetElement().GetBundleName(),
12113         taskInfo.want.GetElement().GetAbilityName(),
12114         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME),
12115         true);
12116     return ERR_OK;
12117 }
12118 
StartUIAbilityByPreInstall(const FreeInstallInfo & taskInfo)12119 int32_t AbilityManagerService::StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo)
12120 {
12121     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12122     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12123     if (!taskInfo.isFreeInstallFinished || !taskInfo.isInstalled) {
12124         TAG_LOGE(AAFwkTag::ABILITYMGR, "free install is not finished or has failed.");
12125         return ERR_INVALID_VALUE;
12126     }
12127     if (!taskInfo.isStartUIAbilityBySCBCalled) {
12128         TAG_LOGI(AAFwkTag::ABILITYMGR, "Free install is finished, StartUIAbilityBySCB has not been called");
12129         return ERR_OK;
12130     }
12131 
12132     const auto& want = taskInfo.want;
12133     auto sessionId = want.GetStringParam(KEY_SESSION_ID);
12134     if (sessionId.empty()) {
12135         TAG_LOGE(AAFwkTag::ABILITYMGR, "session id is empty.");
12136         return ERR_INVALID_VALUE;
12137     }
12138     auto bundleName = want.GetElement().GetBundleName();
12139     auto abilityName = want.GetElement().GetAbilityName();
12140     auto startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME);
12141     TAG_LOGI(AAFwkTag::ABILITYMGR, "called"
12142         "sessionId=%{public}s,bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
12143         sessionId.c_str(), bundleName.c_str(), abilityName.c_str(), startTime.c_str());
12144     sptr<SessionInfo> sessionInfo = nullptr;
12145     {
12146         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12147         auto it = preStartSessionMap_.find(sessionId);
12148         if (it == preStartSessionMap_.end()) {
12149             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s",
12150                 sessionId.c_str());
12151             return ERR_INVALID_VALUE;
12152         }
12153         sessionInfo = it->second;
12154         (sessionInfo->want).SetElement(want.GetElement());
12155     }
12156 
12157     if (sessionInfo == nullptr || sessionInfo->isMinimizedDuringFreeInstall) {
12158         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr or ability is already minimized");
12159         return ERR_INVALID_VALUE;
12160     }
12161 
12162     bool isColdStart = true;
12163     int errCode = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, 0, isColdStart);
12164     if (errCode != ERR_OK) {
12165         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilityByPreInstallInner failed,errCode=%{public}d.", errCode);
12166         return errCode;
12167     }
12168     RemovePreStartSession(sessionId);
12169     return errCode;
12170 }
12171 
12172 // StartUIAbilityByPreInstallInner is called when free install task is already finished
StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo,uint32_t specifyTokenId,uint32_t sceneFlag,bool & isColdStart)12173 int AbilityManagerService::StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo, uint32_t specifyTokenId,
12174     uint32_t sceneFlag, bool &isColdStart)
12175 {
12176     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12177     auto callerToken = sessionInfo->callerToken;
12178     const auto& want = sessionInfo->want;
12179     const auto userId = sessionInfo->userId;
12180     const auto requestCode = sessionInfo->requestCode;
12181     bool isStartAsCaller = false;
12182 
12183     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
12184         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
12185             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
12186         if (!isSpecificSA) {
12187             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
12188             return ERR_INVALID_CALLER;
12189         }
12190         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__);
12191     }
12192 
12193     int32_t oriValidUserId = GetValidUserId(userId);
12194     int32_t validUserId = oriValidUserId;
12195 
12196     int32_t appIndex = 0;
12197     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
12198         return ERR_APP_CLONE_INDEX_INVALID;
12199     }
12200     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
12201     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
12202         true, nullptr);
12203     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
12204         interceptorExecuter_->DoProcess(interceptorParam);
12205     if (result != ERR_OK) {
12206         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
12207         return result;
12208     }
12209 
12210     AbilityRequest abilityRequest;
12211     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
12212     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
12213     std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
12214 
12215     if (result != ERR_OK) {
12216         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
12217         return result;
12218     }
12219 
12220     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
12221         UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
12222     } else if (!isStartAsCaller) {
12223         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
12224         UpdateCallerInfo(abilityRequest.want, callerToken);
12225     } else if (callerBundleName == BUNDLE_NAME_DIALOG) {
12226 #ifdef SUPPORT_SCREEN
12227         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
12228         implicitStartProcessor_->ResetCallingIdentityAsCaller(
12229             abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), true);
12230 #endif // SUPPORT_SCREEN
12231     }
12232 
12233     auto abilityInfo = abilityRequest.abilityInfo;
12234     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
12235     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
12236         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
12237 
12238     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
12239         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false);
12240     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
12241         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
12242         return ERR_STATIC_CFG_PERMISSION;
12243     }
12244 
12245     result = CheckCallPermission(want, abilityInfo, abilityRequest, false,
12246         false, specifyTokenId, callerBundleName);
12247     if (result != ERR_OK) {
12248         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallPermission error, result is %{public}d.", result);
12249         return result;
12250     }
12251 
12252     Want newWant = abilityRequest.want;
12253     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
12254         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
12255     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
12256         afterCheckExecuter_->DoProcess(afterCheckParam);
12257     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
12258     newWant.RemoveParam("queryWantFromErms");
12259     if (result != ERR_OK && isReplaceWantExist == false) {
12260         TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
12261         return result;
12262     }
12263 #ifdef SUPPORT_SCREEN
12264     if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
12265         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
12266     }
12267     if (result == ERR_OK &&
12268         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
12269         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
12270         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
12271     }
12272 #endif // SUPPORT_SCREEN
12273 
12274     if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
12275         abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
12276         return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
12277     }
12278 
12279     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
12280         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s.", abilityInfo.bundleName.c_str());
12281         return ERR_WOULD_BLOCK;
12282     }
12283 
12284     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
12285     if (specifyTokenId > 0) {
12286         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
12287         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
12288         abilityRequest.specifyTokenId = specifyTokenId;
12289     }
12290     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
12291 
12292     auto uiAbilityManager = GetCurrentUIAbilityManager();
12293     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12294 
12295     return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
12296 }
12297 
NotifySCBToHandleAtomicServiceException(const std::string & sessionId,int32_t errCode,const std::string & reason)12298 void AbilityManagerService::NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode,
12299     const std::string& reason)
12300 {
12301     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12302     sptr<SessionInfo> sessionInfo = nullptr;
12303     {
12304         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12305         auto it = preStartSessionMap_.find(sessionId);
12306         if (it == preStartSessionMap_.end()) {
12307             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s",
12308                 sessionId.c_str());
12309             return;
12310         }
12311         sessionInfo = it->second;
12312         preStartSessionMap_.erase(it);
12313     }
12314     if (sessionInfo == nullptr) {
12315         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr.");
12316         return;
12317     }
12318     auto uiAbilityManager = GetCurrentUIAbilityManager();
12319     CHECK_POINTER(uiAbilityManager);
12320     return uiAbilityManager->NotifySCBToHandleAtomicServiceException(sessionInfo, errCode, reason);
12321 }
12322 
RemovePreStartSession(const std::string & sessionId)12323 void AbilityManagerService::RemovePreStartSession(const std::string& sessionId)
12324 {
12325     std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12326     preStartSessionMap_.erase(sessionId);
12327 }
12328 
OpenLink(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int requestCode)12329 ErrCode AbilityManagerService::OpenLink(const Want& want, sptr<IRemoteObject> callerToken,
12330     int32_t userId, int requestCode)
12331 {
12332     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12333     std::string url = want.GetUriString();
12334     bool isAtomicServiceShortUrl = false;
12335 #ifdef APP_DOMAIN_VERIFY_ENABLED
12336     isAtomicServiceShortUrl = AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->IsAtomicServiceUrl(url);
12337 #endif
12338     int32_t retCode = ERR_OK;
12339     if (!isAtomicServiceShortUrl) {
12340         TAG_LOGI(AAFwkTag::ABILITYMGR, "not atomic service short url, start ability by default.");
12341         retCode = StartAbility(want, callerToken, userId, requestCode);
12342         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12343         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12344     }
12345 
12346     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
12347     Want convertedWant = want;
12348     retCode = ConvertToExplicitWant(convertedWant);
12349     if (retCode != ERR_OK) {
12350         TAG_LOGI(AAFwkTag::ABILITYMGR, "failed to convert to explicit want, start ability by default.");
12351         retCode = StartAbility(want, callerToken, userId, requestCode);
12352         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12353         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12354     }
12355 
12356     if (!freeInstallManager_) {
12357         TAG_LOGW(AAFwkTag::ABILITYMGR, "free install manager is nullptr, start ability by default.");
12358         retCode = StartAbility(want, callerToken, userId, requestCode);
12359         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12360         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12361     }
12362 
12363     convertedWant.AddFlags(Want::FLAG_INSTALL_ON_DEMAND);
12364     TAG_LOGD(AAFwkTag::ABILITYMGR, "convertedWant=%{public}s", convertedWant.ToString().c_str());
12365     retCode = freeInstallManager_->StartFreeInstall(convertedWant, GetValidUserId(userId),
12366         requestCode, callerToken, true, 0, true, std::make_shared<Want>(want));
12367     if (retCode != ERR_OK) {
12368         TAG_LOGW(AAFwkTag::ABILITYMGR, "StartFreeInstall returns errCode=%{public}d.", retCode);
12369         if (retCode == NOT_TOP_ABILITY) {
12370             TAG_LOGE(AAFwkTag::ABILITYMGR, "start from background is not allowed.");
12371             return retCode;
12372         }
12373         TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default.");
12374         retCode = StartAbility(want, callerToken, userId, requestCode);
12375         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12376         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12377     }
12378     return ERR_OK;
12379 }
12380 
ConvertToExplicitWant(Want & want)12381 ErrCode AbilityManagerService::ConvertToExplicitWant(Want& want)
12382 {
12383     ErrCode retCode = ERR_OK;
12384 #ifdef APP_DOMAIN_VERIFY_ENABLED
12385     auto bundleMgrHelper = GetBundleManager();
12386     if (bundleMgrHelper == nullptr) {
12387         TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleMgrHelper is invalid.");
12388         return ERR_INVALID_VALUE;
12389     }
12390     int32_t callerUid = IPCSkeleton::GetCallingUid();
12391     std::string callerBundleName;
12392     retCode = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callerUid, callerBundleName));
12393     if (retCode != ERR_OK) {
12394         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callerBundleName failed,retCode=%{public}d.", retCode);
12395         return retCode;
12396     }
12397     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName=%{public}s.", callerBundleName.c_str());
12398     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
12399 
12400     bool isUsed = false;
12401     ffrt::condition_variable callbackDoneCv;
12402     ffrt::mutex callbackDoneMutex;
12403     ConvertCallbackTask task = [&retCode, &isUsed, &callbackDoneCv, &callbackDoneMutex,
12404         &convertedWant = want, this](int resultCode, AAFwk::Want& want) {
12405         TAG_LOGI(AAFwkTag::ABILITYMGR, "in convert callback task, resultCode=%{public}d,want=%{public}s",
12406             resultCode, want.ToString().c_str());
12407         retCode = resultCode;
12408         convertedWant = want;
12409         {
12410             std::lock_guard<ffrt::mutex> lock(callbackDoneMutex);
12411             isUsed = true;
12412         }
12413         TAG_LOGI(AAFwkTag::ABILITYMGR, "start to notify.");
12414         callbackDoneCv.notify_all();
12415         TAG_LOGI(AAFwkTag::ABILITYMGR, "convert callback task finished");
12416     };
12417     sptr<ConvertCallbackImpl> callbackTask = new ConvertCallbackImpl(std::move(task));
12418     sptr<OHOS::AppDomainVerify::IConvertCallback> callback = callbackTask;
12419     AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->ConvertToExplicitWant(want, callback);
12420     auto condition = [&isUsed] { return isUsed; };
12421     std::unique_lock<ffrt::mutex> lock(callbackDoneMutex);
12422     TAG_LOGI(AAFwkTag::ABILITYMGR, "start to wait for condition.");
12423     if (!callbackDoneCv.wait_for(lock, seconds(CONVERT_CALLBACK_TIMEOUT_SECONDS), condition)) {
12424         TAG_LOGE(AAFwkTag::ABILITYMGR, "convert callback timeout.");
12425         callbackTask->Cancel();
12426         retCode = ERR_TIMED_OUT;
12427     }
12428     TAG_LOGI(AAFwkTag::ABILITYMGR, "finish wait for condition.");
12429 #endif
12430     return retCode;
12431 }
12432 
SetAbilityRequestSessionInfo(AbilityRequest & abilityRequest,AppExecFwk::ExtensionAbilityType extensionType)12433 void AbilityManagerService::SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest, AppExecFwk::ExtensionAbilityType extensionType)
12434 {
12435     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12436     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
12437         return;
12438     }
12439 
12440     abilityRequest.want.RemoveParam(WANT_PARAMS_HOST_WINDOW_ID_KEY);
12441     auto callerAbilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
12442     CHECK_POINTER_LOG(callerAbilityRecord, "callerAbilityRecord is nullptr");
12443     sptr<SessionInfo> callerSessionInfo = callerAbilityRecord->GetSessionInfo();
12444     CHECK_POINTER_LOG(callerSessionInfo, "callerSessionInfo is nullptr");
12445 
12446     if (callerAbilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
12447         TAG_LOGI(AAFwkTag::ABILITYMGR, "UIAbility Caller");
12448         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, callerSessionInfo->persistentId);
12449     } else if (AAFwk::UIExtensionUtils::IsUIExtension(callerAbilityRecord->GetAbilityInfo().extensionAbilityType)) {
12450         int32_t mainWindowId = -1;
12451         auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().
12452             GetSceneSessionManagerLiteProxy();
12453         CHECK_POINTER_LOG(sceneSessionManager, "sceneSessionManager is nullptr");
12454         auto err = sceneSessionManager->GetRootMainWindowId(static_cast<int32_t>(callerSessionInfo->hostWindowId),mainWindowId);
12455         TAG_LOGI(AAFwkTag::ABILITYMGR, "callerSessionInfo->hostWindowId = %{public}d, mainWindowId = %{public}d, err = %{public}d",
12456             callerSessionInfo->hostWindowId, mainWindowId, err);
12457         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, mainWindowId);
12458     } else {
12459         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, 0);
12460     }
12461 }
12462 
CleanUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)12463 int32_t AbilityManagerService::CleanUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
12464 {
12465     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12466     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
12467         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is invalid.");
12468         return ERR_INVALID_VALUE;
12469     }
12470 
12471     if (!IsCallerSceneBoard()) {
12472         TAG_LOGE(AAFwkTag::ABILITYMGR, "only support sceneboard call.");
12473         return ERR_WRONG_INTERFACE_CALL;
12474     }
12475 
12476     SetMinimizedDuringFreeInstall(sessionInfo);
12477 
12478     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12479     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12480     TAG_LOGI(AAFwkTag::ABILITYMGR, "user request ot clean session: %{public}d.", sessionInfo->persistentId);
12481     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
12482     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
12483     int32_t errCode = uiAbilityManager->CleanUIAbility(abilityRecord);
12484     ReportCleanSession(sessionInfo, abilityRecord, errCode);
12485     return errCode;
12486 }
12487 
ForceTerminateSerivceExtensionByPid(int32_t pid,int32_t userId)12488 void AbilityManagerService::ForceTerminateSerivceExtensionByPid(int32_t pid, int32_t userId)
12489 {
12490     std::vector<sptr<IRemoteObject>> tokens;
12491     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppScheduler>::GetInstance()->GetAbilityRecordsByProcessID(
12492         pid, tokens));
12493     auto connectManager = GetConnectManagerByUserId(userId);
12494     if (connectManager) {
12495         for (const auto& token : tokens) {
12496             auto abilityRecord = Token::GetAbilityRecordByToken(token);
12497             if (abilityRecord &&
12498                 abilityRecord->GetAbilityInfo().extensionAbilityType ==
12499                 AppExecFwk::ExtensionAbilityType::SERVICE) {
12500                 TAG_LOGI(AAFwkTag::ABILITYMGR, "app ForceTerminateSerivceExtensionByPid, pid is %{public}d", pid);
12501                 connectManager->TerminateAbility(token);
12502             }
12503         }
12504     }
12505 }
12506 
ReportCleanSession(const sptr<SessionInfo> & sessionInfo,const std::shared_ptr<AbilityRecord> & abilityRecord,int32_t errCode)12507 void AbilityManagerService::ReportCleanSession(const sptr<SessionInfo> &sessionInfo,
12508     const std::shared_ptr<AbilityRecord> &abilityRecord, int32_t errCode)
12509 {
12510     if (!sessionInfo || !abilityRecord) {
12511         return;
12512     }
12513 
12514     const auto &abilityInfo = abilityRecord->GetAbilityInfo();
12515     std::string abilityName = abilityInfo.name;
12516     if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
12517         abilityName += std::to_string(sessionInfo->persistentId);
12518     }
12519     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
12520         DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
12521 
12522     EventInfo eventInfo;
12523     eventInfo.errCode = errCode;
12524     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
12525     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
12526     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12527     if (eventInfo.errCode != ERR_OK) {
12528         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
12529     }
12530 }
12531 
SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want,uint32_t specifyTokenId)12532 void AbilityManagerService::SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo& abilityInfo,
12533     const Want& want, uint32_t specifyTokenId)
12534 {
12535     if (abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
12536         abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
12537         EventInfo eventInfo;
12538         eventInfo.bundleName = abilityInfo.bundleName;
12539         eventInfo.moduleName = abilityInfo.moduleName;
12540         eventInfo.abilityName = abilityInfo.name;
12541         eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
12542         if (specifyTokenId > 0) {
12543             // come from want agent or form
12544             Security::AccessToken::HapTokenInfo hapInfo;
12545             if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(specifyTokenId, hapInfo) == ERR_OK) {
12546                 eventInfo.callerBundleName = hapInfo.bundleName;
12547             }
12548         } else {
12549             eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
12550             if (eventInfo.callerBundleName.empty()) {
12551                 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
12552             }
12553         }
12554         TAG_LOGI(AAFwkTag::ABILITYMGR,
12555             "SendStartAbilityOtherExtensionEvent, bundleName:%{public}s, extensionAbilityType:%{public}d",
12556             eventInfo.bundleName.c_str(), eventInfo.extensionType);
12557         EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
12558     }
12559 }
12560 
TerminateMission(int32_t missionId)12561 int32_t AbilityManagerService::TerminateMission(int32_t missionId)
12562 {
12563     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12564     TAG_LOGI(AAFwkTag::ABILITYMGR, "TerminateMission call");
12565     auto missionListManager = GetCurrentMissionListManager();
12566     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
12567     CHECK_CALLER_IS_SYSTEM_APP;
12568 
12569     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
12570         PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
12571         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
12572         return CHECK_PERMISSION_FAILED;
12573     }
12574 
12575     return missionListManager->ClearMission(missionId);
12576 }
12577 
EnableListForSCBRecovery(int32_t userId) const12578 void AbilityManagerService::EnableListForSCBRecovery(int32_t userId) const
12579 {
12580     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
12581     CHECK_POINTER_LOG(uiAbilityManager, "UIAbilityMgr not exist.");
12582     uiAbilityManager->EnableListForSCBRecovery();
12583 }
12584 
UpdateKeepAliveEnableState(const std::string & bundleName,const std::string & moduleName,const std::string & mainElement,bool updateEnable,int32_t userId)12585 int32_t AbilityManagerService::UpdateKeepAliveEnableState(const std::string &bundleName,
12586     const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId)
12587 {
12588     auto connectManager = GetConnectManagerByUserId(userId);
12589     CHECK_POINTER_AND_RETURN(connectManager, ERR_NULL_OBJECT);
12590     int32_t ret = connectManager->UpdateKeepAliveEnableState(bundleName, moduleName, mainElement, updateEnable);
12591     if (ret != ERR_OK) {
12592         TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateKeepAliveEnableState failed, err:%{public}d", ret);
12593     }
12594     return ret;
12595 }
12596 
UpdateAssociateConfigList(const std::map<std::string,std::list<std::string>> & configs,const std::list<std::string> & exportConfigs,int32_t flag)12597 int32_t AbilityManagerService::UpdateAssociateConfigList(const std::map<std::string, std::list<std::string>>& configs,
12598     const std::list<std::string>& exportConfigs, int32_t flag)
12599 {
12600     if (IPCSkeleton::GetCallingUid() != RESOURCE_SCHEDULE_UID) {
12601         TAG_LOGE(AAFwkTag::ABILITYMGR, "Update associate config, current process not rss process");
12602         return CHECK_PERMISSION_FAILED;
12603     }
12604     std::lock_guard<std::mutex> locker(whiteListMutex_);
12605     if (flag == UPDATE_CONFIG_FLAG_COVER) {
12606         whiteListMap_ = configs;
12607         exportWhiteList_ = exportConfigs;
12608     } else if (flag == UPDATE_CONFIG_FLAG_APPEND) {
12609         for (const auto& config : configs) {
12610             for (const auto& item : config.second) {
12611                 whiteListMap_[config.first].push_back(item);
12612             }
12613         }
12614         for (const auto& config : exportConfigs) {
12615             exportWhiteList_.push_back(config);
12616         }
12617     }
12618     return ERR_OK;
12619 }
12620 }  // namespace AAFwk
12621 }  // namespace OHOS
12622