• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ability_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::SERVICE_EXT, "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::SERVICE_EXT,
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::SERVICE_EXT, "CheckDlpForExtension error.");
2825         return result;
2826     }
2827 #endif // WITH_DLP
2828 
2829     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2830         TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{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::SERVICE_EXT, "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::SERVICE_EXT, "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::SERVICE_EXT, "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::SERVICE_EXT, "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::SERVICE_EXT, "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::SERVICE_EXT, "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::SERVICE_EXT, "afterCheckExecuter_ is nullptr or DoProcess return error.");
2909         return result;
2910     }
2911 
2912     auto connectManager = GetConnectManagerByUserId(validUserId);
2913     if (!connectManager) {
2914         TAG_LOGE(AAFwkTag::SERVICE_EXT, "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::SERVICE_EXT, "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 #ifdef SUPPORT_GRAPHICS
3206     // for implicit system selector modal dialog
3207     bool isSCBCall = (callerRecord->GetApplicationInfo().bundleName == AbilityConfig::SCENEBOARD_BUNDLE_NAME);
3208     DialogSessionManager::GetInstance().UpdateExtensionWantWithDialogCallerInfo(abilityRequest, callerToken,
3209         isSCBCall);
3210 #endif // SUPPORT_GRAPHICS
3211     UriUtils::GetInstance().CheckUriPermissionForUIExtension(abilityRequest.want,
3212         abilityRequest.abilityInfo.extensionAbilityType);
3213     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
3214     if (eventInfo.errCode != ERR_OK) {
3215         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3216     }
3217     return eventInfo.errCode;
3218 }
3219 
StopExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)3220 int AbilityManagerService::StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
3221     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
3222 {
3223     TAG_LOGI(AAFwkTag::SERVICE_EXT,
3224         "Stop extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
3225         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3226     if (extensionType != AppExecFwk::ExtensionAbilityType::VPN) {
3227         CHECK_CALLER_IS_SYSTEM_APP;
3228     }
3229     EventInfo eventInfo = BuildEventInfo(want, userId);
3230     eventInfo.extensionType = static_cast<int32_t>(extensionType);
3231 
3232     int result;
3233 #ifdef WITH_DLP
3234     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::STOP_EXTENSION_ERROR);
3235     if (result != ERR_OK) {
3236         TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckDlpForExtension error.");
3237         return result;
3238     }
3239 #endif // WITH_DLP
3240 
3241     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3242         TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s VerificationAllToken failed.", __func__);
3243         if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
3244             TAG_LOGE(AAFwkTag::SERVICE_EXT, "VerificationAllToken failed.");
3245             eventInfo.errCode = ERR_INVALID_VALUE;
3246             EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3247             return ERR_INVALID_CALLER;
3248         }
3249         TAG_LOGD(AAFwkTag::SERVICE_EXT, "Caller is specific system ability.");
3250     }
3251 
3252     int32_t validUserId = GetValidUserId(userId);
3253     if (!JudgeMultiUserConcurrency(validUserId)) {
3254         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Multi-user non-concurrent mode is not satisfied.");
3255         eventInfo.errCode = ERR_INVALID_VALUE;
3256         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3257         return ERR_CROSS_USER;
3258     }
3259 
3260     if (callerToken != nullptr && CheckIfOperateRemote(want)) {
3261         auto callerUid = IPCSkeleton::GetCallingUid();
3262         uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3263         DistributedClient dmsClient;
3264         return dmsClient.StopRemoteExtensionAbility(want, callerUid, accessToken, eventInfo.extensionType);
3265     }
3266 
3267     AbilityRequest abilityRequest;
3268     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
3269     if (result != ERR_OK) {
3270         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Generate ability request local error.");
3271         eventInfo.errCode = result;
3272         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3273         return result;
3274     }
3275 
3276     auto abilityInfo = abilityRequest.abilityInfo;
3277     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3278     TAG_LOGD(AAFwkTag::SERVICE_EXT, "userId is : %{public}d, singleton is : %{public}d",
3279         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3280 
3281     result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
3282     if (result != ERR_OK) {
3283         TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckOptExtensionAbility error.");
3284         eventInfo.errCode = result;
3285         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3286         return result;
3287     }
3288 
3289     auto connectManager = GetConnectManagerByUserId(validUserId);
3290     if (!connectManager) {
3291         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager is nullptr. userId=%{public}d", validUserId);
3292         eventInfo.errCode = ERR_INVALID_VALUE;
3293         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3294         return ERR_INVALID_VALUE;
3295     }
3296     TAG_LOGI(AAFwkTag::SERVICE_EXT, "Stop extension begin, name is %{public}s.", abilityInfo.name.c_str());
3297     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3298     if (eventInfo.errCode != ERR_OK) {
3299         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3300     }
3301     return eventInfo.errCode;
3302 }
3303 
StopSwitchUserDialog()3304 void AbilityManagerService::StopSwitchUserDialog()
3305 {
3306     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog extension ability come");
3307     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3308         TAG_LOGE(AAFwkTag::ABILITYMGR, "Scene board enabled.");
3309         return;
3310     }
3311 
3312     if (userController_ == nullptr || userController_->GetFreezingNewUserId() == DEFAULT_INVAL_VALUE) {
3313         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get last userId error.");
3314         return;
3315     }
3316 
3317     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
3318     if (sysDialog == nullptr) {
3319         TAG_LOGE(AAFwkTag::ABILITYMGR, "System dialog scheduler instance is nullptr.");
3320         return;
3321     }
3322     Want stopWant = sysDialog->GetSwitchUserDialogWant();
3323     StopSwitchUserDialogInner(stopWant, userController_->GetFreezingNewUserId());
3324 
3325     userController_->SetFreezingNewUserId(DEFAULT_INVAL_VALUE);
3326     return;
3327 }
3328 
StopSwitchUserDialogInner(const Want & want,const int32_t lastUserId)3329 void AbilityManagerService::StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)
3330 {
3331     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog inner come");
3332     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
3333     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
3334     AbilityRequest abilityRequest;
3335     auto result =
3336         GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
3337     if (result != ERR_OK) {
3338         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
3339         eventInfo.errCode = result;
3340         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3341         return;
3342     }
3343 
3344     auto abilityInfo = abilityRequest.abilityInfo;
3345     auto stopUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
3346     result = CheckOptExtensionAbility(want, abilityRequest, stopUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
3347     if (result != ERR_OK) {
3348         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check extensionAbility type error.");
3349         eventInfo.errCode = result;
3350         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3351         return;
3352     }
3353 
3354     auto connectManager = GetConnectManagerByUserId(stopUserId);
3355     if (connectManager == nullptr) {
3356         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectManager is nullptr. userId:%{public}d", stopUserId);
3357         eventInfo.errCode = ERR_INVALID_VALUE;
3358         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3359         return;
3360     }
3361 
3362     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3363     if (eventInfo.errCode != ERR_OK) {
3364         TAG_LOGE(AAFwkTag::ABILITYMGR, "EventInfo errCode is %{public}d", eventInfo.errCode);
3365         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3366     }
3367 }
3368 
MoveAbilityToBackground(const sptr<IRemoteObject> & token)3369 int AbilityManagerService::MoveAbilityToBackground(const sptr<IRemoteObject> &token)
3370 {
3371     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3372     TAG_LOGD(AAFwkTag::ABILITYMGR, "Move ability to background begin");
3373     if (!VerificationAllToken(token)) {
3374         return ERR_INVALID_VALUE;
3375     }
3376     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3377     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3378     if (!JudgeSelfCalled(abilityRecord)) {
3379         return CHECK_PERMISSION_FAILED;
3380     }
3381 
3382     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3383         return ERR_WOULD_BLOCK;
3384     }
3385 
3386     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3387     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3388     if (!missionListManager) {
3389         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
3390         return ERR_INVALID_VALUE;
3391     }
3392     return missionListManager->MoveAbilityToBackground(abilityRecord);
3393 }
3394 
MoveUIAbilityToBackground(const sptr<IRemoteObject> token)3395 int32_t AbilityManagerService::MoveUIAbilityToBackground(const sptr<IRemoteObject> token)
3396 {
3397     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3398     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
3399     if (!AppUtils::GetInstance().EnableMoveUIAbilityToBackgroundApi()) {
3400         return ERR_OPERATION_NOT_SUPPORTED_ON_CURRENT_DEVICE;
3401     }
3402     if (!VerificationAllToken(token)) {
3403         return ERR_INVALID_VALUE;
3404     }
3405     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3406     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3407     if (!IsAppSelfCalled(abilityRecord)) {
3408         return CHECK_PERMISSION_FAILED;
3409     }
3410     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3411         TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not move ability to background in Wukong mode.");
3412         return ERR_WUKONG_MODE_CANT_MOVE_STATE;
3413     }
3414     if (!abilityRecord->IsAbilityState(FOREGROUND) && !abilityRecord->IsAbilityState(FOREGROUNDING)) {
3415         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability not in foregorund state.");
3416         return ERR_ABILITY_NOT_FOREGROUND;
3417     }
3418     if (abilityRecord->GetAbilityInfo().type != AppExecFwk::AbilityType::PAGE) {
3419         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot background non UIAbility.");
3420         return RESOLVE_CALL_ABILITY_TYPE_ERR;
3421     }
3422     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3423     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3424         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3425         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3426         return uiAbilityManager->NotifySCBToMinimizeUIAbility(token);
3427     }
3428 
3429     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3430     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3431     return missionListManager->MoveAbilityToBackground(abilityRecord);
3432 }
3433 
TerminateAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3434 int AbilityManagerService::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3435 {
3436     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3437     if (!abilityRecord) {
3438         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
3439         return ERR_INVALID_VALUE;
3440     }
3441     return TerminateAbilityWithFlag(token, resultCode, resultWant, true);
3442 }
3443 
TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> & token)3444 int32_t AbilityManagerService::TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> &token)
3445 {
3446     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3447     if (!VerificationAllToken(token)) {
3448         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
3449         return ERR_INVALID_VALUE;
3450     }
3451 
3452     if (!IsCallerSceneBoard()) {
3453         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3454         return ERR_WRONG_INTERFACE_CALL;
3455     }
3456 
3457     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3458     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3459 
3460     auto type = abilityRecord->GetAbilityInfo().type;
3461     auto extensionAbilityType = abilityRecord->GetAbilityInfo().extensionAbilityType;
3462 
3463     if (type != AppExecFwk::AbilityType::EXTENSION  ||
3464         extensionAbilityType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3465             return ERR_INVALID_VALUE;
3466     }
3467 
3468     auto userId = GetValidUserId(DEFAULT_INVAL_VALUE);
3469     auto connectManager = GetConnectManagerByUserId(userId);
3470     if (!connectManager) {
3471         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
3472         return ERR_INVALID_VALUE;
3473     }
3474     return connectManager->TerminateAbility(token);
3475 }
3476 
BackToCallerAbilityWithResult(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,int64_t callerRequestCode)3477 int AbilityManagerService::BackToCallerAbilityWithResult(const sptr<IRemoteObject> &token, int resultCode,
3478     const Want *resultWant, int64_t callerRequestCode)
3479 {
3480     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3481     if (!abilityRecord) {
3482         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
3483         return ERR_INVALID_VALUE;
3484     }
3485     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3486     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3487         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3488         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3489         return uiAbilityManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant,
3490             callerRequestCode);
3491     }
3492     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3493     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3494     return missionListManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant, callerRequestCode);
3495 }
3496 
CloseAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3497 int AbilityManagerService::CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3498 {
3499     EventInfo eventInfo;
3500     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3501     return TerminateAbilityWithFlag(token, resultCode, resultWant, false);
3502 }
3503 
TerminateAbilityWithFlag(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,bool flag)3504 int AbilityManagerService::TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode,
3505     const Want *resultWant, bool flag)
3506 {
3507     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3508     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ability begin, flag:%{public}d.", flag);
3509     if (!VerificationAllToken(token)) {
3510         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
3511         return ERR_INVALID_VALUE;
3512     }
3513 
3514     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3515     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3516     if (!JudgeSelfCalled(abilityRecord)) {
3517         return CHECK_PERMISSION_FAILED;
3518     }
3519 
3520     if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) {
3521         TAG_LOGE(AAFwkTag::ABILITYMGR, "System ui not allow terminate.");
3522         return ERR_INVALID_VALUE;
3523     }
3524 
3525     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
3526     auto type = abilityRecord->GetAbilityInfo().type;
3527     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
3528         auto connectManager = GetConnectManagerByUserId(userId);
3529         if (!connectManager) {
3530             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
3531             return ERR_INVALID_VALUE;
3532         }
3533         return connectManager->TerminateAbility(token);
3534     }
3535 
3536     if (type == AppExecFwk::AbilityType::DATA) {
3537         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot terminate data ability, use 'ReleaseDataAbility()' instead.");
3538         return ERR_WRONG_INTERFACE_CALL;
3539     }
3540 
3541     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3542         return ERR_WOULD_BLOCK;
3543     }
3544 
3545     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3546     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3547     if (missionListManager) {
3548         return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag);
3549     }
3550     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
3551     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3552         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3553         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3554         return uiAbilityManager->CloseUIAbility(abilityRecord, resultCode, resultWant, false);
3555     }
3556     return ERR_INVALID_VALUE;
3557 }
3558 
TerminateUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int resultCode,const Want * resultWant)3559 int AbilityManagerService::TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode,
3560     const Want *resultWant)
3561 {
3562     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3563     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ui extension ability begin.");
3564     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3565     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3566     std::shared_ptr<AbilityConnectManager> connectManager;
3567     std::shared_ptr<AbilityRecord> targetRecord;
3568     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3569     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3570     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3571 
3572     // self terminate or caller terminate is allowed.
3573     if (!(JudgeSelfCalled(targetRecord) || (abilityRecord != nullptr && JudgeSelfCalled(abilityRecord)))) {
3574         return CHECK_PERMISSION_FAILED;
3575     }
3576 
3577     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3578     if (result != ERR_OK) {
3579         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3580         return result;
3581     }
3582 
3583     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3584         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot terminate except ui extension ability.");
3585         return ERR_WRONG_INTERFACE_CALL;
3586     }
3587 
3588     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension persistentId: %{public}d, element: %{public}s.",
3589         extensionSessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3590     connectManager->TerminateAbilityWindowLocked(targetRecord, extensionSessionInfo);
3591     return ERR_OK;
3592 }
3593 
CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)3594 int AbilityManagerService::CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)
3595 {
3596     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3597     TAG_LOGD(AAFwkTag::ABILITYMGR, "close uiextensionability by scb");
3598     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
3599 
3600     if (!IsCallerSceneBoard()) {
3601         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
3602         return ERR_PERMISSION_DENIED;
3603     }
3604 
3605     if (!VerificationAllToken(token)) {
3606         TAG_LOGE(AAFwkTag::ABILITYMGR, "verificationAllToken failed");
3607         return ERR_INVALID_VALUE;
3608     }
3609 
3610     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3611     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3612     if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
3613         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability %{public}s not an uiextensionability",
3614             abilityRecord->GetURI().c_str());
3615         return ERR_INVALID_VALUE;
3616     }
3617 
3618     auto sessionInfo = abilityRecord->GetSessionInfo();
3619     if (sessionInfo == nullptr) {
3620         TAG_LOGE(AAFwkTag::ABILITYMGR, "target session info is null, ability: %{public}s",
3621             abilityRecord->GetURI().c_str());
3622         return ERR_INVALID_VALUE;
3623     }
3624 
3625     std::shared_ptr<AbilityConnectManager> connectManager;
3626     std::shared_ptr<AbilityRecord> targetRecord;
3627     GetConnectManagerAndUIExtensionBySessionInfo(sessionInfo, connectManager, targetRecord);
3628     if (connectManager == nullptr) {
3629         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null, ability: %{public}s", abilityRecord->GetURI().c_str());
3630         return ERR_INVALID_VALUE;
3631     }
3632 
3633     sptr<Rosen::ISession> sessionProxy = iface_cast<Rosen::ISession>(sessionInfo->sessionToken);
3634     if (sessionProxy == nullptr) {
3635         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get session proxy failed, ability: %{public}s",
3636             abilityRecord->GetURI().c_str());
3637         return ERR_INVALID_VALUE;
3638     }
3639 
3640     // notify caller sync detach
3641     sessionProxy->NotifyExtensionDetachToDisplay();
3642     connectManager->TerminateAbilityWindowLocked(abilityRecord, sessionInfo);
3643     return ERR_OK;
3644 }
3645 
CloseUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)3646 int AbilityManagerService::CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
3647 {
3648     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3649     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3650         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
3651         return ERR_INVALID_VALUE;
3652     }
3653 
3654     if (!IsCallerSceneBoard()) {
3655         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
3656         return ERR_WRONG_INTERFACE_CALL;
3657     }
3658 
3659     SetMinimizedDuringFreeInstall(sessionInfo);
3660 
3661     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3662     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3663     TAG_LOGI(AAFwkTag::ABILITYMGR,
3664         "close session: %{public}d, resultCode: %{public}d", sessionInfo->persistentId, sessionInfo->resultCode);
3665     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3666     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3667     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3668         return ERR_WOULD_BLOCK;
3669     }
3670 
3671     if (sessionInfo->isClearSession) {
3672         const auto &abilityInfo = abilityRecord->GetAbilityInfo();
3673         std::string abilityName = abilityInfo.name;
3674         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
3675             abilityName += std::to_string(sessionInfo->persistentId);
3676         }
3677         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
3678             DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
3679     }
3680     EventInfo eventInfo;
3681     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
3682     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
3683     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3684     eventInfo.errCode = uiAbilityManager->CloseUIAbility(abilityRecord, sessionInfo->resultCode,
3685         &(sessionInfo->want), sessionInfo->isClearSession);
3686     if (eventInfo.errCode != ERR_OK) {
3687         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
3688     }
3689     return eventInfo.errCode;
3690 }
3691 
SendResultToAbility(int32_t requestCode,int32_t resultCode,Want & resultWant)3692 int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)
3693 {
3694     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3695     if (!CheckCallerIsDmsProcess()) {
3696         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check processName failed");
3697         return ERR_INVALID_VALUE;
3698     }
3699     int missionId = resultWant.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
3700     resultWant.RemoveParam(DMS_MISSION_ID);
3701     if (missionId == DEFAULT_DMS_MISSION_ID) {
3702         TAG_LOGE(AAFwkTag::ABILITYMGR, "MissionId is empty");
3703         return ERR_INVALID_VALUE;
3704     }
3705     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
3706     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3707         auto uiAbilityManager = GetCurrentUIAbilityManager();
3708         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3709         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
3710     } else {
3711         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
3712         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3713         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
3714     }
3715     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3716 
3717     abilityRecord->SetResult(std::make_shared<AbilityResult>(requestCode, resultCode, resultWant));
3718     abilityRecord->SendResult(0, 0);
3719     return ERR_OK;
3720 }
3721 
StartRemoteAbility(const Want & want,int requestCode,int32_t validUserId,const sptr<IRemoteObject> & callerToken)3722 int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId,
3723     const sptr<IRemoteObject> &callerToken)
3724 {
3725     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3726     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3727     Want remoteWant = want;
3728     UpdateDmsCallerInfo(remoteWant, callerToken);
3729     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
3730         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
3731         return ERR_INVALID_VALUE;
3732     }
3733     if (AbilityUtil::IsStartFreeInstall(remoteWant)) {
3734         return freeInstallManager_ == nullptr ? ERR_INVALID_VALUE :
3735             freeInstallManager_->StartRemoteFreeInstall(remoteWant, requestCode, validUserId, callerToken);
3736     }
3737     if (remoteWant.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
3738         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: try to StartAbilityForResult", __func__);
3739         int32_t missionId = -1;
3740         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3741             missionId = GetMissionIdByAbilityTokenInner(callerToken);
3742             if (!missionId) {
3743                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
3744                 return ERR_INVALID_VALUE;
3745             }
3746         } else {
3747             missionId = GetMissionIdByAbilityToken(callerToken);
3748         }
3749         if (missionId < 0) {
3750             return ERR_INVALID_VALUE;
3751         }
3752         remoteWant.SetParam(DMS_MISSION_ID, missionId);
3753     }
3754 
3755     int32_t callerUid = IPCSkeleton::GetCallingUid();
3756     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3757     UriUtils::GetInstance().FilterUriWithPermissionDms(remoteWant, accessToken);
3758     DistributedClient dmsClient;
3759     int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken);
3760     if (result != ERR_NONE) {
3761         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartRemoteAbility failed, result = %{public}d", result);
3762     }
3763     return result;
3764 }
3765 
CheckIsRemote(const std::string & deviceId)3766 bool AbilityManagerService::CheckIsRemote(const std::string& deviceId)
3767 {
3768     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3769     if (deviceId.empty()) {
3770         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckIsRemote: deviceId is empty.");
3771         return false;
3772     }
3773     std::string localDeviceId;
3774     if (!GetLocalDeviceId(localDeviceId)) {
3775         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckIsRemote: get local deviceId failed");
3776         return false;
3777     }
3778     if (localDeviceId == deviceId) {
3779         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckIsRemote: deviceId is local.");
3780         return false;
3781     }
3782     TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str());
3783     return true;
3784 }
3785 
CheckIfOperateRemote(const Want & want)3786 bool AbilityManagerService::CheckIfOperateRemote(const Want &want)
3787 {
3788     std::string deviceId = want.GetElement().GetDeviceID();
3789     if (deviceId.empty() || want.GetElement().GetBundleName().empty() ||
3790         want.GetElement().GetAbilityName().empty()) {
3791         TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty");
3792         return false;
3793     }
3794     return CheckIsRemote(deviceId);
3795 }
3796 
GetLocalDeviceId(std::string & localDeviceId)3797 bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId)
3798 {
3799     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3800     auto localNode = std::make_unique<NodeBasicInfo>();
3801     int32_t errCode = GetLocalNodeDeviceInfo(DM_PKG_NAME, localNode.get());
3802     if (errCode != ERR_OK) {
3803         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::GetLocalNodeDeviceInfo errCode = %{public}d", errCode);
3804         return false;
3805     }
3806     if (localNode != nullptr) {
3807         localDeviceId = localNode->networkId;
3808         TAG_LOGD(AAFwkTag::ABILITYMGR, "get local deviceId, deviceId = %{public}s",
3809             AnonymizeDeviceId(localDeviceId).c_str());
3810         return true;
3811     }
3812     TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::GetLocalDeviceId localDeviceId null");
3813     return false;
3814 }
3815 
AnonymizeDeviceId(const std::string & deviceId)3816 std::string AbilityManagerService::AnonymizeDeviceId(const std::string& deviceId)
3817 {
3818     if (deviceId.length() < NON_ANONYMIZE_LENGTH) {
3819         return EMPTY_DEVICE_ID;
3820     }
3821     std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
3822     anonDeviceId.append("******");
3823     return anonDeviceId;
3824 }
3825 
MinimizeAbility(const sptr<IRemoteObject> & token,bool fromUser)3826 int AbilityManagerService::MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)
3827 {
3828     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3829     TAG_LOGI(AAFwkTag::ABILITYMGR, "Minimize ability, fromUser:%{public}d.", fromUser);
3830     if (!VerificationAllToken(token)) {
3831         return ERR_INVALID_VALUE;
3832     }
3833 
3834     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3835     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3836     if (!JudgeSelfCalled(abilityRecord)) {
3837         return CHECK_PERMISSION_FAILED;
3838     }
3839 
3840     auto type = abilityRecord->GetAbilityInfo().type;
3841     if (type != AppExecFwk::AbilityType::PAGE) {
3842         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except page ability.");
3843         return ERR_WRONG_INTERFACE_CALL;
3844     }
3845 
3846     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3847         return ERR_WOULD_BLOCK;
3848     }
3849 
3850     auto missionListManager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
3851     if (!missionListManager) {
3852         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null.");
3853         return ERR_INVALID_VALUE;
3854     }
3855     return missionListManager->MinimizeAbility(token, fromUser);
3856 }
3857 
MinimizeUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,bool fromUser)3858 int AbilityManagerService::MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo,
3859     bool fromUser)
3860 {
3861     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3862     TAG_LOGD(AAFwkTag::ABILITYMGR, "Minimize ui extension ability, fromUser:%{public}d.", fromUser);
3863     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3864     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3865     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3866     if (!JudgeSelfCalled(abilityRecord)) {
3867         return CHECK_PERMISSION_FAILED;
3868     }
3869 
3870     std::shared_ptr<AbilityConnectManager> connectManager;
3871     std::shared_ptr<AbilityRecord> targetRecord;
3872     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3873     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3874     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3875 
3876     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3877     if (result != ERR_OK) {
3878         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3879         return result;
3880     }
3881 
3882     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3883         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except ui extension ability.");
3884         return ERR_WRONG_INTERFACE_CALL;
3885     }
3886     extensionSessionInfo->uiExtensionComponentId = (
3887         static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
3888         static_cast<uint64_t>(extensionSessionInfo->persistentId);
3889     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
3890         extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3891     connectManager->BackgroundAbilityWindowLocked(targetRecord, extensionSessionInfo);
3892     return ERR_OK;
3893 }
3894 
SetMinimizedDuringFreeInstall(const sptr<SessionInfo> & sessionInfo)3895 void AbilityManagerService::SetMinimizedDuringFreeInstall(const sptr<SessionInfo> &sessionInfo)
3896 {
3897     if (sessionInfo == nullptr) {
3898         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
3899         return;
3900     }
3901 
3902     if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
3903         return;
3904     }
3905 
3906     std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
3907     if (sessionId.empty()) {
3908         return;
3909     }
3910 
3911     if (freeInstallManager_ == nullptr) {
3912         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
3913         return;
3914     }
3915     FreeInstallInfo taskInfo;
3916     if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
3917         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task with sessionId=%{public}s does not exist",
3918             sessionId.c_str());
3919         return;
3920     }
3921 
3922     if (taskInfo.isFreeInstallFinished) {
3923         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
3924         return;
3925     }
3926 
3927     {
3928         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
3929         auto it = preStartSessionMap_.find(sessionId);
3930         if (it == preStartSessionMap_.end()) {
3931             TAG_LOGI(AAFwkTag::ABILITYMGR, "session info with sessionId=%{public}s does not exist",
3932                 sessionId.c_str());
3933             return;
3934         }
3935         it->second->isMinimizedDuringFreeInstall = true;
3936     }
3937 }
3938 
MinimizeUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool fromUser,uint32_t sceneFlag)3939 int AbilityManagerService::MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser,
3940     uint32_t sceneFlag)
3941 {
3942     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3943     TAG_LOGI(AAFwkTag::ABILITYMGR, "Called, sceneFlag: %{public}u", sceneFlag);
3944     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3945         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
3946         return ERR_INVALID_VALUE;
3947     }
3948 
3949     if (!IsCallerSceneBoard()) {
3950         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
3951         return ERR_WRONG_INTERFACE_CALL;
3952     }
3953 
3954     SetMinimizedDuringFreeInstall(sessionInfo);
3955 
3956     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3957     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3958     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3959     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3960     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3961         return ERR_WOULD_BLOCK;
3962     }
3963     return uiAbilityManager->MinimizeUIAbility(abilityRecord, fromUser, sceneFlag);
3964 }
3965 
ConnectAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t userId)3966 int AbilityManagerService::ConnectAbility(
3967     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)
3968 {
3969     return ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::SERVICE, userId);
3970 }
3971 
ConnectAbilityCommon(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,AppExecFwk::ExtensionAbilityType extensionType,int32_t userId,bool isQueryExtensionOnly)3972 int AbilityManagerService::ConnectAbilityCommon(
3973     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
3974     AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)
3975 {
3976     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3977     TAG_LOGI(AAFwkTag::SERVICE_EXT,
3978         "Connect ability called, element uri: %{public}s.", want.GetElement().GetURI().c_str());
3979     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3980     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3981     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE && want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
3982         TAG_LOGE(AAFwkTag::SERVICE_EXT, "error to have UISERVICEHOSTPROXY_KEY");
3983         return ERR_WRONG_INTERFACE_CALL;
3984     }
3985     if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && IsCrossUserCall(userId)) {
3986         CHECK_CALLER_IS_SYSTEM_APP;
3987     }
3988     EventInfo eventInfo = BuildEventInfo(want, userId);
3989 
3990     int result;
3991 #ifdef WITH_DLP
3992     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
3993     if (result != ERR_OK) {
3994         TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckDlpForExtension error.");
3995         eventInfo.errCode = result;
3996         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3997         return result;
3998     }
3999 #endif // WITH_DLP
4000 
4001     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
4002     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4003         interceptorExecuter_->DoProcess(interceptorParam);
4004     if (result != ERR_OK) {
4005         TAG_LOGE(AAFwkTag::SERVICE_EXT, "interceptorExecuter_ is nullptr or DoProcess return error.");
4006         eventInfo.errCode = result;
4007         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4008         return result;
4009     }
4010 
4011     int32_t validUserId = GetValidUserId(userId);
4012 
4013     if (AbilityUtil::IsStartFreeInstall(want) && freeInstallManager_ != nullptr) {
4014         std::string localDeviceId;
4015         if (!GetLocalDeviceId(localDeviceId)) {
4016             TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s: Get Local DeviceId failed", __func__);
4017             eventInfo.errCode = ERR_INVALID_VALUE;
4018             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4019             return ERR_INVALID_VALUE;
4020         }
4021         result = freeInstallManager_->ConnectFreeInstall(want, validUserId, callerToken, localDeviceId);
4022         if (result != ERR_OK) {
4023             eventInfo.errCode = result;
4024             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4025             return result;
4026         }
4027     }
4028 
4029     Want abilityWant = want;
4030     AbilityRequest abilityRequest;
4031     std::string uri = abilityWant.GetUri().ToString();
4032     bool isFileUri = (abilityWant.GetUri().GetScheme() == "file");
4033     if (!uri.empty() && !isFileUri) {
4034         // if the want include uri, it may only has uri information. it is probably a datashare extension.
4035         TAG_LOGD(AAFwkTag::SERVICE_EXT,
4036             "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
4037         AppExecFwk::ExtensionAbilityInfo extensionInfo;
4038         auto bms = GetBundleManager();
4039         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4040 
4041         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4042         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4043             TAG_LOGE(AAFwkTag::SERVICE_EXT, "Invalid extension ability info.");
4044             eventInfo.errCode = ERR_INVALID_VALUE;
4045             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4046             return ERR_INVALID_VALUE;
4047         }
4048         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4049     }
4050 
4051     if (CheckIfOperateRemote(abilityWant)) {
4052         TAG_LOGD(AAFwkTag::SERVICE_EXT, "AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility");
4053         eventInfo.errCode = ConnectRemoteAbility(abilityWant, callerToken, connect->AsObject());
4054         if (eventInfo.errCode != ERR_OK) {
4055             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4056         }
4057         return eventInfo.errCode;
4058     }
4059     UpdateCallerInfo(abilityWant, callerToken);
4060 
4061     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4062         TAG_LOGD(AAFwkTag::SERVICE_EXT, "invalid Token.");
4063         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr, extensionType);
4064         if (eventInfo.errCode != ERR_OK) {
4065             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4066         }
4067         return eventInfo.errCode;
4068     }
4069     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken, extensionType, nullptr,
4070         isQueryExtensionOnly);
4071     if (eventInfo.errCode != ERR_OK) {
4072         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4073     }
4074     return eventInfo.errCode;
4075 }
4076 
ConnectUIExtensionAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<SessionInfo> & sessionInfo,int32_t userId,sptr<UIExtensionAbilityConnectInfo> connectInfo)4077 int AbilityManagerService::ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect,
4078     const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4079 {
4080     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4081     TAG_LOGD(AAFwkTag::ABILITYMGR,
4082         "Connect ui extension called, bundlename: %{public}s, ability is %{public}s, userId is %{pravite}d",
4083         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
4084     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4085     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4086     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
4087 
4088     if (IsCrossUserCall(userId)) {
4089         CHECK_CALLER_IS_SYSTEM_APP;
4090     }
4091 
4092     EventInfo eventInfo = BuildEventInfo(want, userId);
4093     sptr<IRemoteObject> callerToken = sessionInfo->callerToken;
4094 
4095     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
4096         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectUIExtensionAbility VerificationAllToken failed.");
4097         eventInfo.errCode = ERR_INVALID_VALUE;
4098         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4099         return ERR_INVALID_CALLER;
4100     }
4101 
4102     int result;
4103 #ifdef WITH_DLP
4104     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
4105     if (result != ERR_OK) {
4106         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
4107         eventInfo.errCode = result;
4108         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4109         return result;
4110     }
4111 #endif // WITH_DLP
4112 
4113     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
4114     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4115         interceptorExecuter_->DoProcess(interceptorParam);
4116     if (result != ERR_OK) {
4117         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
4118         eventInfo.errCode = result;
4119         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4120         return result;
4121     }
4122 
4123     int32_t validUserId = GetValidUserId(userId);
4124 
4125     Want abilityWant = want;
4126     AbilityRequest abilityRequest;
4127     std::string uri = abilityWant.GetUri().ToString();
4128     if (!uri.empty()) {
4129         // if the want include uri, it may only has uri information.
4130         TAG_LOGI(AAFwkTag::ABILITYMGR,
4131             "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
4132         AppExecFwk::ExtensionAbilityInfo extensionInfo;
4133         auto bms = GetBundleManager();
4134         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4135 
4136         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4137         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4138             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid extension ability info.");
4139             eventInfo.errCode = ERR_INVALID_VALUE;
4140             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4141             return ERR_INVALID_VALUE;
4142         }
4143         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4144     }
4145 
4146     UpdateCallerInfo(abilityWant, callerToken);
4147 
4148     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4149         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s invalid Token.", __func__);
4150         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr,
4151             AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4152         if (eventInfo.errCode != ERR_OK) {
4153             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4154         }
4155         return eventInfo.errCode;
4156     }
4157     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken,
4158         AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4159     if (eventInfo.errCode != ERR_OK) {
4160         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4161     }
4162     return eventInfo.errCode;
4163 }
4164 
BuildEventInfo(const Want & want,int32_t userId)4165 EventInfo AbilityManagerService::BuildEventInfo(const Want &want, int32_t userId)
4166 {
4167     EventInfo eventInfo;
4168     eventInfo.userId = userId;
4169     eventInfo.bundleName = want.GetElement().GetBundleName();
4170     eventInfo.moduleName = want.GetElement().GetModuleName();
4171     eventInfo.abilityName = want.GetElement().GetAbilityName();
4172     return eventInfo;
4173 }
4174 
DisconnectAbility(sptr<IAbilityConnection> connect)4175 int AbilityManagerService::DisconnectAbility(sptr<IAbilityConnection> connect)
4176 {
4177     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4178     TAG_LOGD(AAFwkTag::SERVICE_EXT, "Disconnect ability begin.");
4179     EventInfo eventInfo;
4180     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4181     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4182 
4183     if (ERR_OK != DisconnectLocalAbility(connect) &&
4184         ERR_OK != DisconnectRemoteAbility(connect->AsObject())) {
4185         eventInfo.errCode = INNER_ERR;
4186         EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4187     }
4188     return ERR_OK;
4189 }
4190 
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)4191 int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId,
4192     const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
4193     AppExecFwk::ExtensionAbilityType extensionType, const sptr<SessionInfo> &sessionInfo,
4194     bool isQueryExtensionOnly, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4195 {
4196     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4197     TAG_LOGD(AAFwkTag::SERVICE_EXT, "called");
4198     StartAbilityInfoWrap threadLocalInfo;
4199     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
4200     if (!CheckCrossUser(userId, extensionType)) {
4201         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Multi-user non-concurrent mode is not satisfied.");
4202         return ERR_CROSS_USER;
4203     }
4204 
4205     AbilityRequest abilityRequest;
4206     ErrCode result = ERR_OK;
4207     if (isQueryExtensionOnly ||
4208         AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4209         result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, userId);
4210     } else {
4211         result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId);
4212     }
4213     abilityRequest.sessionInfo = sessionInfo;
4214 
4215     Want requestWant = want;
4216     CHECK_POINTER_AND_RETURN_LOG(connect, ERR_INVALID_VALUE, "connect is nullptr");
4217     TAG_LOGD(AAFwkTag::SERVICE_EXT, "requestWant SetParam success");
4218 
4219     if (result != ERR_OK) {
4220         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Generate ability request error.");
4221         return result;
4222     }
4223 
4224     result = CheckPermissionForUIService(extensionType, want, abilityRequest);
4225     if (result != ERR_OK) {
4226         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckPermissionForUIService failed");
4227         return result;
4228     }
4229     auto abilityInfo = abilityRequest.abilityInfo;
4230     threadLocalInfo.SetStartAbilityInfo(abilityInfo);
4231     if (abilityInfo.isStageBasedModel) {
4232         bool isService = (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE);
4233         if (isService && extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
4234             TAG_LOGE(AAFwkTag::SERVICE_EXT, "Service extension type, please use ConnectAbility.");
4235             return ERR_WRONG_INTERFACE_CALL;
4236         }
4237         // not allow app to connect other extension by using connectServiceExtensionAbility
4238         bool isVpn = abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::VPN;
4239         if (callerToken && extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && !isService && !isVpn) {
4240             TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability, type not service");
4241             return TARGET_ABILITY_NOT_SERVICE;
4242         }
4243     }
4244     int32_t validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : userId;
4245     TAG_LOGD(AAFwkTag::SERVICE_EXT, "validUserId : %{public}d, singleton is : %{public}d",
4246         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
4247 
4248     result = CheckStaticCfgPermission(abilityRequest, false, -1);
4249     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
4250         TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckStaticCfgPermission error, result is %{public}d.", result);
4251         return ERR_STATIC_CFG_PERMISSION;
4252     }
4253 
4254     AppExecFwk::ExtensionAbilityType targetExtensionType = abilityInfo.extensionAbilityType;
4255     TAG_LOGD(AAFwkTag::SERVICE_EXT, "extension type %{public}d.", targetExtensionType);
4256     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4257         if (!AAFwk::UIExtensionUtils::IsUIExtension(targetExtensionType)
4258             && targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW) {
4259             TAG_LOGE(AAFwkTag::SERVICE_EXT, "Try to connect UI extension, but target ability is not UI extension.");
4260             return ERR_WRONG_INTERFACE_CALL;
4261         }
4262 
4263         // Cause window has used this api, don't check it when type is window.
4264         if (targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW &&
4265             !PermissionVerification::GetInstance()->VerifyCallingPermission(
4266                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY)) {
4267             TAG_LOGE(AAFwkTag::SERVICE_EXT, "Permission %{public}s verification failed.",
4268                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY);
4269             return ERR_PERMISSION_DENIED;
4270         }
4271     }
4272 
4273     auto type = abilityInfo.type;
4274     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4275         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Connect ability failed, target ability is not Service.");
4276         return TARGET_ABILITY_NOT_SERVICE;
4277     }
4278 
4279     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
4280         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
4281     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
4282         afterCheckExecuter_->DoProcess(afterCheckParam);
4283     if (result != ERR_OK) {
4284         TAG_LOGE(AAFwkTag::SERVICE_EXT, "afterCheckExecuter_ is nullptr or DoProcess return error.");
4285         return result;
4286     }
4287 
4288     result = CheckCallServicePermission(abilityRequest);
4289     if (result != ERR_OK) {
4290         TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s CheckCallServicePermission error.", __func__);
4291         return result;
4292     }
4293 
4294     ReportAppConnectOtherExtensionEvent(abilityInfo, want);
4295 
4296     if (!ExtensionPermissionsUtil::CheckSAPermission(targetExtensionType)) {
4297         TAG_LOGE(AAFwkTag::SERVICE_EXT, "The SA doesn't have permission for target extension.");
4298         return CHECK_PERMISSION_FAILED;
4299     }
4300 
4301     result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
4302     if (result != ERR_OK) {
4303         TAG_LOGE(AAFwkTag::SERVICE_EXT, "ConnectAbility: App data ability preloading failed, '%{public}s', %{public}d",
4304             abilityInfo.bundleName.c_str(),
4305             result);
4306         return result;
4307     }
4308 
4309     auto connectManager = GetConnectManagerByUserId(validUserId);
4310     if (connectManager == nullptr) {
4311         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager is nullptr. userId=%{public}d", validUserId);
4312         return ERR_INVALID_VALUE;
4313     }
4314 
4315     if (!ResSchedUtil::GetInstance().NeedReportByPidWhenConnect(abilityInfo)) {
4316         // these extension type is reported in connectManager instead of here
4317         ReportEventToRSS(abilityInfo, callerToken);
4318     }
4319     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(const_cast<Want &>(abilityRequest.want),
4320         abilityRequest.abilityInfo.extensionAbilityType);
4321     SetAbilityRequestSessionInfo(abilityRequest, targetExtensionType);
4322     return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo);
4323 }
4324 
ConnectRemoteAbility(Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)4325 int AbilityManagerService::ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken,
4326     const sptr<IRemoteObject> &connect)
4327 {
4328     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin ConnectAbilityRemote", __func__);
4329     UpdateDmsCallerInfo(want, callerToken);
4330     if (AddStartControlParam(want, callerToken) != ERR_OK) {
4331         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
4332         return ERR_INVALID_VALUE;
4333     }
4334     DistributedClient dmsClient;
4335     return dmsClient.ConnectRemoteAbility(want, connect);
4336 }
4337 
DisconnectLocalAbility(const sptr<IAbilityConnection> & connect)4338 int AbilityManagerService::DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)
4339 {
4340     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4341     auto currentConnectManager = GetCurrentConnectManager();
4342     CHECK_POINTER_AND_RETURN(currentConnectManager, ERR_NO_INIT);
4343     if (currentConnectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4344         return ERR_OK;
4345     }
4346     // If current connectManager does not exist connect, then try connectManagerU0
4347     auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
4348     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4349     if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4350         return ERR_OK;
4351     }
4352 
4353     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
4354     if (userId == U0_USER_ID) {
4355         auto connectManagers = GetConnectManagers();
4356         for (auto& item : connectManagers) {
4357             if (item.second && item.second->DisconnectAbilityLocked(connect) == ERR_OK) {
4358                 return ERR_OK;
4359             }
4360         }
4361     }
4362 
4363     // EnterpriseAdminExtensionAbility Scene
4364     connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT);
4365     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4366     return connectManager->DisconnectAbilityLocked(connect);
4367 }
4368 
DisconnectRemoteAbility(const sptr<IRemoteObject> & connect)4369 int AbilityManagerService::DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)
4370 {
4371     TAG_LOGI(AAFwkTag::SERVICE_EXT, "%{public}s begin DisconnectAbilityRemote", __func__);
4372     int32_t callerUid = IPCSkeleton::GetCallingUid();
4373     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4374     DistributedClient dmsClient;
4375     return dmsClient.DisconnectRemoteAbility(connect, callerUid, accessToken);
4376 }
4377 
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callBack,AAFwk::WantParams & wantParams)4378 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
4379     int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
4380 {
4381     CHECK_CALLER_IS_SYSTEM_APP;
4382     TAG_LOGI(AAFwkTag::ABILITYMGR, "ContinueMission missionId: %{public}d", missionId);
4383     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4384         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4385         return CHECK_PERMISSION_FAILED;
4386     }
4387 
4388     DistributedClient dmsClient;
4389     return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams);
4390 }
4391 
ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,const sptr<IRemoteObject> & callback)4392 int AbilityManagerService::ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,
4393     const sptr<IRemoteObject> &callback)
4394 {
4395     CHECK_CALLER_IS_SYSTEM_APP;
4396     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
4397     AAFWK::ContinueRadar::GetInstance().ClickIconContinue("ContinueMission");
4398     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4399         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4400         return CHECK_PERMISSION_FAILED;
4401     }
4402 
4403     DistributedClient dmsClient;
4404     return dmsClient.ContinueMission(continueMissionInfo, callback);
4405 }
4406 
ContinueAbility(const std::string & deviceId,int32_t missionId,uint32_t versionCode)4407 int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)
4408 {
4409     TAG_LOGI(AAFwkTag::ABILITYMGR,
4410         "ContinueAbility missionId = %{public}d, version = %{public}u.", missionId, versionCode);
4411     if (!CheckCallerIsDmsProcess()) {
4412         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check processName failed");
4413         return ERR_INVALID_VALUE;
4414     }
4415 
4416     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4417     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4418         auto uiAbilityManager = GetCurrentUIAbilityManager();
4419         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4420         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4421     } else {
4422         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4423         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4424         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4425     }
4426     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4427 
4428     abilityRecord->ContinueAbility(deviceId, versionCode);
4429     return ERR_OK;
4430 }
4431 
StartContinuation(const Want & want,const sptr<IRemoteObject> & abilityToken,int32_t status)4432 int AbilityManagerService::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)
4433 {
4434     TAG_LOGI(AAFwkTag::ABILITYMGR, "Start Continuation.");
4435     if (!CheckIfOperateRemote(want)) {
4436         TAG_LOGE(AAFwkTag::ABILITYMGR, "deviceId or bundle name or abilityName empty");
4437         return ERR_INVALID_VALUE;
4438     }
4439     CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4440 
4441     int32_t appUid = IPCSkeleton::GetCallingUid();
4442     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4443         TAG_LOGI(AAFwkTag::ABILITYMGR,
4444             "AbilityManagerService::Try to StartContinuation");
4445     int32_t missionId = -1;
4446     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4447         missionId = GetMissionIdByAbilityTokenInner(abilityToken);
4448         if (!missionId) {
4449             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
4450             return ERR_INVALID_VALUE;
4451         }
4452     } else {
4453         missionId = GetMissionIdByAbilityToken(abilityToken);
4454     }
4455     if (missionId < 0) {
4456         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartContinuation failed to get missionId.");
4457         return ERR_INVALID_VALUE;
4458     }
4459     AAFWK::ContinueRadar::GetInstance().SaveDataRemoteWant("StartContinuation");
4460     DistributedClient dmsClient;
4461     auto result =  dmsClient.StartContinuation(want, missionId, appUid, status, accessToken);
4462     if (result != ERR_OK) {
4463         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartContinuation failed, result = %{public}d, notify caller", result);
4464         NotifyContinuationResult(missionId, result);
4465     }
4466     return result;
4467 }
4468 
NotifyCompleteContinuation(const std::string & deviceId,int32_t sessionId,bool isSuccess)4469 void AbilityManagerService::NotifyCompleteContinuation(const std::string &deviceId,
4470     int32_t sessionId, bool isSuccess)
4471 {
4472     TAG_LOGI(AAFwkTag::ABILITYMGR, "NotifyCompleteContinuation.");
4473     AAFWK::ContinueRadar::GetInstance().ClickIconRecvOver("NotifyCompleteContinuation");
4474     sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4475     if (samgrProxy == nullptr) {
4476         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get samgrProxy");
4477         return;
4478     }
4479     sptr<IRemoteObject> bmsProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
4480     if (bmsProxy == nullptr) {
4481         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms from samgr");
4482         return;
4483     }
4484     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bmsProxy);
4485     if (bundleMgr == nullptr) {
4486         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms");
4487         return;
4488     }
4489     int32_t callerUid = IPCSkeleton::GetCallingUid();
4490     std::string callerBundleName;
4491     // reset ipc identity
4492     auto identity = IPCSkeleton::ResetCallingIdentity();
4493     bool result = bundleMgr->GetBundleNameForUid(callerUid, callerBundleName);
4494     // set ipc identity to raw
4495     IPCSkeleton::SetCallingIdentity(identity);
4496     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName: %{public}s", callerBundleName.c_str());
4497     DistributedClient dmsClient;
4498     dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess, callerBundleName);
4499 }
4500 
NotifyContinuationResult(int32_t missionId,int32_t result)4501 int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result)
4502 {
4503     TAG_LOGI(AAFwkTag::ABILITYMGR, "Notify Continuation Result : %{public}d.", result);
4504 
4505     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4506     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4507         auto uiAbilityManager = GetCurrentUIAbilityManager();
4508         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4509         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4510     } else {
4511         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4512         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4513         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4514     }
4515     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4516 
4517     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
4518         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
4519         return ERR_INVALID_VALUE;
4520     }
4521     abilityRecord->NotifyContinuationResult(result);
4522     return ERR_OK;
4523 }
4524 
StartSyncRemoteMissions(const std::string & devId,bool fixConflict,int64_t tag)4525 int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
4526 {
4527     CHECK_CALLER_IS_SYSTEM_APP;
4528     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4529         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4530         return CHECK_PERMISSION_FAILED;
4531     }
4532     DistributedClient dmsClient;
4533     return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag);
4534 }
4535 
StopSyncRemoteMissions(const std::string & devId)4536 int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId)
4537 {
4538     CHECK_CALLER_IS_SYSTEM_APP;
4539     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4540         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4541         return CHECK_PERMISSION_FAILED;
4542     }
4543     DistributedClient dmsClient;
4544     return dmsClient.StopSyncRemoteMissions(devId);
4545 }
4546 
RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4547 int AbilityManagerService::RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4548 {
4549     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4550         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
4551         return CHECK_PERMISSION_FAILED;
4552     }
4553     return DelayedSingleton<ConnectionStateManager>::GetInstance()->RegisterObserver(observer);
4554 }
4555 
UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4556 int AbilityManagerService::UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4557 {
4558     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4559         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
4560         return CHECK_PERMISSION_FAILED;
4561     }
4562     return DelayedSingleton<ConnectionStateManager>::GetInstance()->UnregisterObserver(observer);
4563 }
4564 
4565 #ifdef WITH_DLP
GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> & infos)4566 int AbilityManagerService::GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)
4567 {
4568     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4569         TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get dlp connection infos if caller is not sa.");
4570         return CHECK_PERMISSION_FAILED;
4571     }
4572     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetDlpConnectionInfos(infos);
4573 
4574     return ERR_OK;
4575 }
4576 #endif // WITH_DLP
4577 
GetConnectionData(std::vector<AbilityRuntime::ConnectionData> & connectionData)4578 int AbilityManagerService::GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)
4579 {
4580     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4581         TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get connection data if caller is not sa.");
4582         return CHECK_PERMISSION_FAILED;
4583     }
4584     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetConnectionData(connectionData);
4585 
4586     return ERR_OK;
4587 }
4588 
RegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4589 int AbilityManagerService::RegisterMissionListener(const std::string &deviceId,
4590     const sptr<IRemoteMissionListener> &listener)
4591 {
4592     CHECK_CALLER_IS_SYSTEM_APP;
4593     std::string localDeviceId;
4594     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4595         TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterMissionListener: Check DeviceId failed");
4596         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4597     }
4598     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4599     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4600         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4601         return CHECK_PERMISSION_FAILED;
4602     }
4603     DistributedClient dmsClient;
4604     return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4605 }
4606 
RegisterOnListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4607 int AbilityManagerService::RegisterOnListener(const std::string &type,
4608     const sptr<IRemoteOnListener> &listener)
4609 {
4610     CHECK_CALLER_IS_SYSTEM_APP;
4611     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4612     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4613         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4614         return CHECK_PERMISSION_FAILED;
4615     }
4616     DistributedClient dmsClient;
4617     return dmsClient.RegisterOnListener(type, listener->AsObject());
4618 }
4619 
RegisterOffListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4620 int AbilityManagerService::RegisterOffListener(const std::string &type,
4621     const sptr<IRemoteOnListener> &listener)
4622 {
4623     CHECK_CALLER_IS_SYSTEM_APP;
4624     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4625     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4626         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4627         return CHECK_PERMISSION_FAILED;
4628     }
4629     DistributedClient dmsClient;
4630     return dmsClient.RegisterOffListener(type, listener->AsObject());
4631 }
4632 
UnRegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4633 int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId,
4634     const sptr<IRemoteMissionListener> &listener)
4635 {
4636     CHECK_CALLER_IS_SYSTEM_APP;
4637     std::string localDeviceId;
4638     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4639         TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterMissionListener: Check DeviceId failed");
4640         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4641     }
4642     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4643     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4644         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4645         return CHECK_PERMISSION_FAILED;
4646     }
4647     DistributedClient dmsClient;
4648     return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4649 }
4650 
GetWantSender(const WantSenderInfo & wantSenderInfo,const sptr<IRemoteObject> & callerToken,int32_t uid)4651 sptr<IWantSender> AbilityManagerService::GetWantSender(
4652     const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken,
4653     int32_t uid)
4654 {
4655     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4656     auto pendingWantManager = GetCurrentPendingWantManager();
4657     CHECK_POINTER_AND_RETURN(pendingWantManager, nullptr);
4658 
4659     auto bms = GetBundleManager();
4660     CHECK_POINTER_AND_RETURN(bms, nullptr);
4661 
4662     int32_t callerUid = IPCSkeleton::GetCallingUid();
4663     int32_t userId = wantSenderInfo.userId;
4664     int32_t bundleMgrResult = 0;
4665 
4666     if (userId < 0) {
4667         if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4668             GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4669             TAG_LOGE(AAFwkTag::ABILITYMGR, "GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
4670             return nullptr;
4671         }
4672     }
4673     //sa caller and has uid,no need find from bms.
4674     bool isSpecifyUidBySa = (uid != -1) && (AAFwk::PermissionVerification::GetInstance()->IsSACall());
4675 
4676     int32_t appUid = 0;
4677     int32_t appIndex = 0;
4678     if (!wantSenderInfo.allWants.empty()) {
4679         AppExecFwk::BundleInfo bundleInfo;
4680         std::string bundleName = wantSenderInfo.allWants.back().want.GetElement().GetBundleName();
4681         GetRunningMultiAppIndex(bundleName, callerUid, appIndex);
4682         if (!isSpecifyUidBySa) {
4683             bundleMgrResult = IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName,
4684                 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
4685                 appIndex, bundleInfo, userId));
4686             if (bundleMgrResult == ERR_OK) {
4687                 appUid = bundleInfo.uid;
4688             }
4689         } else {
4690             appUid = uid;
4691         }
4692         TAG_LOGD(AAFwkTag::ABILITYMGR, "App bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), appUid);
4693     }
4694     if (!CheckSenderWantInfo(callerUid, wantSenderInfo)) {
4695         TAG_LOGE(AAFwkTag::ABILITYMGR, "check bundleName failed");
4696         return nullptr;
4697     }
4698 
4699     bool isSystemApp = false;
4700     if (!wantSenderInfo.bundleName.empty() && !isSpecifyUidBySa) {
4701         AppExecFwk::BundleInfo bundleInfo;
4702         bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(wantSenderInfo.bundleName,
4703             AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
4704         if (bundleMgrResult) {
4705             isSystemApp = bundleInfo.applicationInfo.isSystemApp;
4706         }
4707     }
4708 
4709     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName = %{public}s, appIndex:%{public}d",
4710         wantSenderInfo.bundleName.c_str(), appIndex);
4711     return pendingWantManager->GetWantSender(callerUid, appUid, isSystemApp, wantSenderInfo, callerToken, appIndex);
4712 }
4713 
SendWantSender(sptr<IWantSender> target,const SenderInfo & senderInfo)4714 int AbilityManagerService::SendWantSender(sptr<IWantSender> target, const SenderInfo &senderInfo)
4715 {
4716     TAG_LOGI(AAFwkTag::ABILITYMGR, "Send want sender.");
4717     auto pendingWantManager = GetCurrentPendingWantManager();
4718     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4719     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4720     return pendingWantManager->SendWantSender(target, senderInfo);
4721 }
4722 
CancelWantSender(const sptr<IWantSender> & sender)4723 void AbilityManagerService::CancelWantSender(const sptr<IWantSender> &sender)
4724 {
4725     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4726     auto pendingWantManager = GetCurrentPendingWantManager();
4727     CHECK_POINTER(pendingWantManager);
4728     CHECK_POINTER(sender);
4729 
4730     sptr<IRemoteObject> obj = sender->AsObject();
4731     if (!obj || obj->IsProxyObject()) {
4732         TAG_LOGE(AAFwkTag::ABILITYMGR, "obj is nullptr or obj is a proxy obj.");
4733         return;
4734     }
4735 
4736     auto bms = GetBundleManager();
4737     CHECK_POINTER(bms);
4738 
4739     int32_t callerUid = IPCSkeleton::GetCallingUid();
4740     sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
4741 
4742     int userId = -1;
4743     if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4744         GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4745         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
4746         return;
4747     }
4748 
4749     bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
4750     pendingWantManager->CancelWantSender(isSystemAppCall, sender);
4751 }
4752 
CancelWantSenderByFlags(const sptr<IWantSender> & sender,uint32_t flags)4753 void AbilityManagerService::CancelWantSenderByFlags(const sptr<IWantSender> &sender, uint32_t flags)
4754 {
4755     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4756     auto pendingWantManager = GetCurrentPendingWantManager();
4757     CHECK_POINTER(pendingWantManager);
4758     CHECK_POINTER(sender);
4759 
4760     sptr<IRemoteObject> obj = sender->AsObject();
4761     if (!obj || obj->IsProxyObject()) {
4762         TAG_LOGE(AAFwkTag::ABILITYMGR, "obj is nullptr or obj is a proxy obj.");
4763         return;
4764     }
4765 
4766     auto bms = GetBundleManager();
4767     CHECK_POINTER(bms);
4768 
4769     sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
4770 
4771     if (flags != 0 && record->GetKey() != nullptr &&
4772         (static_cast<uint32_t>(record->GetKey()->GetFlags()) & flags) == 0) {
4773         TAG_LOGI(AAFwkTag::ABILITYMGR, "flags=%{public}u not match wantAgent flags=%{public}d",
4774                 flags, record->GetKey()->GetFlags());
4775         return;
4776     }
4777 
4778     TAG_LOGI(AAFwkTag::ABILITYMGR, "code=%{public}d cancel by flags=%{public}u",
4779         record->GetKey() != nullptr ? record->GetKey()->GetCode() : -1, flags);
4780     bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
4781     pendingWantManager->CancelWantSender(isSystemAppCall, sender);
4782 }
4783 
GetPendingWantUid(const sptr<IWantSender> & target)4784 int AbilityManagerService::GetPendingWantUid(const sptr<IWantSender> &target)
4785 {
4786     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4787     auto pendingWantManager = GetCurrentPendingWantManager();
4788     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4789     if (target == nullptr) {
4790         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4791         return -1;
4792     }
4793     return pendingWantManager->GetPendingWantUid(target);
4794 }
4795 
GetPendingWantUserId(const sptr<IWantSender> & target)4796 int AbilityManagerService::GetPendingWantUserId(const sptr<IWantSender> &target)
4797 {
4798     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4799     auto pendingWantManager = GetCurrentPendingWantManager();
4800     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4801     if (target == nullptr) {
4802         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4803         return -1;
4804     }
4805     return pendingWantManager->GetPendingWantUserId(target);
4806 }
4807 
GetPendingWantBundleName(const sptr<IWantSender> & target)4808 std::string AbilityManagerService::GetPendingWantBundleName(const sptr<IWantSender> &target)
4809 {
4810     TAG_LOGI(AAFwkTag::ABILITYMGR, "Get pending want bundle name.");
4811     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantBundleName");
4812     auto pendingWantManager = GetCurrentPendingWantManager();
4813     CHECK_POINTER_AND_RETURN(pendingWantManager, "");
4814     CHECK_POINTER_AND_RETURN(target, "");
4815     return pendingWantManager->GetPendingWantBundleName(target);
4816 }
4817 
GetPendingWantCode(const sptr<IWantSender> & target)4818 int AbilityManagerService::GetPendingWantCode(const sptr<IWantSender> &target)
4819 {
4820     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4821     auto pendingWantManager = GetCurrentPendingWantManager();
4822     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4823     if (target == nullptr) {
4824         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4825         return -1;
4826     }
4827     return pendingWantManager->GetPendingWantCode(target);
4828 }
4829 
GetPendingWantType(const sptr<IWantSender> & target)4830 int AbilityManagerService::GetPendingWantType(const sptr<IWantSender> &target)
4831 {
4832     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4833     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantType");
4834     auto pendingWantManager = GetCurrentPendingWantManager();
4835     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4836     if (target == nullptr) {
4837         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4838         return -1;
4839     }
4840     return pendingWantManager->GetPendingWantType(target);
4841 }
4842 
RegisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)4843 void AbilityManagerService::RegisterCancelListener(const sptr<IWantSender> &sender,
4844     const sptr<IWantReceiver> &receiver)
4845 {
4846     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register cancel listener.");
4847     auto pendingWantManager = GetCurrentPendingWantManager();
4848     CHECK_POINTER(pendingWantManager);
4849     CHECK_POINTER(sender);
4850     CHECK_POINTER(receiver);
4851     pendingWantManager->RegisterCancelListener(sender, receiver);
4852 }
4853 
UnregisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)4854 void AbilityManagerService::UnregisterCancelListener(
4855     const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)
4856 {
4857     TAG_LOGI(AAFwkTag::ABILITYMGR, "Unregister cancel listener.");
4858     auto pendingWantManager = GetCurrentPendingWantManager();
4859     CHECK_POINTER(pendingWantManager);
4860     CHECK_POINTER(sender);
4861     CHECK_POINTER(receiver);
4862     pendingWantManager->UnregisterCancelListener(sender, receiver);
4863 }
4864 
GetPendingRequestWant(const sptr<IWantSender> & target,std::shared_ptr<Want> & want)4865 int AbilityManagerService::GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)
4866 {
4867     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4868     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get pending request want.");
4869     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingRequestWant");
4870     auto pendingWantManager = GetCurrentPendingWantManager();
4871     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4872     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4873     CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE);
4874     CHECK_CALLER_IS_SYSTEM_APP;
4875     return pendingWantManager->GetPendingRequestWant(target, want);
4876 }
4877 
LockMissionForCleanup(int32_t missionId)4878 int AbilityManagerService::LockMissionForCleanup(int32_t missionId)
4879 {
4880     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock mission for clean up all, id :%{public}d", missionId);
4881     auto missionListManager = GetCurrentMissionListManager();
4882     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4883     CHECK_CALLER_IS_SYSTEM_APP;
4884 
4885     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4886         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4887         return CHECK_PERMISSION_FAILED;
4888     }
4889     return missionListManager->SetMissionLockedState(missionId, true);
4890 }
4891 
UnlockMissionForCleanup(int32_t missionId)4892 int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId)
4893 {
4894     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4895     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock mission for clean up all, id :%{public}d", missionId);
4896     auto missionListManager = GetCurrentMissionListManager();
4897     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4898     CHECK_CALLER_IS_SYSTEM_APP;
4899 
4900     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4901         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4902         return CHECK_PERMISSION_FAILED;
4903     }
4904     return missionListManager->SetMissionLockedState(missionId, false);
4905 }
4906 
SetLockedState(int32_t sessionId,bool lockedState)4907 void AbilityManagerService::SetLockedState(int32_t sessionId, bool lockedState)
4908 {
4909     TAG_LOGI(AAFwkTag::ABILITYMGR, "request lock abilityRecord, sessionId :%{public}d", sessionId);
4910     if (!IsCallerSceneBoard()) {
4911         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
4912         return;
4913     }
4914     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4915     CHECK_POINTER(uiAbilityManager);
4916     auto abilityRecord = uiAbilityManager->GetAbilityRecordsById(sessionId);
4917     if (!abilityRecord) {
4918         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
4919         return;
4920     }
4921     abilityRecord->SetLockedState(lockedState);
4922 }
4923 
RegisterMissionListener(const sptr<IMissionListener> & listener)4924 int AbilityManagerService::RegisterMissionListener(const sptr<IMissionListener> &listener)
4925 {
4926     TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
4927     auto missionListManager = GetCurrentMissionListManager();
4928     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4929     CHECK_CALLER_IS_SYSTEM_APP;
4930 
4931     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4932         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4933         return CHECK_PERMISSION_FAILED;
4934     }
4935     return missionListManager->RegisterMissionListener(listener);
4936 }
4937 
UnRegisterMissionListener(const sptr<IMissionListener> & listener)4938 int AbilityManagerService::UnRegisterMissionListener(const sptr<IMissionListener> &listener)
4939 {
4940     TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
4941     auto missionListManager = GetCurrentMissionListManager();
4942     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4943     CHECK_CALLER_IS_SYSTEM_APP;
4944 
4945     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4946         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4947         return CHECK_PERMISSION_FAILED;
4948     }
4949     return missionListManager->UnRegisterMissionListener(listener);
4950 }
4951 
GetMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)4952 int AbilityManagerService::GetMissionInfos(const std::string& deviceId, int32_t numMax,
4953     std::vector<MissionInfo> &missionInfos)
4954 {
4955     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4956     TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfos.");
4957     auto missionListManager = GetCurrentMissionListManager();
4958     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4959     CHECK_CALLER_IS_SYSTEM_APP;
4960 
4961     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4962         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4963         return CHECK_PERMISSION_FAILED;
4964     }
4965 
4966     if (CheckIsRemote(deviceId)) {
4967         return GetRemoteMissionInfos(deviceId, numMax, missionInfos);
4968     }
4969 
4970     return missionListManager->GetMissionInfos(numMax, missionInfos);
4971 }
4972 
GetRemoteMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)4973 int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax,
4974     std::vector<MissionInfo> &missionInfos)
4975 {
4976     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetRemoteMissionInfos begin");
4977     DistributedClient dmsClient;
4978     int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos);
4979     if (result != ERR_OK) {
4980         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetRemoteMissionInfos failed, result = %{public}d", result);
4981         return result;
4982     }
4983     return ERR_OK;
4984 }
4985 
GetMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)4986 int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId,
4987     MissionInfo &missionInfo)
4988 {
4989     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4990     TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfo, missionId:%{public}d", missionId);
4991     auto missionListManager = GetCurrentMissionListManager();
4992     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4993     CHECK_CALLER_IS_SYSTEM_APP;
4994 
4995     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4996         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4997         return CHECK_PERMISSION_FAILED;
4998     }
4999 
5000     if (CheckIsRemote(deviceId)) {
5001         return GetRemoteMissionInfo(deviceId, missionId, missionInfo);
5002     }
5003 
5004     return missionListManager->GetMissionInfo(missionId, missionInfo);
5005 }
5006 
GetRemoteMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)5007 int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId,
5008     MissionInfo &missionInfo)
5009 {
5010     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5011     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetMissionInfoFromDms begin");
5012     std::vector<MissionInfo> missionVector;
5013     int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector);
5014     if (result != ERR_OK) {
5015         return result;
5016     }
5017     for (auto iter = missionVector.begin(); iter != missionVector.end(); iter++) {
5018         if (iter->id == missionId) {
5019             missionInfo = *iter;
5020             return ERR_OK;
5021         }
5022     }
5023     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionId not found");
5024     return ERR_INVALID_VALUE;
5025 }
5026 
CleanMission(int32_t missionId)5027 int AbilityManagerService::CleanMission(int32_t missionId)
5028 {
5029     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5030     TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanMission, missionId:%{public}d", missionId);
5031     auto missionListManager = GetCurrentMissionListManager();
5032     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5033     CHECK_CALLER_IS_SYSTEM_APP;
5034 
5035     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5036         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5037         return CHECK_PERMISSION_FAILED;
5038     }
5039 
5040     return missionListManager->ClearMission(missionId);
5041 }
5042 
CleanAllMissions()5043 int AbilityManagerService::CleanAllMissions()
5044 {
5045     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5046     TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanAllMissions ");
5047     auto missionListManager = GetCurrentMissionListManager();
5048     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5049     CHECK_CALLER_IS_SYSTEM_APP;
5050 
5051     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5052         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5053         return CHECK_PERMISSION_FAILED;
5054     }
5055 
5056     Want want;
5057     want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME);
5058     if (!IsAbilityControllerStart(want, AbilityConfig::LAUNCHER_BUNDLE_NAME)) {
5059         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
5060         return ERR_WOULD_BLOCK;
5061     }
5062 
5063     return missionListManager->ClearAllMissions();
5064 }
5065 
MoveMissionToFront(int32_t missionId)5066 int AbilityManagerService::MoveMissionToFront(int32_t missionId)
5067 {
5068     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5069     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5070     CHECK_CALLER_IS_SYSTEM_APP;
5071     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5072         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5073         return CHECK_PERMISSION_FAILED;
5074     }
5075 
5076     if (!IsAbilityControllerStartById(missionId)) {
5077         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
5078         return ERR_WOULD_BLOCK;
5079     }
5080 
5081     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5082         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5083         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5084         return uiAbilityManager->MoveMissionToFront(missionId);
5085     }
5086 
5087     auto missionListManager = GetCurrentMissionListManager();
5088     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5089     return missionListManager->MoveMissionToFront(missionId);
5090 }
5091 
MoveMissionToFront(int32_t missionId,const StartOptions & startOptions)5092 int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)
5093 {
5094     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5095     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5096     CHECK_CALLER_IS_SYSTEM_APP;
5097     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5098         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5099         return CHECK_PERMISSION_FAILED;
5100     }
5101 
5102     if (!IsAbilityControllerStartById(missionId)) {
5103         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
5104         return ERR_WOULD_BLOCK;
5105     }
5106 
5107     auto options = std::make_shared<StartOptions>(startOptions);
5108     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5109         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5110         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5111         return uiAbilityManager->MoveMissionToFront(missionId, options);
5112     }
5113 
5114     auto missionListManager = GetCurrentMissionListManager();
5115     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5116     return missionListManager->MoveMissionToFront(missionId, options);
5117 }
5118 
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)5119 int AbilityManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
5120 {
5121     CHECK_CALLER_IS_SYSTEM_APP;
5122     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5123         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5124         return CHECK_PERMISSION_FAILED;
5125     }
5126     if (wmsHandler_) {
5127         auto ret = wmsHandler_->MoveMissionsToForeground(missionIds, topMissionId);
5128         if (ret) {
5129             TAG_LOGE(AAFwkTag::ABILITYMGR, "MoveMissionsToForeground failed, missiondIds may be invalid");
5130             return ERR_INVALID_VALUE;
5131         } else {
5132             return NO_ERROR;
5133         }
5134     }
5135     return ERR_NO_INIT;
5136 }
5137 
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)5138 int AbilityManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
5139     std::vector<int32_t>& result)
5140 {
5141     CHECK_CALLER_IS_SYSTEM_APP;
5142     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5143         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
5144         return CHECK_PERMISSION_FAILED;
5145     }
5146     if (wmsHandler_) {
5147         auto ret = wmsHandler_->MoveMissionsToBackground(missionIds, result);
5148         if (ret) {
5149             TAG_LOGE(AAFwkTag::ABILITYMGR, "MoveMissionsToBackground failed, missiondIds may be invalid");
5150             return ERR_INVALID_VALUE;
5151         } else {
5152             return NO_ERROR;
5153         }
5154     }
5155     return ERR_NO_INIT;
5156 }
5157 
GetMissionIdByToken(const sptr<IRemoteObject> & token)5158 int32_t AbilityManagerService::GetMissionIdByToken(const sptr<IRemoteObject> &token)
5159 {
5160     TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken.");
5161     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5162     if (!abilityRecord) {
5163         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
5164         return ERR_INVALID_VALUE;
5165     }
5166     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
5167         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5168         return ERR_INVALID_VALUE;
5169     }
5170     return GetMissionIdByAbilityTokenInner(token);
5171 }
5172 
IsAbilityControllerStartById(int32_t missionId)5173 bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId)
5174 {
5175     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5176     auto missionListWrap = GetMissionListWrap();
5177     if (missionListWrap == nullptr) {
5178         TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null.");
5179         return true;
5180     }
5181     InnerMissionInfo innerMissionInfo;
5182     int getMission = missionListWrap->GetInnerMissionInfoById(missionId, innerMissionInfo);
5183     if (getMission != ERR_OK) {
5184         TAG_LOGE(AAFwkTag::ABILITYMGR,
5185             "cannot find mission info from MissionInfoList by missionId: %{public}d", missionId);
5186         return true;
5187     }
5188     if (!IsAbilityControllerStart(innerMissionInfo.missionInfo.want, innerMissionInfo.missionInfo.want.GetBundle())) {
5189         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s",
5190             innerMissionInfo.missionInfo.want.GetBundle().c_str());
5191         return false;
5192     }
5193     return true;
5194 }
5195 
GetConnectRecordListByCallback(sptr<IAbilityConnection> callback)5196 std::list<std::shared_ptr<ConnectionRecord>> AbilityManagerService::GetConnectRecordListByCallback(
5197     sptr<IAbilityConnection> callback)
5198 {
5199     auto connectManager = GetCurrentConnectManager();
5200     CHECK_POINTER_AND_RETURN(connectManager, std::list<std::shared_ptr<ConnectionRecord>>());
5201     return connectManager->GetConnectRecordListByCallback(callback);
5202 }
5203 
GenerateDataAbilityRequestByUri(const std::string & dataAbilityUri,AbilityRequest & abilityRequest,sptr<IRemoteObject> callerToken,int32_t userId)5204 bool AbilityManagerService::GenerateDataAbilityRequestByUri(const std::string& dataAbilityUri,
5205     AbilityRequest &abilityRequest, sptr<IRemoteObject> callerToken, int32_t userId)
5206 {
5207     auto bms = GetBundleManager();
5208     CHECK_POINTER_AND_RETURN(bms, false);
5209     TAG_LOGI(AAFwkTag::ABILITYMGR, "called. userId %{public}d", userId);
5210     bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo));
5211     if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) {
5212         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ability info for data ability acquiring.");
5213         return false;
5214     }
5215     abilityRequest.callerToken = callerToken;
5216     return true;
5217 }
5218 
AcquireDataAbility(const Uri & uri,bool tryBind,const sptr<IRemoteObject> & callerToken)5219 sptr<IAbilityScheduler> AbilityManagerService::AcquireDataAbility(
5220     const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
5221 {
5222     auto localUri(uri);
5223     if (localUri.GetScheme() != AbilityConfig::SCHEME_DATA_ABILITY) {
5224         TAG_LOGE(AAFwkTag::ABILITYMGR, "Acquire data ability with invalid uri scheme.");
5225         return nullptr;
5226     }
5227     std::vector<std::string> pathSegments;
5228     localUri.GetPathSegments(pathSegments);
5229     if (pathSegments.empty()) {
5230         TAG_LOGE(AAFwkTag::ABILITYMGR, "Acquire data ability with invalid uri path.");
5231         return nullptr;
5232     }
5233 
5234     auto userId = GetValidUserId(INVALID_USER_ID);
5235     AbilityRequest abilityRequest;
5236     if (!GenerateDataAbilityRequestByUri(localUri.ToString(), abilityRequest, callerToken, userId)) {
5237         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate data ability request by uri failed.");
5238         return nullptr;
5239     }
5240 
5241     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5242     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5243     if (!isSaCall && CheckCallDataAbilityPermission(abilityRequest, isShellCall, isSaCall) != ERR_OK) {
5244         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ability request info for data ability acquiring.");
5245         return nullptr;
5246     }
5247 
5248     TAG_LOGD(AAFwkTag::ABILITYMGR, "Query data ability info: %{public}s|%{public}s|%{public}s",
5249         abilityRequest.appInfo.name.c_str(), abilityRequest.appInfo.bundleName.c_str(),
5250         abilityRequest.abilityInfo.name.c_str());
5251 
5252     if (CheckStaticCfgPermission(abilityRequest, false, -1, true, isSaCall) !=
5253         AppExecFwk::Constants::PERMISSION_GRANTED) {
5254         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission fail");
5255         return nullptr;
5256     }
5257 
5258     if (!VerificationAllToken(callerToken)) {
5259         TAG_LOGI(AAFwkTag::ABILITYMGR, "VerificationAllToken fail");
5260         return nullptr;
5261     }
5262 
5263     if (abilityRequest.abilityInfo.applicationInfo.singleton) {
5264         userId = U0_USER_ID;
5265     }
5266 
5267     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5268     CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr);
5269     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
5270     bool isNotHap = isSaCall || isShellCall;
5271     UpdateCallerInfo(abilityRequest.want, callerToken);
5272     return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap);
5273 }
5274 
ReleaseDataAbility(sptr<IAbilityScheduler> dataAbilityScheduler,const sptr<IRemoteObject> & callerToken)5275 int AbilityManagerService::ReleaseDataAbility(
5276     sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
5277 {
5278     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
5279     if (!dataAbilityScheduler || !callerToken) {
5280         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilitySchedule or callerToken is nullptr");
5281         return ERR_INVALID_VALUE;
5282     }
5283 
5284     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler);
5285     if (!dataAbilityManager) {
5286         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityScheduler is not exists");
5287         return ERR_INVALID_VALUE;
5288     }
5289 
5290     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5291     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5292     bool isNotHap = isSaCall || isShellCall;
5293     return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isNotHap);
5294 }
5295 
AttachAbilityThread(const sptr<IAbilityScheduler> & scheduler,const sptr<IRemoteObject> & token)5296 int AbilityManagerService::AttachAbilityThread(
5297     const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
5298 {
5299     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5300     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called", __func__);
5301     CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE);
5302     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5303         return ERR_INVALID_VALUE;
5304     }
5305     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5306     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5307     if (!JudgeSelfCalled(abilityRecord)) {
5308         return CHECK_PERMISSION_FAILED;
5309     }
5310 
5311     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5312     auto abilityInfo = abilityRecord->GetAbilityInfo();
5313     auto type = abilityInfo.type;
5314     // force timeout ability for test
5315     if (IsNeedTimeoutForTest(abilityInfo.name, AbilityRecord::ConvertAbilityState(AbilityState::INITIAL))) {
5316         TAG_LOGW(AAFwkTag::ABILITYMGR,
5317             "force timeout ability for test, state:INITIAL, ability: %{public}s", abilityInfo.name.c_str());
5318         return ERR_OK;
5319     }
5320     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5321         auto connectManager = GetConnectManagerByUserId(userId);
5322         if (!connectManager) {
5323             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5324             return ERR_INVALID_VALUE;
5325         }
5326         return connectManager->AttachAbilityThreadLocked(scheduler, token);
5327     } else if (type == AppExecFwk::AbilityType::DATA) {
5328         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5329         if (!dataAbilityManager) {
5330             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
5331             return ERR_INVALID_VALUE;
5332         }
5333         return dataAbilityManager->AttachAbilityThread(scheduler, token);
5334     } else {
5335         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::LOAD };
5336         std::string entry = "AbilityManagerService::AttachAbilityThread; the end of load lifecycle.";
5337         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5338         int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5339         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5340             auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5341             CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5342             return uiAbilityManager->AttachAbilityThread(scheduler, token);
5343         }
5344         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5345         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
5346         return missionListManager->AttachAbilityThread(scheduler, token);
5347     }
5348 }
5349 
DumpSysInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5350 void AbilityManagerService::DumpSysInner(
5351     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5352 {
5353     std::vector<std::string> argList;
5354     SplitStr(args, " ", argList);
5355     if (argList.empty()) {
5356         return;
5357     }
5358 
5359     DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5360     DumpSysStateInner(args, info, isClient, isUserID, userId);
5361     DumpSysPendingInner(args, info, isClient, isUserID, userId);
5362     DumpSysProcess(args, info, isClient, isUserID, userId);
5363 }
5364 
DumpSysMissionListInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5365 void AbilityManagerService::DumpSysMissionListInner(
5366     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5367 {
5368     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5369         DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId);
5370         return;
5371     }
5372     std::shared_ptr<MissionListManagerInterface> targetManager;
5373     if (isUserID) {
5374         auto missionListManager = GetMissionListManagerByUserId(userId);
5375         if (missionListManager == nullptr) {
5376             info.push_back("error: No user found.");
5377             return;
5378         }
5379         targetManager = missionListManager;
5380     } else {
5381         targetManager = GetCurrentMissionListManager();
5382     }
5383 
5384     CHECK_POINTER(targetManager);
5385 
5386     std::vector<std::string> argList;
5387     SplitStr(args, " ", argList);
5388     if (argList.empty()) {
5389         return;
5390     }
5391 
5392     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5393         targetManager->DumpMissionList(info, isClient, argList[1]);
5394     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5395         targetManager->DumpMissionList(info, isClient);
5396     } else {
5397         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5398     }
5399 }
5400 
DumpSysMissionListInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5401 void AbilityManagerService::DumpSysMissionListInnerBySCB(
5402     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5403 {
5404     if (!isUserID) {
5405         userId = GetUserId();
5406     }
5407 
5408     std::vector<std::string> argList;
5409     SplitStr(args, " ", argList);
5410     if (argList.empty()) {
5411         return;
5412     }
5413 
5414     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5415     CHECK_POINTER(uiAbilityManager);
5416     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5417         uiAbilityManager->DumpMissionList(info, isClient, argList[1]);
5418     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5419         uiAbilityManager->DumpMissionList(info, isClient);
5420     } else {
5421         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5422     }
5423 }
5424 
DumpSysAbilityInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5425 void AbilityManagerService::DumpSysAbilityInner(
5426     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5427 {
5428     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5429         DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId);
5430         return;
5431     }
5432     std::shared_ptr<MissionListManagerInterface> targetManager;
5433     if (isUserID) {
5434         auto missionListManager = GetMissionListManagerByUserId(userId);
5435         if (missionListManager == nullptr) {
5436             info.push_back("error: No user found.");
5437             return;
5438         }
5439         targetManager = missionListManager;
5440     } else {
5441         targetManager = GetCurrentMissionListManager();
5442     }
5443 
5444     CHECK_POINTER(targetManager);
5445 
5446     std::vector<std::string> argList;
5447     SplitStr(args, " ", argList);
5448     if (argList.empty()) {
5449         return;
5450     }
5451     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5452         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList = %{public}s", argList[1].c_str());
5453         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5454         try {
5455             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5456             targetManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5457         } catch (...) {
5458             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5459             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5460         }
5461     } else {
5462         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5463     }
5464 }
5465 
DumpSysAbilityInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5466 void AbilityManagerService::DumpSysAbilityInnerBySCB(
5467     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5468 {
5469     if (!isUserID) {
5470         userId = GetUserId();
5471     }
5472 
5473     std::vector<std::string> argList;
5474     SplitStr(args, " ", argList);
5475     if (argList.empty()) {
5476         return;
5477     }
5478     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5479         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList = %{public}s", argList[1].c_str());
5480         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5481         try {
5482             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5483             auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5484             CHECK_POINTER(uiAbilityManager);
5485             uiAbilityManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5486         } catch (...) {
5487             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5488             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5489         }
5490     } else {
5491         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5492     }
5493 }
5494 
DumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5495 void AbilityManagerService::DumpSysStateInner(
5496     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5497 {
5498     TAG_LOGI(AAFwkTag::ABILITYMGR, "DumpSysStateInner begin:%{public}s", args.c_str());
5499     std::shared_ptr<AbilityConnectManager> targetManager;
5500 
5501     if (isUserID) {
5502         auto connectManager = GetConnectManagerByUserId(userId);
5503         if (connectManager == nullptr) {
5504             info.push_back("error: No user found.");
5505             return;
5506         }
5507         targetManager = connectManager;
5508     } else {
5509         targetManager = GetCurrentConnectManager();
5510     }
5511 
5512     CHECK_POINTER(targetManager);
5513 
5514     std::vector<std::string> argList;
5515     SplitStr(args, " ", argList);
5516     if (argList.empty()) {
5517         return;
5518     }
5519 
5520     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5521         targetManager->DumpState(info, isClient, argList[1]);
5522     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5523         targetManager->DumpState(info, isClient);
5524     } else {
5525         TAG_LOGI(AAFwkTag::ABILITYMGR, "uri = %{public}s", argList[1].c_str());
5526         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5527         targetManager->DumpStateByUri(info, isClient, argList[1], params);
5528     }
5529 }
5530 
DumpSysPendingInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5531 void AbilityManagerService::DumpSysPendingInner(
5532     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5533 {
5534     std::shared_ptr<PendingWantManager> targetManager;
5535     if (isUserID) {
5536         auto pendingWantManager = GetPendingWantManagerByUserId(userId);
5537         if (pendingWantManager == nullptr) {
5538             info.push_back("error: No user found.");
5539             return;
5540         }
5541         targetManager = pendingWantManager;
5542     } else {
5543         targetManager = GetCurrentPendingWantManager();
5544     }
5545 
5546     CHECK_POINTER(targetManager);
5547 
5548     std::vector<std::string> argList;
5549     SplitStr(args, " ", argList);
5550     if (argList.empty()) {
5551         return;
5552     }
5553 
5554     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5555         targetManager->DumpByRecordId(info, argList[1]);
5556     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5557         targetManager->Dump(info);
5558     } else {
5559         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5560     }
5561 }
5562 
DumpSysProcess(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5563 void AbilityManagerService::DumpSysProcess(
5564     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5565 {
5566     std::vector<std::string> argList;
5567     SplitStr(args, " ", argList);
5568     if (argList.empty()) {
5569         return;
5570     }
5571     std::vector<AppExecFwk::RunningProcessInfo> processInfos;
5572     int ret = 0;
5573     if (isUserID) {
5574         ret = GetProcessRunningInfosByUserId(processInfos, userId);
5575     } else {
5576         ret = GetProcessRunningInfos(processInfos);
5577     }
5578 
5579     if (ret != ERR_OK || processInfos.size() == 0) {
5580         return;
5581     }
5582 
5583     std::string dumpInfo = "  AppRunningRecords:";
5584     info.push_back(dumpInfo);
5585     auto processInfoID = 0;
5586     auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false);
5587     for (const auto& processInfo : processInfos) {
5588         if (hasProcessName && argList[1] != processInfo.processName_) {
5589             continue;
5590         }
5591 
5592         dumpInfo = "    AppRunningRecord ID #" + std::to_string(processInfoID);
5593         processInfoID++;
5594         info.push_back(dumpInfo);
5595         dumpInfo = "      process name [" + processInfo.processName_ + "]";
5596         info.push_back(dumpInfo);
5597         dumpInfo = "      pid #" + std::to_string(processInfo.pid_) +
5598             "  uid #" + std::to_string(processInfo.uid_);
5599         info.push_back(dumpInfo);
5600         auto appState = static_cast<AppState>(processInfo.state_);
5601         dumpInfo = "      state #" + DelayedSingleton<AppScheduler>::GetInstance()->ConvertAppState(appState);
5602         info.push_back(dumpInfo);
5603         DumpUIExtensionRootHostRunningInfos(processInfo.pid_, info);
5604         DumpUIExtensionProviderRunningInfos(processInfo.pid_, info);
5605     }
5606 }
5607 
DumpUIExtensionRootHostRunningInfos(pid_t pid,std::vector<std::string> & info)5608 void AbilityManagerService::DumpUIExtensionRootHostRunningInfos(pid_t pid, std::vector<std::string> &info)
5609 {
5610     auto appMgr = GetAppMgr();
5611     if (appMgr == nullptr) {
5612         TAG_LOGW(AAFwkTag::ABILITYMGR, "Get AppMgr failed.");
5613         return;
5614     }
5615 
5616     std::vector<pid_t> hostPids;
5617     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionRootHostPid(pid, hostPids));
5618     if (ret != ERR_OK) {
5619         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get root host process info faild.");
5620         return;
5621     }
5622 
5623     if (hostPids.size() == 0) {
5624         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extenson root host of pid %{public}d.", pid);
5625         return;
5626     }
5627 
5628     std::string temp;
5629     for (size_t i = 0; i < hostPids.size(); i++) {
5630         temp = "      root caller #" + std::to_string(i);
5631         info.push_back(temp);
5632         temp = "        pid #" + std::to_string(hostPids[i]);
5633         info.push_back(temp);
5634     }
5635 }
5636 
DumpUIExtensionProviderRunningInfos(pid_t hostPid,std::vector<std::string> & info)5637 void AbilityManagerService::DumpUIExtensionProviderRunningInfos(pid_t hostPid, std::vector<std::string> &info)
5638 {
5639     auto appMgr = GetAppMgr();
5640     if (appMgr == nullptr) {
5641         TAG_LOGW(AAFwkTag::ABILITYMGR, "Get AppMgr failed.");
5642         return;
5643     }
5644 
5645     std::vector<pid_t> providerPids;
5646     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionProviderPid(hostPid, providerPids));
5647     if (ret != ERR_OK) {
5648         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get provider process info faild.");
5649         return;
5650     }
5651 
5652     if (providerPids.size() == 0) {
5653         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extension provider of pid %{public}d.", hostPid);
5654         return;
5655     }
5656 
5657     std::string temp;
5658     for (size_t i = 0; i < providerPids.size(); i++) {
5659         temp = "      uiextension provider #" + std::to_string(i);
5660         info.push_back(temp);
5661         temp = "        pid #" + std::to_string(providerPids[i]);
5662         info.push_back(temp);
5663     }
5664 }
5665 
DataDumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5666 void AbilityManagerService::DataDumpSysStateInner(
5667     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5668 {
5669     std::shared_ptr<DataAbilityManager> targetManager;
5670     if (isUserID) {
5671         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5672         if (dataAbilityManager == nullptr) {
5673             info.push_back("error: No user found.");
5674             return;
5675         }
5676         targetManager = dataAbilityManager;
5677     } else {
5678         targetManager = GetCurrentDataAbilityManager();
5679     }
5680 
5681     CHECK_POINTER(targetManager);
5682 
5683     std::vector<std::string> argList;
5684     SplitStr(args, " ", argList);
5685     if (argList.empty()) {
5686         return;
5687     }
5688     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5689         targetManager->DumpSysState(info, isClient, argList[1]);
5690     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5691         targetManager->DumpSysState(info, isClient);
5692     } else {
5693         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5694     }
5695 }
5696 
DumpInner(const std::string & args,std::vector<std::string> & info)5697 void AbilityManagerService::DumpInner(const std::string &args, std::vector<std::string> &info)
5698 {
5699     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5700         auto uiAbilityManager = GetCurrentUIAbilityManager();
5701         CHECK_POINTER(uiAbilityManager);
5702         uiAbilityManager->Dump(info);
5703         return;
5704     }
5705 
5706     auto missionListManager = GetCurrentMissionListManager();
5707     if (missionListManager) {
5708         missionListManager->Dump(info);
5709     }
5710 }
5711 
DumpMissionListInner(const std::string & args,std::vector<std::string> & info)5712 void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector<std::string> &info)
5713 {
5714     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5715         auto uiAbilityManager = GetCurrentUIAbilityManager();
5716         CHECK_POINTER(uiAbilityManager);
5717         uiAbilityManager->DumpMissionList(info, false, " ");
5718         return;
5719     }
5720     auto missionListManager = GetCurrentMissionListManager();
5721     if (missionListManager) {
5722         missionListManager->DumpMissionList(info, false, "");
5723     }
5724 }
5725 
DumpMissionInfosInner(const std::string & args,std::vector<std::string> & info)5726 void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)
5727 {
5728     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5729         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5730         Rosen::WindowManager::GetInstance().DumpSessionAll(info);
5731         return;
5732     }
5733     auto missionListManager = GetCurrentMissionListManager();
5734     if (missionListManager) {
5735         missionListManager->DumpMissionInfos(info);
5736     }
5737 }
5738 
DumpMissionInner(const std::string & args,std::vector<std::string> & info)5739 void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector<std::string> &info)
5740 {
5741     std::vector<std::string> argList;
5742     SplitStr(args, " ", argList);
5743     if (argList.empty()) {
5744         return;
5745     }
5746     if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5747         info.push_back("error: invalid argument, please see 'ability dump -h'.");
5748         return;
5749     }
5750     int missionId = DEFAULT_INVAL_VALUE;
5751     (void)StrToInt(argList[1], missionId);
5752 
5753     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5754         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5755         Rosen::WindowManager::GetInstance().DumpSessionWithId(missionId, info);
5756         return;
5757     }
5758 
5759     auto missionListManager = GetCurrentMissionListManager();
5760     CHECK_POINTER_LOG(missionListManager, "Current mission manager not init.");
5761     missionListManager->DumpMission(missionId, info);
5762 }
5763 
DumpStateInner(const std::string & args,std::vector<std::string> & info)5764 void AbilityManagerService::DumpStateInner(const std::string &args, std::vector<std::string> &info)
5765 {
5766     auto connectManager = GetCurrentConnectManager();
5767     CHECK_POINTER_LOG(connectManager, "Current mission manager not init.");
5768     std::vector<std::string> argList;
5769     SplitStr(args, " ", argList);
5770     if (argList.empty()) {
5771         return;
5772     }
5773     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5774         connectManager->DumpState(info, false, argList[1]);
5775     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5776         connectManager->DumpState(info, false);
5777     } else {
5778         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5779     }
5780 }
5781 
DataDumpStateInner(const std::string & args,std::vector<std::string> & info)5782 void AbilityManagerService::DataDumpStateInner(const std::string &args, std::vector<std::string> &info)
5783 {
5784     auto dataAbilityManager = GetCurrentDataAbilityManager();
5785     CHECK_POINTER(dataAbilityManager);
5786     std::vector<std::string> argList;
5787     SplitStr(args, " ", argList);
5788     if (argList.empty()) {
5789         return;
5790     }
5791     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5792         dataAbilityManager->DumpState(info, argList[1]);
5793     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5794         dataAbilityManager->DumpState(info);
5795     } else {
5796         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5797     }
5798 }
5799 
DumpState(const std::string & args,std::vector<std::string> & info)5800 void AbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
5801 {
5802     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5803     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5804     if (!isShellCall && !isHidumperServiceCall) {
5805         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5806         return;
5807     }
5808     std::vector<std::string> argList;
5809     SplitStr(args, " ", argList);
5810     if (argList.empty()) {
5811         return;
5812     }
5813     auto key = DumpUtils::DumpMap(argList[0]);
5814     if (!key.first) {
5815         return;
5816     }
5817     switch (key.second) {
5818         case DumpUtils::KEY_DUMP_SERVICE:
5819             DumpStateInner(args, info);
5820             break;
5821         case DumpUtils::KEY_DUMP_DATA:
5822             DataDumpStateInner(args, info);
5823             break;
5824         case DumpUtils::KEY_DUMP_ALL:
5825             DumpInner(args, info);
5826             break;
5827         case DumpUtils::KEY_DUMP_MISSION:
5828             DumpMissionInner(args, info);
5829             break;
5830         case DumpUtils::KEY_DUMP_MISSION_LIST:
5831             DumpMissionListInner(args, info);
5832             break;
5833         case DumpUtils::KEY_DUMP_MISSION_INFOS:
5834             DumpMissionInfosInner(args, info);
5835             break;
5836         default:
5837             info.push_back("error: invalid argument, please see 'ability dump -h'.");
5838             break;
5839     }
5840 }
5841 
DumpSysState(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5842 void AbilityManagerService::DumpSysState(
5843     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5844 {
5845     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
5846     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5847     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5848     if (!isShellCall && !isHidumperServiceCall) {
5849         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5850         return;
5851     }
5852     std::vector<std::string> argList;
5853     SplitStr(args, " ", argList);
5854     if (argList.empty()) {
5855         return;
5856     }
5857     auto key = DumpUtils::DumpsysMap(argList[0]);
5858     if (!key.first) {
5859         return;
5860     }
5861     switch (key.second) {
5862         case DumpUtils::KEY_DUMP_SYS_ALL:
5863             DumpSysInner(args, info, isClient, isUserID, userId);
5864             break;
5865         case DumpUtils::KEY_DUMP_SYS_SERVICE:
5866             DumpSysStateInner(args, info, isClient, isUserID, userId);
5867             break;
5868         case DumpUtils::KEY_DUMP_SYS_PENDING:
5869             DumpSysPendingInner(args, info, isClient, isUserID, userId);
5870             break;
5871         case DumpUtils::KEY_DUMP_SYS_PROCESS:
5872             DumpSysProcess(args, info, isClient, isUserID, userId);
5873             break;
5874         case DumpUtils::KEY_DUMP_SYS_DATA:
5875             DataDumpSysStateInner(args, info, isClient, isUserID, userId);
5876             break;
5877         case DumpUtils::KEY_DUMP_SYS_MISSION_LIST:
5878             DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5879             break;
5880         case DumpUtils::KEY_DUMP_SYS_ABILITY:
5881             DumpSysAbilityInner(args, info, isClient, isUserID, userId);
5882             break;
5883         default:
5884             info.push_back("error: invalid argument, please see 'ability dump -h'.");
5885             break;
5886     }
5887 }
5888 
AbilityTransitionDone(const sptr<IRemoteObject> & token,int state,const PacMap & saveData)5889 int AbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
5890 {
5891     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5892     TAG_LOGD(AAFwkTag::ABILITYMGR, "Lifecycle: state:%{public}d.", state);
5893     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5894         return ERR_INVALID_VALUE;
5895     }
5896     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5897     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
5898     if (!JudgeSelfCalled(abilityRecord)) {
5899         return CHECK_PERMISSION_FAILED;
5900     }
5901 
5902     auto abilityInfo = abilityRecord->GetAbilityInfo();
5903     TAG_LOGI(AAFwkTag::ABILITYMGR, "Lifecycle: ability: %{public}s.", abilityRecord->GetURI().c_str());
5904     auto type = abilityInfo.type;
5905     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5906     // force timeout ability for test
5907     int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast<AbilityLifeCycleState>(state));
5908     bool isTerminate = abilityRecord->IsAbilityState(AbilityState::TERMINATING) && targetState == AbilityState::INITIAL;
5909     std::string tempState = isTerminate ? AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) :
5910         AbilityRecord::ConvertAbilityState(static_cast<AbilityState>(targetState));
5911     if (IsNeedTimeoutForTest(abilityInfo.name, tempState)) {
5912         TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability for test, state:%{public}s, ability: %{public}s",
5913             tempState.c_str(),
5914             abilityInfo.name.c_str());
5915         return ERR_OK;
5916     }
5917     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5918         auto connectManager = GetConnectManagerByUserId(userId);
5919         if (!connectManager) {
5920             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5921             return ERR_INVALID_VALUE;
5922         }
5923         return connectManager->AbilityTransitionDone(token, state);
5924     }
5925     if (type == AppExecFwk::AbilityType::DATA) {
5926         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5927         if (!dataAbilityManager) {
5928             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
5929             return ERR_INVALID_VALUE;
5930         }
5931         return dataAbilityManager->AbilityTransitionDone(token, state);
5932     }
5933 
5934     if (targetState == AbilityState::BACKGROUND) {
5935         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::BACKGROUND };
5936         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of background lifecycle.";
5937         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5938     } else if (targetState != AbilityState::INITIAL) {
5939         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::FOREGROUND };
5940         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of foreground lifecycle."
5941             " the end of foreground lifecycle.";
5942         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5943     }
5944 
5945     int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5946     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5947         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5948         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5949         return uiAbilityManager->AbilityTransactionDone(token, state, saveData);
5950     } else {
5951         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5952         if (!missionListManager) {
5953             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", ownerMissionUserId);
5954             return ERR_INVALID_VALUE;
5955         }
5956         return missionListManager->AbilityTransactionDone(token, state, saveData);
5957     }
5958 }
5959 
AbilityWindowConfigTransitionDone(const sptr<IRemoteObject> & token,const WindowConfig & windowConfig)5960 int AbilityManagerService::AbilityWindowConfigTransitionDone(
5961     const sptr<IRemoteObject> &token, const WindowConfig &windowConfig)
5962 {
5963     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5964     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5965         return ERR_INVALID_VALUE;
5966     }
5967     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5968     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
5969     if (!JudgeSelfCalled(abilityRecord)) {
5970         return CHECK_PERMISSION_FAILED;
5971     }
5972 
5973     TAG_LOGI(AAFwkTag::ABILITYMGR, "Lifecycle: ability: %{public}s.", abilityRecord->GetURI().c_str());
5974     auto abilityInfo = abilityRecord->GetAbilityInfo();
5975     auto type = abilityInfo.extensionAbilityType;
5976     if (type != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
5977         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid type");
5978         return ERR_INVALID_VALUE;
5979     }
5980     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5981     auto connectManager = GetConnectManagerByUserId(userId);
5982     if(!connectManager) {
5983         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5984         return ERR_INVALID_VALUE;
5985     }
5986     return connectManager->AbilityWindowConfigTransactionDone(token, windowConfig);
5987 }
5988 
ScheduleConnectAbilityDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & remoteObject)5989 int AbilityManagerService::ScheduleConnectAbilityDone(
5990     const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
5991 {
5992     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5993     TAG_LOGD(AAFwkTag::SERVICE_EXT, "called");
5994     if (!VerificationAllToken(token)) {
5995         return ERR_INVALID_VALUE;
5996     }
5997 
5998     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5999     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6000     if (!JudgeSelfCalled(abilityRecord)) {
6001         return CHECK_PERMISSION_FAILED;
6002     }
6003 
6004     auto type = abilityRecord->GetAbilityInfo().type;
6005     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6006         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Connect ability failed, target ability is not service.");
6007         return TARGET_ABILITY_NOT_SERVICE;
6008     }
6009     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6010     auto connectManager = GetConnectManagerByUserId(userId);
6011     if (!connectManager) {
6012         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager is nullptr. userId=%{public}d", userId);
6013         return ERR_INVALID_VALUE;
6014     }
6015     return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject);
6016 }
6017 
ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> & token)6018 int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
6019 {
6020     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6021     TAG_LOGI(AAFwkTag::SERVICE_EXT, "Schedule disconnect ability done.");
6022     if (!VerificationAllToken(token)) {
6023         return ERR_INVALID_VALUE;
6024     }
6025 
6026     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6027     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6028     if (!JudgeSelfCalled(abilityRecord)) {
6029         return CHECK_PERMISSION_FAILED;
6030     }
6031 
6032     auto type = abilityRecord->GetAbilityInfo().type;
6033     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6034         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Connect ability failed, target ability is not service.");
6035         return TARGET_ABILITY_NOT_SERVICE;
6036     }
6037     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6038     auto connectManager = GetConnectManagerByUserId(userId);
6039     if (!connectManager) {
6040         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager is nullptr. userId=%{public}d", userId);
6041         return ERR_INVALID_VALUE;
6042     }
6043     return connectManager->ScheduleDisconnectAbilityDoneLocked(token);
6044 }
6045 
ScheduleCommandAbilityDone(const sptr<IRemoteObject> & token)6046 int AbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
6047 {
6048     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6049     TAG_LOGD(AAFwkTag::SERVICE_EXT, "Schedule command ability done.");
6050     if (!VerificationAllToken(token)) {
6051         return ERR_INVALID_VALUE;
6052     }
6053 
6054     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6055     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6056     if (!JudgeSelfCalled(abilityRecord)) {
6057         return CHECK_PERMISSION_FAILED;
6058     }
6059     // force timeout ability for test
6060     if (IsNeedTimeoutForTest(abilityRecord->GetAbilityInfo().name, std::string("COMMAND"))) {
6061         TAG_LOGW(AAFwkTag::SERVICE_EXT, "force timeout ability for test, state:COMMAND, ability: %{public}s",
6062             abilityRecord->GetAbilityInfo().name.c_str());
6063         return ERR_OK;
6064     }
6065     auto type = abilityRecord->GetAbilityInfo().type;
6066     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6067         TAG_LOGE(AAFwkTag::SERVICE_EXT, "Connect ability failed, target ability is not service.");
6068         return TARGET_ABILITY_NOT_SERVICE;
6069     }
6070     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6071     auto connectManager = GetConnectManagerByUserId(userId);
6072     if (!connectManager) {
6073         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager is nullptr. userId=%{public}d", userId);
6074         return ERR_INVALID_VALUE;
6075     }
6076     return connectManager->ScheduleCommandAbilityDoneLocked(token);
6077 }
6078 
ScheduleCommandAbilityWindowDone(const sptr<IRemoteObject> & token,const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd,AbilityCommand abilityCmd)6079 int AbilityManagerService::ScheduleCommandAbilityWindowDone(
6080     const sptr<IRemoteObject> &token,
6081     const sptr<SessionInfo> &sessionInfo,
6082     WindowCommand winCmd,
6083     AbilityCommand abilityCmd)
6084 {
6085     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6086     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter.");
6087     if (!VerificationAllToken(token)) {
6088         return ERR_INVALID_VALUE;
6089     }
6090 
6091     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6092     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6093     if (!JudgeSelfCalled(abilityRecord)) {
6094         return CHECK_PERMISSION_FAILED;
6095     }
6096 
6097     if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)
6098         && !UIExtensionUtils::IsWindowExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
6099         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability is not ui or window extension.");
6100         return ERR_INVALID_VALUE;
6101     }
6102     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6103     auto connectManager = GetConnectManagerByUserId(userId);
6104     if (!connectManager) {
6105         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
6106         return ERR_INVALID_VALUE;
6107     }
6108     return connectManager->ScheduleCommandAbilityWindowDone(token, sessionInfo, winCmd, abilityCmd);
6109 }
6110 
OnAbilityRequestDone(const sptr<IRemoteObject> & token,const int32_t state)6111 void AbilityManagerService::OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)
6112 {
6113     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6114     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6115     CHECK_POINTER(abilityRecord);
6116     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnAbilityRequestDone, bundleName: %{public}s, abilityName: %{public}s",
6117         abilityRecord->GetAbilityInfo().bundleName.c_str(), abilityRecord->GetAbilityInfo().name.c_str());
6118     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6119 
6120     auto type = abilityRecord->GetAbilityInfo().type;
6121     switch (type) {
6122         case AppExecFwk::AbilityType::DATA: {
6123             auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6124             if (!dataAbilityManager) {
6125                 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
6126                 return;
6127             }
6128             dataAbilityManager->OnAbilityRequestDone(token, state);
6129             break;
6130         }
6131         case AppExecFwk::AbilityType::SERVICE:
6132         case AppExecFwk::AbilityType::EXTENSION: {
6133             auto connectManager = GetConnectManagerByUserId(userId);
6134             if (!connectManager) {
6135                 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
6136                 return;
6137             }
6138             connectManager->OnAbilityRequestDone(token, state);
6139             break;
6140         }
6141         default: {
6142             int32_t ownerUserId = abilityRecord->GetOwnerMissionUserId();
6143             if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6144                 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
6145                 CHECK_POINTER(uiAbilityManager);
6146                 uiAbilityManager->OnAbilityRequestDone(token, state);
6147             } else {
6148                 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
6149                 if (!missionListManager) {
6150                     TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", ownerUserId);
6151                     return;
6152                 }
6153                 missionListManager->OnAbilityRequestDone(token, state);
6154             }
6155             break;
6156         }
6157     }
6158 }
6159 
OnAppStateChanged(const AppInfo & info)6160 void AbilityManagerService::OnAppStateChanged(const AppInfo &info)
6161 {
6162     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6163     auto connectManager = GetCurrentConnectManager();
6164     CHECK_POINTER_LOG(connectManager, "Connect manager not init.");
6165     connectManager->OnAppStateChanged(info);
6166     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6167         auto uiAbilityManager = GetCurrentUIAbilityManager();
6168         CHECK_POINTER(uiAbilityManager);
6169         uiAbilityManager->OnAppStateChanged(info);
6170     } else {
6171         auto missionListManager = GetCurrentMissionListManager();
6172         CHECK_POINTER_LOG(missionListManager, "Current mission list manager not init.");
6173         missionListManager->OnAppStateChanged(info);
6174     }
6175     auto dataAbilityManager = GetCurrentDataAbilityManager();
6176     CHECK_POINTER(dataAbilityManager);
6177     dataAbilityManager->OnAppStateChanged(info);
6178 
6179     auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
6180     CHECK_POINTER(residentProcessMgr);
6181     residentProcessMgr->OnAppStateChanged(info);
6182 }
6183 
GetEventHandler()6184 std::shared_ptr<AbilityEventHandler> AbilityManagerService::GetEventHandler()
6185 {
6186     return eventHandler_;
6187 }
6188 
6189 // multi user scene
GetUserId() const6190 int32_t AbilityManagerService::GetUserId() const
6191 {
6192     if (userController_) {
6193         auto userId = userController_->GetCurrentUserId();
6194         TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is %{public}d", userId);
6195         return userId;
6196     }
6197     return U0_USER_ID;
6198 }
6199 
StartHighestPriorityAbility(int32_t userId,bool isBoot)6200 void AbilityManagerService::StartHighestPriorityAbility(int32_t userId, bool isBoot)
6201 {
6202     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
6203     auto bms = GetBundleManager();
6204     CHECK_POINTER(bms);
6205 
6206     /* Query the highest priority ability or extension ability, and start it. usually, it is OOBE or launcher */
6207     Want want;
6208     want.AddEntity(HIGHEST_PRIORITY_ABILITY_ENTITY);
6209     AppExecFwk::AbilityInfo abilityInfo;
6210     AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
6211     int attemptNums = 0;
6212     while (!IN_PROCESS_CALL(bms->ImplicitQueryInfoByPriority(want,
6213         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId,
6214         abilityInfo, extensionAbilityInfo))) {
6215         TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting query highest priority ability info completed.");
6216         ++attemptNums;
6217         if (!isBoot && attemptNums > SWITCH_ACCOUNT_TRY) {
6218             TAG_LOGE(AAFwkTag::ABILITYMGR, "Query highest priority ability failed.");
6219             return;
6220         }
6221         AbilityRequest abilityRequest;
6222         usleep(REPOLL_TIME_MICRO_SECONDS);
6223     }
6224 
6225     if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
6226         TAG_LOGE(AAFwkTag::ABILITYMGR, "Query highest priority ability failed");
6227         return;
6228     }
6229 
6230     Want abilityWant; // donot use 'want' here, because the entity of 'want' is not empty
6231     if (!abilityInfo.name.empty()) {
6232         /* highest priority ability */
6233         TAG_LOGI(AAFwkTag::ABILITYMGR, "Start the highest priority ability. bundleName: %{public}s, ability:%{public}s",
6234             abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
6235         abilityWant.SetElementName(abilityInfo.bundleName, abilityInfo.name);
6236     } else {
6237         /* highest priority extension ability */
6238         TAG_LOGI(AAFwkTag::ABILITYMGR,
6239             "Start the highest priority extension ability. bundleName: %{public}s, ability:%{public}s",
6240             extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str());
6241         abilityWant.SetElementName(extensionAbilityInfo.bundleName, extensionAbilityInfo.name);
6242     }
6243 
6244 #ifdef SUPPORT_GRAPHICS
6245     abilityWant.SetParam(NEED_STARTINGWINDOW, false);
6246     // wait BOOT_ANIMATION_STARTED to start LAUNCHER
6247     WaitBootAnimationStart();
6248 #endif
6249 
6250     /* note: OOBE APP need disable itself, otherwise, it will be started when restart system everytime */
6251     (void)StartAbility(abilityWant, userId, DEFAULT_INVAL_VALUE);
6252 }
6253 
GenerateAbilityRequest(const Want & want,int requestCode,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)6254 int AbilityManagerService::GenerateAbilityRequest(const Want &want, int requestCode, AbilityRequest &request,
6255     const sptr<IRemoteObject> &callerToken, int32_t userId)
6256 {
6257     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6258     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6259     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6260         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6261         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6262         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6263     }
6264 
6265     int32_t appIndex = 0;
6266     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
6267     if (abilityRecord != nullptr &&
6268         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName() &&
6269         abilityRecord->GetAppIndex() == appIndex) {
6270         (const_cast<Want &>(want)).SetParam(DEBUG_APP, abilityRecord->IsDebugApp());
6271     }
6272 
6273     request.want = want;
6274     request.requestCode = requestCode;
6275     request.callerToken = callerToken;
6276     auto setting = AbilityStartSetting::GetEmptySetting();
6277     if (setting != nullptr) {
6278         setting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "false"); // default is false
6279         request.startSetting = std::make_shared<AbilityStartSetting>(*(setting.get()));
6280     }
6281 
6282     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6283     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6284         int32_t appIndex = 0;
6285         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6286             return ERR_APP_CLONE_INDEX_INVALID;
6287         }
6288         Want localWant = want;
6289         if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
6290             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
6291             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
6292         }
6293         abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(localWant, userId, appIndex);
6294     }
6295     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6296     if (abilityInfo->status != ERR_OK) {
6297         return abilityInfo->status;
6298     }
6299     request.abilityInfo = abilityInfo->abilityInfo;
6300     request.extensionProcessMode = abilityInfo->extensionProcessMode;
6301 
6302     if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
6303         request.collaboratorType = CollaboratorType::RESERVE_TYPE;
6304     } else if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::OTHERS_TYPE)) {
6305         request.collaboratorType = CollaboratorType::OTHERS_TYPE;
6306     }
6307 
6308     if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) {
6309         TAG_LOGI(AAFwkTag::ABILITYMGR, "Stage mode, abilityInfo SERVICE type reset EXTENSION.");
6310         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
6311     }
6312 
6313     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6314         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app info failed.");
6315         return RESOLVE_APP_ERR;
6316     }
6317     if (want.GetIntParam(AAFwk::SCREEN_MODE_KEY, ScreenMode::IDLE_SCREEN_MODE) == ScreenMode::JUMP_SCREEN_MODE &&
6318         (request.abilityInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE ||
6319         request.abilityInfo.launchMode != AppExecFwk::LaunchMode::SINGLETON)) {
6320         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface of starting atomicService can start only atomicService.");
6321         return TARGET_ABILITY_NOT_SERVICE;
6322     }
6323     request.appInfo = request.abilityInfo.applicationInfo;
6324     request.uid = request.appInfo.uid;
6325     TAG_LOGD(AAFwkTag::ABILITYMGR,
6326         "GenerateAbilityRequest end, app name: %{public}s, moduleName name: %{public}s, uid: %{public}d.",
6327         request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid);
6328 
6329     request.want.SetModuleName(request.abilityInfo.moduleName);
6330 
6331     if (want.GetBoolParam(Want::PARAM_RESV_START_RECENT, false) &&
6332         AAFwk::PermissionVerification::GetInstance()->VerifyStartRecentAbilityPermission()) {
6333         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set start recent.");
6334         request.startRecent = true;
6335     }
6336 
6337     return ERR_OK;
6338 }
6339 
GenerateExtensionAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)6340 int AbilityManagerService::GenerateExtensionAbilityRequest(
6341     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
6342 {
6343     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6344     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6345         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6346         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6347         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6348     }
6349     request.want = want;
6350     request.callerToken = callerToken;
6351     request.startSetting = nullptr;
6352 
6353     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6354     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6355         int32_t appIndex = 0;
6356         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6357             return ERR_APP_CLONE_INDEX_INVALID;
6358         }
6359         abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, appIndex);
6360     }
6361     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6362     if (abilityInfo->status != ERR_OK) {
6363         return abilityInfo->status;
6364     }
6365 
6366     auto result = InitialAbilityRequest(request, *abilityInfo);
6367     return result;
6368 }
6369 
InitialAbilityRequest(AbilityRequest & request,const StartAbilityInfo & abilityInfo) const6370 int32_t AbilityManagerService::InitialAbilityRequest(AbilityRequest &request,
6371     const StartAbilityInfo &abilityInfo) const
6372 {
6373     request.abilityInfo = abilityInfo.abilityInfo;
6374     request.extensionProcessMode = abilityInfo.extensionProcessMode;
6375     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6376         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app info failed.");
6377         return RESOLVE_APP_ERR;
6378     }
6379     request.appInfo = request.abilityInfo.applicationInfo;
6380     request.uid = request.appInfo.uid;
6381     TAG_LOGD(AAFwkTag::ABILITYMGR,
6382         "GenerateAbilityRequest end, app name: %{public}s, bundle name: %{public}s, uid: %{public}d.",
6383         request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid);
6384 
6385     TAG_LOGD(AAFwkTag::ABILITYMGR,
6386         "GenerateExtensionAbilityRequest, moduleName: %{public}s.", request.abilityInfo.moduleName.c_str());
6387     request.want.SetModuleName(request.abilityInfo.moduleName);
6388 
6389     return ERR_OK;
6390 }
6391 
StopServiceAbility(const Want & want,int32_t userId,const sptr<IRemoteObject> & token)6392 int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)
6393 {
6394     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6395     TAG_LOGD(AAFwkTag::ABILITYMGR, "call.");
6396 
6397     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6398     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6399     if (!isSaCall && !isShellCall) {
6400         auto abilityRecord = Token::GetAbilityRecordByToken(token);
6401         if (abilityRecord == nullptr) {
6402             TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord is nullptr");
6403             return ERR_INVALID_VALUE;
6404         }
6405     }
6406 
6407     int32_t validUserId = GetValidUserId(userId);
6408     if (!JudgeMultiUserConcurrency(validUserId)) {
6409         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
6410         return ERR_CROSS_USER;
6411     }
6412 
6413     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
6414     AbilityRequest abilityRequest;
6415     auto result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId);
6416     if (result != ERR_OK) {
6417         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
6418         return result;
6419     }
6420 
6421     auto abilityInfo = abilityRequest.abilityInfo;
6422     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
6423     TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
6424         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
6425 
6426     auto type = abilityInfo.type;
6427     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6428         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is not service type.");
6429         return TARGET_ABILITY_NOT_SERVICE;
6430     }
6431 
6432     auto res = JudgeAbilityVisibleControl(abilityInfo);
6433     if (res != ERR_OK) {
6434         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is invisible");
6435         return res;
6436     }
6437 
6438     auto connectManager = GetConnectManagerByUserId(validUserId);
6439     if (connectManager == nullptr) {
6440         return ERR_INVALID_VALUE;
6441     }
6442 
6443     return connectManager->StopServiceAbility(abilityRequest);
6444 }
6445 
OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)6446 void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)
6447 {
6448     CHECK_POINTER(abilityRecord);
6449     if (abilityRecord->GetToken()) {
6450         FreezeUtil::GetInstance().DeleteLifecycleEvent(abilityRecord->GetToken()->AsObject());
6451     }
6452     FreezeUtil::GetInstance().DeleteAppLifecycleEvent(abilityRecord->GetPid());
6453     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6454         if (abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6455             auto uiAbilityManager = GetUIAbilityManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6456             CHECK_POINTER(uiAbilityManager);
6457             uiAbilityManager->OnAbilityDied(abilityRecord);
6458             return;
6459         }
6460     } else {
6461         auto manager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6462         if (manager && abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6463             ReleaseAbilityTokenMap(abilityRecord->GetToken());
6464             manager->OnAbilityDied(abilityRecord, GetUserId());
6465             return;
6466         }
6467     }
6468 
6469     auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
6470     if (connectManager) {
6471         connectManager->OnAbilityDied(abilityRecord, GetUserId());
6472         return;
6473     }
6474 
6475     auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken());
6476     if (dataAbilityManager) {
6477         dataAbilityManager->OnAbilityDied(abilityRecord);
6478     }
6479 }
6480 
OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)6481 void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
6482 {
6483     CHECK_POINTER(callRecord);
6484     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6485         auto uiAbilityManager = GetCurrentUIAbilityManager();
6486         CHECK_POINTER(uiAbilityManager);
6487         uiAbilityManager->OnCallConnectDied(callRecord);
6488         return;
6489     }
6490     auto missionListManager = GetCurrentMissionListManager();
6491     if (missionListManager) {
6492         missionListManager->OnCallConnectDied(callRecord);
6493     }
6494 }
6495 
ReleaseAbilityTokenMap(const sptr<IRemoteObject> & token)6496 void AbilityManagerService::ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)
6497 {
6498     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
6499     for (auto iter = callStubTokenMap_.begin(); iter != callStubTokenMap_.end(); iter++) {
6500         if (iter->second == token) {
6501             callStubTokenMap_.erase(iter);
6502             break;
6503         }
6504     }
6505 }
6506 
KillProcess(const std::string & bundleName,const bool clearPageStack)6507 int AbilityManagerService::KillProcess(const std::string &bundleName, const bool clearPageStack)
6508 {
6509     TAG_LOGI(AAFwkTag::ABILITYMGR, "Kill process, bundleName: %{public}s", bundleName.c_str());
6510     auto bms = GetBundleManager();
6511     CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED);
6512     int32_t userId = GetUserId();
6513     AppExecFwk::BundleInfo bundleInfo;
6514     if (!IN_PROCESS_CALL(
6515         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
6516         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info when kill process.");
6517         return GET_BUNDLE_INFO_FAILED;
6518     }
6519 
6520     bool keepAliveEnable = bundleInfo.isKeepAlive;
6521     AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleName, keepAliveEnable);
6522     if (keepAliveEnable && DelayedSingleton<AppScheduler>::GetInstance()->IsMemorySizeSufficent()) {
6523         TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not kill keep alive process.");
6524         return KILL_PROCESS_KEEP_ALIVE;
6525     }
6526 
6527     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName, clearPageStack);
6528     if (ret != ERR_OK) {
6529         return KILL_PROCESS_FAILED;
6530     }
6531 
6532     return ERR_OK;
6533 }
6534 
UninstallApp(const std::string & bundleName,int32_t uid)6535 int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid)
6536 {
6537     return UninstallApp(bundleName, uid, 0);
6538 }
6539 
UninstallApp(const std::string & bundleName,int32_t uid,int32_t appIndex)6540 int32_t AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex)
6541 {
6542     TAG_LOGI(AAFwkTag::ABILITYMGR, "Uninstall app, bundleName: %{public}s, uid=%{public}d, appIndex:%{public}d",
6543         bundleName.c_str(), uid, appIndex);
6544     return UninstallAppInner(bundleName, uid, appIndex, false, "");
6545 }
6546 
UpgradeApp(const std::string & bundleName,const int32_t uid,const std::string & exitMsg,int32_t appIndex)6547 int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg,
6548     int32_t appIndex)
6549 {
6550     TAG_LOGI(AAFwkTag::ABILITYMGR,
6551         "UpgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg: %{public}s, appIndex:%{public}d",
6552         bundleName.c_str(), uid, exitMsg.c_str(), appIndex);
6553     return UninstallAppInner(bundleName, uid, appIndex, true, exitMsg);
6554 }
6555 
UninstallAppInner(const std::string & bundleName,const int32_t uid,int32_t appIndex,const bool isUpgrade,const std::string & exitMsg)6556 int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex,
6557     const bool isUpgrade, const std::string &exitMsg)
6558 {
6559     pid_t callingPid = IPCSkeleton::GetCallingPid();
6560     pid_t pid = getprocpid();
6561     if (callingPid != pid) {
6562         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Not bundleMgr call.", __func__);
6563         return CHECK_PERMISSION_FAILED;
6564     }
6565 
6566     auto userId = uid / BASE_USER_RANGE;
6567     if (isUpgrade) {
6568         CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
6569         AAFwk::ExitReason exitReason = { REASON_UPGRADE, exitMsg };
6570         appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
6571     }
6572     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppExecFwk::AppMgrClient>::
6573         GetInstance()->SetKeepAliveEnableState(bundleName, false, uid));
6574     auto connectManager = GetConnectManagerByUserId(userId);
6575     if (connectManager) {
6576         connectManager->UninstallApp(bundleName, uid);
6577     }
6578 
6579     CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT);
6580     subManagersHelper_->UninstallApp(bundleName, uid);
6581     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplicationByUid(bundleName, uid, "UninstallApp");
6582     if (ret != ERR_OK) {
6583         return UNINSTALL_APP_FAILED;
6584     }
6585     if (!isUpgrade) {
6586         DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->DeleteAppExitReason(bundleName, uid,
6587             appIndex);
6588     }
6589     return ERR_OK;
6590 }
6591 
GetBundleManager()6592 std::shared_ptr<AppExecFwk::BundleMgrHelper> AbilityManagerService::GetBundleManager()
6593 {
6594     if (bundleMgrHelper_ == nullptr) {
6595         bundleMgrHelper_ = AbilityUtil::GetBundleManagerHelper();
6596     }
6597     return bundleMgrHelper_;
6598 }
6599 
PreLoadAppDataAbilities(const std::string & bundleName,const int32_t userId)6600 int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)
6601 {
6602     if (bundleName.empty()) {
6603         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name when app data abilities preloading.");
6604         return ERR_INVALID_VALUE;
6605     }
6606 
6607     if (taskHandler_ == nullptr) {
6608         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler nullptr.");
6609         return ERR_INVALID_STATE;
6610     }
6611 
6612     taskHandler_->SubmitTask([weak = weak_from_this(), bundleName, userId]() {
6613         auto pthis = weak.lock();
6614         if (pthis == nullptr) {
6615             TAG_LOGE(AAFwkTag::ABILITYMGR, "pthis nullptr.");
6616             return;
6617         }
6618         pthis->PreLoadAppDataAbilitiesTask(bundleName, userId);
6619         });
6620 
6621     return ERR_OK;
6622 }
6623 
PreLoadAppDataAbilitiesTask(const std::string & bundleName,const int32_t userId)6624 void AbilityManagerService::PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId)
6625 {
6626     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6627     auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6628     if (dataAbilityManager == nullptr) {
6629         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid data ability manager when app data abilities preloading.");
6630         return;
6631     }
6632 
6633     auto bms = GetBundleManager();
6634     CHECK_POINTER(bms);
6635 
6636     AppExecFwk::BundleInfo bundleInfo;
6637     bool ret = IN_PROCESS_CALL(
6638         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
6639     if (!ret) {
6640         TAG_LOGE(AAFwkTag::ABILITYMGR,
6641             "Failed to get bundle info when app data abilities preloading, userId is %{public}d", userId);
6642         return;
6643     }
6644 
6645     auto begin = system_clock::now();
6646     AbilityRequest dataAbilityRequest;
6647     UpdateCallerInfo(dataAbilityRequest.want, nullptr);
6648     dataAbilityRequest.appInfo = bundleInfo.applicationInfo;
6649     for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
6650         if (it->type != AppExecFwk::AbilityType::DATA) {
6651             continue;
6652         }
6653         if ((system_clock::now() - begin) >= DATA_ABILITY_START_TIMEOUT) {
6654             TAG_LOGE(AAFwkTag::ABILITYMGR, "App data ability preloading for '%{public}s' timeout.", bundleName.c_str());
6655             return;
6656         }
6657         dataAbilityRequest.abilityInfo = *it;
6658         dataAbilityRequest.uid = bundleInfo.uid;
6659         TAG_LOGD(AAFwkTag::ABILITYMGR, "App data ability preloading: '%{public}s.%{public}s'...",
6660             it->bundleName.c_str(), it->name.c_str());
6661 
6662         auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false);
6663         if (dataAbility == nullptr) {
6664             TAG_LOGE(AAFwkTag::ABILITYMGR,
6665                 "Failed to preload data ability '%{public}s.%{public}s'.", it->bundleName.c_str(), it->name.c_str());
6666             return;
6667         }
6668     }
6669 }
6670 
IsSystemUiApp(const AppExecFwk::AbilityInfo & info) const6671 bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const
6672 {
6673     if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) {
6674         return false;
6675     }
6676     return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR ||
6677         info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR ||
6678         info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME);
6679 }
6680 
IsSystemUI(const std::string & bundleName) const6681 bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const
6682 {
6683     return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME;
6684 }
6685 
HandleLoadTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)6686 void AbilityManagerService::HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6687 {
6688     TAG_LOGD(AAFwkTag::ABILITYMGR, "load timeout %{public}" PRId64, abilityRecordId);
6689     if (isExtension) {
6690         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6691         if (connectManager != nullptr) {
6692             connectManager->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6693         }
6694         return;
6695     }
6696 
6697     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6698         auto uiAbilityManagers = GetUIAbilityManagers();
6699         for (auto& item : uiAbilityManagers) {
6700             if (item.second) {
6701                 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6702             }
6703         }
6704         return;
6705     }
6706     auto missionListManagers = GetMissionListManagers();
6707     for (auto& item : missionListManagers) {
6708         if (item.second) {
6709             item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6710         }
6711     }
6712 }
6713 
HandleActiveTimeOut(int64_t abilityRecordId)6714 void AbilityManagerService::HandleActiveTimeOut(int64_t abilityRecordId)
6715 {
6716     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle active timeout.");
6717     auto missionListManagers = GetMissionListManagers();
6718     for (auto& item : missionListManagers) {
6719         if (item.second) {
6720             item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecordId);
6721         }
6722     }
6723 }
6724 
HandleInactiveTimeOut(int64_t abilityRecordId)6725 void AbilityManagerService::HandleInactiveTimeOut(int64_t abilityRecordId)
6726 {
6727     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle inactive timeout.");
6728     auto missionListManagers = GetMissionListManagers();
6729     for (auto& item : missionListManagers) {
6730         if (item.second) {
6731             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6732         }
6733     }
6734     auto connectManagers = GetConnectManagers();
6735     for (auto& item : connectManagers) {
6736         if (item.second) {
6737             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6738         }
6739     }
6740 }
6741 
HandleForegroundTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)6742 void AbilityManagerService::HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6743 {
6744     TAG_LOGD(AAFwkTag::ABILITYMGR, "foreground timeout %{public}" PRId64, abilityRecordId);
6745     if (isExtension) {
6746         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6747         if (connectManager != nullptr) {
6748             connectManager->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6749         }
6750         return;
6751     }
6752 
6753     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6754         auto uiAbilityManagers = GetUIAbilityManagers();
6755         for (auto& item : uiAbilityManagers) {
6756             if (item.second) {
6757                 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6758             }
6759         }
6760         return;
6761     }
6762     auto missionListManagers = GetMissionListManagers();
6763     for (auto& item : missionListManagers) {
6764         if (item.second) {
6765             item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6766         }
6767     }
6768 }
6769 
HandleShareDataTimeOut(int64_t uniqueId)6770 void AbilityManagerService::HandleShareDataTimeOut(int64_t uniqueId)
6771 {
6772     WantParams wantParam;
6773     int32_t ret = GetShareDataPairAndReturnData(nullptr, ERR_TIMED_OUT, uniqueId, wantParam);
6774     if (ret) {
6775         TAG_LOGE(AAFwkTag::ABILITYMGR, "acqurieShareData failed.");
6776     }
6777 }
6778 
GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)6779 int32_t AbilityManagerService::GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,
6780     const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
6781 {
6782     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d, wantParam size:%{public}d.",
6783         resultCode, uniqueId, wantParam.Size());
6784     {
6785         std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
6786         auto it = iAcquireShareDataMap_.find(uniqueId);
6787         if (it != iAcquireShareDataMap_.end()) {
6788             auto shareDataPair = it->second;
6789             if (abilityRecord && shareDataPair.first != abilityRecord->GetAbilityRecordId()) {
6790                 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is not the abilityRecord from request.");
6791                 return ERR_INVALID_VALUE;
6792             }
6793             auto callback = shareDataPair.second;
6794             if (!callback) {
6795                 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback object is nullptr.");
6796                 return ERR_INVALID_VALUE;
6797             }
6798             auto ret = callback->AcquireShareDataDone(resultCode, wantParam);
6799             iAcquireShareDataMap_.erase(it);
6800             return ret;
6801         }
6802     }
6803     TAG_LOGE(AAFwkTag::ABILITYMGR, "iAcquireShareData is null.");
6804     return ERR_INVALID_VALUE;
6805 }
6806 
VerificationToken(const sptr<IRemoteObject> & token)6807 bool AbilityManagerService::VerificationToken(const sptr<IRemoteObject> &token)
6808 {
6809     TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token.");
6810     auto dataAbilityManager = GetCurrentDataAbilityManager();
6811     CHECK_POINTER_RETURN_BOOL(dataAbilityManager);
6812     auto connectManager = GetCurrentConnectManager();
6813     CHECK_POINTER_RETURN_BOOL(connectManager);
6814     auto missionListManager = GetCurrentMissionListManager();
6815     CHECK_POINTER_RETURN_BOOL(missionListManager);
6816 
6817     if (missionListManager->GetAbilityRecordByToken(token)) {
6818         return true;
6819     }
6820     if (missionListManager->GetAbilityFromTerminateList(token)) {
6821         return true;
6822     }
6823 
6824     if (dataAbilityManager->GetAbilityRecordByToken(token)) {
6825         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token4.");
6826         return true;
6827     }
6828 
6829     if (connectManager->GetExtensionByTokenFromServiceMap(token)) {
6830         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6831         return true;
6832     }
6833 
6834     if (connectManager->GetExtensionByTokenFromAbilityCache(token)) {
6835         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6836         return true;
6837     }
6838 
6839     if (connectManager->GetExtensionByTokenFromTerminatingMap(token)) {
6840         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6841         return true;
6842     }
6843 
6844     TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to verify token.");
6845     return false;
6846 }
6847 
VerificationAllToken(const sptr<IRemoteObject> & token)6848 bool AbilityManagerService::VerificationAllToken(const sptr<IRemoteObject> &token)
6849 {
6850     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6851     CHECK_POINTER_AND_RETURN(subManagersHelper_, false);
6852     return subManagersHelper_->VerificationAllToken(token);
6853 }
6854 
GetCurrentDataAbilityManager()6855 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetCurrentDataAbilityManager()
6856 {
6857     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6858     return subManagersHelper_->GetCurrentDataAbilityManager();
6859 }
6860 
GetDataAbilityManager(const sptr<IAbilityScheduler> & scheduler)6861 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManager(
6862     const sptr<IAbilityScheduler> &scheduler)
6863 {
6864     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6865     return subManagersHelper_->GetDataAbilityManager(scheduler);
6866 }
6867 
GetDataAbilityManagerByUserId(int32_t userId)6868 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId)
6869 {
6870     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6871     return subManagersHelper_->GetDataAbilityManagerByUserId(userId);
6872 }
6873 
GetDataAbilityManagerByToken(const sptr<IRemoteObject> & token)6874 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByToken(
6875     const sptr<IRemoteObject> &token)
6876 {
6877     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6878     return subManagersHelper_->GetDataAbilityManagerByToken(token);
6879 }
6880 
GetConnectManagers()6881 std::unordered_map<int, std::shared_ptr<AbilityConnectManager>> AbilityManagerService::GetConnectManagers()
6882 {
6883     if (subManagersHelper_ == nullptr) {
6884         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6885         return std::unordered_map<int, std::shared_ptr<AbilityConnectManager>>();
6886     }
6887     return subManagersHelper_->GetConnectManagers();
6888 }
6889 
GetCurrentConnectManager()6890 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetCurrentConnectManager()
6891 {
6892     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6893     return subManagersHelper_->GetCurrentConnectManager();
6894 }
6895 
GetConnectManagerByUserId(int32_t userId)6896 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByUserId(int32_t userId)
6897 {
6898     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6899     return subManagersHelper_->GetConnectManagerByUserId(userId);
6900 }
6901 
GetConnectManagerByToken(const sptr<IRemoteObject> & token)6902 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByToken(
6903     const sptr<IRemoteObject> &token)
6904 {
6905     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6906     return subManagersHelper_->GetConnectManagerByToken(token);
6907 }
6908 
GetConnectManagerByAbilityRecordId(const int64_t & abilityRecordId)6909 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByAbilityRecordId(
6910     const int64_t &abilityRecordId)
6911 {
6912     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6913     return subManagersHelper_->GetConnectManagerByAbilityRecordId(abilityRecordId);
6914 }
6915 
GetCurrentPendingWantManager()6916 std::shared_ptr<PendingWantManager> AbilityManagerService::GetCurrentPendingWantManager()
6917 {
6918     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6919     return subManagersHelper_->GetCurrentPendingWantManager();
6920 }
6921 
GetPendingWantManagerByUserId(int32_t userId)6922 std::shared_ptr<PendingWantManager> AbilityManagerService::GetPendingWantManagerByUserId(int32_t userId)
6923 {
6924     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6925     return subManagersHelper_->GetPendingWantManagerByUserId(userId);
6926 }
6927 
GetMissionListManagers()6928 std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>> AbilityManagerService::GetMissionListManagers()
6929 {
6930     if (subManagersHelper_ == nullptr) {
6931         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6932         return std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>>();
6933     }
6934     return subManagersHelper_->GetMissionListManagers();
6935 }
6936 
GetCurrentMissionListManager()6937 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetCurrentMissionListManager()
6938 {
6939     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6940     return subManagersHelper_->GetCurrentMissionListManager();
6941 }
6942 
GetMissionListManagerByUserId(int32_t userId)6943 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetMissionListManagerByUserId(int32_t userId)
6944 {
6945     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6946     return subManagersHelper_->GetMissionListManagerByUserId(userId);
6947 }
6948 
GetMissionListWrap()6949 std::shared_ptr<MissionListWrap> AbilityManagerService::GetMissionListWrap()
6950 {
6951     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6952     return subManagersHelper_->GetMissionListWrap();
6953 }
6954 
GetUIAbilityManagers()6955 std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>> AbilityManagerService::GetUIAbilityManagers()
6956 {
6957     if (subManagersHelper_ == nullptr) {
6958         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6959         return std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>>();
6960     }
6961     return subManagersHelper_->GetUIAbilityManagers();
6962 }
6963 
GetCurrentUIAbilityManager()6964 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetCurrentUIAbilityManager()
6965 {
6966     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6967     return subManagersHelper_->GetCurrentUIAbilityManager();
6968 }
6969 
GetUIAbilityManagerByUserId(int32_t userId) const6970 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUserId(int32_t userId) const
6971 {
6972     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6973     return subManagersHelper_->GetUIAbilityManagerByUserId(userId);
6974 }
6975 
GetUIAbilityManagerByUid(int32_t uid)6976 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUid(int32_t uid)
6977 {
6978     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6979     return subManagersHelper_->GetUIAbilityManagerByUid(uid);
6980 }
6981 
StartResidentApps(int32_t userId)6982 void AbilityManagerService::StartResidentApps(int32_t userId)
6983 {
6984     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps %{public}d", userId);
6985     ConnectBmsService();
6986     auto bms = GetBundleManager();
6987     CHECK_POINTER_IS_NULLPTR(bms);
6988     std::vector<AppExecFwk::BundleInfo> bundleInfos;
6989     if (!DelayedSingleton<ResidentProcessManager>::GetInstance()->GetResidentBundleInfosForUser(bundleInfos, userId)) {
6990         TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident bundleinfos failed");
6991         return;
6992     }
6993     DelayedSingleton<ResidentProcessManager>::GetInstance()->Init();
6994     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps GetBundleInfos size: %{public}zu", bundleInfos.size());
6995 
6996     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId);
6997     if (!bundleInfos.empty()) {
6998 #ifdef SUPPORT_GRAPHICS
6999         if (userId == U0_USER_ID) {
7000             WaitBootAnimationStart();
7001         }
7002 #endif
7003         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
7004     }
7005 }
7006 
StartAutoStartupApps()7007 void AbilityManagerService::StartAutoStartupApps()
7008 {
7009     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7010     if (abilityAutoStartupService_ == nullptr) {
7011         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
7012         return;
7013     }
7014     std::vector<AutoStartupInfo> infoList;
7015     int32_t result = abilityAutoStartupService_->QueryAllAutoStartupApplicationsWithoutPermission(infoList,
7016         GetUserId());
7017     if (result != ERR_OK) {
7018         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to query data.");
7019         return;
7020     }
7021 
7022     constexpr int retryCount = 5;
7023     RetryStartAutoStartupApps(infoList, retryCount);
7024 }
7025 
RetryStartAutoStartupApps(const std::vector<AutoStartupInfo> & infoList,int32_t retryCount)7026 void AbilityManagerService::RetryStartAutoStartupApps(
7027     const std::vector<AutoStartupInfo> &infoList, int32_t retryCount)
7028 {
7029     TAG_LOGD(AAFwkTag::ABILITYMGR,
7030         "Called, retryCount: %{public}d, infoList.size:%{public}zu", retryCount, infoList.size());
7031     std::vector<AutoStartupInfo> failedList;
7032     for (auto info : infoList) {
7033         AppExecFwk::ElementName element;
7034         element.SetBundleName(info.bundleName);
7035         element.SetAbilityName(info.abilityName);
7036         element.SetModuleName(info.moduleName);
7037         Want want;
7038         want.SetElement(element);
7039         want.SetParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, true);
7040         if (info.appCloneIndex > 0 && info.appCloneIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
7041             want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, info.appCloneIndex);
7042         }
7043         if (StartAbility(want) != ERR_OK) {
7044             failedList.push_back(info);
7045         }
7046     }
7047 
7048     TAG_LOGD(AAFwkTag::ABILITYMGR,
7049         "RetryCount: %{public}d, failedList.size:%{public}zu", retryCount, failedList.size());
7050     if (!failedList.empty() && retryCount > 0) {
7051         auto retryStartAutoStartupAppsTask = [aams = weak_from_this(), list = failedList, retryCount]() {
7052             auto obj = aams.lock();
7053             if (obj == nullptr) {
7054                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Retry start auto startup app error, obj is nullptr");
7055                 return;
7056             }
7057             obj->RetryStartAutoStartupApps(list, retryCount - 1);
7058         };
7059         constexpr int delaytime = 2000;
7060         taskHandler_->SubmitTask(retryStartAutoStartupAppsTask, "RetryStartAutoStartupApps", delaytime);
7061     }
7062 }
7063 
SubscribeScreenUnlockedEvent()7064 void AbilityManagerService::SubscribeScreenUnlockedEvent()
7065 {
7066     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7067     // add listen screen unlocked.
7068     EventFwk::MatchingSkills matchingSkills;
7069     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
7070     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
7071     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
7072     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
7073     auto callback = [abilityManager = weak_from_this()]() {
7074         TAG_LOGD(AAFwkTag::ABILITYMGR, "On screen unlocked.");
7075         auto abilityMgr = abilityManager.lock();
7076         if (abilityMgr == nullptr) {
7077             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
7078             return;
7079         }
7080         auto taskHandler = abilityMgr->GetTaskHandler();
7081         if (taskHandler == nullptr) {
7082             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid taskHandler pointer.");
7083             return;
7084         }
7085         auto startAutoStartupAppsTask = [abilityManager]() {
7086             auto abilityMgr = abilityManager.lock();
7087             if (abilityMgr == nullptr) {
7088                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
7089                 return;
7090             }
7091             abilityMgr->RemoveScreenUnlockInterceptor();
7092             abilityMgr->StartAutoStartupApps();
7093             abilityMgr->UnSubscribeScreenUnlockedEvent();
7094         };
7095         taskHandler->SubmitTask(startAutoStartupAppsTask, "StartAutoStartupApps");
7096     };
7097     auto userScreenUnlockCallback = [abilityManager = weak_from_this()]() {
7098         TAG_LOGD(AAFwkTag::ABILITYMGR, "On user screen unlocked.");
7099         auto abilityMgr = abilityManager.lock();
7100         if (abilityMgr == nullptr) {
7101             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
7102             return;
7103         }
7104         abilityMgr->RemoveScreenUnlockInterceptor();
7105     };
7106     screenSubscriber_ = std::make_shared<AbilityRuntime::AbilityManagerEventSubscriber>(subscribeInfo, callback,
7107         userScreenUnlockCallback);
7108     bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber_);
7109     if (!subResult) {
7110         constexpr int retryCount = 20;
7111         RetrySubscribeScreenUnlockedEvent(retryCount);
7112     }
7113 }
7114 
UnSubscribeScreenUnlockedEvent()7115 void AbilityManagerService::UnSubscribeScreenUnlockedEvent()
7116 {
7117     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7118     bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_);
7119     TAG_LOGD(AAFwkTag::ABILITYMGR, "Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult);
7120 }
7121 
RetrySubscribeScreenUnlockedEvent(int32_t retryCount)7122 void AbilityManagerService::RetrySubscribeScreenUnlockedEvent(int32_t retryCount)
7123 {
7124     TAG_LOGD(AAFwkTag::ABILITYMGR, "RetryCount: %{public}d.", retryCount);
7125     auto retrySubscribeScreenUnlockedEventTask = [aams = weak_from_this(), screenSubscriber = screenSubscriber_,
7126                                                      retryCount]() {
7127         bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber);
7128         auto obj = aams.lock();
7129         if (obj == nullptr) {
7130             TAG_LOGE(AAFwkTag::ABILITYMGR, "Retry subscribe screen unlocked event, obj is nullptr.");
7131             return;
7132         }
7133         if (!subResult && retryCount > 0) {
7134             obj->RetrySubscribeScreenUnlockedEvent(retryCount - 1);
7135         }
7136     };
7137     constexpr int delaytime = 200;
7138     taskHandler_->SubmitTask(retrySubscribeScreenUnlockedEventTask, "RetrySubscribeScreenUnlockedEvent", delaytime);
7139 }
7140 
RemoveScreenUnlockInterceptor()7141 void AbilityManagerService::RemoveScreenUnlockInterceptor()
7142 {
7143     interceptorExecuter_->RemoveInterceptor("ScreenUnlock");
7144 }
7145 
ConnectBmsService()7146 void AbilityManagerService::ConnectBmsService()
7147 {
7148     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7149     TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting AppMgr Service run completed.");
7150     while (!DelayedSingleton<AppScheduler>::GetInstance()->Init(shared_from_this())) {
7151         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to init AppScheduler");
7152         usleep(REPOLL_TIME_MICRO_SECONDS);
7153     }
7154 
7155     TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting BundleMgr Service run completed.");
7156     /* wait until connected to bundle manager service */
7157     std::lock_guard<ffrt::mutex> guard(globalLock_);
7158     while (iBundleManager_ == nullptr) {
7159         sptr<IRemoteObject> bundle_obj =
7160             OHOS::DelayedSingleton<SaMgrClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
7161         if (bundle_obj == nullptr) {
7162             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bundle manager service");
7163             usleep(REPOLL_TIME_MICRO_SECONDS);
7164             continue;
7165         }
7166         iBundleManager_ = iface_cast<AppExecFwk::IBundleMgr>(bundle_obj);
7167     }
7168 
7169     TAG_LOGI(AAFwkTag::ABILITYMGR, "Connect bms success!");
7170 }
7171 
GetWantSenderInfo(const sptr<IWantSender> & target,std::shared_ptr<WantSenderInfo> & info)7172 int AbilityManagerService::GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)
7173 {
7174     TAG_LOGI(AAFwkTag::ABILITYMGR, "Get pending request info.");
7175     auto pendingWantManager = GetCurrentPendingWantManager();
7176     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
7177     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
7178     CHECK_POINTER_AND_RETURN(info, ERR_INVALID_VALUE);
7179     return pendingWantManager->GetWantSenderInfo(target, info);
7180 }
7181 
GetAppMemorySize()7182 int AbilityManagerService::GetAppMemorySize()
7183 {
7184     TAG_LOGI(AAFwkTag::ABILITYMGR, "service GetAppMemorySize start");
7185     const char *key = "const.product.arkheaplimit";
7186     const char *def = "512m";
7187     char *valueGet = nullptr;
7188     unsigned int len = 128;
7189     int ret = GetParameter(key, def, valueGet, len);
7190     int resultInt = 0;
7191     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7192         if (valueGet == nullptr) {
7193             TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, valueGet is nullptr", __func__);
7194             return APP_MEMORY_SIZE;
7195         }
7196         int len = strlen(valueGet);
7197         for (int i = 0; i < len; i++) {
7198             if (valueGet[i] >= '0' && valueGet[i] <= '9') {
7199                 resultInt *= SIZE_10;
7200                 resultInt += valueGet[i] - '0';
7201             }
7202         }
7203         if (resultInt == 0) {
7204             return APP_MEMORY_SIZE;
7205         }
7206         return resultInt;
7207     }
7208     return APP_MEMORY_SIZE;
7209 }
7210 
IsRamConstrainedDevice()7211 bool AbilityManagerService::IsRamConstrainedDevice()
7212 {
7213     TAG_LOGI(AAFwkTag::ABILITYMGR, "service IsRamConstrainedDevice start");
7214     const char *key = "const.product.islowram";
7215     const char *def = "0";
7216     char *valueGet = nullptr;
7217     unsigned int len = 128;
7218     int ret = GetParameter(key, def, valueGet, len);
7219     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7220         int value = atoi(valueGet);
7221         if (value) {
7222             return true;
7223         }
7224         return false;
7225     }
7226     return false;
7227 }
7228 
GetMissionIdByAbilityToken(const sptr<IRemoteObject> & token)7229 int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)
7230 {
7231     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7232     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7233     if (!abilityRecord) {
7234         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
7235         return -1;
7236     }
7237     if (!JudgeSelfCalled(abilityRecord)) {
7238         return -1;
7239     }
7240     return GetMissionIdByAbilityTokenInner(token);
7241 }
7242 
GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> & token)7243 int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)
7244 {
7245     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7246     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7247     if (!abilityRecord) {
7248         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
7249         return -1;
7250     }
7251     auto userId = abilityRecord->GetOwnerMissionUserId();
7252     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7253         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7254         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7255         return uiAbilityManager->GetSessionIdByAbilityToken(token);
7256     }
7257     auto missionListManager = GetMissionListManagerByUserId(userId);
7258     if (!missionListManager) {
7259         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. owner mission userId=%{public}d", userId);
7260         return -1;
7261     }
7262     return missionListManager->GetMissionIdByAbilityToken(token);
7263 }
7264 
GetAbilityTokenByMissionId(int32_t missionId)7265 sptr<IRemoteObject> AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId)
7266 {
7267     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7268     auto missionListManager = GetCurrentMissionListManager();
7269     if (!missionListManager) {
7270         return nullptr;
7271     }
7272     return missionListManager->GetAbilityTokenByMissionId(missionId);
7273 }
7274 
StartRemoteAbilityByCall(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)7275 int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken,
7276     const sptr<IRemoteObject> &connect)
7277 {
7278     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin StartRemoteAbilityByCall", __func__);
7279     Want remoteWant = want;
7280     UpdateDmsCallerInfo(remoteWant, callerToken);
7281     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
7282         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
7283         return ERR_INVALID_VALUE;
7284     }
7285     int32_t missionId = -1;
7286     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7287         missionId = GetMissionIdByAbilityTokenInner(callerToken);
7288         if (!missionId) {
7289             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
7290             return ERR_INVALID_VALUE;
7291         }
7292     } else {
7293         missionId = GetMissionIdByAbilityToken(callerToken);
7294 }
7295     if (missionId < 0) {
7296         return ERR_INVALID_VALUE;
7297     }
7298     remoteWant.SetParam(DMS_MISSION_ID, missionId);
7299     DistributedClient dmsClient;
7300     return dmsClient.StartRemoteAbilityByCall(remoteWant, connect);
7301 }
7302 
ReleaseRemoteAbility(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element)7303 int AbilityManagerService::ReleaseRemoteAbility(const sptr<IRemoteObject> &connect,
7304     const AppExecFwk::ElementName &element)
7305 {
7306     DistributedClient dmsClient;
7307     return dmsClient.ReleaseRemoteAbility(connect, element);
7308 }
7309 
StartAbilityByCall(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId)7310 int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect,
7311     const sptr<IRemoteObject> &callerToken, int32_t accountId)
7312 {
7313     TAG_LOGI(AAFwkTag::ABILITYMGR, "call ability.");
7314     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7315     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7316     if (IsCrossUserCall(accountId)) {
7317         CHECK_CALLER_IS_SYSTEM_APP;
7318     }
7319 
7320     if (VerifyAccountPermission(accountId) == CHECK_PERMISSION_FAILED) {
7321         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed.", __func__);
7322         return CHECK_PERMISSION_FAILED;
7323     }
7324 
7325     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7326     if (abilityRecord && !JudgeSelfCalled(abilityRecord)) {
7327         return CHECK_PERMISSION_FAILED;
7328     }
7329 
7330     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
7331     int32_t appIndex = 0;
7332     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
7333         return ERR_APP_CLONE_INDEX_INVALID;
7334     }
7335     auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
7336         GetUserId(), appIndex, callerToken);
7337     if (checkRet != ERR_OK) {
7338         return checkRet;
7339     }
7340     StartAbilityInfoWrap threadLocalInfo(want, GetUserId(), appIndex, callerToken);
7341     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), true, nullptr);
7342     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
7343         interceptorExecuter_->DoProcess(interceptorParam);
7344     if (result != ERR_OK) {
7345         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
7346         return result;
7347     }
7348 
7349     if (CheckIfOperateRemote(want)) {
7350         TAG_LOGI(AAFwkTag::ABILITYMGR, "start remote ability by call");
7351         return StartRemoteAbilityByCall(want, callerToken, connect->AsObject());
7352     }
7353 
7354     if (accountId == U0_USER_ID) {
7355         accountId = DEFAULT_INVAL_VALUE;
7356     }
7357     int32_t oriValidUserId = GetValidUserId(accountId);
7358     if (!JudgeMultiUserConcurrency(oriValidUserId)) {
7359         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
7360         return ERR_CROSS_USER;
7361     }
7362 
7363     AbilityRequest abilityRequest;
7364     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
7365     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
7366     abilityRequest.callerToken = callerToken;
7367     abilityRequest.startSetting = nullptr;
7368     abilityRequest.want = want;
7369     abilityRequest.connect = connect;
7370     result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
7371     if (result != ERR_OK) {
7372         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
7373         return result;
7374     }
7375 
7376     if (!abilityRequest.abilityInfo.isStageBasedModel) {
7377         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability is not stage base model.");
7378         return RESOLVE_CALL_ABILITY_VERSION_ERR;
7379     }
7380 
7381     result = CheckStartByCallPermission(abilityRequest);
7382     if (result != ERR_OK) {
7383         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStartByCallPermission fail, result: %{public}d", result);
7384         return result;
7385     }
7386 
7387     TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityInfo.applicationInfo.singleton is %{public}s",
7388         abilityRequest.abilityInfo.applicationInfo.singleton ? "true" : "false");
7389     UpdateCallerInfo(abilityRequest.want, callerToken);
7390     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
7391         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityRequest.abilityInfo), false, appIndex);
7392     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
7393         afterCheckExecuter_->DoProcess(afterCheckParam);
7394     if (result != ERR_OK) {
7395         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
7396         return result;
7397     }
7398     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7399         ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7400         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
7401         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
7402         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7403         return uiAbilityManager->ResolveLocked(abilityRequest);
7404     }
7405 
7406     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
7407     if (missionListMgr == nullptr) {
7408         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is Null. Designated User Id=%{public}d", oriValidUserId);
7409         return ERR_INVALID_VALUE;
7410     }
7411     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7412 
7413     return missionListMgr->ResolveLocked(abilityRequest);
7414 }
7415 
StartAbilityJust(AbilityRequest & abilityRequest,int32_t validUserId)7416 int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)
7417 {
7418     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7419     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
7420     UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
7421     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7422         ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7423         auto uiAbilityManager = GetUIAbilityManagerByUserId(validUserId);
7424         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7425         return uiAbilityManager->ResolveLocked(abilityRequest);
7426     }
7427 
7428     auto missionListMgr = GetMissionListManagerByUserId(validUserId);
7429     if (missionListMgr == nullptr) {
7430         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is Null. Designated User Id=%{public}d", validUserId);
7431         return ERR_INVALID_VALUE;
7432     }
7433     ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7434 
7435     return missionListMgr->ResolveLocked(abilityRequest);
7436 }
7437 
ReleaseCall(const sptr<IAbilityConnection> & connect,const AppExecFwk::ElementName & element)7438 int AbilityManagerService::ReleaseCall(
7439     const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
7440 {
7441     TAG_LOGD(AAFwkTag::ABILITYMGR, "Release called ability.");
7442 
7443     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7444     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7445 
7446     std::string elementName = element.GetURI();
7447     TAG_LOGD(AAFwkTag::ABILITYMGR, "try to release called ability, name: %{public}s.", elementName.c_str());
7448 
7449     if (CheckIsRemote(element.GetDeviceID())) {
7450         TAG_LOGI(AAFwkTag::ABILITYMGR, "release remote ability");
7451         return ReleaseRemoteAbility(connect->AsObject(), element);
7452     }
7453 
7454     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7455         auto uiAbilityManager = GetCurrentUIAbilityManager();
7456         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7457         return uiAbilityManager->ReleaseCallLocked(connect, element);
7458     }
7459     auto missionListManager = GetCurrentMissionListManager();
7460     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
7461     return missionListManager->ReleaseCallLocked(connect, element);
7462 }
7463 
JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo & abilityInfo)7464 int AbilityManagerService::JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)
7465 {
7466     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
7467     if (abilityInfo.visible) {
7468         return ERR_OK;
7469     }
7470     auto callerTokenId = IPCSkeleton::GetCallingTokenID();
7471     if (callerTokenId == abilityInfo.applicationInfo.accessTokenId ||
7472         callerTokenId == static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID())) {  // foundation call is allowed
7473         return ERR_OK;
7474     }
7475     if (AccessTokenKit::VerifyAccessToken(callerTokenId,
7476         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == AppExecFwk::Constants::PERMISSION_GRANTED) {
7477         return ERR_OK;
7478     }
7479     TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken: %{private}u, targetToken: %{private}u, caller doesn's have permission",
7480         callerTokenId, abilityInfo.applicationInfo.accessTokenId);
7481     return ABILITY_VISIBLE_FALSE_DENY_REQUEST;
7482 }
7483 
StartUser(int userId,sptr<IUserCallback> callback)7484 int AbilityManagerService::StartUser(int userId, sptr<IUserCallback> callback)
7485 {
7486     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartUser in service:%{public}d.", userId);
7487     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7488         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUser permission verification failed, not account process.");
7489         if (callback != nullptr) {
7490             callback->OnStartUserDone(userId, CHECK_PERMISSION_FAILED);
7491         }
7492         return CHECK_PERMISSION_FAILED;
7493     }
7494 
7495     if (userController_) {
7496         userController_->StartUser(userId, callback);
7497     }
7498     return 0;
7499 }
7500 
StopUser(int userId,const sptr<IUserCallback> & callback)7501 int AbilityManagerService::StopUser(int userId, const sptr<IUserCallback> &callback)
7502 {
7503     TAG_LOGI(AAFwkTag::ABILITYMGR, "StopUser in service:%{public}d", userId);
7504     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7505         TAG_LOGE(AAFwkTag::ABILITYMGR, "StopUser permission verification failed, not account process");
7506         if (callback != nullptr) {
7507             callback->OnStopUserDone(userId, CHECK_PERMISSION_FAILED);
7508         }
7509         return CHECK_PERMISSION_FAILED;
7510     }
7511 
7512     auto ret = -1;
7513     if (userController_) {
7514         ret = userController_->StopUser(userId);
7515         TAG_LOGD(AAFwkTag::ABILITYMGR, "ret = %{public}d", ret);
7516     }
7517     if (callback) {
7518         callback->OnStopUserDone(userId, ret);
7519     }
7520     return 0;
7521 }
7522 
LogoutUser(int32_t userId)7523 int AbilityManagerService::LogoutUser(int32_t userId)
7524 {
7525     TAG_LOGI(AAFwkTag::ABILITYMGR, "LogoutUser in service:%{public}d", userId);
7526     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7527         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed, not account process");
7528         return CHECK_PERMISSION_FAILED;
7529     }
7530 
7531     // Lister screen unlock for auto startup apps.
7532     if (system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) {
7533         InitInterceptorForScreenUnlock();
7534         SubscribeScreenUnlockedEvent();
7535     }
7536 
7537     if (userController_) {
7538         auto ret = userController_->LogoutUser(userId);
7539         TAG_LOGD(AAFwkTag::ABILITYMGR, "logout user return = %{public}d", ret);
7540         return ret;
7541     }
7542     return ERR_OK;
7543 }
7544 
OnAcceptWantResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)7545 void AbilityManagerService::OnAcceptWantResponse(
7546     const AAFwk::Want &want, const std::string &flag, int32_t requestId)
7547 {
7548     TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
7549     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7550         auto uiAbilityManager = GetCurrentUIAbilityManager();
7551         CHECK_POINTER(uiAbilityManager);
7552         uiAbilityManager->OnAcceptWantResponse(want, flag, requestId);
7553         return;
7554     }
7555     auto missionListManager = GetCurrentMissionListManager();
7556     if (!missionListManager) {
7557         return;
7558     }
7559     missionListManager->OnAcceptWantResponse(want, flag);
7560 }
7561 
OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want & want,int32_t requestId)7562 void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7563 {
7564     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str());
7565     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7566         auto uiAbilityManager = GetCurrentUIAbilityManager();
7567         CHECK_POINTER(uiAbilityManager);
7568         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7569         return;
7570     }
7571     auto missionListManager = GetCurrentMissionListManager();
7572     if (!missionListManager) {
7573         return;
7574     }
7575     missionListManager->OnStartSpecifiedAbilityTimeoutResponse(want);
7576 }
7577 
OnStartSpecifiedProcessResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)7578 void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag,
7579     int32_t requestId)
7580 {
7581     TAG_LOGD(AAFwkTag::ABILITYMGR, "flag = %{public}s", flag.c_str());
7582     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7583         auto uiAbilityManager = GetCurrentUIAbilityManager();
7584         CHECK_POINTER(uiAbilityManager);
7585         uiAbilityManager->OnStartSpecifiedProcessResponse(want, flag, requestId);
7586         return;
7587     }
7588 }
7589 
OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want & want,int32_t requestId)7590 void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7591 {
7592     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str());
7593     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7594         auto uiAbilityManager = GetCurrentUIAbilityManager();
7595         CHECK_POINTER(uiAbilityManager);
7596         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7597         return;
7598     }
7599 }
7600 
GetAbilityRunningInfos(std::vector<AbilityRunningInfo> & info)7601 int AbilityManagerService::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
7602 {
7603     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7604     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get running ability infos.");
7605     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7606     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7607         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
7608         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7609         uiAbilityManager->GetAbilityRunningInfos(info, isPerm);
7610     } else {
7611         auto missionListManager = GetCurrentMissionListManager();
7612         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
7613         missionListManager->GetAbilityRunningInfos(info, isPerm);
7614     }
7615 
7616     UpdateFocusState(info);
7617 
7618     return ERR_OK;
7619 }
7620 
UpdateFocusState(std::vector<AbilityRunningInfo> & info)7621 void AbilityManagerService::UpdateFocusState(std::vector<AbilityRunningInfo> &info)
7622 {
7623     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7624     if (info.empty()) {
7625         return;
7626     }
7627 
7628 #ifdef SUPPORT_GRAPHICS
7629     sptr<IRemoteObject> token;
7630     int ret = IN_PROCESS_CALL(GetTopAbility(token));
7631     if (ret != ERR_OK || token == nullptr) {
7632         return;
7633     }
7634 
7635     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7636     if (abilityRecord == nullptr) {
7637         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
7638         return;
7639     }
7640 
7641     for (auto &item : info) {
7642         if (item.uid == abilityRecord->GetUid() && item.pid == abilityRecord->GetPid() &&
7643             item.ability == abilityRecord->GetElementName()) {
7644             item.abilityState = static_cast<int>(AbilityState::ACTIVE);
7645             break;
7646         }
7647     }
7648 #endif
7649 }
7650 
GetExtensionRunningInfos(int upperLimit,std::vector<ExtensionRunningInfo> & info)7651 int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)
7652 {
7653     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7654     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension infos, upperLimit : %{public}d", upperLimit);
7655     CHECK_CALLER_IS_SYSTEM_APP;
7656     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7657     auto connectManager = GetCurrentConnectManager();
7658     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
7659     connectManager->GetExtensionRunningInfos(upperLimit, info, GetUserId(), isPerm);
7660     return ERR_OK;
7661 }
7662 
GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> & info)7663 int AbilityManagerService::GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)
7664 {
7665     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfos(info);
7666 }
7667 
GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> & info,int32_t userId)7668 int AbilityManagerService::GetProcessRunningInfosByUserId(
7669     std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)
7670 {
7671     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfosByUserId(info, userId);
7672 }
7673 
ClearUserData(int32_t userId)7674 void AbilityManagerService::ClearUserData(int32_t userId)
7675 {
7676     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7677     CHECK_POINTER(subManagersHelper_);
7678     subManagersHelper_->ClearSubManagers(userId);
7679 }
7680 
RegisterSnapshotHandler(const sptr<ISnapshotHandler> & handler)7681 int AbilityManagerService::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
7682 {
7683     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7684     if (!isSaCall) {
7685         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
7686         return 0;
7687     }
7688 
7689     auto missionListManager = GetCurrentMissionListManager();
7690     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7691     missionListManager->RegisterSnapshotHandler(handler);
7692     TAG_LOGI(AAFwkTag::ABILITYMGR, "snapshot: AbilityManagerService register snapshot handler success.");
7693     return ERR_OK;
7694 }
7695 
GetMissionSnapshot(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot,bool isLowResolution)7696 int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId,
7697     MissionSnapshot& missionSnapshot, bool isLowResolution)
7698 {
7699     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7700     CHECK_CALLER_IS_SYSTEM_APP;
7701     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
7702         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
7703         return CHECK_PERMISSION_FAILED;
7704     }
7705 
7706     if (CheckIsRemote(deviceId)) {
7707         TAG_LOGI(AAFwkTag::ABILITYMGR, "get remote mission snapshot.");
7708         return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot);
7709     }
7710     TAG_LOGI(AAFwkTag::ABILITYMGR, "get local mission snapshot.");
7711     auto missionListManager = GetCurrentMissionListManager();
7712     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7713     auto token = GetAbilityTokenByMissionId(missionId);
7714     bool result = missionListManager->GetMissionSnapshot(missionId, token, missionSnapshot, isLowResolution);
7715     if (!result) {
7716         return INNER_ERR;
7717     }
7718     return ERR_OK;
7719 }
7720 
UpdateMissionSnapShot(const sptr<IRemoteObject> & token,const std::shared_ptr<Media::PixelMap> & pixelMap)7721 void AbilityManagerService::UpdateMissionSnapShot(const sptr<IRemoteObject> &token,
7722     const std::shared_ptr<Media::PixelMap> &pixelMap)
7723 {
7724     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)) {
7725         return;
7726     }
7727     auto missionListManager = GetCurrentMissionListManager();
7728     if (missionListManager) {
7729         missionListManager->UpdateSnapShot(token, pixelMap);
7730     }
7731 }
7732 
EnableRecoverAbility(const sptr<IRemoteObject> & token)7733 void AbilityManagerService::EnableRecoverAbility(const sptr<IRemoteObject>& token)
7734 {
7735     TAG_LOGD(AAFwkTag::ABILITYMGR, "Enable recovery ability.");
7736     if (token == nullptr) {
7737         return;
7738     }
7739     auto record = Token::GetAbilityRecordByToken(token);
7740     if (record == nullptr) {
7741         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
7742         return;
7743     }
7744     if (record->IsClearMissionFlag()) {
7745         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::not allow EnableRecoverAbility before clearMission.",
7746             __func__);
7747         return;
7748     }
7749 
7750     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7751     auto tokenID = record->GetApplicationInfo().accessTokenId;
7752     if (callingTokenId != tokenID) {
7753         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery ScheduleRecoverAbility not self, not enabled");
7754         return;
7755     }
7756     {
7757         std::lock_guard<ffrt::mutex> guard(globalLock_);
7758         auto it = appRecoveryHistory_.find(record->GetUid());
7759         if (it == appRecoveryHistory_.end()) {
7760             appRecoveryHistory_.emplace(record->GetUid(), 0);
7761         }
7762     }
7763     auto userId = record->GetOwnerMissionUserId();
7764     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7765         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7766         CHECK_POINTER(uiAbilityManager);
7767         const auto& abilityInfo = record->GetAbilityInfo();
7768         std::string abilityName = abilityInfo.name;
7769         auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
7770         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
7771             abilityName += std::to_string(sessionId);
7772         }
7773         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->AddAbilityRecoverInfo(
7774             abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName, sessionId);
7775     } else {
7776         auto missionListMgr = GetMissionListManagerByUserId(userId);
7777         if (missionListMgr == nullptr) {
7778             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is nullptr");
7779             return;
7780         }
7781         missionListMgr->EnableRecoverAbility(record->GetMissionId());
7782     }
7783 }
7784 
ScheduleClearRecoveryPageStack()7785 void AbilityManagerService::ScheduleClearRecoveryPageStack()
7786 {
7787     int32_t callerUid = IPCSkeleton::GetCallingUid();
7788     std::string bundleName;
7789     auto bms = GetBundleManager();
7790     if (bms == nullptr) {
7791         TAG_LOGE(AAFwkTag::ABILITYMGR, "ScheduleClearRecoveryPageStack failed to get bms");
7792         return;
7793     }
7794 
7795     if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
7796         TAG_LOGE(AAFwkTag::ABILITYMGR, "ScheduleClearRecoveryPageStack failed to get bundleName by uid");
7797         return;
7798     }
7799 
7800     auto tokenId = IPCSkeleton::GetCallingTokenID();
7801 
7802     TAG_LOGI(AAFwkTag::ABILITYMGR,
7803         "ScheduleClearRecoveryPageStack bundleName = %{public}s, callerUid = %{public}d, tokenId = %{public}d",
7804         bundleName.c_str(), callerUid, tokenId);
7805     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
7806         DeleteAppExitReason(bundleName, tokenId);
7807     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
7808         DeleteAllRecoverInfoByTokenId(tokenId);
7809 }
7810 
ReportAppRecoverResult(const int32_t appId,const AppExecFwk::ApplicationInfo & appInfo,const std::string & abilityName,const std::string & result)7811 void AbilityManagerService::ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo,
7812     const std::string& abilityName, const std::string& result)
7813 {
7814     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
7815         "APP_UID", appId,
7816         "VERSION_CODE", std::to_string(appInfo.versionCode),
7817         "VERSION_NAME", appInfo.versionName,
7818         "BUNDLE_NAME", appInfo.bundleName,
7819         "ABILITY_NAME", abilityName,
7820         "RECOVERY_RESULT", result);
7821 }
7822 
SubmitSaveRecoveryInfo(const sptr<IRemoteObject> & token)7823 void AbilityManagerService::SubmitSaveRecoveryInfo(const sptr<IRemoteObject>& token)
7824 {
7825     if (token == nullptr) {
7826         TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo token is nullptr");
7827         return;
7828     }
7829     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7830     if (abilityRecord == nullptr) {
7831         TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo abilityRecord is nullptr");
7832         return;
7833     }
7834     auto abilityInfo = abilityRecord->GetAbilityInfo();
7835     auto userId = abilityRecord->GetOwnerMissionUserId();
7836     auto tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
7837     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7838     if (callingTokenId != tokenId) {
7839         TAG_LOGE(AAFwkTag::ABILITYMGR, "SubmitSaveRecoveryInfo not self, not enabled");
7840         return;
7841     }
7842     std::string abilityName = abilityInfo.name;
7843     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7844         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7845         CHECK_POINTER(uiAbilityManager);
7846         auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
7847         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
7848             abilityName += std::to_string(sessionId);
7849         }
7850     } else {
7851         auto missionListMgr = GetMissionListManagerByUserId(userId);
7852         if (missionListMgr == nullptr) {
7853             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is nullptr");
7854             return;
7855         }
7856         abilityName += std::to_string(abilityRecord->GetMissionId());
7857     }
7858     TAG_LOGI(AAFwkTag::ABILITYMGR,
7859         "submitInfo bundleName = %{public}s, moduleName = %{public}s, abilityName = %{public}s, tokenId = %{public}d",
7860         abilityInfo.bundleName.c_str(),  abilityInfo.moduleName.c_str(), abilityName.c_str(), tokenId);
7861     RecoveryInfo recoveryInfo;
7862     recoveryInfo.bundleName = abilityInfo.bundleName;
7863     recoveryInfo.moduleName = abilityInfo.moduleName;
7864     recoveryInfo.abilityName = abilityName;
7865     recoveryInfo.time = time(nullptr);
7866     OHOS::AAFwk::RecoveryInfoTimer::GetInstance().SubmitSaveRecoveryInfo(recoveryInfo);
7867 }
7868 
AppRecoverKill(pid_t pid,int32_t reason)7869 void AbilityManagerService::AppRecoverKill(pid_t pid, int32_t reason)
7870 {
7871     AppExecFwk::AppFaultDataBySA faultDataSA;
7872     faultDataSA.errorObject.name = "appRecovery";
7873     switch (reason) {
7874         case AppExecFwk::StateReason::CPP_CRASH:
7875             faultDataSA.faultType = AppExecFwk::FaultDataType::CPP_CRASH;
7876             break;
7877         case AppExecFwk::StateReason::JS_ERROR:
7878             faultDataSA.faultType = AppExecFwk::FaultDataType::JS_ERROR;
7879             break;
7880         case AppExecFwk::StateReason::LIFECYCLE:
7881         case AppExecFwk::StateReason::APP_FREEZE:
7882             faultDataSA.faultType = AppExecFwk::FaultDataType::APP_FREEZE;
7883             break;
7884         default:
7885             faultDataSA.faultType = AppExecFwk::FaultDataType::UNKNOWN;
7886     }
7887     faultDataSA.pid = pid;
7888     IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFaultBySA(faultDataSA));
7889 }
7890 
ScheduleRecoverAbility(const sptr<IRemoteObject> & token,int32_t reason,const Want * want)7891 void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)
7892 {
7893     if (token == nullptr) {
7894         return;
7895     }
7896     auto record = Token::GetAbilityRecordByToken(token);
7897     if (record == nullptr) {
7898         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
7899         return;
7900     }
7901     if (!record->IsForeground() && !record->GetAbilityForegroundingFlag()) {
7902         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed to recoveryAbility."
7903             "due to it is background", __func__);
7904         return;
7905     }
7906 
7907     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7908     auto tokenID = record->GetApplicationInfo().accessTokenId;
7909     if (callingTokenId != tokenID) {
7910         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery ScheduleRecoverAbility not self, not enabled");
7911         return;
7912     }
7913 
7914     AAFwk::Want curWant;
7915     {
7916         std::lock_guard<ffrt::mutex> guard(globalLock_);
7917         auto type = record->GetAbilityInfo().type;
7918         if (type != AppExecFwk::AbilityType::PAGE) {
7919             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::only do recover for page ability.", __func__);
7920             return;
7921         }
7922 
7923         constexpr int64_t MIN_RECOVERY_TIME = 60;
7924         int64_t now = time(nullptr);
7925         auto it = appRecoveryHistory_.find(record->GetUid());
7926         auto appInfo = record->GetApplicationInfo();
7927         auto abilityInfo = record->GetAbilityInfo();
7928 
7929         if ((it != appRecoveryHistory_.end()) &&
7930             (it->second + MIN_RECOVERY_TIME > now)) {
7931             TAG_LOGE(AAFwkTag::ABILITYMGR,
7932                 "%{public}s AppRecovery recover app more than once in one minute, just kill app(%{public}d).",
7933                 __func__, record->GetPid());
7934             ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_WITHIN_ONE_MINUTE");
7935             AppRecoverKill(record->GetPid(), reason);
7936             return;
7937         }
7938 
7939         if (want != nullptr) {
7940             TAG_LOGD(AAFwkTag::ABILITYMGR, "BundleName:%{public}s targetBundleName:%{public}s.",
7941                 appInfo.bundleName.c_str(), want->GetElement().GetBundleName().c_str());
7942             if (want->GetElement().GetBundleName().empty() ||
7943                 (appInfo.bundleName.compare(want->GetElement().GetBundleName()) != 0)) {
7944                 TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery BundleName not match, Not recovery ability!");
7945                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_BUNDLE_NAME_NOT_MATCH");
7946                 return;
7947             } else if (want->GetElement().GetAbilityName().empty()) {
7948                 TAG_LOGD(AAFwkTag::ABILITYMGR, "AppRecovery recovery target ability is empty");
7949                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_TARGET_ABILITY_EMPTY");
7950                 return;
7951             } else {
7952                 auto bms = GetBundleManager();
7953                 if (bms == nullptr) {
7954                     TAG_LOGE(AAFwkTag::ABILITYMGR, "bms is nullptr");
7955                     return;
7956                 }
7957                 AppExecFwk::BundleInfo bundleInfo;
7958                 auto bundleName = want->GetElement().GetBundleName();
7959                 int32_t userId = GetUserId();
7960                 bool ret = IN_PROCESS_CALL(
7961                     bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo,
7962                     userId));
7963                 if (!ret) {
7964                     TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery Failed to get bundle info, not do recovery!");
7965                     return;
7966                 }
7967                 bool isRestartPage = false;
7968                 auto abilityName = want->GetElement().GetAbilityName();
7969                 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
7970                     if ((abilityName.compare(it->name) == 0) && it->type == AppExecFwk::AbilityType::PAGE) {
7971                         isRestartPage = true;
7972                         break;
7973                     }
7974                 }
7975                 if (!isRestartPage) {
7976                     TAG_LOGI(AAFwkTag::ABILITYMGR, "AppRecovery the target ability type is not PAGE!");
7977                     ReportAppRecoverResult(record->GetUid(), appInfo, abilityName, "FAIL_TARGET_ABILITY_NOT_PAGE");
7978                     return;
7979                 }
7980             }
7981         }
7982 
7983         appRecoveryHistory_[record->GetUid()] = now;
7984         curWant = (want == nullptr) ? record->GetWant() : *want;
7985         curWant.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
7986 
7987         ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "SUCCESS");
7988     }
7989     RestartApp(curWant, true);
7990 }
7991 
GetRemoteMissionSnapshotInfo(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot)7992 int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId,
7993     MissionSnapshot& missionSnapshot)
7994 {
7995     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7996     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetRemoteMissionSnapshotInfo begin");
7997     std::unique_ptr<MissionSnapshot> missionSnapshotPtr = std::make_unique<MissionSnapshot>();
7998     DistributedClient dmsClient;
7999     int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr);
8000     if (result != ERR_OK) {
8001         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetRemoteMissionSnapshotInfo failed, result = %{public}d", result);
8002         return result;
8003     }
8004     missionSnapshot = *missionSnapshotPtr;
8005     return ERR_OK;
8006 }
8007 
StartSwitchUserDialog()8008 void AbilityManagerService::StartSwitchUserDialog()
8009 {
8010     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog extension ability come");
8011     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8012         TAG_LOGE(AAFwkTag::ABILITYMGR, "Scene board enabled, dialog not show.");
8013         return;
8014     }
8015 
8016     if (userController_ == nullptr) {
8017         TAG_LOGE(AAFwkTag::ABILITYMGR, "User Controller instance is nullptr.");
8018         return;
8019     }
8020 
8021     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
8022     if (sysDialog == nullptr) {
8023         TAG_LOGE(AAFwkTag::ABILITYMGR, "System dialog scheduler instance is nullptr.");
8024         return;
8025     }
8026 
8027     Want dialogWant = sysDialog->GetSwitchUserDialogWant();
8028     StartSwitchUserDialogInner(dialogWant, userController_->GetFreezingNewUserId());
8029 }
8030 
8031 
StartSwitchUserDialogInner(const Want & want,int32_t lastUserId)8032 void AbilityManagerService::StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)
8033 {
8034     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog inner come");
8035     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
8036     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
8037     AbilityRequest abilityRequest;
8038     auto result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
8039     if (result != ERR_OK) {
8040         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
8041         eventInfo.errCode = result;
8042         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8043         return;
8044     }
8045 
8046     auto abilityInfo = abilityRequest.abilityInfo;
8047     auto startUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
8048     result = CheckOptExtensionAbility(want, abilityRequest, startUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
8049     if (result != ERR_OK) {
8050         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check extensionAbility type error.");
8051         eventInfo.errCode = result;
8052         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8053         return;
8054     }
8055 
8056     auto connectManager = GetConnectManagerByUserId(startUserId);
8057     if (connectManager == nullptr) {
8058         CHECK_POINTER(subManagersHelper_);
8059         subManagersHelper_->InitConnectManager(startUserId, false);
8060         connectManager = GetConnectManagerByUserId(startUserId);
8061         if (connectManager == nullptr) {
8062             TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectManager is nullptr. userId=%{public}d", startUserId);
8063             eventInfo.errCode = ERR_INVALID_VALUE;
8064             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8065             return;
8066         }
8067     }
8068 
8069     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
8070         abilityRequest.abilityInfo.extensionAbilityType);
8071     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
8072     if (eventInfo.errCode != ERR_OK) {
8073         TAG_LOGE(AAFwkTag::ABILITYMGR, "EventInfo errCode is %{public}d", eventInfo.errCode);
8074         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8075     }
8076 }
8077 
StartFreezingScreen()8078 void AbilityManagerService::StartFreezingScreen()
8079 {
8080     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8081 #ifdef SUPPORT_GRAPHICS
8082     StartSwitchUserDialog();
8083     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8084     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Freeze(displayIds));
8085 #endif
8086 }
8087 
StopFreezingScreen()8088 void AbilityManagerService::StopFreezingScreen()
8089 {
8090     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8091 #ifdef SUPPORT_GRAPHICS
8092     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8093     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Unfreeze(displayIds));
8094     StopSwitchUserDialog();
8095 #endif
8096 }
8097 
UserStarted(int32_t userId)8098 void AbilityManagerService::UserStarted(int32_t userId)
8099 {
8100     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8101     CHECK_POINTER(subManagersHelper_);
8102     subManagersHelper_->InitSubManagers(userId, false);
8103 }
8104 
SwitchToUser(int32_t oldUserId,int32_t userId,sptr<IUserCallback> callback)8105 void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId, sptr<IUserCallback> callback)
8106 {
8107     TAG_LOGI(AAFwkTag::ABILITYMGR,
8108         "%{public}s, oldUserId:%{public}d, newUserId:%{public}d", __func__, oldUserId, userId);
8109     SwitchManagers(userId);
8110     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8111         PauseOldUser(oldUserId);
8112         ConnectBmsService();
8113         StartUserApps();
8114     }
8115     callback->OnStartUserDone(userId, ERR_OK);
8116     bool isBoot = oldUserId == U0_USER_ID ? true : false;
8117     StartHighestPriorityAbility(userId, isBoot);
8118      if (taskHandler_) {
8119         taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() {
8120             TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps userId:%{public}d", userId);
8121             abilityMs->StartResidentApps(userId);
8122             });
8123     }
8124     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
8125         AmsConfigurationParameter::GetInstance().MultiUserType() != 0) {
8126         TAG_LOGI(AAFwkTag::ABILITYMGR, "no need to terminate old scb.");
8127         return;
8128     }
8129     PauseOldConnectManager(oldUserId);
8130 }
8131 
SwitchManagers(int32_t userId,bool switchUser)8132 void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser)
8133 {
8134     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId);
8135     CHECK_POINTER(subManagersHelper_);
8136     subManagersHelper_->InitSubManagers(userId, switchUser);
8137     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----end", __func__, userId);
8138 }
8139 
PauseOldUser(int32_t userId)8140 void AbilityManagerService::PauseOldUser(int32_t userId)
8141 {
8142     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId);
8143     PauseOldMissionListManager(userId);
8144     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----end", __func__, userId);
8145 }
8146 
PauseOldMissionListManager(int32_t userId)8147 void AbilityManagerService::PauseOldMissionListManager(int32_t userId)
8148 {
8149     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId);
8150     auto manager = GetMissionListManagerByUserId(userId);
8151     CHECK_POINTER(manager);
8152     manager->PauseManager();
8153     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId);
8154 }
8155 
PauseOldConnectManager(int32_t userId)8156 void AbilityManagerService::PauseOldConnectManager(int32_t userId)
8157 {
8158     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----begin", __func__, userId);
8159     if (userId == U0_USER_ID) {
8160         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, u0 not stop, id:%{public}d-----nullptr", __func__, userId);
8161         return;
8162     }
8163 
8164     auto manager = GetConnectManagerByUserId(userId);
8165     CHECK_POINTER(manager);
8166     manager->PauseExtensions();
8167     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----end", __func__, userId);
8168 }
8169 
StartUserApps()8170 void AbilityManagerService::StartUserApps()
8171 {
8172     auto missionListManager = GetCurrentMissionListManager();
8173     if (missionListManager && missionListManager->IsStarted()) {
8174         TAG_LOGI(AAFwkTag::ABILITYMGR, "missionListManager ResumeManager");
8175         missionListManager->ResumeManager();
8176     }
8177 }
8178 
GetValidUserId(const int32_t userId)8179 int32_t AbilityManagerService::GetValidUserId(const int32_t userId)
8180 {
8181     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId = %{public}d.", userId);
8182     int32_t validUserId = userId;
8183 
8184     if (DEFAULT_INVAL_VALUE == userId) {
8185         validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
8186         TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId = %{public}d, CallingUid = %{public}d.", validUserId,
8187             IPCSkeleton::GetCallingUid());
8188         if (validUserId == U0_USER_ID) {
8189             validUserId = GetUserId();
8190         }
8191     }
8192     return validUserId;
8193 }
8194 
SetAbilityController(const sptr<IAbilityController> & abilityController,bool imAStabilityTest)8195 int AbilityManagerService::SetAbilityController(const sptr<IAbilityController> &abilityController,
8196     bool imAStabilityTest)
8197 {
8198     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest);
8199     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyControllerPerm();
8200     if (!isPerm) {
8201         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
8202         return CHECK_PERMISSION_FAILED;
8203     }
8204 
8205     std::lock_guard<ffrt::mutex> guard(globalLock_);
8206     abilityController_ = abilityController;
8207     controllerIsAStabilityTest_ = imAStabilityTest;
8208     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, end", __func__);
8209     return ERR_OK;
8210 }
8211 
IsRunningInStabilityTest()8212 bool AbilityManagerService::IsRunningInStabilityTest()
8213 {
8214     std::lock_guard<ffrt::mutex> guard(globalLock_);
8215     bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_;
8216     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret);
8217     return ret;
8218 }
8219 
IsAbilityControllerStart(const Want & want,const std::string & bundleName)8220 bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName)
8221 {
8222     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8223     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8224     if (abilityController_ == nullptr) {
8225         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8226         return true;
8227     }
8228 
8229     if (controllerIsAStabilityTest_) {
8230         bool isStart = abilityController_->AllowAbilityStart(want, bundleName);
8231         if (!isStart) {
8232             TAG_LOGI(AAFwkTag::ABILITYMGR,
8233                 "Not finishing start ability because controller starting: %{public}s", bundleName.c_str());
8234             return false;
8235         }
8236     }
8237     return true;
8238 }
8239 
IsAbilityControllerForeground(const std::string & bundleName)8240 bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName)
8241 {
8242     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8243     if (abilityController_ == nullptr) {
8244         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8245         return true;
8246     }
8247 
8248     if (controllerIsAStabilityTest_) {
8249         bool isResume = abilityController_->AllowAbilityBackground(bundleName);
8250         if (!isResume) {
8251             TAG_LOGI(AAFwkTag::ABILITYMGR,
8252                 "Not finishing terminate ability because controller resuming: %{public}s", bundleName.c_str());
8253             return false;
8254         }
8255     }
8256     return true;
8257 }
8258 
StartUserTest(const Want & want,const sptr<IRemoteObject> & observer)8259 int AbilityManagerService::StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)
8260 {
8261     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8262     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
8263         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
8264         return ERR_NOT_DEVELOPER_MODE;
8265     }
8266 
8267     if (observer == nullptr) {
8268         TAG_LOGE(AAFwkTag::ABILITYMGR, "observer is nullptr");
8269         return ERR_INVALID_VALUE;
8270     }
8271 
8272     std::string bundleName = want.GetStringParam("-b");
8273     if (bundleName.empty()) {
8274         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name");
8275         return ERR_INVALID_VALUE;
8276     }
8277 
8278     auto checkResult = AbilityUtil::CheckInstanceKey(want);
8279     if (checkResult != ERR_OK) {
8280         return checkResult;
8281     }
8282     int32_t appIndex = 0;
8283     if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex) || appIndex != 0) {
8284         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support app clone");
8285         return ERR_NOT_SUPPORT_APP_CLONE;
8286     }
8287 
8288     auto bms = GetBundleManager();
8289     CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL);
8290     AppExecFwk::BundleInfo bundleInfo;
8291     if (!IN_PROCESS_CALL(
8292         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID))) {
8293         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info by U0_USER_ID %{public}d.", U0_USER_ID);
8294         int32_t userId = GetUserId();
8295         if (!IN_PROCESS_CALL(
8296             bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
8297             TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info by userId %{public}d.", userId);
8298             return GET_BUNDLE_INFO_FAILED;
8299         }
8300     }
8301 
8302     return DelayedSingleton<AppScheduler>::GetInstance()->StartUserTest(want, observer, bundleInfo, GetUserId());
8303 }
8304 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName)8305 int AbilityManagerService::FinishUserTest(
8306     const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
8307 {
8308     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8309     if (bundleName.empty()) {
8310         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name.");
8311         return ERR_INVALID_VALUE;
8312     }
8313 
8314     return DelayedSingleton<AppScheduler>::GetInstance()->FinishUserTest(msg, resultCode, bundleName);
8315 }
8316 
GetTopAbility(sptr<IRemoteObject> & token)8317 int AbilityManagerService::GetTopAbility(sptr<IRemoteObject> &token)
8318 {
8319     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8320     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8321     if (!isSaCall) {
8322         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
8323         return CHECK_PERMISSION_FAILED;
8324     }
8325 #ifdef SUPPORT_GRAPHICS
8326     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8327         Rosen::FocusChangeInfo focusChangeInfo;
8328         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
8329         token = focusChangeInfo.abilityToken_;
8330     } else {
8331         if (!wmsHandler_) {
8332             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
8333             return ERR_INVALID_VALUE;
8334         }
8335         wmsHandler_->GetFocusWindow(token);
8336     }
8337 
8338     if (!token) {
8339         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
8340         return ERR_INVALID_VALUE;
8341     }
8342 #endif
8343     return ERR_OK;
8344 }
8345 
DelegatorDoAbilityForeground(const sptr<IRemoteObject> & token)8346 int AbilityManagerService::DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)
8347 {
8348     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8349     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8350     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8351     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8352     int32_t callerPid = IPCSkeleton::GetCallingPid();
8353     int32_t appPid = abilityRecord->GetPid();
8354     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8355     if (callerPid != appPid) {
8356         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not the application itself");
8357         return ERR_INVALID_VALUE;
8358     }
8359     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8360         auto sessionId = GetMissionIdByAbilityTokenInner(token);
8361         if (!sessionId) {
8362             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid session id.");
8363             return ERR_INVALID_VALUE;
8364         }
8365         auto want = abilityRecord->GetWant();
8366         if (!IsAbilityControllerStart(want, want.GetBundle())) {
8367             TAG_LOGE(AAFwkTag::ABILITYMGR,
8368                 "SceneBoard IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
8369             return ERR_WOULD_BLOCK;
8370         }
8371         return ERR_OK;
8372     }
8373     auto missionId = GetMissionIdByAbilityToken(token);
8374     if (missionId < 0) {
8375         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid mission id.");
8376         return ERR_INVALID_VALUE;
8377     }
8378     return DelegatorMoveMissionToFront(missionId);
8379 }
8380 
DelegatorDoAbilityBackground(const sptr<IRemoteObject> & token)8381 int AbilityManagerService::DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)
8382 {
8383     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8384     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8385     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8386     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8387     int32_t appPid = abilityRecord->GetPid();
8388     int32_t callerPid = IPCSkeleton::GetCallingPid();
8389     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8390     if (callerPid != appPid) {
8391         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not the application itself");
8392         return ERR_INVALID_VALUE;
8393     }
8394     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8395         return ERR_OK;
8396     }
8397     return MinimizeAbility(token, true);
8398 }
8399 
DoAbilityForeground(const sptr<IRemoteObject> & token,uint32_t flag)8400 int AbilityManagerService::DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)
8401 {
8402     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityForeground, sceneFlag:%{public}u", flag);
8403     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8404     if (!VerificationToken(token) && !VerificationAllToken(token)) {
8405         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s token error.", __func__);
8406         return ERR_INVALID_VALUE;
8407     }
8408 
8409     std::lock_guard<ffrt::mutex> guard(globalLock_);
8410     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8411     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8412     if (!JudgeSelfCalled(abilityRecord)) {
8413         return CHECK_PERMISSION_FAILED;
8414     }
8415 
8416     auto type = abilityRecord->GetAbilityInfo().type;
8417     if (type != AppExecFwk::AbilityType::PAGE) {
8418         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except page ability.");
8419         return ERR_WRONG_INTERFACE_CALL;
8420     }
8421 
8422     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
8423         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerForeground false.");
8424         return ERR_WOULD_BLOCK;
8425     }
8426 
8427     auto missionListManager = GetCurrentMissionListManager();
8428     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8429     return missionListManager->DoAbilityForeground(abilityRecord, flag);
8430 }
8431 
DoAbilityBackground(const sptr<IRemoteObject> & token,uint32_t flag)8432 int AbilityManagerService::DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)
8433 {
8434     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityBackground, sceneFlag:%{public}u", flag);
8435     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8436 
8437     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8438     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8439 
8440     abilityRecord->lifeCycleStateInfo_.sceneFlag = flag;
8441     int ret = MinimizeAbility(token);
8442     abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL;
8443     return ret;
8444 }
8445 
DelegatorMoveMissionToFront(int32_t missionId)8446 int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId)
8447 {
8448     TAG_LOGI(AAFwkTag::ABILITYMGR, "enter missionId : %{public}d", missionId);
8449     auto missionListManager = GetCurrentMissionListManager();
8450     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8451 
8452     if (!IsAbilityControllerStartById(missionId)) {
8453         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
8454         return ERR_WOULD_BLOCK;
8455     }
8456 
8457     return missionListManager->MoveMissionToFront(missionId);
8458 }
8459 
UpdateCallerInfo(Want & want,const sptr<IRemoteObject> & callerToken)8460 void AbilityManagerService::UpdateCallerInfo(Want& want, const sptr<IRemoteObject> &callerToken)
8461 {
8462     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8463     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
8464         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8465         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8466         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8467     }
8468     int32_t tokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
8469     int32_t callerUid = IPCSkeleton::GetCallingUid();
8470     int32_t callerPid = IPCSkeleton::GetCallingPid();
8471     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8472     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8473     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8474     want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
8475     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8476     want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
8477     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8478     want.RemoveParam(IS_SHELL_CALL);
8479     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8480     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8481     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8482 
8483     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8484     if (!abilityRecord) {
8485         std::string bundleName;
8486         auto bundleMgr = GetBundleManager();
8487         if (bundleMgr != nullptr) {
8488             IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, bundleName));
8489         }
8490         if (bundleName == "") {
8491             std::string nativeName;
8492             Security::AccessToken::NativeTokenInfo nativeTokenInfo;
8493             int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
8494             if (result == ERR_OK) {
8495                 nativeName = "_" + nativeTokenInfo.processName;
8496             }
8497             want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8498             want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME, nativeName);
8499         }
8500         want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, bundleName);
8501         want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, std::string(""));
8502         want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, 0);
8503         return;
8504     }
8505     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8506     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8507     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8508     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8509     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, abilityRecord->GetAppIndex());
8510     UpdateSignatureInfo(callerBundleName, want);
8511 }
8512 
UpdateCallerInfoFromToken(Want & want,const sptr<IRemoteObject> & token)8513 void AbilityManagerService::UpdateCallerInfoFromToken(Want& want, const sptr<IRemoteObject> &token)
8514 {
8515     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8516     if (!abilityRecord) {
8517         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller abilityRecord is null.");
8518         return;
8519     }
8520 
8521     int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
8522     int32_t callerUid = abilityRecord->GetUid();
8523     int32_t callerPid = abilityRecord->GetPid();
8524     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8525     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8526     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8527     want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
8528     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8529     want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
8530     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8531     want.RemoveParam(IS_SHELL_CALL);
8532 
8533     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8534     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8535     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8536     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8537     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8538     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8539     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8540     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, abilityRecord->GetAppIndex());
8541     UpdateSignatureInfo(callerBundleName, want);
8542 }
8543 
UpdateSignatureInfo(std::string bundleName,Want & want,bool isRemote)8544 void AbilityManagerService::UpdateSignatureInfo(std::string bundleName, Want& want, bool isRemote)
8545 {
8546     auto bundleMgr = GetBundleManager();
8547     if (bundleMgr != nullptr) {
8548         AppExecFwk::SignatureInfo signatureInfo;
8549         IN_PROCESS_CALL(bundleMgr->GetSignatureInfoByBundleName(bundleName, signatureInfo));
8550         std::string callerAppId = isRemote ? DMS_CALLER_APP_ID : Want::PARAM_RESV_CALLER_APP_ID;
8551         std::string callerAppIdentifier = isRemote ? DMS_CALLER_APP_IDENTIFIER : Want::PARAM_RESV_CALLER_APP_IDENTIFIER;
8552         want.RemoveParam(callerAppId);
8553         want.SetParam(callerAppId, signatureInfo.appId);
8554         want.RemoveParam(callerAppIdentifier);
8555         want.SetParam(callerAppIdentifier, signatureInfo.appIdentifier);
8556     }
8557 }
8558 
UpdateDmsCallerInfo(Want & want,const sptr<IRemoteObject> & callerToken)8559 void AbilityManagerService::UpdateDmsCallerInfo(Want& want, const sptr<IRemoteObject> &callerToken)
8560 {
8561     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8562     int32_t tokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
8563     int32_t callerUid = IPCSkeleton::GetCallingUid();
8564 
8565     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8566     if (!abilityRecord) {
8567         std::string bundleName;
8568         auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
8569         if (bundleMgr != nullptr) {
8570             IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, bundleName));
8571         }
8572         if (bundleName == "") {
8573             std::string nativeName;
8574             Security::AccessToken::NativeTokenInfo nativeTokenInfo;
8575             int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
8576             if (result == ERR_OK) {
8577                 nativeName = "_" + nativeTokenInfo.processName;
8578             }
8579             want.RemoveParam(DMS_CALLER_NATIVE_NAME);
8580             want.SetParam(DMS_CALLER_NATIVE_NAME, nativeName);
8581         }
8582         want.RemoveParam(DMS_CALLER_BUNDLE_NAME);
8583         want.SetParam(DMS_CALLER_BUNDLE_NAME, bundleName);
8584         want.RemoveParam(DMS_CALLER_ABILITY_NAME);
8585         want.SetParam(DMS_CALLER_ABILITY_NAME, std::string(""));
8586         return;
8587     }
8588     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8589     want.RemoveParam(DMS_CALLER_BUNDLE_NAME);
8590     want.SetParam(DMS_CALLER_BUNDLE_NAME, callerBundleName);
8591     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8592     want.RemoveParam(DMS_CALLER_ABILITY_NAME);
8593     want.SetParam(DMS_CALLER_ABILITY_NAME, callerAbilityName);
8594     UpdateSignatureInfo(callerBundleName, want, true);
8595 }
8596 
JudgeMultiUserConcurrency(const int32_t userId)8597 bool AbilityManagerService::JudgeMultiUserConcurrency(const int32_t userId)
8598 {
8599     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8600     if (userId == U0_USER_ID) {
8601         TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, userId is 0.", __func__);
8602         return true;
8603     }
8604 
8605     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, current userId : %{public}d", userId, GetUserId());
8606 
8607     // Only non-concurrent mode is supported
8608     bool concurrencyMode = CONCURRENCY_MODE_FALSE;
8609     if (!concurrencyMode) {
8610         return (userId == GetUserId());
8611     }
8612 
8613     return true;
8614 }
8615 
8616 #ifdef ABILITY_COMMAND_FOR_TEST
ForceTimeoutForTest(const std::string & abilityName,const std::string & state)8617 int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, const std::string &state)
8618 {
8619     if (abilityName.empty()) {
8620         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityName is empty.");
8621         return INVALID_DATA;
8622     }
8623     if (abilityName == "clean") {
8624         timeoutMap_.clear();
8625         return ERR_OK;
8626     }
8627     if (state != AbilityRecord::ConvertAbilityState(AbilityState::INITIAL) &&
8628         state != AbilityRecord::ConvertAbilityState(AbilityState::INACTIVE) &&
8629         state != AbilityRecord::ConvertAbilityState(AbilityState::FOREGROUND) &&
8630         state != AbilityRecord::ConvertAbilityState(AbilityState::BACKGROUND) &&
8631         state != AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) &&
8632         state != std::string("COMMAND")) {
8633         TAG_LOGE(AAFwkTag::ABILITYMGR, "lifecycle state is invalid.");
8634         return INVALID_DATA;
8635     }
8636     timeoutMap_.insert(std::make_pair(state, abilityName));
8637     return ERR_OK;
8638 }
8639 #endif
8640 
UpdateAsCallerSourceInfo(Want & want,sptr<IRemoteObject> asCallerSourceToken,sptr<IRemoteObject> callerToken)8641 void AbilityManagerService::UpdateAsCallerSourceInfo(Want& want, sptr<IRemoteObject> asCallerSourceToken,
8642     sptr<IRemoteObject> callerToken)
8643 {
8644 #ifdef SUPPORT_SCREEN
8645     if (UpdateAsCallerInfoFromDialog(want)) {
8646         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from dialog.");
8647         return;
8648     }
8649 #endif // SUPPORT_SCREEN
8650     if (asCallerSourceToken != nullptr) {
8651         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from token.");
8652         UpdateAsCallerInfoFromToken(want, asCallerSourceToken);
8653     } else if (callerToken != nullptr) {
8654         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from callerRecord.");
8655         UpdateAsCallerInfoFromCallerRecord(want, callerToken);
8656     }
8657 }
8658 
UpdateAsCallerInfoFromToken(Want & want,sptr<IRemoteObject> asCallerSourceToken)8659 void AbilityManagerService::UpdateAsCallerInfoFromToken(Want& want, sptr<IRemoteObject> asCallerSourceToken)
8660 {
8661     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(asCallerSourceToken)) {
8662         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8663         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8664         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8665     }
8666     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8667     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8668     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8669     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8670     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8671     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8672     want.RemoveParam(IS_SHELL_CALL);
8673 
8674     auto abilityRecord = Token::GetAbilityRecordByToken(asCallerSourceToken);
8675     if (abilityRecord == nullptr) {
8676         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to update as caller info from token");
8677         return;
8678     }
8679     AppExecFwk::RunningProcessInfo processInfo = {};
8680     DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByToken(asCallerSourceToken, processInfo);
8681     int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
8682     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8683     want.SetParam(Want::PARAM_RESV_CALLER_UID, processInfo.uid_);
8684     want.SetParam(Want::PARAM_RESV_CALLER_PID, processInfo.pid_);
8685 
8686     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8687     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8688     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8689     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8690     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8691     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, abilityRecord->GetAppIndex());
8692     UpdateSignatureInfo(callerBundleName, want);
8693 }
8694 
UpdateAsCallerInfoFromCallerRecord(Want & want,sptr<IRemoteObject> callerToken)8695 void AbilityManagerService::UpdateAsCallerInfoFromCallerRecord(Want& want, sptr<IRemoteObject> callerToken)
8696 {
8697     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
8698         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8699         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8700         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8701     }
8702     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8703     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8704     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8705     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8706     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8707     want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8708     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8709     want.RemoveParam(IS_SHELL_CALL);
8710     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
8711     CHECK_POINTER(callerRecord);
8712     auto sourceInfo = callerRecord->GetCallerInfo();
8713     CHECK_POINTER(sourceInfo);
8714     std::string callerBundleName = sourceInfo->callerBundleName;
8715     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, sourceInfo->callerTokenId);
8716     want.SetParam(Want::PARAM_RESV_CALLER_UID, sourceInfo->callerUid);
8717     want.SetParam(Want::PARAM_RESV_CALLER_PID, sourceInfo->callerPid);
8718     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8719     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, sourceInfo->callerAbilityName);
8720     want.RemoveParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX);
8721     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, sourceInfo->callerAppCloneIndex);
8722     if (callerBundleName == "") {
8723         want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME, sourceInfo->callerNativeName);
8724         return;
8725     }
8726     UpdateSignatureInfo(callerBundleName, want);
8727 }
8728 
UpdateAsCallerInfoFromDialog(Want & want)8729 bool AbilityManagerService::UpdateAsCallerInfoFromDialog(Want& want)
8730 {
8731     std::string dialogSessionId = want.GetStringParam("dialogSessionId");
8732     auto dialogCallerInfo = DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId);
8733     if (dialogCallerInfo == nullptr) {
8734         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed to get dialog caller info.");
8735         return false;
8736     }
8737     Want dialogCallerWant = dialogCallerInfo->targetWant;
8738     int32_t tokenId = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0);
8739     int32_t uid = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_UID, 0);
8740     int32_t pid = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_PID, 0);
8741     std::string callerBundleName = dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8742     std::string callerAbilityName = dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8743     int32_t callerAppCloneIndex = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, 0);
8744     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8745     want.SetParam(Want::PARAM_RESV_CALLER_UID, uid);
8746     want.SetParam(Want::PARAM_RESV_CALLER_PID, pid);
8747     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8748     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8749     want.SetParam(Want::PARAM_RESV_CALLER_APP_CLONE_INDEX, callerAppCloneIndex);
8750     want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8751     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8752     want.RemoveParam(IS_SHELL_CALL);
8753     if (callerBundleName == "") {
8754         want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME,
8755             dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME));
8756         return true;
8757     }
8758     UpdateSignatureInfo(callerBundleName, want);
8759     return true;
8760 }
8761 
UpdateBackToCallerFlag(const sptr<IRemoteObject> & callerToken,Want & want,int32_t requestCode,bool backFlag)8762 void AbilityManagerService::UpdateBackToCallerFlag(const sptr<IRemoteObject> &callerToken, Want &want,
8763     int32_t requestCode, bool backFlag)
8764 {
8765     if (want.HasParameter(CALLER_REQUEST_CODE)) {
8766         want.RemoveParam(CALLER_REQUEST_CODE);
8767     }
8768     auto callerAbilityRecord = Token::GetAbilityRecordByToken(callerToken);
8769     if (requestCode > 0 && callerAbilityRecord != nullptr) {
8770         // default return true on oh
8771         if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8772             backFlag = AmsConfigurationParameter::GetInstance().IsSupportBackToCaller();
8773         }
8774         auto fullRequestCode = StartupUtil::GenerateFullRequestCode(
8775             callerAbilityRecord->GetPid(), backFlag, requestCode);
8776         want.SetParam(CALLER_REQUEST_CODE, std::to_string(fullRequestCode));
8777         TAG_LOGI(AAFwkTag::ABILITYMGR,
8778             "pid: %{public}d, backFlag:%{private}d, requestCode: %{private}d, fullRequestCode: %{private}s",
8779             callerAbilityRecord->GetPid(), backFlag, requestCode, std::to_string(fullRequestCode).c_str());
8780     }
8781 }
8782 
CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo & abilityInfo,uint32_t tokenId)8783 int AbilityManagerService::CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo,
8784     uint32_t tokenId)
8785 {
8786     if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId,
8787         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) {
8788         return AppExecFwk::Constants::PERMISSION_GRANTED;
8789     }
8790 
8791     for (auto permission : abilityInfo.permissions) {
8792         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8793             AppExecFwk::Constants::PERMISSION_GRANTED) {
8794             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Ability permission: %{public}s",
8795                 permission.c_str());
8796             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8797         }
8798     }
8799 
8800     return AppExecFwk::Constants::PERMISSION_GRANTED;
8801 }
8802 
CheckOneSkillPermission(const AppExecFwk::Skill & skill,uint32_t tokenId)8803 bool AbilityManagerService::CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId)
8804 {
8805     for (auto permission : skill.permissions) {
8806         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8807             AppExecFwk::Constants::PERMISSION_GRANTED) {
8808             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Skill permission: %{public}s",
8809                 permission.c_str());
8810             return false;
8811         }
8812     }
8813 
8814     return true;
8815 }
8816 
CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest & abilityRequest,uint32_t tokenId)8817 int AbilityManagerService::CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest,
8818     uint32_t tokenId)
8819 {
8820     auto abilityInfo = abilityRequest.abilityInfo;
8821     auto resultAbilityPermission = CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8822     if (resultAbilityPermission != AppExecFwk::Constants::PERMISSION_GRANTED) {
8823         return resultAbilityPermission;
8824     }
8825 
8826     if (abilityInfo.skills.empty()) {
8827         return AppExecFwk::Constants::PERMISSION_GRANTED;
8828     }
8829     int32_t result = AppExecFwk::Constants::PERMISSION_GRANTED;
8830     for (auto skill : abilityInfo.skills) {
8831         if (skill.Match(abilityRequest.want)) {
8832             if (CheckOneSkillPermission(skill, tokenId)) {
8833                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8834             } else {
8835                 result = AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8836             }
8837         }
8838     }
8839     return result;
8840 }
8841 
CheckStaticCfgPermission(const AppExecFwk::AbilityRequest & abilityRequest,bool isStartAsCaller,uint32_t callerTokenId,bool isData,bool isSaCall,bool isImplicit)8842 int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest,
8843     bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit)
8844 {
8845     auto abilityInfo = abilityRequest.abilityInfo;
8846     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8847     if (AppUtils::GetInstance().IsSupportAncoApp() &&
8848         StartAbilityUtils::IsCallFromAncoShellOrBroker(abilityRequest.callerToken)) {
8849         TAG_LOGD(AAFwkTag::ABILITYMGR,
8850             "Check static permission, name is %{public}s.", abilityInfo.name.c_str());
8851         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
8852         if (collaborator == nullptr) {
8853             TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator is nullptr.");
8854             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8855         }
8856         int result = collaborator->CheckStaticCfgPermission(abilityRequest.want, isImplicit);
8857         if (result != ERR_OK) {
8858             TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker.");
8859             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8860         }
8861     }
8862     if (!isData) {
8863         isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8864     }
8865     if (isSaCall) {
8866         // do not need check static config permission when start ability by SA
8867         return AppExecFwk::Constants::PERMISSION_GRANTED;
8868     }
8869 
8870     uint32_t tokenId;
8871     if (isStartAsCaller) {
8872         tokenId = callerTokenId;
8873     } else {
8874         tokenId = IPCSkeleton::GetCallingTokenID();
8875     }
8876 
8877     if (abilityInfo.applicationInfo.accessTokenId == tokenId) {
8878         return ERR_OK;
8879     }
8880 
8881     if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
8882         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) ||
8883         (abilityInfo.type == AppExecFwk::AbilityType::DATA)) {
8884         // just need check the read permission and write permission of extension ability or data ability
8885         if (!abilityInfo.readPermission.empty()) {
8886             int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission, false);
8887             if (checkReadPermission == ERR_OK) {
8888                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8889             }
8890             TAG_LOGW(AAFwkTag::ABILITYMGR,
8891                 "verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str());
8892         }
8893         if (!abilityInfo.writePermission.empty()) {
8894             int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission, false);
8895             if (checkWritePermission == ERR_OK) {
8896                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8897             }
8898             TAG_LOGW(AAFwkTag::ABILITYMGR,
8899                 "verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str());
8900         }
8901 
8902         if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) {
8903             // 'readPermission' and 'writePermission' take precedence over 'permission'
8904             // when 'readPermission' or 'writePermission' is not empty, no need check 'permission'
8905             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8906         }
8907     }
8908 
8909     if (!isImplicit) {
8910         return CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8911     }
8912     return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId);
8913 }
8914 
CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,const Want & want,const AbilityRequest & abilityRequest)8915 int AbilityManagerService::CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,
8916     const Want &want, const AbilityRequest &abilityRequest)
8917 {
8918     AppExecFwk::ExtensionAbilityType targetExtType = abilityRequest.abilityInfo.extensionAbilityType;
8919     if (targetExtType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
8920         return ERR_OK;
8921     }
8922     if (!want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
8923         TAG_LOGE(AAFwkTag::ABILITYMGR, "need UISERVICEHOSTPROXY_KEY to connect UI_SERVICE");
8924         return ERR_WRONG_INTERFACE_CALL;
8925     }
8926     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
8927         TAG_LOGE(AAFwkTag::ABILITYMGR, "interface not support connect UI_SERVICE");
8928         return ERR_WRONG_INTERFACE_CALL;
8929     }
8930     if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
8931         TAG_LOGE(AAFwkTag::ABILITYMGR, "ABILITYMS_ENABLE_UISERVICE false");
8932         return ERR_CAPABILITY_NOT_SUPPORT;
8933     }
8934 
8935     return ERR_OK;
8936 }
8937 
IsNeedTimeoutForTest(const std::string & abilityName,const std::string & state) const8938 bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const
8939 {
8940     for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) {
8941         if (iter->first == state && iter->second == abilityName) {
8942             return true;
8943         }
8944     }
8945     return false;
8946 }
8947 
GetValidDataAbilityUri(const std::string & abilityInfoUri,std::string & adjustUri)8948 bool AbilityManagerService::GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)
8949 {
8950     // note: do not use abilityInfo.uri directly, need check uri first.
8951     size_t firstSeparator = abilityInfoUri.find_first_of('/');
8952     size_t lastSeparator = abilityInfoUri.find_last_of('/');
8953     if (lastSeparator - firstSeparator != 1) {
8954         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability info uri error, uri: %{public}s", abilityInfoUri.c_str());
8955         return false;
8956     }
8957 
8958     adjustUri = abilityInfoUri;
8959     adjustUri.insert(lastSeparator, "/");
8960     return true;
8961 }
8962 
GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> & abilityInfos,const std::string & mainAbility,std::string & uri)8963 bool AbilityManagerService::GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos,
8964     const std::string &mainAbility, std::string &uri)
8965 {
8966     if (abilityInfos.empty() || mainAbility.empty()) {
8967         TAG_LOGE(AAFwkTag::ABILITYMGR,
8968             "abilityInfos or mainAbility is empty. mainAbility: %{public}s", mainAbility.c_str());
8969         return false;
8970     }
8971 
8972     std::string dataAbilityUri;
8973     for (auto abilityInfo : abilityInfos) {
8974         if (abilityInfo.type == AppExecFwk::AbilityType::DATA &&
8975             abilityInfo.name == mainAbility) {
8976             dataAbilityUri = abilityInfo.uri;
8977             TAG_LOGI(AAFwkTag::ABILITYMGR, "get data ability uri: %{public}s", dataAbilityUri.c_str());
8978             break;
8979         }
8980     }
8981 
8982     return GetValidDataAbilityUri(dataAbilityUri, uri);
8983 }
8984 
GetAbilityRunningInfo(std::vector<AbilityRunningInfo> & info,std::shared_ptr<AbilityRecord> & abilityRecord)8985 void AbilityManagerService::GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info,
8986     std::shared_ptr<AbilityRecord> &abilityRecord)
8987 {
8988     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8989     AbilityRunningInfo runningInfo;
8990     AppExecFwk::RunningProcessInfo processInfo;
8991 
8992     runningInfo.ability = abilityRecord->GetElementName();
8993     runningInfo.startTime = abilityRecord->GetStartTime();
8994     runningInfo.abilityState = static_cast<int>(abilityRecord->GetAbilityState());
8995 
8996     DelayedSingleton<AppScheduler>::GetInstance()->
8997         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
8998     runningInfo.pid = processInfo.pid_;
8999     runningInfo.uid = processInfo.uid_;
9000     runningInfo.processName = processInfo.processName_;
9001     runningInfo.appCloneIndex = processInfo.appCloneIndex;
9002     info.emplace_back(runningInfo);
9003 }
9004 
VerifyAccountPermission(int32_t userId)9005 int AbilityManagerService::VerifyAccountPermission(int32_t userId)
9006 {
9007     if ((userId < 0) || (userController_ && (userController_->GetCurrentUserId() == userId))) {
9008         return ERR_OK;
9009     }
9010     return AAFwk::PermissionVerification::GetInstance()->VerifyAccountPermission();
9011 }
9012 
FreeInstallAbilityFromRemote(const Want & want,const sptr<IRemoteObject> & callback,int32_t userId,int requestCode)9013 int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
9014     int32_t userId, int requestCode)
9015 {
9016     auto callingUid = IPCSkeleton::GetCallingUid();
9017     if (callingUid != DMS_UID) {
9018         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for DMS");
9019         return CHECK_PERMISSION_FAILED;
9020     }
9021     int32_t validUserId = GetValidUserId(userId);
9022     if (freeInstallManager_ == nullptr) {
9023         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr");
9024         return ERR_INVALID_VALUE;
9025     }
9026     return freeInstallManager_->FreeInstallAbilityFromRemote(want, callback, validUserId, requestCode);
9027 }
9028 
GetTopAbility(bool isNeedLocalDeviceId)9029 AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId)
9030 {
9031     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9032     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
9033     AppExecFwk::ElementName elementName = {};
9034     if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
9035         auto callerPid = IPCSkeleton::GetCallingPid();
9036         AppExecFwk::RunningProcessInfo processInfo;
9037         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
9038         if (!processInfo.isTestProcess) {
9039             TAG_LOGE(AAFwkTag::ABILITYMGR, "caller can not use system-api or not test process.");
9040             return elementName;
9041         }
9042     }
9043 #ifdef SUPPORT_GRAPHICS
9044     sptr<IRemoteObject> token;
9045     int ret = IN_PROCESS_CALL(GetTopAbility(token));
9046     if (ret) {
9047         return elementName;
9048     }
9049     if (!token) {
9050         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
9051         return elementName;
9052     }
9053     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9054     if (abilityRecord == nullptr) {
9055         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
9056         return elementName;
9057     }
9058     elementName = abilityRecord->GetElementName();
9059     bool isDeviceEmpty = elementName.GetDeviceID().empty();
9060     std::string localDeviceId;
9061     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
9062         elementName.SetDeviceID(localDeviceId);
9063     }
9064 #endif
9065     return elementName;
9066 }
9067 
GetElementNameByToken(sptr<IRemoteObject> token,bool isNeedLocalDeviceId)9068 AppExecFwk::ElementName AbilityManagerService::GetElementNameByToken(sptr<IRemoteObject> token,
9069     bool isNeedLocalDeviceId)
9070 {
9071     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9072     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
9073     AppExecFwk::ElementName elementName = {};
9074 #ifdef SUPPORT_GRAPHICS
9075     if (!token) {
9076         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
9077         return elementName;
9078     }
9079     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9080     if (abilityRecord == nullptr) {
9081         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
9082         return elementName;
9083     }
9084     elementName = abilityRecord->GetElementName();
9085     bool isDeviceEmpty = elementName.GetDeviceID().empty();
9086     std::string localDeviceId;
9087     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
9088         elementName.SetDeviceID(localDeviceId);
9089     }
9090 #endif
9091     return elementName;
9092 }
9093 
Dump(int fd,const std::vector<std::u16string> & args)9094 int AbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
9095 {
9096     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump begin fd: %{public}d", fd);
9097     std::string result;
9098     auto errCode = Dump(args, result);
9099     int ret = dprintf(fd, "%s\n", result.c_str());
9100     if (ret < 0) {
9101         TAG_LOGE(AAFwkTag::ABILITYMGR, "dprintf error");
9102         return ERR_AAFWK_HIDUMP_ERROR;
9103     }
9104     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump end");
9105     return errCode;
9106 }
9107 
Dump(const std::vector<std::u16string> & args,std::string & result)9108 int AbilityManagerService::Dump(const std::vector<std::u16string>& args, std::string& result)
9109 {
9110     ErrCode errCode = ERR_OK;
9111     auto size = args.size();
9112     if (size == 0) {
9113         ShowHelp(result);
9114         return errCode;
9115     }
9116 
9117     std::vector<std::string> argsStr;
9118     for (auto arg : args) {
9119         argsStr.emplace_back(Str16ToStr8(arg));
9120     }
9121 
9122     if (argsStr[0] == "-h") {
9123         ShowHelp(result);
9124     } else {
9125         errCode = ProcessMultiParam(argsStr, result);
9126         if (errCode == ERR_AAFWK_HIDUMP_INVALID_ARGS) {
9127             ShowIllegalInfomation(result);
9128         }
9129     }
9130     return errCode;
9131 }
9132 
ProcessMultiParam(std::vector<std::string> & argsStr,std::string & result)9133 ErrCode AbilityManagerService::ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)
9134 {
9135     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
9136     bool isClient = false;
9137     bool isUser = false;
9138     int userID = DEFAULT_INVAL_VALUE;
9139     std::vector<std::string>::iterator it;
9140     for (it = argsStr.begin(); it != argsStr.end();) {
9141         if (*it == ARGS_CLIENT) {
9142             isClient = true;
9143             it = argsStr.erase(it);
9144             continue;
9145         }
9146         if (*it == ARGS_USER_ID) {
9147             it = argsStr.erase(it);
9148             if (it == argsStr.end()) {
9149                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
9150                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
9151             }
9152             (void)StrToInt(*it, userID);
9153             if (userID < 0) {
9154                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
9155                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
9156             }
9157             isUser = true;
9158             it = argsStr.erase(it);
9159             continue;
9160         }
9161         it++;
9162     }
9163     std::string cmd;
9164     for (unsigned int i = 0; i < argsStr.size(); i++) {
9165         cmd.append(argsStr[i]);
9166         if (i != argsStr.size() - 1) {
9167             cmd.append(" ");
9168         }
9169     }
9170     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, isClient:%{public}d, userID is : %{public}d, cmd is : %{public}s",
9171         __func__, isClient, userID, cmd.c_str());
9172 
9173     std::vector<std::string> dumpResults;
9174     DumpSysState(cmd, dumpResults, isClient, isUser, userID);
9175     for (auto it : dumpResults) {
9176         result += it + "\n";
9177     }
9178     return ERR_OK;
9179 }
9180 
ShowHelp(std::string & result)9181 void AbilityManagerService::ShowHelp(std::string& result)
9182 {
9183     result.append("Usage:\n")
9184         .append("-h                          ")
9185         .append("help text for the tool\n")
9186         .append("-a [-c | -u {UserId}]       ")
9187         .append("dump all ability infomation in the system or all ability infomation of client/UserId\n")
9188         .append("-l                          ")
9189         .append("dump all mission list information in the system\n")
9190         .append("-i {AbilityRecordId}        ")
9191         .append("dump an ability infomation by ability record id\n")
9192         .append("-e                          ")
9193         .append("dump all extension infomation in the system(FA: ServiceAbilityRecords, Stage: ExtensionRecords)\n")
9194         .append("-p [PendingWantRecordId]    ")
9195         .append("dump all pendingwant record infomation in the system\n")
9196         .append("-r                          ")
9197         .append("dump all process in the system\n")
9198         .append("-d                          ")
9199         .append("dump all data ability infomation in the system");
9200 }
9201 
ShowIllegalInfomation(std::string & result)9202 void AbilityManagerService::ShowIllegalInfomation(std::string& result)
9203 {
9204     result.append(ILLEGAL_INFOMATION);
9205 }
9206 
DumpAbilityInfoDone(std::vector<std::string> & infos,const sptr<IRemoteObject> & callerToken)9207 int AbilityManagerService::DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)
9208 {
9209     TAG_LOGD(AAFwkTag::ABILITYMGR, "DumpAbilityInfoDone begin");
9210     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
9211     if (abilityRecord == nullptr) {
9212         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord nullptr");
9213         return ERR_INVALID_VALUE;
9214     }
9215     if (!JudgeSelfCalled(abilityRecord)) {
9216         return CHECK_PERMISSION_FAILED;
9217     }
9218     abilityRecord->DumpAbilityInfoDone(infos);
9219     return ERR_OK;
9220 }
9221 
SetMissionContinueState(const sptr<IRemoteObject> & token,const AAFwk::ContinueState & state)9222 int AbilityManagerService::SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)
9223 {
9224     TAG_LOGD(AAFwkTag::ABILITYMGR, "SetMissionContinueState begin. State: %{public}d", state);
9225 
9226     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
9227 
9228     int32_t missionId = GetMissionIdByAbilityToken(token);
9229     if (missionId == -1) {
9230         TAG_LOGE(AAFwkTag::ABILITYMGR, "SetMissionContinueState failed to get missionId. State: %{public}d", state);
9231         return ERR_INVALID_VALUE;
9232     }
9233 
9234     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9235     if (!abilityRecord) {
9236         TAG_LOGE(AAFwkTag::ABILITYMGR,
9237             "SetMissionContinueState: No such ability record. Mission id: %{public}d, state: %{public}d",
9238             missionId, state);
9239         return -1;
9240     }
9241 
9242     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9243     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9244     if (callingTokenId != tokenID) {
9245         TAG_LOGE(AAFwkTag::ABILITYMGR,
9246             "SetMissionContinueState not self, not enabled. Mission id: %{public}d, state: %{public}d",
9247             missionId, state);
9248         return -1;
9249     }
9250 
9251     auto userId = abilityRecord->GetOwnerMissionUserId();
9252     auto missionListManager = GetMissionListManagerByUserId(userId);
9253     if (!missionListManager) {
9254         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager. Mission id: %{public}d, state: %{public}d",
9255             missionId, state);
9256         return -1;
9257     }
9258 
9259     auto setResult = missionListManager->SetMissionContinueState(token, missionId, state);
9260     if (setResult != ERR_OK) {
9261         TAG_LOGE(AAFwkTag::ABILITYMGR,
9262             "missionListManager set failed, result: %{public}d, mission id: %{public}d, state: %{public}d",
9263             setResult, missionId, state);
9264         return setResult;
9265     }
9266 
9267     DistributedClient dmsClient;
9268     auto result =  dmsClient.SetMissionContinueState(missionId, state);
9269     if (result != ERR_OK) {
9270         TAG_LOGE(AAFwkTag::ABILITYMGR,
9271             "Notify DMS client failed, result: %{public}d. Mission id: %{public}d, state: %{public}d",
9272             result, missionId, state);
9273     }
9274 
9275     TAG_LOGD(AAFwkTag::ABILITYMGR,
9276         "SetMissionContinueState end. Mission id: %{public}d, state: %{public}d", missionId, state);
9277     return ERR_OK;
9278 }
9279 
9280 #ifdef SUPPORT_GRAPHICS
SetMissionLabel(const sptr<IRemoteObject> & token,const std::string & label)9281 int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
9282 {
9283     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9284     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9285     if (!abilityRecord) {
9286         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
9287         return -1;
9288     }
9289 
9290     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9291     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9292     if (callingTokenId != tokenID) {
9293         TAG_LOGE(AAFwkTag::ABILITYMGR, "SetMissionLabel not self, not enabled");
9294         return -1;
9295     }
9296 
9297     auto userId = abilityRecord->GetOwnerMissionUserId();
9298     auto missionListManager = GetMissionListManagerByUserId(userId);
9299     if (!missionListManager) {
9300         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager when set mission label.");
9301         return -1;
9302     }
9303 
9304     return missionListManager->SetMissionLabel(token, label);
9305 }
9306 
SetMissionIcon(const sptr<IRemoteObject> & token,const std::shared_ptr<OHOS::Media::PixelMap> & icon)9307 int AbilityManagerService::SetMissionIcon(const sptr<IRemoteObject> &token,
9308     const std::shared_ptr<OHOS::Media::PixelMap> &icon)
9309 {
9310     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9311     CHECK_CALLER_IS_SYSTEM_APP;
9312     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9313     if (!abilityRecord) {
9314         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
9315         return -1;
9316     }
9317 
9318     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9319     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9320     if (callingTokenId != tokenID) {
9321         TAG_LOGE(AAFwkTag::ABILITYMGR, "not self, not enable to set mission icon");
9322         return -1;
9323     }
9324 
9325     auto userId = abilityRecord->GetOwnerMissionUserId();
9326     auto missionListManager = GetMissionListManagerByUserId(userId);
9327     if (!missionListManager) {
9328         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager.");
9329         return -1;
9330     }
9331 
9332     return missionListManager->SetMissionIcon(token, icon);
9333 }
9334 
RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> & handler,bool animationEnabled)9335 int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler,
9336     bool animationEnabled)
9337 {
9338     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9339     if (!isSaCall) {
9340         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
9341         return CHECK_PERMISSION_FAILED;
9342     }
9343     wmsHandler_ = handler;
9344     isAnimationEnabled_ = animationEnabled;
9345     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s: WMS handler registered successfully.", __func__);
9346     return ERR_OK;
9347 }
9348 
GetWMSHandler() const9349 sptr<IWindowManagerServiceHandler> AbilityManagerService::GetWMSHandler() const
9350 {
9351     return wmsHandler_;
9352 }
9353 
CompleteFirstFrameDrawing(const sptr<IRemoteObject> & abilityToken)9354 void AbilityManagerService::CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)
9355 {
9356     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9357     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
9358         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not foundation call.");
9359         return;
9360     }
9361     auto abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
9362     CHECK_POINTER(abilityRecord);
9363 
9364     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
9365     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
9366     CHECK_POINTER(missionListManager);
9367     missionListManager->CompleteFirstFrameDrawing(abilityToken);
9368 }
9369 
CompleteFirstFrameDrawing(int32_t sessionId)9370 void AbilityManagerService::CompleteFirstFrameDrawing(int32_t sessionId)
9371 {
9372     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9373     if (!IsCallerSceneBoard()) {
9374         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
9375         return;
9376     }
9377     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
9378     CHECK_POINTER(uiAbilityManager);
9379     uiAbilityManager->CompleteFirstFrameDrawing(sessionId);
9380 }
9381 
ShowPickerDialog(const Want & want,int32_t userId,const sptr<IRemoteObject> & callerToken)9382 int32_t AbilityManagerService::ShowPickerDialog(
9383     const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)
9384 {
9385     AAFwk::Want newWant = want;
9386     std::string sharePickerBundleName =
9387         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME);
9388     std::string sharePickerAbilityName =
9389         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_ABILITY_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME);
9390     newWant.SetElementName(sharePickerBundleName, sharePickerAbilityName);
9391     newWant.SetParam(TOKEN_KEY, callerToken);
9392     // note: clear actions
9393     newWant.SetAction("");
9394     return IN_PROCESS_CALL(StartAbility(newWant, DEFAULT_INVAL_VALUE, userId));
9395 }
9396 
CheckWindowMode(int32_t windowMode,const std::vector<AppExecFwk::SupportWindowMode> & windowModes) const9397 bool AbilityManagerService::CheckWindowMode(int32_t windowMode,
9398     const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const
9399 {
9400     TAG_LOGI(AAFwkTag::ABILITYMGR, "Window mode is %{public}d.", windowMode);
9401     if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED) {
9402         return true;
9403     }
9404 
9405     auto bmsWindowMode = WindowOptionsUtils::WindowModeMap(windowMode);
9406     if (bmsWindowMode.first) {
9407         for (const auto& mode : windowModes) {
9408             if (mode == bmsWindowMode.second) {
9409                 return true;
9410             }
9411         }
9412     }
9413     return false;
9414 }
9415 
PrepareTerminateAbility(const sptr<IRemoteObject> & token,sptr<IPrepareTerminateCallback> & callback)9416 int AbilityManagerService::PrepareTerminateAbility(const sptr<IRemoteObject> &token,
9417     sptr<IPrepareTerminateCallback> &callback)
9418 {
9419     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
9420     if (callback == nullptr) {
9421         TAG_LOGE(AAFwkTag::ABILITYMGR, "callback is nullptr.");
9422         return ERR_INVALID_VALUE;
9423     }
9424     if (!CheckPrepareTerminateEnable()) {
9425         callback->DoPrepareTerminate();
9426         return ERR_INVALID_VALUE;
9427     }
9428 
9429     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9430     if (abilityRecord == nullptr) {
9431         TAG_LOGE(AAFwkTag::ABILITYMGR, "record is nullptr.");
9432         callback->DoPrepareTerminate();
9433         return ERR_INVALID_VALUE;
9434     }
9435 
9436     if (!JudgeSelfCalled(abilityRecord)) {
9437         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not self call.");
9438         callback->DoPrepareTerminate();
9439         return CHECK_PERMISSION_FAILED;
9440     }
9441 
9442     auto type = abilityRecord->GetAbilityInfo().type;
9443     if (type != AppExecFwk::AbilityType::PAGE) {
9444         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support PAGE.");
9445         callback->DoPrepareTerminate();
9446         return RESOLVE_CALL_ABILITY_TYPE_ERR;
9447     }
9448 
9449     auto timeoutTask = [&callback]() {
9450         callback->DoPrepareTerminate();
9451     };
9452     int prepareTerminateTimeout =
9453         AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * PREPARE_TERMINATE_TIMEOUT_MULTIPLE;
9454     if (taskHandler_) {
9455         taskHandler_->SubmitTask(timeoutTask, "PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()),
9456             prepareTerminateTimeout);
9457     }
9458 
9459     bool res = abilityRecord->PrepareTerminateAbility();
9460     if (!res) {
9461         callback->DoPrepareTerminate();
9462     }
9463     if (taskHandler_) {
9464         taskHandler_->CancelTask("PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()));
9465     }
9466     return ERR_OK;
9467 }
9468 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9469 void AbilityManagerService::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9470 {
9471     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle focused event");
9472     auto missionListManager = GetCurrentMissionListManager();
9473     CHECK_POINTER(missionListManager);
9474 
9475     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9476     missionListManager->NotifyMissionFocused(missionId);
9477 }
9478 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9479 void AbilityManagerService::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9480 {
9481     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle unfocused event");
9482     auto missionListManager = GetCurrentMissionListManager();
9483     CHECK_POINTER(missionListManager);
9484 
9485     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9486     missionListManager->NotifyMissionUnfocused(missionId);
9487 }
9488 
InitFocusListener()9489 void AbilityManagerService::InitFocusListener()
9490 {
9491     TAG_LOGI(AAFwkTag::ABILITYMGR, "Init ability focus listener");
9492     if (focusListener_) {
9493         return;
9494     }
9495 
9496     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
9497     auto registerTask = [innerService = shared_from_this()]() {
9498         if (innerService) {
9499             TAG_LOGI(AAFwkTag::ABILITYMGR, "RegisterFocusListener task");
9500             innerService->RegisterFocusListener();
9501         }
9502     };
9503     if (taskHandler_) {
9504         taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
9505     }
9506 }
9507 
RegisterFocusListener()9508 void AbilityManagerService::RegisterFocusListener()
9509 {
9510     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register focus listener");
9511     if (!focusListener_) {
9512         TAG_LOGE(AAFwkTag::ABILITYMGR, "no listener obj");
9513         return;
9514     }
9515     Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
9516     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register focus listener success");
9517 }
9518 
InitPrepareTerminateConfig()9519 void AbilityManagerService::InitPrepareTerminateConfig()
9520 {
9521     char value[PREPARE_TERMINATE_ENABLE_SIZE] = "false";
9522     int retSysParam = GetParameter(PREPARE_TERMINATE_ENABLE_PARAMETER, "false", value, PREPARE_TERMINATE_ENABLE_SIZE);
9523     TAG_LOGI(AAFwkTag::ABILITYMGR,
9524         "CheckPrepareTerminateEnable, %{public}s value is %{public}s.", PREPARE_TERMINATE_ENABLE_PARAMETER,
9525         value);
9526     if (retSysParam > 0 && !std::strcmp(value, "true")) {
9527         isPrepareTerminateEnable_ = true;
9528     }
9529 }
9530 
RegisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer,const std::string & targetBundleName)9531 int AbilityManagerService::RegisterAbilityFirstFrameStateObserver(
9532     const sptr<IAbilityFirstFrameStateObserver> &observer, const std::string &targetBundleName)
9533 {
9534     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9535         RegisterAbilityFirstFrameStateObserver(observer, targetBundleName);
9536 }
9537 
UnregisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer)9538 int AbilityManagerService::UnregisterAbilityFirstFrameStateObserver(
9539     const sptr<IAbilityFirstFrameStateObserver> &observer)
9540 {
9541     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9542         UnregisterAbilityFirstFrameStateObserver(observer);
9543 }
9544 
GetAnimationFlag()9545 bool AbilityManagerService::GetAnimationFlag()
9546 {
9547     return isAnimationEnabled_;
9548 }
9549 
9550 #endif
9551 
CheckCallServicePermission(const AbilityRequest & abilityRequest)9552 int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest)
9553 {
9554     if (abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()) == BROKER_UID &&
9555         abilityRequest.want.GetElement().GetBundleName() == SHELL_ASSISTANT_BUNDLENAME) {
9556         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9557         if (collaborator != nullptr) {
9558             TAG_LOGI(AAFwkTag::ABILITYMGR, "Collaborator CheckCallAbilityPermission.");
9559             return collaborator->CheckCallAbilityPermission(abilityRequest.want);
9560         }
9561     }
9562     if (abilityRequest.abilityInfo.isStageBasedModel) {
9563         auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9564         TAG_LOGD(AAFwkTag::ABILITYMGR, "extensionType is %{public}d.", static_cast<int>(extensionType));
9565         if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE ||
9566             extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
9567             extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9568             return CheckCallServiceExtensionPermission(abilityRequest);
9569         } else {
9570             return CheckCallOtherExtensionPermission(abilityRequest);
9571         }
9572     } else {
9573         return CheckCallServiceAbilityPermission(abilityRequest);
9574     }
9575 }
9576 
CheckCallDataAbilityPermission(AbilityRequest & abilityRequest,bool isShell,bool isSACall)9577 int AbilityManagerService::CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)
9578 {
9579     abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo;
9580     abilityRequest.uid = abilityRequest.appInfo.uid;
9581     if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) {
9582         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid app info for data ability acquiring.");
9583         return ERR_INVALID_VALUE;
9584     }
9585     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) {
9586         TAG_LOGE(AAFwkTag::ABILITYMGR, "BMS query result is not a data ability.");
9587         return ERR_WRONG_INTERFACE_CALL;
9588     }
9589 
9590     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest,
9591         true, isShell, isSACall);
9592     if (isShell) {
9593         verificationInfo.isBackgroundCall = true;
9594     }
9595     if (!isShell && IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall, true) != ERR_OK) {
9596         return ERR_INVALID_VALUE;
9597     }
9598     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallDataAbilityPermission(verificationInfo,
9599         isShell);
9600     if (result != ERR_OK) {
9601         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start DataAbility");
9602         return result;
9603     }
9604 
9605     return ERR_OK;
9606 }
9607 
CreateVerificationInfo(const AbilityRequest & abilityRequest,bool isData,bool isShell,bool isSA)9608 AAFwk::PermissionVerification::VerificationInfo AbilityManagerService::CreateVerificationInfo(
9609     const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)
9610 {
9611     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9612     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9613     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9614     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9615     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call ServiceAbility or DataAbility, target bundleName: %{public}s.",
9616         abilityRequest.appInfo.bundleName.c_str());
9617     if (whiteListassociatedWakeUpFlag_ &&
9618         abilityRequest.appInfo.bundleName == BUNDLE_NAME_SETTINGSDATA) {
9619         TAG_LOGD(AAFwkTag::ABILITYMGR,
9620             "Call ServiceAbility or DataAbility, target bundle in white-list, allow associatedWakeUp.");
9621         verificationInfo.associatedWakeUp = true;
9622     } else {
9623         verificationInfo.associatedWakeUp = abilityRequest.appInfo.associatedWakeUp;
9624     }
9625     if (!isData) {
9626         isSA = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9627         isShell = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
9628     }
9629     if (isSA || isShell) {
9630         return verificationInfo;
9631     }
9632     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9633     if (callerAbility) {
9634         verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9635     }
9636 
9637     return verificationInfo;
9638 }
9639 
CheckCallServiceExtensionPermission(const AbilityRequest & abilityRequest)9640 int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)
9641 {
9642     TAG_LOGD(AAFwkTag::ABILITYMGR, "begin");
9643 
9644     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9645     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9646     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9647     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9648     verificationInfo.isBackgroundCall = false;
9649     if (isParamStartAbilityEnable_) {
9650         bool stopContinuousTaskFlag = ShouldPreventStartAbility(abilityRequest);
9651         if (stopContinuousTaskFlag) {
9652             TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension");
9653             return CHECK_PERMISSION_FAILED;
9654         }
9655     }
9656 
9657     if (abilityRequest.abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9658         TAG_LOGE(AAFwkTag::ABILITYMGR, "background startup UI_SERVICE");
9659         verificationInfo.isBackgroundCall = true;
9660         std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9661         if (callerAbility) {
9662             verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9663         }
9664         if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9665             TAG_LOGE(AAFwkTag::ABILITYMGR, "not background startup UI_SERVICE");
9666             return ERR_INVALID_VALUE;
9667         }
9668     }
9669 
9670     int result = AAFwk::AbilityPermissionUtil::GetInstance().CheckCallServiceExtensionPermissionOrHasFloatingWindow(
9671         verificationInfo, abilityRequest.callerToken);
9672     if (result != ERR_OK) {
9673         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension or DataShareExtension");
9674     }
9675     return result;
9676 }
CheckCallAutoFillExtensionPermission(const AbilityRequest & abilityRequest)9677 int AbilityManagerService::CheckCallAutoFillExtensionPermission(const AbilityRequest &abilityRequest)
9678 {
9679     if (!abilityRequest.appInfo.isSystemApp) {
9680         TAG_LOGE(AAFwkTag::ABILITYMGR, "application requesting call isn't system application");
9681         return CHECK_PERMISSION_FAILED;
9682     }
9683     std::string jsonDataStr = abilityRequest.want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY);
9684     AbilityBase::ViewData viewData;
9685     viewData.FromJsonString(jsonDataStr.c_str());
9686     std::string callerName;
9687     int32_t uid = 0;
9688     auto callerPid = IPCSkeleton::GetCallingPid();
9689     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
9690     if (viewData.bundleName != callerName) {
9691         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not %{public}s called, no allowed", viewData.bundleName.c_str());
9692         return ERR_WRONG_INTERFACE_CALL;
9693     }
9694     return ERR_OK;
9695 }
9696 
CheckCallOtherExtensionPermission(const AbilityRequest & abilityRequest)9697 int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)
9698 {
9699     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9700     if (IPCSkeleton::GetCallingUid() != BROKER_UID && AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9701         return ERR_OK;
9702     }
9703     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9704     TAG_LOGD(AAFwkTag::ABILITYMGR, "OtherExtension type: %{public}d.", static_cast<int32_t>(extensionType));
9705     if (system::GetBoolParameter(DEVELOPER_MODE_STATE, false) &&
9706         PermissionVerification::GetInstance()->VerifyShellStartExtensionType(static_cast<int32_t>(extensionType))) {
9707         return ERR_OK;
9708     }
9709     if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) {
9710         CHECK_CALLER_IS_SYSTEM_APP;
9711         return ERR_OK;
9712     }
9713     if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) {
9714         return ERR_OK;
9715     }
9716     if (extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD ||
9717         extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART) {
9718         return CheckCallAutoFillExtensionPermission(abilityRequest);
9719     }
9720     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
9721         return CheckUIExtensionPermission(abilityRequest);
9722     }
9723     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
9724         return ERR_OK;
9725     }
9726     if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION) {
9727         return CheckFileAccessExtensionPermission(abilityRequest);
9728     }
9729     if (extensionType == AppExecFwk::ExtensionAbilityType::CALLER_INFO_QUERY) {
9730         return CheckCallerInfoQueryExtensionPermission(abilityRequest);
9731     }
9732     TAG_LOGE(AAFwkTag::ABILITYMGR, "not SA, can't start other extension");
9733     return CHECK_PERMISSION_FAILED;
9734 }
9735 
CheckCallerInfoQueryExtensionPermission(const AbilityRequest & abilityRequest)9736 int AbilityManagerService::CheckCallerInfoQueryExtensionPermission(const AbilityRequest &abilityRequest)
9737 {
9738     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9739         PermissionConstants::PERMISSION_GET_TELEPHONY_STATE);
9740     if (!ret) {
9741         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny for callerInfoQueryExtension");
9742         return CHECK_PERMISSION_FAILED;
9743     }
9744     TAG_LOGI(AAFwkTag::ABILITYMGR, "check permission success");
9745     return ERR_OK;
9746 }
9747 
CheckFileAccessExtensionPermission(const AbilityRequest & abilityRequest)9748 int AbilityManagerService::CheckFileAccessExtensionPermission(const AbilityRequest &abilityRequest)
9749 {
9750     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9751         PermissionConstants::PERMISSION_FILE_ACCESS_MANAGER);
9752     if (!ret) {
9753         return CHECK_PERMISSION_FAILED;
9754     }
9755     TAG_LOGD(AAFwkTag::ABILITYMGR, "Temporary, FILEACCESS_EXTENSION use serviceExtension start-up rule.");
9756     return CheckCallServiceExtensionPermission(abilityRequest);
9757 }
9758 
CheckUIExtensionPermission(const AbilityRequest & abilityRequest)9759 int AbilityManagerService::CheckUIExtensionPermission(const AbilityRequest &abilityRequest)
9760 {
9761     if (abilityRequest.want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
9762         // If started by embedded atomic service, allow it.
9763         return ERR_OK;
9764     }
9765 
9766     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9767     if (AAFwk::UIExtensionUtils::IsSystemUIExtension(extensionType)) {
9768         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9769         if (callerRecord == nullptr) {
9770             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid caller.");
9771             return NO_FOUND_ABILITY_BY_CALLER;
9772         }
9773 
9774         if (!abilityRequest.appInfo.isSystemApp) {
9775             TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle %{public}s wanna to start or caller bundle %{public}s "
9776                 "isn't system app, type %{public}d not allowed.", abilityRequest.appInfo.bundleName.c_str(),
9777                 callerRecord->GetApplicationInfo().bundleName.c_str(), extensionType);
9778             return CHECK_PERMISSION_FAILED;
9779         }
9780     }
9781 
9782     if (AAFwk::UIExtensionUtils::IsSystemCallerNeeded(extensionType)) {
9783         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9784         if (callerRecord == nullptr) {
9785             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid caller.");
9786             return NO_FOUND_ABILITY_BY_CALLER;
9787         }
9788 
9789         if (!callerRecord->GetApplicationInfo().isSystemApp
9790             && !AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9791             TAG_LOGE(AAFwkTag::ABILITYMGR,
9792                      "Bundle %{public}s wanna to start but caller bundle %{public}s "
9793                      "isn't system app, type %{public}d not allowed.",
9794                      abilityRequest.appInfo.bundleName.c_str(), callerRecord->GetApplicationInfo().bundleName.c_str(),
9795                      extensionType);
9796             return CHECK_PERMISSION_FAILED;
9797         }
9798     }
9799 
9800     if (!CheckUIExtensionCallerIsForeground(abilityRequest)) {
9801         return CHECK_PERMISSION_FAILED;
9802     }
9803 
9804     if (!CheckUIExtensionCallerPidByHostWindowId(abilityRequest)) {
9805         return ERR_INVALID_CALLER;
9806     }
9807 
9808     return ERR_OK;
9809 }
9810 
CheckUIExtensionCallerIsForeground(const AbilityRequest & abilityRequest)9811 bool AbilityManagerService::CheckUIExtensionCallerIsForeground(const AbilityRequest &abilityRequest)
9812 {
9813     if (!CheckUIExtensionCallerIsUIAbility(abilityRequest)) {
9814         // Check only if the caller is uiability, if caller is not a uiability, don't check.
9815         return true;
9816     }
9817 
9818     bool isBackgroundCall = true;
9819     auto ret = IsCallFromBackground(abilityRequest, isBackgroundCall);
9820     if (ret != ERR_OK) {
9821         TAG_LOGE(AAFwkTag::UI_EXT, "start uea when background");
9822         return false;
9823     }
9824 
9825     if (!isBackgroundCall) {
9826         return true;
9827     }
9828 
9829     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9830     if (callerAbility != nullptr) {
9831         if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9832             auto tokenId = callerAbility->GetApplicationInfo().accessTokenId;
9833             bool isFocused = false;
9834             if (CheckUIExtensionIsFocused(tokenId, isFocused) == ERR_OK && isFocused) {
9835                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Root caller is foreground");
9836                 return true;
9837             }
9838         }
9839 
9840         if (callerAbility->IsSceneBoard()) {
9841             return true;
9842         }
9843     }
9844 
9845     if (PermissionVerification::GetInstance()->VerifyCallingPermission(
9846         PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
9847         return true;
9848     }
9849 
9850     TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller app is not foreground, can't start %{public}s",
9851         abilityRequest.want.GetElement().GetURI().c_str());
9852     return false;
9853 }
9854 
CheckUIExtensionCallerIsUIAbility(const AbilityRequest & abilityRequest)9855 bool AbilityManagerService::CheckUIExtensionCallerIsUIAbility(const AbilityRequest &abilityRequest)
9856 {
9857     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9858     if (callerAbility == nullptr) {
9859         TAG_LOGE(AAFwkTag::UI_EXT, "caller ability invalid");
9860         return false;
9861     }
9862 
9863     if (callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9864         return true;
9865     }
9866 
9867     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9868         callerAbility = GetUIExtensionRootCaller(abilityRequest.callerToken, abilityRequest.userId);
9869         if (callerAbility != nullptr && callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9870             return true;
9871         }
9872     }
9873 
9874     return false;
9875 }
9876 
CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest & abilityRequest)9877 bool AbilityManagerService::CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest &abilityRequest)
9878 {
9879 #ifdef SUPPORT_SCREEN
9880     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9881         return true;
9882     }
9883 
9884     auto sessionInfo = abilityRequest.sessionInfo;
9885     CHECK_POINTER_AND_RETURN(sessionInfo, false);
9886     auto hostWindowId = sessionInfo->hostWindowId;
9887     auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
9888     CHECK_POINTER_AND_RETURN(sceneSessionManager, false);
9889     pid_t hostPid = 0;
9890     // If host window id is scb, it will return with error.
9891     auto tokenId = abilityRequest.appInfo.accessTokenId;
9892     auto element = abilityRequest.want.GetElement();
9893     auto extType = abilityRequest.abilityInfo.extensionAbilityType;
9894     {
9895         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "Rosen::SceneSessionManager::CheckUIExtensionCreation");
9896         auto ret = sceneSessionManager->CheckUIExtensionCreation(hostWindowId, tokenId, element, extType, hostPid);
9897         if (ret == Rosen::WMError::WM_ERROR_INVALID_PERMISSION) {
9898             // If check permission failed, means target ability can't show on lock screen.
9899             TAG_LOGE(AAFwkTag::UI_EXT, "Check fail, tokenId: %{public}d, element: %{public}s, ret: %{public}d",
9900                 tokenId, element.GetURI().c_str(), ret);
9901             return false;
9902         }
9903     }
9904 
9905     TAG_LOGD(AAFwkTag::UI_EXT, "get pid %{public}d by windowId %{public}d", hostPid, hostWindowId);
9906     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9907     CHECK_POINTER_AND_RETURN(callerAbility, false);
9908     if (callerAbility->IsSceneBoard()) {
9909         return true;
9910     }
9911     if (hostPid != 0 && callerAbility->GetPid() == hostPid) {
9912         return true;
9913     }
9914 
9915     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9916         TAG_LOGD(AAFwkTag::UI_EXT, "caller is nested uiextability");
9917         auto connectManager = GetCurrentConnectManager();
9918         CHECK_POINTER_AND_RETURN(connectManager, false);
9919         bool matched = false;
9920         std::list<sptr<IRemoteObject>> callerList;
9921         connectManager->GetUIExtensionCallerTokenList(callerAbility, callerList);
9922         for (auto &item : callerList) {
9923             auto ability = AAFwk::Token::GetAbilityRecordByToken(item);
9924             if (ability == nullptr) {
9925                 TAG_LOGW(AAFwkTag::UI_EXT, "wrong ability");
9926                 continue;
9927             }
9928 
9929             if ((hostPid != 0 && ability->GetPid() == hostPid) || ability->IsSceneBoard()) {
9930                 matched = true;
9931                 return true;
9932             }
9933         }
9934         if (!matched) {
9935             TAG_LOGE(AAFwkTag::UI_EXT, "Check nested uiextability failed");
9936         }
9937     }
9938 
9939     TAG_LOGE(AAFwkTag::UI_EXT, "Check pid by windowId %{public}d failed, got %{public}d but actual is %{public}d",
9940         hostWindowId, hostPid, callerAbility->GetPid());
9941     return false;
9942 #else
9943     return true;
9944 #endif // SUPPORT_SCREEN
9945 }
9946 
CheckCallServiceAbilityPermission(const AbilityRequest & abilityRequest)9947 int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)
9948 {
9949     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9950     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest);
9951     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9952         return ERR_INVALID_VALUE;
9953     }
9954 
9955     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceAbilityPermission(verificationInfo);
9956     if (result != ERR_OK) {
9957         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceAbility");
9958     }
9959     return result;
9960 }
9961 
CheckCallAbilityPermission(const AbilityRequest & abilityRequest,uint32_t specifyTokenId,bool isCallByShortcut)9962 int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId,
9963     bool isCallByShortcut)
9964 {
9965     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9966     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9967 
9968     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9969     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9970     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9971     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9972     verificationInfo.specifyTokenId = specifyTokenId;
9973     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9974         return ERR_INVALID_VALUE;
9975     }
9976 
9977     int result = AAFwk::AbilityPermissionUtil::GetInstance().CheckCallAbilityPermissionOrHasFloatingWindow(
9978         verificationInfo, abilityRequest.callerToken, isCallByShortcut);
9979     if (result != ERR_OK) {
9980         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start PageAbility(FA) or Ability(Stage)");
9981     }
9982     return result;
9983 }
9984 
CheckStartByCallPermission(const AbilityRequest & abilityRequest)9985 int AbilityManagerService::CheckStartByCallPermission(const AbilityRequest &abilityRequest)
9986 {
9987     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call");
9988     // check whether the target ability is page type and not specified mode.
9989     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::PAGE ||
9990         abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
9991         TAG_LOGE(AAFwkTag::ABILITYMGR, "Called ability is not common ability.");
9992         return RESOLVE_CALL_ABILITY_TYPE_ERR;
9993     }
9994 
9995     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9996     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9997     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9998     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9999     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
10000         return ERR_INVALID_VALUE;
10001     }
10002 
10003     if (AAFwk::AbilityPermissionUtil::GetInstance().CheckStartByCallPermissionOrHasFloatingWindow(
10004         verificationInfo, abilityRequest.callerToken) != ERR_OK) {
10005         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to StartAbilityByCall.");
10006         return RESOLVE_CALL_NO_PERMISSIONS;
10007     }
10008     TAG_LOGD(AAFwkTag::ABILITYMGR, "The caller has permission to resolve the call proxy of common ability.");
10009     return ERR_OK;
10010 }
10011 
IsCallFromBackground(const AbilityRequest & abilityRequest,bool & isBackgroundCall,bool isData)10012 int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall,
10013     bool isData)
10014 {
10015     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10016     if (!isData && AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10017         isBackgroundCall = true;
10018         return ERR_OK;
10019     }
10020 
10021     if (!isData && (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
10022         AbilityUtil::IsStartFreeInstall(abilityRequest.want))) {
10023         isBackgroundCall = false;
10024         return ERR_OK;
10025     }
10026 
10027     AppExecFwk::RunningProcessInfo processInfo;
10028     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10029     if (callerAbility && callerAbility->GetAbilityInfo().bundleName == BUNDLE_NAME_DIALOG) {
10030         callerAbility = callerAbility->GetCallerRecord();
10031     }
10032     if (callerAbility) {
10033         if (callerAbility->IsForeground() || callerAbility->GetAbilityForegroundingFlag()) {
10034             isBackgroundCall = false;
10035             return ERR_OK;
10036         }
10037         // CallerAbility is not foreground, so check process state
10038         DelayedSingleton<AppScheduler>::GetInstance()->
10039             GetRunningProcessInfoByToken(callerAbility->GetToken(), processInfo);
10040         if (IsDelegatorCall(processInfo, abilityRequest)) {
10041             TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
10042             isBackgroundCall = false;
10043             return ERR_OK;
10044         }
10045         auto abilityState = callerAbility->GetAbilityState();
10046         if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING ||
10047             // If uiability or uiextensionability ability state is foreground when terminate,
10048             // it will move to background firstly. So if startAbility in onBackground() lifecycle,
10049             // the actual ability state may be had changed to terminating from background or backgrounding.
10050             abilityState == AbilityState::TERMINATING) {
10051             return ERR_OK;
10052         }
10053     } else {
10054         auto callerPid = IPCSkeleton::GetCallingPid();
10055         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
10056         if (processInfo.processName_.empty()) {
10057             TAG_LOGD(AAFwkTag::ABILITYMGR, "Can not find caller application by callerPid: %{private}d.", callerPid);
10058             if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
10059                 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
10060                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller has PERMISSION_START_ABILITIES_FROM_BACKGROUND, PASS.");
10061                 isBackgroundCall = false;
10062                 return ERR_OK;
10063             }
10064             TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller does not have PERMISSION_START_ABILITIES_FROM_BACKGROUND, REJECT.");
10065             return ERR_INVALID_VALUE;
10066         }
10067     }
10068     return SetBackgroundCall(processInfo, abilityRequest, isBackgroundCall);
10069 }
10070 
SetBackgroundCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest,bool & isBackgroundCall) const10071 int32_t AbilityManagerService::SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo,
10072     const AbilityRequest &abilityRequest, bool &isBackgroundCall) const
10073 {
10074     if (IsDelegatorCall(processInfo, abilityRequest)) {
10075         TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
10076         isBackgroundCall = false;
10077         return ERR_OK;
10078     }
10079 
10080     if (backgroundJudgeFlag_) {
10081         isBackgroundCall = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND &&
10082             !processInfo.isFocused && !processInfo.isAbilityForegrounding;
10083     } else {
10084         isBackgroundCall = !processInfo.isFocused;
10085         if (!processInfo.isFocused && processInfo.state_ == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) {
10086             // Allow background startup within 1 second after application startup if state is FOREGROUND
10087             int64_t aliveTime = AbilityUtil::SystemTimeMillis() - processInfo.startTimeMillis_;
10088             isBackgroundCall = aliveTime > APP_ALIVE_TIME_MS;
10089             TAG_LOGD(AAFwkTag::ABILITYMGR, "Process %{public}s is alive %{public}s ms.",
10090                 processInfo.processName_.c_str(), std::to_string(aliveTime).c_str());
10091         }
10092     }
10093     TAG_LOGD(AAFwkTag::ABILITYMGR,
10094         "backgroundJudgeFlag: %{public}d, isBackgroundCall: %{public}d, callerAppState: %{public}d.",
10095         static_cast<int32_t>(backgroundJudgeFlag_),
10096         static_cast<int32_t>(isBackgroundCall),
10097         static_cast<int32_t>(processInfo.state_));
10098 
10099     return ERR_OK;
10100 }
10101 
IsTargetPermission(const Want & want) const10102 bool AbilityManagerService::IsTargetPermission(const Want &want) const
10103 {
10104     if (want.GetElement().GetBundleName() == PERMISSIONMGR_BUNDLE_NAME &&
10105         want.GetElement().GetAbilityName() == PERMISSIONMGR_ABILITY_NAME) {
10106         return true;
10107     }
10108 
10109     return false;
10110 }
10111 
IsDelegatorCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest) const10112 inline bool AbilityManagerService::IsDelegatorCall(
10113     const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest) const
10114 {
10115     /*  To make sure the AbilityDelegator is not counterfeited
10116      *   1. The caller-process must be test-process
10117      *   2. The callerToken must be nullptr
10118      */
10119     if (processInfo.isTestProcess &&
10120         !abilityRequest.callerToken && abilityRequest.want.GetBoolParam(IS_DELEGATOR_CALL, false)) {
10121         return true;
10122     }
10123     return false;
10124 }
10125 
CheckNewRuleSwitchState(const std::string & param)10126 bool AbilityManagerService::CheckNewRuleSwitchState(const std::string &param)
10127 {
10128     char value[NEW_RULE_VALUE_SIZE] = "false";
10129     int retSysParam = GetParameter(param.c_str(), "false", value, NEW_RULE_VALUE_SIZE);
10130     TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckNewRuleSwitchState, %{public}s value is %{public}s.", param.c_str(), value);
10131     if (retSysParam > 0 && !std::strcmp(value, "true")) {
10132         return true;
10133     }
10134     return false;
10135 }
10136 
GetStartUpNewRuleFlag() const10137 bool AbilityManagerService::GetStartUpNewRuleFlag() const
10138 {
10139     return startUpNewRule_;
10140 }
10141 
CallRequestDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callStub)10142 void AbilityManagerService::CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)
10143 {
10144     {
10145         std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
10146         callStubTokenMap_[callStub] = token;
10147     }
10148     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10149     CHECK_POINTER(abilityRecord);
10150     if (!JudgeSelfCalled(abilityRecord)) {
10151         return;
10152     }
10153 
10154     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10155         auto uiAbilityManager = GetCurrentUIAbilityManager();
10156         CHECK_POINTER(uiAbilityManager);
10157         uiAbilityManager->CallRequestDone(abilityRecord, callStub);
10158         return;
10159     }
10160 
10161     auto missionListManager = GetCurrentMissionListManager();
10162     CHECK_POINTER(missionListManager);
10163     missionListManager->CallRequestDone(abilityRecord, callStub);
10164 }
10165 
GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> & callStub,sptr<IRemoteObject> & token)10166 void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)
10167 {
10168     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
10169     auto it = callStubTokenMap_.find(callStub);
10170     if (it == callStubTokenMap_.end()) {
10171         token = nullptr;
10172         return;
10173     }
10174     token = callStubTokenMap_[callStub];
10175 }
10176 
AddStartControlParam(Want & want,const sptr<IRemoteObject> & callerToken)10177 int AbilityManagerService::AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)
10178 {
10179     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10180     if (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
10181         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10182         return ERR_OK;
10183     }
10184     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
10185     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
10186     int32_t apiVersion = abilityRecord->GetApplicationInfo().apiTargetVersion;
10187     want.SetParam(DMS_API_VERSION, apiVersion);
10188     bool isCallerBackground = true;
10189     AppExecFwk::RunningProcessInfo processInfo;
10190     DelayedSingleton<AppScheduler>::GetInstance()->
10191         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
10192     if (backgroundJudgeFlag_) {
10193         isCallerBackground = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND;
10194     } else {
10195         isCallerBackground = !processInfo.isFocused;
10196     }
10197     want.SetParam(DMS_IS_CALLER_BACKGROUND, isCallerBackground);
10198     return ERR_OK;
10199 }
10200 
10201 #ifdef WITH_DLP
CheckDlpForExtension(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,EventInfo & eventInfo,const EventName & eventName)10202 int AbilityManagerService::CheckDlpForExtension(
10203     const Want &want, const sptr<IRemoteObject> &callerToken,
10204     int32_t userId, EventInfo &eventInfo, const EventName &eventName)
10205 {
10206     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10207     // check if form frs
10208     auto callingUid = IPCSkeleton::GetCallingUid();
10209     std::string bundleName = want.GetBundle();
10210     if (callingUid == FOUNDATION_UID && FRS_BUNDLE_NAME == bundleName) {
10211         return ERR_OK;
10212     }
10213 
10214     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
10215         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
10216         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
10217         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
10218         eventInfo.errCode = CHECK_PERMISSION_FAILED;
10219         EventReport::SendExtensionEvent(eventName, HiSysEventType::FAULT, eventInfo);
10220         return CHECK_PERMISSION_FAILED;
10221     }
10222     return ERR_OK;
10223 }
10224 #endif // WITH_DLP
10225 
JudgeSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)10226 bool AbilityManagerService::JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
10227 {
10228     if (IPCSkeleton::GetCallingPid() == getprocpid()) {
10229         return true;
10230     }
10231 
10232     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10233     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10234     if (callingTokenId != tokenID) {
10235         TAG_LOGE(AAFwkTag::ABILITYMGR, "Is not self, not enabled");
10236         return false;
10237     }
10238 
10239     return true;
10240 }
10241 
IsAppSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)10242 bool AbilityManagerService::IsAppSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
10243 {
10244     CHECK_POINTER_RETURN_BOOL(abilityRecord);
10245     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10246     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10247     if (callingTokenId != tokenID) {
10248         TAG_LOGE(AAFwkTag::ABILITYMGR, "not app self called");
10249         return false;
10250     }
10251     return true;
10252 }
10253 
GetFocusAbility()10254 std::shared_ptr<AbilityRecord> AbilityManagerService::GetFocusAbility()
10255 {
10256 #ifdef SUPPORT_GRAPHICS
10257     sptr<IRemoteObject> token;
10258     if (!wmsHandler_) {
10259         TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
10260         return nullptr;
10261     }
10262 
10263     wmsHandler_->GetFocusWindow(token);
10264     if (!token) {
10265         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
10266         return nullptr;
10267     }
10268 
10269     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10270     if (!abilityRecord) {
10271         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr.");
10272     }
10273     return abilityRecord;
10274 #endif
10275 
10276     return nullptr;
10277 }
10278 
CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId,bool & isFocused)10279 int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)
10280 {
10281     sptr<IRemoteObject> token;
10282     auto ret = GetTopAbility(token);
10283     if (ret != ERR_OK) {
10284         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetTopAbility failed");
10285         return ret;
10286     }
10287 
10288     auto topAbility = Token::GetAbilityRecordByToken(token);
10289     if (topAbility != nullptr) {
10290         TAG_LOGD(AAFwkTag::ABILITYMGR, "top ability: %{public}s, pid: %{public}d, tokenId: %{public}d",
10291             topAbility->GetWant().GetElement().GetURI().c_str(), topAbility->GetPid(),
10292             topAbility->GetApplicationInfo().accessTokenId);
10293     }
10294 
10295     bool focused = false;
10296     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10297     auto connectManager = GetConnectManagerByUserId(userId);
10298     if (connectManager) {
10299         focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
10300             || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
10301     } else {
10302         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", userId);
10303     }
10304     if (!focused && userId != U0_USER_ID) {
10305         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check connectManager in user0");
10306         connectManager = GetConnectManagerByUserId(U0_USER_ID);
10307         if (connectManager) {
10308             focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
10309                 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
10310         } else {
10311             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: 0");
10312         }
10313     }
10314     isFocused = focused;
10315     TAG_LOGD(AAFwkTag::ABILITYMGR, "isFocused: %{public}d", isFocused);
10316     return ERR_OK;
10317 }
10318 
AddFreeInstallObserver(const sptr<IRemoteObject> & callerToken,const sptr<AbilityRuntime::IFreeInstallObserver> & observer)10319 int AbilityManagerService::AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken,
10320     const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
10321 {
10322     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10323     if (freeInstallManager_ == nullptr) {
10324         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
10325         return ERR_INVALID_VALUE;
10326     }
10327     return freeInstallManager_->AddFreeInstallObserver(callerToken, observer);
10328 }
10329 
IsValidMissionIds(const std::vector<int32_t> & missionIds,std::vector<MissionValidResult> & results)10330 int32_t AbilityManagerService::IsValidMissionIds(
10331     const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)
10332 {
10333     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
10334     auto missionlistMgr = GetMissionListManagerByUserId(userId);
10335     if (missionlistMgr == nullptr) {
10336         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionlistMgr is nullptr.");
10337         return ERR_INVALID_VALUE;
10338     }
10339 
10340     return missionlistMgr->IsValidMissionIds(missionIds, results);
10341 }
10342 
VerifyPermission(const std::string & permission,int pid,int uid)10343 int AbilityManagerService::VerifyPermission(const std::string &permission, int pid, int uid)
10344 {
10345     TAG_LOGI(AAFwkTag::ABILITYMGR, "permission=%{public}s, pid=%{public}d, uid=%{public}d",
10346         permission.c_str(),
10347         pid,
10348         uid);
10349     if (permission.empty()) {
10350         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission permission invalid");
10351         return CHECK_PERMISSION_FAILED;
10352     }
10353 
10354     auto bms = GetBundleManager();
10355     CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
10356 
10357     std::string bundleName;
10358     if (IN_PROCESS_CALL(bms->GetNameForUid(uid, bundleName)) != ERR_OK) {
10359         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get bundle name by uid");
10360         return CHECK_PERMISSION_FAILED;
10361     }
10362 
10363     int account = -1;
10364     DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, account);
10365     AppExecFwk::ApplicationInfo appInfo;
10366     if (!IN_PROCESS_CALL(bms->GetApplicationInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
10367         account, appInfo))) {
10368         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get application info");
10369         return CHECK_PERMISSION_FAILED;
10370     }
10371 
10372     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false);
10373     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
10374         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission %{public}d: PERMISSION_DENIED", appInfo.accessTokenId);
10375         return CHECK_PERMISSION_FAILED;
10376     }
10377 
10378     return ERR_OK;
10379 }
10380 
AcquireShareData(const int32_t & missionId,const sptr<IAcquireShareDataCallback> & shareData)10381 int32_t AbilityManagerService::AcquireShareData(
10382     const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)
10383 {
10384     TAG_LOGD(AAFwkTag::ABILITYMGR, "missionId is %{public}d.", missionId);
10385     CHECK_CALLER_IS_SYSTEM_APP;
10386     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
10387     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10388         auto uiAbilityManager = GetCurrentUIAbilityManager();
10389         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10390         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
10391     } else {
10392         auto missionListManager = GetCurrentMissionListManager();
10393         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
10394         abilityRecord = missionListManager->GetAbilityRecordByMissionId(missionId);
10395     }
10396     if (!abilityRecord) {
10397         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
10398         return ERR_INVALID_VALUE;
10399     }
10400     std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
10401     uniqueId_ = (uniqueId_ == INT_MAX) ? 0 : (uniqueId_ + 1);
10402     std::pair<int64_t, const sptr<IAcquireShareDataCallback>> shareDataPair =
10403         std::make_pair(abilityRecord->GetAbilityRecordId(), shareData);
10404     iAcquireShareDataMap_.emplace(uniqueId_, shareDataPair);
10405     abilityRecord->ShareData(uniqueId_);
10406     return ERR_OK;
10407 }
10408 
ShareDataDone(const sptr<IRemoteObject> & token,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)10409 int32_t AbilityManagerService::ShareDataDone(
10410     const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
10411 {
10412     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d.", resultCode, uniqueId);
10413     if (!VerificationAllToken(token)) {
10414         return ERR_INVALID_VALUE;
10415     }
10416     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10417     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record is nullptr.");
10418     if (!JudgeSelfCalled(abilityRecord)) {
10419         return CHECK_PERMISSION_FAILED;
10420     }
10421     CHECK_POINTER_AND_RETURN_LOG(eventHandler_, ERR_INVALID_VALUE, "fail to get abilityEventHandler.");
10422     eventHandler_->RemoveEvent(SHAREDATA_TIMEOUT_MSG, uniqueId);
10423     return GetShareDataPairAndReturnData(abilityRecord, resultCode, uniqueId, wantParam);
10424 }
10425 
NotifySaveAsResult(const Want & want,int resultCode,int requestCode)10426 int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCode, int requestCode)
10427 {
10428     TAG_LOGD(AAFwkTag::ABILITYMGR, "requestCode is %{public}d.", requestCode);
10429     CHECK_CALLER_IS_SYSTEM_APP;
10430 #ifdef WITH_DLP
10431     //caller check
10432     if (!DlpUtils::CheckCallerIsDlpManager(GetBundleManager())) {
10433         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller check failed");
10434         return CHECK_PERMISSION_FAILED;
10435     }
10436 #endif // WITH_DLP
10437     auto checkResult = AbilityUtil::CheckInstanceKey(want);
10438     if (checkResult != ERR_OK) {
10439         return checkResult;
10440     }
10441 
10442     for (const auto &item : startAbilityChain_) {
10443         if (item.second->GetHandlerName() == StartAbilitySandboxSavefile::handlerName_) {
10444             auto savefileHandler = (StartAbilitySandboxSavefile*)(item.second.get());
10445             savefileHandler->HandleResult(want, resultCode, requestCode);
10446             break;
10447         }
10448     }
10449     return ERR_OK;
10450 }
10451 
SetRootSceneSession(const sptr<IRemoteObject> & rootSceneSession)10452 void AbilityManagerService::SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)
10453 {
10454     if (!IsCallerSceneBoard()) {
10455         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10456         return;
10457     }
10458     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10459     CHECK_POINTER(uiAbilityManager);
10460     uiAbilityManager->SetRootSceneSession(rootSceneSession);
10461 }
10462 
CallUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isColdStart)10463 void AbilityManagerService::CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isColdStart)
10464 {
10465     if (!IsCallerSceneBoard()) {
10466         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10467         return;
10468     }
10469     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10470     CHECK_POINTER(uiAbilityManager);
10471     uiAbilityManager->CallUIAbilityBySCB(sessionInfo, isColdStart);
10472 }
10473 
SetSessionManagerService(const sptr<IRemoteObject> & sessionManagerService)10474 int32_t AbilityManagerService::SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)
10475 {
10476     if (!IsCallerSceneBoard()) {
10477         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10478         return ERR_WRONG_INTERFACE_CALL;
10479     }
10480 
10481     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10482     auto ret = Rosen::MockSessionManagerService::GetInstance().SetSessionManagerService(sessionManagerService);
10483     if (ret) {
10484         TAG_LOGD(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10485         return ERR_OK;
10486     }
10487     TAG_LOGE(AAFwkTag::ABILITYMGR, "SMS SetSessionManagerService return false.");
10488     return ERR_OK;
10489 }
10490 
CheckPrepareTerminateEnable()10491 bool AbilityManagerService::CheckPrepareTerminateEnable()
10492 {
10493     if (!isPrepareTerminateEnable_) {
10494         TAG_LOGD(AAFwkTag::ABILITYMGR, "Only support PC.");
10495         return false;
10496     }
10497     if (!AAFwk::PermissionVerification::GetInstance()->VerifyPrepareTerminatePermission()) {
10498         TAG_LOGD(AAFwkTag::ABILITYMGR, "failed, please apply permission ohos.permission.PREPARE_APP_TERMINATE");
10499         return false;
10500     }
10501     return true;
10502 }
10503 
StartSpecifiedAbilityBySCB(const Want & want)10504 void AbilityManagerService::StartSpecifiedAbilityBySCB(const Want &want)
10505 {
10506     if (!IsCallerSceneBoard()) {
10507         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10508         return;
10509     }
10510     int32_t appIndex = 0;
10511     if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex)) {
10512         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app clone index");
10513     }
10514     (void)AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
10515         GetUserId(), appIndex, nullptr);
10516     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10517     CHECK_POINTER(uiAbilityManager);
10518     uiAbilityManager->StartSpecifiedAbilityBySCB(want);
10519 }
10520 
RegisterIAbilityManagerCollaborator(int32_t type,const sptr<IAbilityManagerCollaborator> & impl)10521 int32_t AbilityManagerService::RegisterIAbilityManagerCollaborator(
10522     int32_t type, const sptr<IAbilityManagerCollaborator> &impl)
10523 {
10524     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10525     auto callingUid = IPCSkeleton::GetCallingUid();
10526     if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
10527         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
10528         return CHECK_PERMISSION_FAILED;
10529     }
10530     if (!CheckCollaboratorType(type)) {
10531         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator register failed, invalid type.");
10532         return ERR_INVALID_VALUE;
10533     }
10534     {
10535         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10536         collaboratorMap_[type] = impl;
10537     }
10538     return ERR_OK;
10539 }
10540 
UnregisterIAbilityManagerCollaborator(int32_t type)10541 int32_t AbilityManagerService::UnregisterIAbilityManagerCollaborator(int32_t type)
10542 {
10543     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10544     auto callingUid = IPCSkeleton::GetCallingUid();
10545     if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
10546         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
10547         return CHECK_PERMISSION_FAILED;
10548     }
10549     if (!CheckCollaboratorType(type)) {
10550         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator unregister failed, invalid type.");
10551         return ERR_INVALID_VALUE;
10552     }
10553     {
10554         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10555         collaboratorMap_.erase(type);
10556     }
10557     return ERR_OK;
10558 }
10559 
GetCollaborator(int32_t type)10560 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetCollaborator(int32_t type)
10561 {
10562     if (!CheckCollaboratorType(type)) {
10563         return nullptr;
10564     }
10565     {
10566         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10567         auto it = collaboratorMap_.find(type);
10568         if (it != collaboratorMap_.end()) {
10569             return it->second;
10570         }
10571     }
10572     return nullptr;
10573 }
10574 
CheckCollaboratorType(int32_t type)10575 bool AbilityManagerService::CheckCollaboratorType(int32_t type)
10576 {
10577     if (type != CollaboratorType::RESERVE_TYPE && type != CollaboratorType::OTHERS_TYPE) {
10578         return false;
10579     }
10580     return true;
10581 }
10582 
GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> & sessionInfo,std::shared_ptr<AbilityConnectManager> & connectManager,std::shared_ptr<AbilityRecord> & targetAbility)10583 void AbilityManagerService::GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo,
10584     std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility)
10585 {
10586     targetAbility = nullptr;
10587     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10588     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId=%{public}d", userId);
10589     connectManager = GetConnectManagerByUserId(userId);
10590     if (connectManager) {
10591         targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
10592     } else {
10593         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", userId);
10594     }
10595     if (targetAbility == nullptr && userId != U0_USER_ID) {
10596         TAG_LOGD(AAFwkTag::ABILITYMGR, "try to find UIExtension in user0");
10597         connectManager = GetConnectManagerByUserId(U0_USER_ID);
10598         if (connectManager) {
10599             targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
10600         } else {
10601             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: 0");
10602         }
10603     }
10604 }
10605 
RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)10606 int32_t AbilityManagerService::RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)
10607 {
10608     if (!IsCallerSceneBoard()) {
10609         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10610         return ERR_WRONG_INTERFACE_CALL;
10611     }
10612     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10613     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10614     return uiAbilityManager->RegisterStatusBarDelegate(delegate);
10615 }
10616 
KillProcessWithPrepareTerminate(const std::vector<int32_t> & pids)10617 int32_t AbilityManagerService::KillProcessWithPrepareTerminate(const std::vector<int32_t>& pids)
10618 {
10619     if (!IsCallerSceneBoard()) {
10620         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10621         return ERR_WRONG_INTERFACE_CALL;
10622     }
10623     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10624     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10625     return uiAbilityManager->TryPrepareTerminateByPids(pids);
10626 }
10627 
RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10628 int32_t AbilityManagerService::RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10629 {
10630     if (abilityAutoStartupService_ == nullptr) {
10631         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10632         return ERR_NO_INIT;
10633     }
10634     return abilityAutoStartupService_->RegisterAutoStartupSystemCallback(callback);
10635 }
10636 
UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10637 int32_t AbilityManagerService::UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10638 {
10639     if (abilityAutoStartupService_ == nullptr) {
10640         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10641         return ERR_NO_INIT;
10642     }
10643     return abilityAutoStartupService_->UnregisterAutoStartupSystemCallback(callback);
10644 }
10645 
SetApplicationAutoStartup(const AutoStartupInfo & info)10646 int32_t AbilityManagerService::SetApplicationAutoStartup(const AutoStartupInfo &info)
10647 {
10648     if (abilityAutoStartupService_ == nullptr) {
10649         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10650         return ERR_NO_INIT;
10651     }
10652     return abilityAutoStartupService_->SetApplicationAutoStartup(info);
10653 }
10654 
CancelApplicationAutoStartup(const AutoStartupInfo & info)10655 int32_t AbilityManagerService::CancelApplicationAutoStartup(const AutoStartupInfo &info)
10656 {
10657     if (abilityAutoStartupService_ == nullptr) {
10658         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10659         return ERR_NO_INIT;
10660     }
10661     return abilityAutoStartupService_->CancelApplicationAutoStartup(info);
10662 }
10663 
QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> & infoList)10664 int32_t AbilityManagerService::QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)
10665 {
10666     if (abilityAutoStartupService_ == nullptr) {
10667         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10668         return ERR_NO_INIT;
10669     }
10670     return abilityAutoStartupService_->QueryAllAutoStartupApplications(infoList, GetUserId());
10671 }
10672 
PrepareTerminateAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isTerminate)10673 int AbilityManagerService::PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)
10674 {
10675     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10676     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
10677     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
10678         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
10679         return ERR_INVALID_VALUE;
10680     }
10681 
10682     if (!IsCallerSceneBoard()) {
10683         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10684         return ERR_WRONG_INTERFACE_CALL;
10685     }
10686 
10687     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10688     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10689     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
10690     isTerminate = uiAbilityManager->PrepareTerminateAbility(abilityRecord);
10691 
10692     return ERR_OK;
10693 }
10694 
RegisterSessionHandler(const sptr<IRemoteObject> & object)10695 int AbilityManagerService::RegisterSessionHandler(const sptr<IRemoteObject> &object)
10696 {
10697     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
10698     if (!IsCallerSceneBoard()) {
10699         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10700         return ERR_WRONG_INTERFACE_CALL;
10701     }
10702     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10703     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10704     sptr<ISessionHandler> handler = iface_cast<ISessionHandler>(object);
10705     uiAbilityManager->SetSessionHandler(handler);
10706     return ERR_OK;
10707 }
10708 
CheckUserIdActive(int32_t userId)10709 bool AbilityManagerService::CheckUserIdActive(int32_t userId)
10710 {
10711     std::vector<int32_t> osActiveAccountIds;
10712     auto ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
10713         QueryActiveOsAccountIds(osActiveAccountIds);
10714     if (ret != ERR_OK) {
10715         TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryActiveOsAccountIds failed");
10716         return false;
10717     }
10718     if (osActiveAccountIds.empty()) {
10719         TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryActiveOsAccountIds empty");
10720         return false;
10721     }
10722     auto iter = std::find(osActiveAccountIds.begin(), osActiveAccountIds.end(), userId);
10723     if (iter == osActiveAccountIds.end()) {
10724         return false;
10725     }
10726     return true;
10727 }
10728 
CheckProcessOptions(const Want & want,const StartOptions & startOptions,int32_t userId)10729 int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const StartOptions &startOptions, int32_t userId)
10730 {
10731     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10732     if (startOptions.processOptions == nullptr ||
10733         !ProcessOptions::IsValidProcessMode(startOptions.processOptions->processMode)) {
10734         return ERR_OK;
10735     }
10736 
10737     TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability with process options.");
10738     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
10739     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
10740         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support process options.");
10741         return ERR_CAPABILITY_NOT_SUPPORT;
10742     }
10743 
10744     auto element = want.GetElement();
10745     if (element.GetAbilityName().empty() || want.GetAction().compare(ACTION_CHOOSE) == 0) {
10746         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not allow implicit start.");
10747         return ERR_NOT_ALLOW_IMPLICIT_START;
10748     }
10749 
10750     int32_t appIndex = 0;
10751     appIndex = !AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex) ? 0 : appIndex;
10752     if (!CheckCallingTokenId(element.GetBundleName(), userId, appIndex)) {
10753         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not self application.");
10754         return ERR_NOT_SELF_APPLICATION;
10755     }
10756 
10757     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10758     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10759 
10760     if (ProcessOptions::IsAttachToStatusBarMode(startOptions.processOptions->processMode) &&
10761         !uiAbilityManager->IsCallerInStatusBar()) {
10762         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not in status bar in attch to status bar mode.");
10763         return ERR_START_OPTIONS_CHECK_FAILED;
10764     }
10765 
10766     auto abilityRecords = uiAbilityManager->GetAbilityRecordsByName(element);
10767     if (!abilityRecords.empty() && abilityRecords[0] &&
10768         abilityRecords[0]->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::STANDARD) {
10769         TAG_LOGE(AAFwkTag::ABILITYMGR, "If it is not in STANDARD mode, repeated starts are not allowed");
10770         return ERR_ABILITY_ALREADY_RUNNING;
10771     }
10772 
10773     return ERR_OK;
10774 }
10775 
RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10776 int32_t AbilityManagerService::RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10777 {
10778     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10779     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10780         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10781         return CHECK_PERMISSION_FAILED;
10782     }
10783     return DelayedSingleton<AppScheduler>::GetInstance()->RegisterAppDebugListener(listener);
10784 }
10785 
UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10786 int32_t AbilityManagerService::UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10787 {
10788     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10789     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10790         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10791         return CHECK_PERMISSION_FAILED;
10792     }
10793     return DelayedSingleton<AppScheduler>::GetInstance()->UnregisterAppDebugListener(listener);
10794 }
10795 
ConnectInitAbilityDebugDeal()10796 std::shared_ptr<AbilityDebugDeal> AbilityManagerService::ConnectInitAbilityDebugDeal()
10797 {
10798     if (abilityDebugDeal_ != nullptr) {
10799         return abilityDebugDeal_;
10800     }
10801 
10802     std::unique_lock<ffrt::mutex> lock(abilityDebugDealLock_);
10803     if (abilityDebugDeal_ != nullptr) {
10804         return abilityDebugDeal_;
10805     }
10806 
10807     TAG_LOGD(AAFwkTag::ABILITYMGR, "Creat ability debug deal object.");
10808     abilityDebugDeal_ = std::make_shared<AbilityDebugDeal>();
10809     if (abilityDebugDeal_ == nullptr) {
10810         TAG_LOGE(AAFwkTag::ABILITYMGR, "Creat ability debug deal object failed.");
10811         return nullptr;
10812     }
10813 
10814     abilityDebugDeal_->RegisterAbilityDebugResponse();
10815     return abilityDebugDeal_;
10816 }
10817 
AttachAppDebug(const std::string & bundleName)10818 int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName)
10819 {
10820     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10821     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10822         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
10823         return ERR_NOT_DEVELOPER_MODE;
10824     }
10825 
10826     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10827         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10828         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10829         return CHECK_PERMISSION_FAILED;
10830     }
10831 
10832     ConnectInitAbilityDebugDeal();
10833     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->AttachAppDebug(bundleName));
10834 }
10835 
DetachAppDebug(const std::string & bundleName)10836 int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName)
10837 {
10838     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10839     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10840         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
10841         return ERR_NOT_DEVELOPER_MODE;
10842     }
10843 
10844     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10845         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10846         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10847         return CHECK_PERMISSION_FAILED;
10848     }
10849 
10850     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->DetachAppDebug(bundleName));
10851 }
10852 
ExecuteIntent(uint64_t key,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)10853 int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken,
10854     const InsightIntentExecuteParam &param)
10855 {
10856     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10857     auto paramPtr = std::make_shared<InsightIntentExecuteParam>(param);
10858     int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateParam(key, callerToken,
10859         paramPtr);
10860     if (ret != ERR_OK) {
10861         return ret;
10862     }
10863 
10864     Want want;
10865     ret = InsightIntentExecuteManager::GenerateWant(paramPtr, want);
10866     if (ret != ERR_OK) {
10867         return ret;
10868     }
10869 
10870     switch (param.executeMode_) {
10871         case AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND:
10872             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_FOREGROUND.");
10873             ret = StartAbilityWithInsightIntent(want);
10874             break;
10875         case AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND: {
10876             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_BACKGROUND.");
10877             ret = StartAbilityByCallWithInsightIntent(want, callerToken, param);
10878             break;
10879         }
10880         case AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY:
10881             TAG_LOGW(AAFwkTag::ABILITYMGR, "ExecuteMode UI_EXTENSION_ABILITY not supported.");
10882             ret = ERR_INVALID_OPERATION;
10883             break;
10884         case AppExecFwk::ExecuteMode::SERVICE_EXTENSION_ABILITY:
10885             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode SERVICE_EXTENSION_ABILITY.");
10886             ret = StartExtensionAbilityWithInsightIntent(want, AppExecFwk::ExtensionAbilityType::SERVICE);
10887             break;
10888         default:
10889             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ExecuteMode.");
10890             ret = ERR_INVALID_OPERATION;
10891             break;
10892     }
10893     if (ret == START_ABILITY_WAITING) {
10894         TAG_LOGD(AAFwkTag::ABILITYMGR, "Top ability is foregrounding. The intent will be queued for execution");
10895         ret = ERR_OK;
10896     }
10897     if (ret != ERR_OK) {
10898         DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->RemoveExecuteIntent(paramPtr->insightIntentId_);
10899     }
10900 
10901     TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteIntent done, ret: %{public}d.", ret);
10902     return ret;
10903 }
10904 
IsAbilityStarted(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord,const int32_t oriValidUserId)10905 bool AbilityManagerService::IsAbilityStarted(AbilityRequest &abilityRequest,
10906     std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)
10907 {
10908     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10909         TAG_LOGI(AAFwkTag::ABILITYMGR, "scene board is enable");
10910         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
10911         CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
10912         return uiAbilityManager->IsAbilityStarted(abilityRequest, targetRecord);
10913     }
10914 
10915     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10916     if (missionListMgr == nullptr) {
10917         return false;
10918     }
10919     return missionListMgr->IsAbilityStarted(abilityRequest, targetRecord);
10920 }
10921 
OnExecuteIntent(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord)10922 int32_t AbilityManagerService::OnExecuteIntent(AbilityRequest &abilityRequest,
10923     std::shared_ptr<AbilityRecord> &targetRecord)
10924 {
10925     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnExecuteIntent");
10926     if (targetRecord == nullptr || targetRecord->GetScheduler() == nullptr) {
10927         return ERR_INVALID_VALUE;
10928     }
10929     targetRecord->GetScheduler()->OnExecuteIntent(abilityRequest.want);
10930 
10931     return ERR_OK;
10932 }
10933 
StartAbilityWithInsightIntent(const Want & want,int32_t userId,int requestCode)10934 int32_t AbilityManagerService::StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)
10935 {
10936     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10937     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
10938     if (startWithAccount || IsCrossUserCall(userId)) {
10939         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
10940         CHECK_CALLER_IS_SYSTEM_APP;
10941     }
10942     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
10943     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
10944     EventInfo eventInfo = BuildEventInfo(want, userId);
10945     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
10946     int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
10947     if (ret != ERR_OK) {
10948         eventInfo.errCode = ret;
10949         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
10950     }
10951     return ret;
10952 }
10953 
StartExtensionAbilityWithInsightIntent(const Want & want,AppExecFwk::ExtensionAbilityType extensionType)10954 int32_t AbilityManagerService::StartExtensionAbilityWithInsightIntent(const Want &want,
10955     AppExecFwk::ExtensionAbilityType extensionType)
10956 {
10957     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10958     return StartExtensionAbilityInner(want, nullptr, DEFAULT_INVAL_VALUE, extensionType, true);
10959 }
10960 
StartAbilityByCallWithInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)10961 int32_t AbilityManagerService::StartAbilityByCallWithInsightIntent(const Want &want,
10962     const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam &param)
10963 {
10964     TAG_LOGI(AAFwkTag::ABILITYMGR, "call StartAbilityByCallWithInsightIntent.");
10965     sptr<IAbilityConnection> connect = sptr<AbilityBackgroundConnection>::MakeSptr();
10966     if (connect == nullptr) {
10967         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid connect.");
10968         return ERR_INVALID_VALUE;
10969     }
10970 
10971     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
10972     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
10973     AbilityRequest abilityRequest;
10974     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
10975     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
10976     abilityRequest.callerToken = callerToken;
10977     abilityRequest.startSetting = nullptr;
10978     abilityRequest.want = want;
10979     abilityRequest.connect = connect;
10980     int32_t result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
10981     if (result != ERR_OK) {
10982         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
10983         return result;
10984     }
10985     std::shared_ptr<AbilityRecord> targetRecord;
10986     int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
10987     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10988     if (IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId)) {
10989         TAG_LOGI(AAFwkTag::ABILITYMGR, "ability has already started");
10990         UpdateCallerInfo(abilityRequest.want, callerToken);
10991         result = OnExecuteIntent(abilityRequest, targetRecord);
10992     }  else {
10993         result = StartAbilityByCall(want, connect, callerToken);
10994     }
10995 
10996     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartAbilityByCallWithInsightIntent %{public}d", result);
10997     return result;
10998 }
10999 
IsAbilityControllerStart(const Want & want)11000 bool AbilityManagerService::IsAbilityControllerStart(const Want &want)
11001 {
11002     auto callingUid = IPCSkeleton::GetCallingUid();
11003     bool isBrokerCall = (callingUid == BROKER_UID || callingUid == BROKER_RESERVE_UID);
11004     if (isBrokerCall) {
11005         return IsAbilityControllerStart(want, want.GetBundle());
11006     }
11007     TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
11008     return true;
11009 }
11010 
ExecuteInsightIntentDone(const sptr<IRemoteObject> & token,uint64_t intentId,const InsightIntentExecuteResult & result)11011 int32_t AbilityManagerService::ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId,
11012     const InsightIntentExecuteResult &result)
11013 {
11014     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11015     auto abilityRecord = Token::GetAbilityRecordByToken(token);
11016     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
11017     if (!JudgeSelfCalled(abilityRecord)) {
11018         return CHECK_PERMISSION_FAILED;
11019     }
11020 
11021     // check send by same bundleName.
11022     std::string bundleNameStored = "";
11023     auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetBundleName(intentId, bundleNameStored);
11024     if (ret != ERR_OK) {
11025         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get matched bundleName failed, intentId: %{public}" PRIu64"", intentId);
11026         return ERR_INVALID_VALUE;
11027     }
11028 
11029     std::string bundleName = abilityRecord->GetAbilityInfo().bundleName;
11030     if (bundleNameStored != bundleName) {
11031         TAG_LOGE(AAFwkTag::ABILITYMGR,
11032             "BundleName %{public}s and %{public}s mismatch.", bundleName.c_str(), bundleNameStored.c_str());
11033         return ERR_INVALID_VALUE;
11034     }
11035 
11036     return DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
11037         intentId, result.innerErr, result);
11038 }
11039 
SetApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)11040 int32_t AbilityManagerService::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
11041 {
11042     if (abilityAutoStartupService_ == nullptr) {
11043         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
11044         return ERR_NO_INIT;
11045     }
11046     return abilityAutoStartupService_->SetApplicationAutoStartupByEDM(info, flag);
11047 }
11048 
CancelApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)11049 int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
11050 {
11051     if (abilityAutoStartupService_ == nullptr) {
11052         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
11053         return ERR_NO_INIT;
11054     }
11055     return abilityAutoStartupService_->CancelApplicationAutoStartupByEDM(info, flag);
11056 }
11057 
GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> & list)11058 int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)
11059 {
11060     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11061     CHECK_CALLER_IS_SYSTEM_APP;
11062     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
11063     if (!isPerm) {
11064         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
11065         return CHECK_PERMISSION_FAILED;
11066     }
11067 
11068     std::vector<AbilityRunningInfo> abilityRunningInfos;
11069     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11070         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11071         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11072         uiAbilityManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
11073     } else {
11074         auto missionListManager = GetCurrentMissionListManager();
11075         CHECK_POINTER_AND_RETURN(missionListManager, ERR_NULL_OBJECT);
11076         missionListManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
11077     }
11078 
11079     for (auto &info : abilityRunningInfos) {
11080         if (info.abilityState != AbilityState::FOREGROUND) {
11081             continue;
11082         }
11083 
11084         AppExecFwk::AbilityStateData abilityData;
11085         abilityData.bundleName = info.ability.GetBundleName();
11086         abilityData.moduleName = info.ability.GetModuleName();
11087         abilityData.abilityName = info.ability.GetAbilityName();
11088         abilityData.abilityState = info.abilityState;
11089         abilityData.pid = info.pid;
11090         abilityData.uid = info.uid;
11091         abilityData.abilityType = static_cast<int32_t>(AppExecFwk::AbilityType::PAGE);
11092         abilityData.appCloneIndex = info.appCloneIndex;
11093         AppExecFwk::ApplicationInfo appInfo;
11094         if (!StartAbilityUtils::GetApplicationInfo(abilityData.bundleName, GetUserId(), appInfo)) {
11095             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get applicationInfo through bundleName");
11096         } else if (appInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
11097             abilityData.isAtomicService = true;
11098         }
11099         list.push_back(abilityData);
11100     }
11101     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get foreground ui abilities end, list.size = %{public}zu.", list.size());
11102     return ERR_OK;
11103 }
11104 
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)11105 void AbilityManagerService::NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)
11106 {
11107     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
11108     if (collaborator == nullptr) {
11109         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator GetCollaborator is nullptr.");
11110         return;
11111     }
11112     collaborator->UpdateConfiguration(config, userId);
11113 }
11114 
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)11115 void AbilityManagerService::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
11116 {
11117     if (userController_ == nullptr) {
11118         TAG_LOGE(AAFwkTag::ABILITYMGR, "userController_ null");
11119         return;
11120     }
11121     auto currentUser = userController_->GetCurrentUserId();
11122     std::vector<AppExecFwk::BundleInfo> bundleInfosForU0;
11123     std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
11124     for (const auto &item: bundleInfos) {
11125         auto user = item.uid / BASE_USER_RANGE;
11126         if (user == U0_USER_ID) {
11127             bundleInfosForU0.push_back(item);
11128         } else if (user == currentUser) {
11129             bundleInfosForCurrentUser.push_back(item);
11130         }
11131     }
11132 
11133     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
11134         bundleInfosForU0, U0_USER_ID);
11135     if (!bundleInfosForU0.empty()) {
11136         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForU0);
11137     }
11138 
11139     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
11140         bundleInfosForCurrentUser, currentUser);
11141     if (!bundleInfosForCurrentUser.empty()) {
11142         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForCurrentUser);
11143     }
11144 }
11145 
NotifyAppPreCache(int32_t pid,int32_t userId)11146 void AbilityManagerService::NotifyAppPreCache(int32_t pid, int32_t userId)
11147 {
11148     ForceTerminateSerivceExtensionByPid(pid, userId);
11149 }
11150 
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> & abilityTokens)11151 void AbilityManagerService::OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens)
11152 {
11153     std::shared_ptr<AbilityRecord> abilityRecord;
11154     for (auto &token : abilityTokens) {
11155         abilityRecord = Token::GetAbilityRecordByToken(token);
11156         if (abilityRecord == nullptr) {
11157             continue;
11158         }
11159         TAG_LOGI(AAFwkTag::ABILITYMGR, "App OnRemoteDied, ability is %{public}s, app is %{public}s",
11160             abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
11161         abilityRecord->OnProcessDied();
11162     }
11163 }
11164 
OnStartProcessFailed(sptr<IRemoteObject> token)11165 void AbilityManagerService::OnStartProcessFailed(sptr<IRemoteObject> token)
11166 {
11167     auto abilityRecord = Token::GetAbilityRecordByToken(token);
11168     CHECK_POINTER_LOG(abilityRecord, "Null record.");
11169     TAG_LOGW(AAFwkTag::ABILITYMGR, "NotifStartProcessFailed, ability:%{public}s, bundle:%{public}s",
11170         abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
11171 
11172     if (abilityRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::EXTENSION) {
11173         auto connectManager = GetConnectManagerByToken(token);
11174         CHECK_POINTER(connectManager);
11175         connectManager->OnLoadAbilityFailed(abilityRecord);
11176         return;
11177     }
11178 }
11179 
OpenFile(const Uri & uri,uint32_t flag)11180 int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag)
11181 {
11182     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
11183     if (!IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission(
11184         uri, flag, accessTokenId))) {
11185         TAG_LOGE(AAFwkTag::ABILITYMGR, "premission check failed");
11186         return -1;
11187     }
11188     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
11189     if (collaborator == nullptr) {
11190         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator GetCollaborator is nullptr.");
11191         return ERR_COLLABORATOR_NOT_REGISTER;
11192     }
11193     return collaborator->OpenFile(uri, flag);
11194 }
11195 
GetDialogSessionInfo(const std::string & dialogSessionId,sptr<DialogSessionInfo> & dialogSessionInfo)11196 int AbilityManagerService::GetDialogSessionInfo(const std::string &dialogSessionId,
11197     sptr<DialogSessionInfo> &dialogSessionInfo)
11198 {
11199     CHECK_CALLER_IS_SYSTEM_APP;
11200     dialogSessionInfo = DialogSessionManager::GetInstance().GetDialogSessionInfo(dialogSessionId);
11201     if (dialogSessionInfo) {
11202         TAG_LOGD(AAFwkTag::ABILITYMGR, "success");
11203         return ERR_OK;
11204     }
11205     TAG_LOGD(AAFwkTag::ABILITYMGR, "fail");
11206     return INNER_ERR;
11207 }
11208 
SendDialogResult(const Want & want,const std::string & dialogSessionId,bool isAllowed)11209 int AbilityManagerService::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed)
11210 {
11211     CHECK_CALLER_IS_SYSTEM_APP;
11212     return DialogSessionManager::GetInstance().SendDialogResult(want, dialogSessionId, isAllowed);
11213 }
11214 
CreateCloneSelectorDialog(AbilityRequest & request,int32_t userId,const std::string & replaceWantString)11215 int AbilityManagerService::CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId,
11216     const std::string &replaceWantString)
11217 {
11218     CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
11219     return implicitStartProcessor_->ImplicitStartAbility(request, userId, 0, replaceWantString, true);
11220 }
11221 
RemoveSelectorIdentity(int32_t tokenId)11222 void AbilityManagerService::RemoveSelectorIdentity(int32_t tokenId)
11223 {
11224     CHECK_POINTER(implicitStartProcessor_);
11225     implicitStartProcessor_->RemoveIdentity(tokenId);
11226 }
11227 
SetTargetCloneIndexInSameBundle(const Want & want,sptr<IRemoteObject> callerToken)11228 void AbilityManagerService::SetTargetCloneIndexInSameBundle(const Want &want, sptr<IRemoteObject> callerToken)
11229 {
11230     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
11231     CHECK_POINTER(callerRecord);
11232     if (callerRecord->GetAbilityInfo().bundleName != want.GetElement().GetBundleName()) {
11233         TAG_LOGD(AAFwkTag::ABILITYMGR, "not the same bundle");
11234         return;
11235     }
11236     if (want.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY)) {
11237         TAG_LOGD(AAFwkTag::ABILITYMGR, "want with app clone index.");
11238         return;
11239     }
11240     int32_t appIndex = callerRecord->GetApplicationInfo().appIndex;
11241     if (appIndex >= 0 && appIndex < AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
11242         (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
11243     }
11244 }
11245 
RemoveLauncherDeathRecipient(int32_t userId)11246 void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId)
11247 {
11248     auto connectManager = GetConnectManagerByUserId(userId);
11249     if (connectManager == nullptr) {
11250         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
11251         return;
11252     }
11253     connectManager->RemoveLauncherDeathRecipient();
11254 }
11255 
CheckDebugAssertPermission()11256 int32_t AbilityManagerService::CheckDebugAssertPermission()
11257 {
11258     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11259     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11260     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
11261         TAG_LOGE(AAFwkTag::ABILITYMGR, "Product of assert fault dialog is not enabled.");
11262         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11263     }
11264     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
11265         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
11266         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11267     }
11268 
11269     auto bundleMgr = GetBundleManager();
11270     if (bundleMgr == nullptr) {
11271         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle manager instance is nullptr.");
11272         return ERR_INVALID_VALUE;
11273     }
11274     int32_t flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
11275     AppExecFwk::BundleInfo bundleInfo;
11276     auto ret = bundleMgr->GetBundleInfoForSelf(flags, bundleInfo);
11277     if (ret != ERR_OK) {
11278         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle Info failed.");
11279         return ret;
11280     }
11281     if (!bundleInfo.applicationInfo.debug) {
11282         TAG_LOGE(AAFwkTag::ABILITYMGR, "Non-debug version application.");
11283         return ERR_INVALID_VALUE;
11284     }
11285     return ERR_OK;
11286 }
11287 
SetResidentProcessEnabled(const std::string & bundleName,bool enable)11288 int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable)
11289 {
11290     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11291     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) {
11292         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
11293         return ERR_NOT_SYSTEM_APP;
11294     }
11295 
11296     auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
11297     if (residentProcessManager == nullptr) {
11298         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get resident proces mgr is nullptr");
11299         return INNER_ERR;
11300     }
11301 
11302     std::string callerName;
11303     int32_t uid = 0;
11304     auto callerPid = IPCSkeleton::GetCallingPid();
11305     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
11306     if (callerName.empty()) {
11307         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to obtain caller name.");
11308         return INNER_ERR;
11309     }
11310 
11311     return residentProcessManager->SetResidentProcessEnabled(bundleName, callerName, enable);
11312 }
11313 
CloseAssertDialog(const std::string & assertSessionId)11314 void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId)
11315 {
11316     TAG_LOGD(AAFwkTag::ABILITYMGR, "Close assert fault dialog begin.");
11317     auto validUserId = GetUserId();
11318     auto connectManager = GetConnectManagerByUserId(validUserId);
11319     if (connectManager == nullptr) {
11320         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11321         return;
11322     }
11323 
11324     connectManager->CloseAssertDialog(assertSessionId);
11325 }
11326 
RequestAssertFaultDialog(const sptr<IRemoteObject> & callback,const AAFwk::WantParams & wantParams)11327 int32_t AbilityManagerService::RequestAssertFaultDialog(
11328     const sptr<IRemoteObject> &callback, const AAFwk::WantParams &wantParams)
11329 {
11330     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog begin.");
11331     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11332     auto checkRet = CheckDebugAssertPermission();
11333     if (checkRet != ERR_OK) {
11334         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check debug assert permission error.");
11335         return checkRet;
11336     }
11337     sptr<IRemoteObject> remoteCallback = callback;
11338     if (remoteCallback == nullptr) {
11339         TAG_LOGE(AAFwkTag::ABILITYMGR, "Params remote callback is nullptr");
11340         return ERR_INVALID_VALUE;
11341     }
11342     auto debugDeal = ConnectInitAbilityDebugDeal();
11343     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
11344     if (sysDialog == nullptr || debugDeal == nullptr) {
11345         TAG_LOGE(AAFwkTag::ABILITYMGR, "sysDialog or debugDeal is nullptr.");
11346         return ERR_INVALID_VALUE;
11347     }
11348     Want want;
11349     if (!sysDialog->GetAssertFaultDialogWant(want)) {
11350         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get assert fault dialog want failed.");
11351         return ERR_INVALID_VALUE;
11352     }
11353     uint64_t assertFaultSessionId = reinterpret_cast<uint64_t>(remoteCallback.GetRefPtr());
11354     want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, std::to_string(assertFaultSessionId));
11355     want.SetParam(ASSERT_FAULT_DETAIL, wantParams.GetStringParam(ASSERT_FAULT_DETAIL));
11356     auto &connection = AbilityRuntime::ModalSystemAssertUIExtension::GetInstance();
11357     want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
11358     if (!IN_PROCESS_CALL(connection.CreateModalUIExtension(want))) {
11359         TAG_LOGE(AAFwkTag::ABILITYMGR, "Create modal ui extension failed.");
11360         return ERR_INVALID_VALUE;
11361     }
11362     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11363     if (callbackDeathMgr == nullptr) {
11364         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callback death manager instance is nullptr.");
11365         return ERR_INVALID_VALUE;
11366     }
11367     auto callbackTask = [weak = weak_from_this()] (const std::string &assertSessionId) {
11368         auto abilityMgr = weak.lock();
11369         if (abilityMgr == nullptr) {
11370             TAG_LOGE(AAFwkTag::ABILITYMGR, "ability manager instance is nullptr.");
11371             return;
11372         }
11373         abilityMgr->CloseAssertDialog(assertSessionId);
11374     };
11375     callbackDeathMgr->AddAssertFaultCallback(remoteCallback, callbackTask);
11376     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog end.");
11377     return ERR_OK;
11378 }
11379 
NotifyDebugAssertResult(uint64_t assertFaultSessionId,AAFwk::UserStatus userStatus)11380 int32_t AbilityManagerService::NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus)
11381 {
11382     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11383     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
11384         TAG_LOGE(AAFwkTag::ABILITYMGR, "Product of assert fault dialog is not enabled.");
11385         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11386     }
11387 
11388     CHECK_CALLER_IS_SYSTEM_APP;
11389     auto permissionSA = PermissionVerification::GetInstance();
11390     if (permissionSA == nullptr) {
11391         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification instance is nullptr.");
11392         return ERR_INVALID_VALUE;
11393     }
11394     if (!permissionSA->VerifyCallingPermission(PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT)) {
11395         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
11396             PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT);
11397         return ERR_PERMISSION_DENIED;
11398     }
11399 
11400     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11401     if (callbackDeathMgr == nullptr) {
11402         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callback death manager instance is nullptr.");
11403         return ERR_INVALID_VALUE;
11404     }
11405     callbackDeathMgr->CallAssertFaultCallback(assertFaultSessionId, userStatus);
11406     return ERR_OK;
11407 }
11408 
UpdateSessionInfoBySCB(std::list<SessionInfo> & sessionInfos,int32_t userId,std::vector<int32_t> & sessionIds)11409 int32_t AbilityManagerService::UpdateSessionInfoBySCB(std::list<SessionInfo> &sessionInfos, int32_t userId,
11410     std::vector<int32_t> &sessionIds)
11411 {
11412     if (!IsCallerSceneBoard()) {
11413         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
11414         return ERR_WRONG_INTERFACE_CALL;
11415     }
11416     TAG_LOGI(AAFwkTag::ABILITYMGR, "The sceneboard is being restored.");
11417     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11418     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11419     return uiAbilityManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds);
11420 }
11421 
CheckSenderWantInfo(int32_t callerUid,const WantSenderInfo & wantSenderInfo)11422 bool AbilityManagerService::CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)
11423 {
11424     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
11425         auto bms = GetBundleManager();
11426         CHECK_POINTER_AND_RETURN(bms, false);
11427 
11428         std::string bundleName;
11429         if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
11430             TAG_LOGE(AAFwkTag::ABILITYMGR, "Get Bundle Name failed.");
11431             return false;
11432         }
11433         if (wantSenderInfo.bundleName != bundleName) {
11434             TAG_LOGE(AAFwkTag::ABILITYMGR, "wantSender bundleName check failed");
11435             return false;
11436         }
11437     }
11438     return true;
11439 }
11440 
CheckCallerIsDmsProcess()11441 bool AbilityManagerService::CheckCallerIsDmsProcess()
11442 {
11443     Security::AccessToken::NativeTokenInfo nativeTokenInfo;
11444     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
11445     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
11446     int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
11447     if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
11448         result != ERR_OK || nativeTokenInfo.processName != DMS_PROCESS_NAME) {
11449         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not dms");
11450         return false;
11451     }
11452     return true;
11453 }
11454 
GenerateEmbeddableUIAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)11455 int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest(
11456     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
11457 {
11458     int32_t screenMode = want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
11459     int32_t result = ERR_OK;
11460     if (screenMode == AAFwk::EMBEDDED_FULL_SCREEN_MODE) {
11461         result = GenerateAbilityRequest(want, -1, request, callerToken, userId);
11462         request.abilityInfo.isModuleJson = true;
11463         request.abilityInfo.isStageBasedModel = true;
11464         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
11465         request.abilityInfo.extensionAbilityType = AppExecFwk::ExtensionAbilityType::UI;
11466         struct timespec time = {0, 0};
11467         clock_gettime(CLOCK_MONOTONIC, &time);
11468         int64_t times = static_cast<int64_t>(time.tv_sec);
11469         request.abilityInfo.process = request.abilityInfo.bundleName + PROCESS_SUFFIX + std::to_string(times);
11470     } else {
11471         result = GenerateExtensionAbilityRequest(want, request, callerToken, userId);
11472     }
11473     return result;
11474 }
11475 
WaitBootAnimationStart()11476 void AbilityManagerService::WaitBootAnimationStart()
11477 {
11478     char value[BOOTEVENT_BOOT_ANIMATION_READY_SIZE] = "";
11479     int32_t ret = GetParameter(BOOTEVENT_BOOT_ANIMATION_READY, "", value,
11480         BOOTEVENT_BOOT_ANIMATION_READY_SIZE);
11481     if (ret > 0 && !std::strcmp(value, "false")) {
11482         // Get new param success and new param is not ready, wait the new param.
11483         WaitParameter(BOOTEVENT_BOOT_ANIMATION_READY, "true",
11484             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11485     } else if (ret <= 0 || !std::strcmp(value, "")) {
11486         // Get new param failed or new param is not set, wait the old param.
11487         WaitParameter(BOOTEVENT_BOOT_ANIMATION_STARTED, "true",
11488             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11489     }
11490     // other, the animation is ready, not wait.
11491 }
11492 
GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,UIExtensionSessionInfo & uiExtensionSessionInfo,int32_t userId)11493 int32_t AbilityManagerService::GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,
11494     UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId)
11495 {
11496     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11497     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11498     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11499 
11500     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11501         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
11502         return ERR_PERMISSION_DENIED;
11503     }
11504 
11505     auto validUserId = GetValidUserId(userId);
11506     auto connectManager = GetConnectManagerByUserId(validUserId);
11507     if (connectManager == nullptr) {
11508         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11509         return ERR_INVALID_VALUE;
11510     }
11511 
11512     auto ret = connectManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo);
11513     if (ret != ERR_OK) {
11514         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get ui extension session info failed.");
11515         return ret;
11516     }
11517 
11518     return ERR_OK;
11519 }
11520 
RestartApp(const AAFwk::Want & want,bool isAppRecovery)11521 int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want, bool isAppRecovery)
11522 {
11523     TAG_LOGI(AAFwkTag::ABILITYMGR, "RestartApp, isAppRecovery: %{public}d", isAppRecovery);
11524     auto appIndex = GetAppIndex(want);
11525     int result = CheckRestartAppWant(want, appIndex);
11526     if (result != ERR_OK) {
11527         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckRestartAppWant error.");
11528         return result;
11529     }
11530 
11531     int32_t callerUid = IPCSkeleton::GetCallingUid();
11532     int64_t now = time(nullptr);
11533     if (!isAppRecovery && RestartAppManager::GetInstance().IsRestartAppFrequent(callerUid, now)) {
11534         return AAFwk::ERR_RESTART_APP_FREQUENT;
11535     }
11536 
11537     bool isForegroundToRestartApp = RestartAppManager::GetInstance().IsForegroundToRestartApp();
11538     if (!isForegroundToRestartApp) {
11539         TAG_LOGE(AAFwkTag::ABILITYMGR, "RestartApp, IsForegroundToRestartApp failed.");
11540         return AAFwk::NOT_TOP_ABILITY;
11541     }
11542 
11543     int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11544     result = SignRestartAppFlag(userId, callerUid, isAppRecovery);
11545     if (result != ERR_OK) {
11546         TAG_LOGE(AAFwkTag::ABILITYMGR, "SignRestartAppFlag error.");
11547         return result;
11548     }
11549     result = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->KillApplicationSelf(false, "RestartApp");
11550     if (result != ERR_OK) {
11551         TAG_LOGE(AAFwkTag::ABILITYMGR, "KillApplicationSelf error.");
11552         return result;
11553     }
11554 
11555     TAG_LOGD(AAFwkTag::ABILITYMGR, "RestartApp, start ability without CheckCallAbilityPermission.");
11556     (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
11557     result = StartAbilityWrap(want, nullptr,
11558         DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, 0, isForegroundToRestartApp);
11559     if (result != ERR_OK) {
11560         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility error.");
11561         return result;
11562     }
11563     if (!isAppRecovery) {
11564         RestartAppManager::GetInstance().AddRestartAppHistory(callerUid, now);
11565     }
11566     return result;
11567 }
11568 
GetAppIndex(const Want & want)11569 int32_t AbilityManagerService::GetAppIndex(const Want& want)
11570 {
11571     int32_t appIndex = want.GetIntParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, -1);
11572     if (appIndex == -1) {
11573         auto appMgr = AppMgrUtil::GetAppMgr();
11574         if (appMgr == nullptr) {
11575             TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
11576             return appIndex;
11577         }
11578         auto callingPid = IPCSkeleton::GetCallingPid();
11579         auto ret = IN_PROCESS_CALL(appMgr->GetAppIndexByPid(callingPid, appIndex));
11580         if (ret != ERR_OK) {
11581             TAG_LOGE(AAFwkTag::ABILITYMGR, "appMgr GetAppIndexByPid error");
11582         }
11583     }
11584     return appIndex;
11585 }
11586 
CheckRestartAppWant(const AAFwk::Want & want,int32_t appIndex)11587 int32_t AbilityManagerService::CheckRestartAppWant(const AAFwk::Want &want, int32_t appIndex)
11588 {
11589     std::string bundleName = want.GetElement().GetBundleName();
11590     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11591     if (!CheckCallingTokenId(bundleName, userId, appIndex)) {
11592         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not itself called, not allowed.");
11593         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11594     }
11595 
11596     auto bms = GetBundleManager();
11597     CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
11598     auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
11599     AppExecFwk::AbilityInfo abilityInfo;
11600     auto queryResult = IN_PROCESS_CALL(
11601         bms->QueryCloneAbilityInfo(want.GetElement(), abilityInfoFlag, appIndex, abilityInfo, userId));
11602     if (queryResult != ERR_OK || abilityInfo.name.empty() || abilityInfo.bundleName.empty() ||
11603         abilityInfo.type != AbilityType::PAGE) {
11604         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability is invalid or not UIAbility.");
11605         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11606     }
11607     return ERR_OK;
11608 }
11609 
SignRestartAppFlag(int32_t userId,int32_t uid,bool isAppRecovery)11610 int32_t AbilityManagerService::SignRestartAppFlag(int32_t userId, int32_t uid, bool isAppRecovery)
11611 {
11612     auto appMgr = GetAppMgr();
11613     if (appMgr == nullptr) {
11614         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
11615         return ERR_INVALID_VALUE;
11616     }
11617     auto ret = IN_PROCESS_CALL(appMgr->SignRestartAppFlag(uid));
11618     if (ret != ERR_OK) {
11619         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppMgr SignRestartAppFlag error");
11620         return ret;
11621     }
11622 
11623     auto connectManager = GetConnectManagerByUserId(userId);
11624     connectManager->SignRestartAppFlag(uid);
11625     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11626         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
11627         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11628         uiAbilityManager->SignRestartAppFlag(uid, isAppRecovery);
11629         return ERR_OK;
11630     }
11631     auto missionListManager = GetMissionListManagerByUserId(userId);
11632     if (missionListManager == nullptr) {
11633         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is nullptr. userId:%{public}d", userId);
11634         return ERR_INVALID_VALUE;
11635     }
11636     missionListManager->SignRestartAppFlag(uid);
11637     return ERR_OK;
11638 }
11639 
GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,UIExtensionHostInfo & hostInfo,int32_t userId)11640 int32_t AbilityManagerService::GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,
11641     UIExtensionHostInfo &hostInfo, int32_t userId)
11642 {
11643     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11644     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11645     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11646 
11647     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11648         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
11649         return ERR_PERMISSION_DENIED;
11650     }
11651 
11652     auto callerRecord = GetUIExtensionRootCaller(token, userId);
11653     if (callerRecord == nullptr) {
11654         TAG_LOGE(AAFwkTag::UI_EXT, "Get root host info failed.");
11655         return ERR_INVALID_VALUE;
11656     }
11657 
11658     hostInfo.elementName_ = callerRecord->GetElementName();
11659     TAG_LOGD(AAFwkTag::UI_EXT, "Root host uri: %{public}s.", hostInfo.elementName_.GetURI().c_str());
11660     return ERR_OK;
11661 }
11662 
GetUIExtensionRootCaller(const sptr<IRemoteObject> token,int32_t userId)11663 std::shared_ptr<AbilityRecord> AbilityManagerService::GetUIExtensionRootCaller(const sptr<IRemoteObject> token,
11664     int32_t userId)
11665 {
11666     auto validUserId = GetValidUserId(userId);
11667     auto connectManager = GetConnectManagerByUserId(validUserId);
11668     if (connectManager == nullptr) {
11669         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11670         return nullptr;
11671     }
11672 
11673     auto callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11674     if (callerRecord == nullptr && validUserId != U0_USER_ID) {
11675         connectManager = GetConnectManagerByUserId(U0_USER_ID);
11676         if (connectManager == nullptr) {
11677             TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", U0_USER_ID);
11678             return nullptr;
11679         }
11680         callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11681     }
11682 
11683     return callerRecord;
11684 }
11685 
IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken,const std::string & appId)11686 bool AbilityManagerService::IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken, const std::string &appId)
11687 {
11688     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11689     if (!AppUtils::GetInstance().IsLaunchEmbededUIAbility()) {
11690         TAG_LOGE(AAFwkTag::ABILITYMGR, "device type is not allowd.");
11691         return false;
11692     }
11693     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
11694     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
11695     if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
11696         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is not hap.");
11697         return false;
11698     }
11699     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11700     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11701     auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
11702     if (callerAbility == nullptr) {
11703         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is invalid.");
11704         return false;
11705     }
11706     if (callerAbility->GetApplicationInfo().accessTokenId != accessTokenId) {
11707         TAG_LOGE(AAFwkTag::ABILITYMGR, "The callerToken does not belong to the caller.");
11708         return false;
11709     }
11710     if (!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag()) {
11711         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller not foreground.");
11712         return false;
11713     }
11714     std::string bundleName = ATOMIC_SERVICE_PREFIX + appId;
11715     Want want;
11716     want.SetBundle(bundleName);
11717     want.SetParam("send_to_erms_embedded", 1);
11718     int32_t ret = freeInstallManager_->StartFreeInstall(want, GetUserId(), 0, callerToken, false);
11719     if (ret != ERR_OK) {
11720         TAG_LOGE(AAFwkTag::ABILITYMGR, "The target is not allowed to free install.");
11721         return false;
11722     }
11723     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
11724     auto erms = std::make_shared<EcologicalRuleInterceptor>();
11725     return erms->DoProcess(want, GetUserId());
11726 }
11727 
ShouldPreventStartAbility(const AbilityRequest & abilityRequest)11728 bool AbilityManagerService::ShouldPreventStartAbility(const AbilityRequest &abilityRequest)
11729 {
11730     std::shared_ptr<AbilityRecord> abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11731     if (abilityRecord == nullptr) {
11732         TAG_LOGD(AAFwkTag::ABILITYMGR, "No matched token pass");
11733         return false;
11734     }
11735     auto abilityInfo = abilityRequest.abilityInfo;
11736     auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
11737     PrintStartAbilityInfo(callerAbilityInfo, abilityInfo);
11738     if (abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD < API12) {
11739         TAG_LOGD(AAFwkTag::ABILITYMGR, "API version %{public}d pass",
11740             abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD);
11741         return false;
11742     }
11743     bool continuousFlag = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
11744     if (abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::DATASHARE &&
11745         abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
11746         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process did not call service or datashare extension Pass");
11747         return false;
11748     }
11749     if (abilityInfo.applicationInfo.uid == IPCSkeleton::GetCallingUid()) {
11750         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in same bundle Pass");
11751         return false;
11752     }
11753     if (callerAbilityInfo.type != AppExecFwk::AbilityType::PAGE) {
11754         TAG_LOGD(AAFwkTag::ABILITYMGR, "Is not UI Ability Pass");
11755         return false;
11756     }
11757     if (abilityRecord->GetAbilityState() != AAFwk::AbilityState::BACKGROUND) {
11758         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is not on background Pass");
11759         return false;
11760     }
11761     if (continuousFlag) {
11762         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has continuous task Pass");
11763         return false;
11764     }
11765     if (IsInWhiteList(callerAbilityInfo.bundleName, abilityInfo.bundleName, abilityInfo.name)) {
11766         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in white list Pass");
11767         return false;
11768     }
11769     if(!IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->
11770         IsProcessContainsOnlyUIAbility(abilityRecord->GetPid()))) {
11771         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has other extension except UIAbility, pass");
11772         return false;
11773     }
11774     TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension %{public}s.",
11775         abilityRecord->GetURI().c_str());
11776     ReportPreventStartAbilityResult(callerAbilityInfo, abilityInfo);
11777     return true;
11778 }
11779 
PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo,AppExecFwk::AbilityInfo calledInfo)11780 void AbilityManagerService::PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo, AppExecFwk::AbilityInfo calledInfo)
11781 {
11782     TAG_LOGD(AAFwkTag::ABILITYMGR, "calledAbilityInfo toString: "
11783         "calledUid is: %{public}d, "
11784         "name is: %{public}s, "
11785         "bundleName is: %{public}s, "
11786         "type is: %{public}d, "
11787         "extensionAbilityType is: %{public}d, "
11788         "moduleName is: %{public}s, "
11789         "applicationName is: %{public}s",
11790         calledInfo.applicationInfo.uid,
11791         calledInfo.name.c_str(),
11792         calledInfo.bundleName.c_str(),
11793         static_cast<int32_t>(calledInfo.type),
11794         static_cast<int32_t>(calledInfo.extensionAbilityType),
11795         calledInfo.moduleName.c_str(),
11796         calledInfo.applicationName.c_str());
11797 
11798 
11799     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerAbilityInfo toString: "
11800         "callerUid is: %{public}d, "
11801         "callerPid is: %{public}d, "
11802         "name is: %{public}s, "
11803         "bundleName is: %{public}s, "
11804         "type is: %{public}d, "
11805         "extensionAbilityType is: %{public}d, "
11806         "moduleName is: %{public}s, "
11807         "applicationName is: %{public}s",
11808         IPCSkeleton::GetCallingUid(),
11809         IPCSkeleton::GetCallingPid(),
11810         callerInfo.name.c_str(),
11811         callerInfo.bundleName.c_str(),
11812         static_cast<int32_t>(callerInfo.type),
11813         static_cast<int32_t>(callerInfo.extensionAbilityType),
11814         callerInfo.moduleName.c_str(),
11815         callerInfo.applicationName.c_str());
11816 }
11817 
ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo & callerAbilityInfo,const AppExecFwk::AbilityInfo & abilityInfo)11818 void AbilityManagerService::ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo,
11819     const AppExecFwk::AbilityInfo &abilityInfo)
11820 {
11821     int32_t callerUid = IPCSkeleton::GetCallingUid();
11822     int32_t callerPid = IPCSkeleton::GetCallingPid();
11823     int32_t extensionAbilityType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
11824     TAG_LOGD(AAFwkTag::ABILITYMGR,
11825         "Prevent start ability debug log CALLER_BUNDLE_NAME %{public}s CALLEE_BUNDLE_NAME"
11826         "%{public}s ABILITY_NAME %{public}s",
11827         callerAbilityInfo.bundleName.c_str(), abilityInfo.name.c_str(), abilityInfo.name.c_str());
11828     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "PREVENT_START_ABILITY", HiSysEvent::EventType::BEHAVIOR,
11829         "CALLER_UID", callerUid,
11830         "CALLER_PID", callerPid,
11831         "CALLER_PROCESS_NAME", callerAbilityInfo.process,
11832         "CALLER_BUNDLE_NAME", callerAbilityInfo.bundleName,
11833         "CALLEE_BUNDLE_NAME", abilityInfo.bundleName,
11834         "CALLEE_PROCESS_NAME", abilityInfo.process,
11835         "EXTENSION_ABILITY_TYPE", extensionAbilityType,
11836         "ABILITY_NAME", abilityInfo.name);
11837 }
11838 
IsInWhiteList(const std::string & callerBundleName,const std::string & calleeBundleName,const std::string & calleeAbilityName)11839 bool AbilityManagerService::IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName,
11840     const std::string &calleeAbilityName)
11841 {
11842     std::lock_guard<std::mutex> locker(whiteListMutex_);
11843     std::map<std::string, std::list<std::string>>::iterator iter = whiteListMap_.find(callerBundleName);
11844     std::string uri = calleeBundleName + "/" + calleeAbilityName;
11845     if (iter != whiteListMap_.end()) {
11846         if (std::find(std::begin(iter->second), std::end(iter->second), uri) != std::end(iter->second)) {
11847             return true;
11848         }
11849     }
11850     std::list<std::string>::iterator it = std::find(exportWhiteList_.begin(), exportWhiteList_.end(), uri);
11851     if (it != exportWhiteList_.end()) {
11852         return true;
11853     }
11854     return false;
11855 }
11856 
ParseJsonFromBoot(const std::string & relativePath)11857 bool AbilityManagerService::ParseJsonFromBoot(const std::string &relativePath)
11858 {
11859     nlohmann::json jsonObj;
11860     std::string absolutePath = GetConfigFileAbsolutePath(relativePath);
11861     if (ParseJsonValueFromFile(jsonObj, absolutePath) != ERR_OK) {
11862         return false;
11863     }
11864     std::lock_guard<std::mutex> locker(whiteListMutex_);
11865     nlohmann::json whiteListJsonList = jsonObj[WHITE_LIST];
11866     for (const auto& [key, value] : whiteListJsonList.items()) {
11867         if (!value.is_array()) {
11868             continue;
11869         }
11870         whiteListMap_.emplace(key, std::list<std::string>());
11871         for (const auto& it : value) {
11872             if (it.is_string()) {
11873                 whiteListMap_[key].push_back(it);
11874             }
11875         }
11876     }
11877     if (!jsonObj.contains("exposed_white_list")) {
11878         return false;
11879     }
11880     nlohmann::json exportWhiteJsonList = jsonObj["exposed_white_list"];
11881     for (const auto& it : exportWhiteJsonList) {
11882         if (it.is_string()) {
11883             exportWhiteList_.push_back(it);
11884         }
11885     }
11886     return true;
11887 }
11888 
GetConfigFileAbsolutePath(const std::string & relativePath)11889 std::string AbilityManagerService::GetConfigFileAbsolutePath(const std::string &relativePath)
11890 {
11891     if (relativePath.empty()) {
11892         TAG_LOGE(AAFwkTag::ABILITYMGR, "relativePath is empty");
11893         return "";
11894     }
11895     char buf[PATH_MAX];
11896     char *tmpPath = GetOneCfgFile(relativePath.c_str(), buf, PATH_MAX);
11897     char absolutePath[PATH_MAX] = {0};
11898     if (!tmpPath || strlen(tmpPath) > PATH_MAX || !realpath(tmpPath, absolutePath)) {
11899         TAG_LOGE(AAFwkTag::ABILITYMGR, "get file fail.");
11900         return "";
11901     }
11902     return std::string(absolutePath);
11903 }
11904 
ParseJsonValueFromFile(nlohmann::json & value,const std::string & filePath)11905 int32_t AbilityManagerService::ParseJsonValueFromFile(nlohmann::json &value, const std::string &filePath)
11906 {
11907     std::ifstream fin;
11908     std::string realPath;
11909     if (!ConvertFullPath(filePath, realPath)) {
11910         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get real path failed");
11911         return ERR_INVALID_VALUE;
11912     }
11913     fin.open(realPath, std::ios::in);
11914     if (!fin.is_open()) {
11915         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot open file %{private}s", realPath.c_str());
11916         return ERR_INVALID_VALUE;
11917     }
11918     char buffer[MAX_BUFFER];
11919     std::ostringstream os;
11920     while (fin.getline(buffer, MAX_BUFFER)) {
11921         os << buffer;
11922     }
11923     const std::string data = os.str();
11924     value = nlohmann::json::parse(data, nullptr, false);
11925     if (value.is_discarded()) {
11926         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed due to data is discarded");
11927         return ERR_INVALID_VALUE;
11928     }
11929     return ERR_OK;
11930 }
11931 
ConvertFullPath(const std::string & partialPath,std::string & fullPath)11932 bool AbilityManagerService::ConvertFullPath(const std::string& partialPath, std::string& fullPath)
11933 {
11934     if (partialPath.empty() || partialPath.length() >= PATH_MAX) {
11935         return false;
11936     }
11937     char tmpPath[PATH_MAX] = {0};
11938     if (realpath(partialPath.c_str(), tmpPath) == nullptr) {
11939         return false;
11940     }
11941     fullPath = tmpPath;
11942     return true;
11943 }
11944 
StartShortcut(const Want & want,const StartOptions & startOptions)11945 int32_t AbilityManagerService::StartShortcut(const Want &want, const StartOptions &startOptions)
11946 {
11947     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11948     if (!PermissionVerification::GetInstance()->IsSystemAppCall()) {
11949         TAG_LOGE(AAFwkTag::ABILITYMGR, "non-system app calling system api.");
11950         return ERR_NOT_SYSTEM_APP;
11951     }
11952     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
11953         PermissionConstants::PERMISSION_START_SHORTCUT)) {
11954         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
11955             PermissionConstants::PERMISSION_START_SHORTCUT);
11956         return ERR_PERMISSION_DENIED;
11957     }
11958     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
11959     return StartUIAbilityForOptionWrap(want, startOptions, nullptr, false, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE,
11960         0, false, true);
11961 }
11962 
GetAbilityStateByPersistentId(int32_t persistentId,bool & state)11963 int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentId, bool &state)
11964 {
11965     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11966     if (!CheckCallerIsDmsProcess()) {
11967         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetAbilityStateByPersistentId, caller is not dms.");
11968         return ERR_PERMISSION_DENIED;
11969     }
11970 
11971     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11972         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11973         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11974         return uiAbilityManager->GetAbilityStateByPersistentId(persistentId, state);
11975     }
11976     TAG_LOGE(AAFwkTag::ABILITYMGR, "GetAbilityStateByPersistentId, mission not have persistent id.");
11977     return INNER_ERR;
11978 }
11979 
TransferAbilityResultForExtension(const sptr<IRemoteObject> & callerToken,int32_t resultCode,const Want & want)11980 int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptr<IRemoteObject> &callerToken,
11981     int32_t resultCode, const Want &want)
11982 {
11983     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11984     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
11985     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
11986     if (!JudgeSelfCalled(abilityRecord)) {
11987         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller mismatch.");
11988         return ERR_INVALID_VALUE;
11989     }
11990     auto type = abilityRecord->GetAbilityInfo().type;
11991     if (type != AppExecFwk::AbilityType::EXTENSION) {
11992         TAG_LOGE(AAFwkTag::ABILITYMGR, "type is not uiextension.");
11993         return ERR_INVALID_VALUE;
11994     }
11995     // save result to caller AbilityRecord.
11996     Want* newWant = const_cast<Want*>(&want);
11997     newWant->RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
11998     abilityRecord->SaveResultToCallers(resultCode, newWant);
11999     abilityRecord->SendResultToCallers();
12000     return ERR_OK;
12001 }
12002 
GetRunningMultiAppIndex(const std::string & bundleName,int32_t uid,int32_t & appIndex)12003 void AbilityManagerService::GetRunningMultiAppIndex(const std::string &bundleName, int32_t uid, int32_t &appIndex)
12004 {
12005     AppExecFwk::RunningMultiAppInfo runningMultiAppInfo;
12006     auto appMgr = GetAppMgr();
12007     if (appMgr == nullptr) {
12008         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
12009         return;
12010     }
12011     auto ret = IN_PROCESS_CALL(appMgr->GetRunningMultiAppInfoByBundleName(bundleName, runningMultiAppInfo));
12012     if (ret != ERR_OK) {
12013         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetRunningMultiAppInfo failed bundleName = %{public}s",
12014             bundleName.c_str());
12015     }
12016     for (auto &item : runningMultiAppInfo.runningAppClones) {
12017         if (item.uid == uid) {
12018             appIndex = item.appCloneIndex;
12019             break;
12020         }
12021     }
12022 }
12023 
NotifyFrozenProcessByRSS(const std::vector<int32_t> & pidList,int32_t uid)12024 void AbilityManagerService::NotifyFrozenProcessByRSS(const std::vector<int32_t> &pidList, int32_t uid)
12025 {
12026     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(RSS_PROCESS_NAME)) {
12027         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not RSS.");
12028         return;
12029     }
12030     auto userId = uid / BASE_USER_RANGE;
12031     auto connectManager = GetConnectManagerByUserId(userId);
12032     CHECK_POINTER_LOG(connectManager, "can not find user connect manager");
12033     connectManager->HandleProcessFrozen(pidList, uid);
12034 }
12035 
HandleRestartResidentProcessDependedOnWeb()12036 void AbilityManagerService::HandleRestartResidentProcessDependedOnWeb()
12037 {
12038     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
12039     auto appMgr = GetAppMgr();
12040     CHECK_POINTER_LOG(appMgr, "get appMgr fail");
12041     appMgr->RestartResidentProcessDependedOnWeb();
12042 }
12043 
PreStartMission(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & startTime)12044 int32_t AbilityManagerService::PreStartMission(const std::string& bundleName, const std::string& moduleName,
12045     const std::string& abilityName, const std::string& startTime)
12046 {
12047     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12048     CHECK_CALLER_IS_SYSTEM_APP;
12049 
12050     if (!PermissionVerification::GetInstance()->VerifyPreStartAtomicServicePermission()) {
12051         TAG_LOGE(AAFwkTag::ABILITYMGR, "calling user is not ag.");
12052         return ERR_PERMISSION_DENIED;
12053     }
12054 
12055     if (!freeInstallManager_) {
12056         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
12057         return ERR_INVALID_VALUE;
12058     }
12059 
12060     FreeInstallInfo taskInfo;
12061     if (!freeInstallManager_->GetFreeInstallTaskInfo(bundleName, abilityName, startTime, taskInfo)) {
12062         TAG_LOGE(AAFwkTag::ABILITYMGR,
12063             "failed to find free install task info:bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
12064             bundleName.c_str(), abilityName.c_str(), startTime.c_str());
12065         return ERR_FREE_INSTALL_TASK_NOT_EXIST;
12066     }
12067 
12068     if (taskInfo.isFreeInstallFinished) {
12069         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install is finished.");
12070         if (!taskInfo.isInstalled) {
12071             TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
12072                 taskInfo.resultCode);
12073         } else {
12074             TAG_LOGI(AAFwkTag::ABILITYMGR, "free install has succeeded.");
12075         }
12076         // if free install is already finished then either the window is opened (on success)
12077         // or the user is informed of the error (on failure).
12078         return taskInfo.resultCode;
12079     }
12080 
12081     return PreStartInner(taskInfo);
12082 }
12083 
PreStartInner(const FreeInstallInfo & taskInfo)12084 int32_t AbilityManagerService::PreStartInner(const FreeInstallInfo& taskInfo)
12085 {
12086     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12087 
12088     const Want& want = taskInfo.want;
12089     sptr<IRemoteObject> callerToken = taskInfo.callerToken;
12090 
12091     EventInfo eventInfo = BuildEventInfo(want, taskInfo.userId);
12092     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12093 
12094     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
12095         eventInfo.errCode = ERR_INVALID_VALUE;
12096         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
12097         return ERR_INVALID_CALLER;
12098     }
12099 
12100     int32_t oriValidUserId = GetValidUserId(taskInfo.userId);
12101 
12102     int32_t appIndex = 0;
12103     StartAbilityInfoWrap threadLocalInfo(want, oriValidUserId,
12104         StartAbilityUtils::GetAppIndex(want, callerToken, appIndex), callerToken);
12105 
12106     AbilityRequest abilityRequest = {
12107         .want = want,
12108         .requestCode = taskInfo.requestCode,
12109         .callerToken = callerToken,
12110         .startSetting = nullptr
12111     };
12112 
12113     TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
12114     UpdateCallerInfo(abilityRequest.want, callerToken);
12115 
12116     // sceneboard
12117     abilityRequest.userId = oriValidUserId;
12118     abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
12119     std::string sessionId = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
12120         std::chrono::system_clock::now().time_since_epoch()).count());
12121     abilityRequest.want.SetParam(KEY_SESSION_ID, sessionId);
12122     auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
12123     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12124     sptr<SessionInfo> sessionInfo = nullptr;
12125     auto errCode = uiAbilityManager->NotifySCBToPreStartUIAbility(abilityRequest, sessionInfo);
12126     if (errCode != ERR_OK) {
12127         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to notify sceneboard to pre-start uiability.");
12128         return errCode;
12129     }
12130     freeInstallManager_->SetFreeInstallTaskSessionId(taskInfo.want.GetElement().GetBundleName(),
12131         taskInfo.want.GetElement().GetAbilityName(),
12132         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), sessionId);
12133 
12134     freeInstallManager_->SetPreStartMissionCallStatus(taskInfo.want.GetElement().GetBundleName(),
12135         taskInfo.want.GetElement().GetAbilityName(),
12136         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME),
12137         true);
12138     return ERR_OK;
12139 }
12140 
StartUIAbilityByPreInstall(const FreeInstallInfo & taskInfo)12141 int32_t AbilityManagerService::StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo)
12142 {
12143     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12144     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12145     if (!taskInfo.isFreeInstallFinished || !taskInfo.isInstalled) {
12146         TAG_LOGE(AAFwkTag::ABILITYMGR, "free install is not finished or has failed.");
12147         return ERR_INVALID_VALUE;
12148     }
12149     if (!taskInfo.isStartUIAbilityBySCBCalled) {
12150         TAG_LOGI(AAFwkTag::ABILITYMGR, "Free install is finished, StartUIAbilityBySCB has not been called");
12151         return ERR_OK;
12152     }
12153 
12154     const auto& want = taskInfo.want;
12155     auto sessionId = want.GetStringParam(KEY_SESSION_ID);
12156     if (sessionId.empty()) {
12157         TAG_LOGE(AAFwkTag::ABILITYMGR, "session id is empty.");
12158         return ERR_INVALID_VALUE;
12159     }
12160     auto bundleName = want.GetElement().GetBundleName();
12161     auto abilityName = want.GetElement().GetAbilityName();
12162     auto startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME);
12163     TAG_LOGI(AAFwkTag::ABILITYMGR, "called"
12164         "sessionId=%{public}s,bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
12165         sessionId.c_str(), bundleName.c_str(), abilityName.c_str(), startTime.c_str());
12166     sptr<SessionInfo> sessionInfo = nullptr;
12167     {
12168         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12169         auto it = preStartSessionMap_.find(sessionId);
12170         if (it == preStartSessionMap_.end()) {
12171             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s",
12172                 sessionId.c_str());
12173             return ERR_INVALID_VALUE;
12174         }
12175         sessionInfo = it->second;
12176         (sessionInfo->want).SetElement(want.GetElement());
12177     }
12178 
12179     if (sessionInfo == nullptr || sessionInfo->isMinimizedDuringFreeInstall) {
12180         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr or ability is already minimized");
12181         return ATOMIC_SERVICE_MINIMIZED;
12182     }
12183 
12184     bool isColdStart = true;
12185     int errCode = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, 0, isColdStart);
12186     if (errCode != ERR_OK) {
12187         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilityByPreInstallInner failed,errCode=%{public}d.", errCode);
12188         return errCode;
12189     }
12190     RemovePreStartSession(sessionId);
12191     return errCode;
12192 }
12193 
12194 // StartUIAbilityByPreInstallInner is called when free install task is already finished
StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo,uint32_t specifyTokenId,uint32_t sceneFlag,bool & isColdStart)12195 int AbilityManagerService::StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo, uint32_t specifyTokenId,
12196     uint32_t sceneFlag, bool &isColdStart)
12197 {
12198     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12199     auto callerToken = sessionInfo->callerToken;
12200     const auto& want = sessionInfo->want;
12201     const auto userId = sessionInfo->userId;
12202     const auto requestCode = sessionInfo->requestCode;
12203     bool isStartAsCaller = false;
12204 
12205     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
12206         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
12207             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
12208         if (!isSpecificSA) {
12209             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
12210             return ERR_INVALID_CALLER;
12211         }
12212         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__);
12213     }
12214 
12215     int32_t oriValidUserId = GetValidUserId(userId);
12216     int32_t validUserId = oriValidUserId;
12217 
12218     int32_t appIndex = 0;
12219     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
12220         return ERR_APP_CLONE_INDEX_INVALID;
12221     }
12222     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
12223     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
12224         true, nullptr);
12225     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
12226         interceptorExecuter_->DoProcess(interceptorParam);
12227     if (result != ERR_OK) {
12228         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
12229         return result;
12230     }
12231 
12232     AbilityRequest abilityRequest;
12233     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
12234     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
12235     std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
12236 
12237     if (result != ERR_OK) {
12238         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
12239         return result;
12240     }
12241 
12242     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
12243         UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
12244     } else if (!isStartAsCaller) {
12245         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
12246         UpdateCallerInfo(abilityRequest.want, callerToken);
12247     } else if (callerBundleName == BUNDLE_NAME_DIALOG) {
12248 #ifdef SUPPORT_SCREEN
12249         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
12250         implicitStartProcessor_->ResetCallingIdentityAsCaller(
12251             abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), true);
12252 #endif // SUPPORT_SCREEN
12253     }
12254 
12255     auto abilityInfo = abilityRequest.abilityInfo;
12256     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
12257     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
12258         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
12259 
12260     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
12261         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false);
12262     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
12263         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
12264         return ERR_STATIC_CFG_PERMISSION;
12265     }
12266 
12267     result = CheckCallPermission(want, abilityInfo, abilityRequest, false,
12268         false, specifyTokenId, callerBundleName);
12269     if (result != ERR_OK) {
12270         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallPermission error, result is %{public}d.", result);
12271         return result;
12272     }
12273 
12274     Want newWant = abilityRequest.want;
12275     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
12276         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
12277     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
12278         afterCheckExecuter_->DoProcess(afterCheckParam);
12279     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
12280     newWant.RemoveParam("queryWantFromErms");
12281     if (result != ERR_OK && isReplaceWantExist == false) {
12282         TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
12283         return result;
12284     }
12285 #ifdef SUPPORT_SCREEN
12286     if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
12287         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
12288     }
12289     if (result == ERR_OK &&
12290         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
12291         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
12292         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
12293     }
12294 #endif // SUPPORT_SCREEN
12295 
12296     if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
12297         abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
12298         return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
12299     }
12300 
12301     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
12302         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s.", abilityInfo.bundleName.c_str());
12303         return ERR_WOULD_BLOCK;
12304     }
12305 
12306     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
12307     if (specifyTokenId > 0) {
12308         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
12309         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
12310         abilityRequest.specifyTokenId = specifyTokenId;
12311     }
12312     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
12313 
12314     auto uiAbilityManager = GetCurrentUIAbilityManager();
12315     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12316 
12317     return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
12318 }
12319 
NotifySCBToHandleAtomicServiceException(const std::string & sessionId,int32_t errCode,const std::string & reason)12320 void AbilityManagerService::NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode,
12321     const std::string& reason)
12322 {
12323     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12324     sptr<SessionInfo> sessionInfo = nullptr;
12325     {
12326         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12327         auto it = preStartSessionMap_.find(sessionId);
12328         if (it == preStartSessionMap_.end()) {
12329             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s",
12330                 sessionId.c_str());
12331             return;
12332         }
12333         sessionInfo = it->second;
12334         preStartSessionMap_.erase(it);
12335     }
12336     if (sessionInfo == nullptr) {
12337         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr.");
12338         return;
12339     }
12340     auto uiAbilityManager = GetCurrentUIAbilityManager();
12341     CHECK_POINTER(uiAbilityManager);
12342     return uiAbilityManager->NotifySCBToHandleAtomicServiceException(sessionInfo, errCode, reason);
12343 }
12344 
RemovePreStartSession(const std::string & sessionId)12345 void AbilityManagerService::RemovePreStartSession(const std::string& sessionId)
12346 {
12347     std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12348     preStartSessionMap_.erase(sessionId);
12349 }
12350 
OpenLink(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int requestCode)12351 ErrCode AbilityManagerService::OpenLink(const Want& want, sptr<IRemoteObject> callerToken,
12352     int32_t userId, int requestCode)
12353 {
12354     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12355     std::string url = want.GetUriString();
12356     bool isAtomicServiceShortUrl = false;
12357 #ifdef APP_DOMAIN_VERIFY_ENABLED
12358     isAtomicServiceShortUrl = AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->IsAtomicServiceUrl(url);
12359 #endif
12360     int32_t retCode = ERR_OK;
12361     if (!isAtomicServiceShortUrl) {
12362         TAG_LOGI(AAFwkTag::ABILITYMGR, "not atomic service short url, start ability by default.");
12363         retCode = StartAbility(want, callerToken, userId, requestCode);
12364         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12365         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12366     }
12367 
12368     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
12369     Want convertedWant = want;
12370     retCode = ConvertToExplicitWant(convertedWant);
12371     if (retCode != ERR_OK) {
12372         TAG_LOGI(AAFwkTag::ABILITYMGR, "failed to convert to explicit want, start ability by default.");
12373         retCode = StartAbility(want, callerToken, userId, requestCode);
12374         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12375         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12376     }
12377 
12378     if (!freeInstallManager_) {
12379         TAG_LOGW(AAFwkTag::ABILITYMGR, "free install manager is nullptr, start ability by default.");
12380         retCode = StartAbility(want, callerToken, userId, requestCode);
12381         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12382         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12383     }
12384 
12385     convertedWant.AddFlags(Want::FLAG_INSTALL_ON_DEMAND);
12386     TAG_LOGD(AAFwkTag::ABILITYMGR, "convertedWant=%{public}s", convertedWant.ToString().c_str());
12387     retCode = freeInstallManager_->StartFreeInstall(convertedWant, GetValidUserId(userId),
12388         requestCode, callerToken, true, 0, true, std::make_shared<Want>(want));
12389     if (retCode != ERR_OK) {
12390         TAG_LOGW(AAFwkTag::ABILITYMGR, "StartFreeInstall returns errCode=%{public}d.", retCode);
12391         if (retCode == NOT_TOP_ABILITY) {
12392             TAG_LOGE(AAFwkTag::ABILITYMGR, "start from background is not allowed.");
12393             return retCode;
12394         }
12395         TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default.");
12396         retCode = StartAbility(want, callerToken, userId, requestCode);
12397         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12398         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12399     }
12400     return ERR_OK;
12401 }
12402 
ConvertToExplicitWant(Want & want)12403 ErrCode AbilityManagerService::ConvertToExplicitWant(Want& want)
12404 {
12405     ErrCode retCode = ERR_OK;
12406 #ifdef APP_DOMAIN_VERIFY_ENABLED
12407     auto bundleMgrHelper = GetBundleManager();
12408     if (bundleMgrHelper == nullptr) {
12409         TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleMgrHelper is invalid.");
12410         return ERR_INVALID_VALUE;
12411     }
12412     int32_t callerUid = IPCSkeleton::GetCallingUid();
12413     std::string callerBundleName;
12414     retCode = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callerUid, callerBundleName));
12415     if (retCode != ERR_OK) {
12416         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callerBundleName failed,retCode=%{public}d.", retCode);
12417         return retCode;
12418     }
12419     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName=%{public}s.", callerBundleName.c_str());
12420     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
12421 
12422     bool isUsed = false;
12423     ffrt::condition_variable callbackDoneCv;
12424     ffrt::mutex callbackDoneMutex;
12425     ConvertCallbackTask task = [&retCode, &isUsed, &callbackDoneCv, &callbackDoneMutex,
12426         &convertedWant = want, this](int resultCode, AAFwk::Want& want) {
12427         TAG_LOGI(AAFwkTag::ABILITYMGR, "in convert callback task, resultCode=%{public}d,want=%{public}s",
12428             resultCode, want.ToString().c_str());
12429         retCode = resultCode;
12430         convertedWant = want;
12431         {
12432             std::lock_guard<ffrt::mutex> lock(callbackDoneMutex);
12433             isUsed = true;
12434         }
12435         TAG_LOGI(AAFwkTag::ABILITYMGR, "start to notify.");
12436         callbackDoneCv.notify_all();
12437         TAG_LOGI(AAFwkTag::ABILITYMGR, "convert callback task finished");
12438     };
12439     sptr<ConvertCallbackImpl> callbackTask = new ConvertCallbackImpl(std::move(task));
12440     sptr<OHOS::AppDomainVerify::IConvertCallback> callback = callbackTask;
12441     AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->ConvertToExplicitWant(want, callback);
12442     auto condition = [&isUsed] { return isUsed; };
12443     std::unique_lock<ffrt::mutex> lock(callbackDoneMutex);
12444     TAG_LOGI(AAFwkTag::ABILITYMGR, "start to wait for condition.");
12445     if (!callbackDoneCv.wait_for(lock, seconds(CONVERT_CALLBACK_TIMEOUT_SECONDS), condition)) {
12446         TAG_LOGE(AAFwkTag::ABILITYMGR, "convert callback timeout.");
12447         callbackTask->Cancel();
12448         retCode = ERR_TIMED_OUT;
12449     }
12450     TAG_LOGI(AAFwkTag::ABILITYMGR, "finish wait for condition.");
12451 #endif
12452     return retCode;
12453 }
12454 
SetAbilityRequestSessionInfo(AbilityRequest & abilityRequest,AppExecFwk::ExtensionAbilityType extensionType)12455 void AbilityManagerService::SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest, AppExecFwk::ExtensionAbilityType extensionType)
12456 {
12457     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12458     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
12459         return;
12460     }
12461 
12462     abilityRequest.want.RemoveParam(WANT_PARAMS_HOST_WINDOW_ID_KEY);
12463     auto callerAbilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
12464     CHECK_POINTER_LOG(callerAbilityRecord, "callerAbilityRecord is nullptr");
12465     sptr<SessionInfo> callerSessionInfo = callerAbilityRecord->GetSessionInfo();
12466     CHECK_POINTER_LOG(callerSessionInfo, "callerSessionInfo is nullptr");
12467 
12468     if (callerAbilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
12469         TAG_LOGI(AAFwkTag::ABILITYMGR, "UIAbility Caller");
12470         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, callerSessionInfo->persistentId);
12471     } else if (AAFwk::UIExtensionUtils::IsUIExtension(callerAbilityRecord->GetAbilityInfo().extensionAbilityType)) {
12472         int32_t mainWindowId = -1;
12473         auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().
12474             GetSceneSessionManagerLiteProxy();
12475         CHECK_POINTER_LOG(sceneSessionManager, "sceneSessionManager is nullptr");
12476         auto err = sceneSessionManager->GetRootMainWindowId(static_cast<int32_t>(callerSessionInfo->hostWindowId),mainWindowId);
12477         TAG_LOGI(AAFwkTag::ABILITYMGR, "callerSessionInfo->hostWindowId = %{public}d, mainWindowId = %{public}d, err = %{public}d",
12478             callerSessionInfo->hostWindowId, mainWindowId, err);
12479         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, mainWindowId);
12480     } else {
12481         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, 0);
12482     }
12483 }
12484 
CleanUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)12485 int32_t AbilityManagerService::CleanUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
12486 {
12487     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12488     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
12489         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is invalid.");
12490         return ERR_INVALID_VALUE;
12491     }
12492 
12493     if (!IsCallerSceneBoard()) {
12494         TAG_LOGE(AAFwkTag::ABILITYMGR, "only support sceneboard call.");
12495         return ERR_WRONG_INTERFACE_CALL;
12496     }
12497 
12498     SetMinimizedDuringFreeInstall(sessionInfo);
12499 
12500     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12501     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12502     TAG_LOGI(AAFwkTag::ABILITYMGR, "user request ot clean session: %{public}d.", sessionInfo->persistentId);
12503     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
12504     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
12505     int32_t errCode = uiAbilityManager->CleanUIAbility(abilityRecord);
12506     ReportCleanSession(sessionInfo, abilityRecord, errCode);
12507     return errCode;
12508 }
12509 
ForceTerminateSerivceExtensionByPid(int32_t pid,int32_t userId)12510 void AbilityManagerService::ForceTerminateSerivceExtensionByPid(int32_t pid, int32_t userId)
12511 {
12512     std::vector<sptr<IRemoteObject>> tokens;
12513     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppScheduler>::GetInstance()->GetAbilityRecordsByProcessID(
12514         pid, tokens));
12515     auto connectManager = GetConnectManagerByUserId(userId);
12516     if (connectManager) {
12517         for (const auto& token : tokens) {
12518             auto abilityRecord = Token::GetAbilityRecordByToken(token);
12519             if (abilityRecord &&
12520                 abilityRecord->GetAbilityInfo().extensionAbilityType ==
12521                 AppExecFwk::ExtensionAbilityType::SERVICE) {
12522                 TAG_LOGI(AAFwkTag::ABILITYMGR, "app ForceTerminateSerivceExtensionByPid, pid is %{public}d", pid);
12523                 connectManager->TerminateAbility(token);
12524             }
12525         }
12526     }
12527 }
12528 
ReportCleanSession(const sptr<SessionInfo> & sessionInfo,const std::shared_ptr<AbilityRecord> & abilityRecord,int32_t errCode)12529 void AbilityManagerService::ReportCleanSession(const sptr<SessionInfo> &sessionInfo,
12530     const std::shared_ptr<AbilityRecord> &abilityRecord, int32_t errCode)
12531 {
12532     if (!sessionInfo || !abilityRecord) {
12533         return;
12534     }
12535 
12536     const auto &abilityInfo = abilityRecord->GetAbilityInfo();
12537     std::string abilityName = abilityInfo.name;
12538     if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
12539         abilityName += std::to_string(sessionInfo->persistentId);
12540     }
12541     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
12542         DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
12543 
12544     EventInfo eventInfo;
12545     eventInfo.errCode = errCode;
12546     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
12547     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
12548     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12549     if (eventInfo.errCode != ERR_OK) {
12550         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
12551     }
12552 }
12553 
SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want,uint32_t specifyTokenId)12554 void AbilityManagerService::SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo& abilityInfo,
12555     const Want& want, uint32_t specifyTokenId)
12556 {
12557     if (abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
12558         abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
12559         EventInfo eventInfo;
12560         eventInfo.bundleName = abilityInfo.bundleName;
12561         eventInfo.moduleName = abilityInfo.moduleName;
12562         eventInfo.abilityName = abilityInfo.name;
12563         eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
12564         if (specifyTokenId > 0) {
12565             // come from want agent or form
12566             Security::AccessToken::HapTokenInfo hapInfo;
12567             if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(specifyTokenId, hapInfo) == ERR_OK) {
12568                 eventInfo.callerBundleName = hapInfo.bundleName;
12569             }
12570         } else {
12571             eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
12572             if (eventInfo.callerBundleName.empty()) {
12573                 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
12574             }
12575         }
12576         TAG_LOGI(AAFwkTag::ABILITYMGR,
12577             "SendStartAbilityOtherExtensionEvent, bundleName:%{public}s, extensionAbilityType:%{public}d",
12578             eventInfo.bundleName.c_str(), eventInfo.extensionType);
12579         EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
12580     }
12581 }
12582 
TerminateMission(int32_t missionId)12583 int32_t AbilityManagerService::TerminateMission(int32_t missionId)
12584 {
12585     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12586     TAG_LOGI(AAFwkTag::ABILITYMGR, "TerminateMission call");
12587     auto missionListManager = GetCurrentMissionListManager();
12588     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
12589     CHECK_CALLER_IS_SYSTEM_APP;
12590 
12591     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
12592         PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
12593         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
12594         return CHECK_PERMISSION_FAILED;
12595     }
12596 
12597     return missionListManager->ClearMission(missionId);
12598 }
12599 
EnableListForSCBRecovery(int32_t userId) const12600 void AbilityManagerService::EnableListForSCBRecovery(int32_t userId) const
12601 {
12602     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
12603     CHECK_POINTER_LOG(uiAbilityManager, "UIAbilityMgr not exist.");
12604     uiAbilityManager->EnableListForSCBRecovery();
12605 }
12606 
UpdateKeepAliveEnableState(const std::string & bundleName,const std::string & moduleName,const std::string & mainElement,bool updateEnable,int32_t userId)12607 int32_t AbilityManagerService::UpdateKeepAliveEnableState(const std::string &bundleName,
12608     const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId)
12609 {
12610     auto connectManager = GetConnectManagerByUserId(userId);
12611     CHECK_POINTER_AND_RETURN(connectManager, ERR_NULL_OBJECT);
12612     int32_t ret = connectManager->UpdateKeepAliveEnableState(bundleName, moduleName, mainElement, updateEnable);
12613     if (ret != ERR_OK) {
12614         TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateKeepAliveEnableState failed, err:%{public}d", ret);
12615     }
12616     return ret;
12617 }
12618 
UpdateAssociateConfigList(const std::map<std::string,std::list<std::string>> & configs,const std::list<std::string> & exportConfigs,int32_t flag)12619 int32_t AbilityManagerService::UpdateAssociateConfigList(const std::map<std::string, std::list<std::string>>& configs,
12620     const std::list<std::string>& exportConfigs, int32_t flag)
12621 {
12622     if (IPCSkeleton::GetCallingUid() != RESOURCE_SCHEDULE_UID) {
12623         TAG_LOGE(AAFwkTag::ABILITYMGR, "Update associate config, current process not rss process");
12624         return CHECK_PERMISSION_FAILED;
12625     }
12626     std::lock_guard<std::mutex> locker(whiteListMutex_);
12627     if (flag == UPDATE_CONFIG_FLAG_COVER) {
12628         whiteListMap_ = configs;
12629         exportWhiteList_ = exportConfigs;
12630     } else if (flag == UPDATE_CONFIG_FLAG_APPEND) {
12631         for (const auto& config : configs) {
12632             for (const auto& item : config.second) {
12633                 whiteListMap_[config.first].push_back(item);
12634             }
12635         }
12636         for (const auto& config : exportConfigs) {
12637             exportWhiteList_.push_back(config);
12638         }
12639     }
12640     return ERR_OK;
12641 }
12642 
StartSelfUIAbility(const Want & want)12643 int AbilityManagerService::StartSelfUIAbility(const Want &want)
12644 {
12645     TAG_LOGE(AAFwkTag::ABILITYMGR, "not supported");
12646     return ERR_CAPABILITY_NOT_SUPPORT;
12647 }
12648 
CheckCrossUser(const int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)12649 bool AbilityManagerService::CheckCrossUser(const int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
12650 {
12651     if (AAFwk::UIExtensionUtils::IsEnterpriseAdmin(extensionType) || JudgeMultiUserConcurrency(userId)) {
12652         return true;
12653     }
12654     if (AppUtils::GetInstance().IsConnectSupportCrossUser() && (extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE
12655         || extensionType == AppExecFwk::ExtensionAbilityType::SERVICE)) {
12656         return true;
12657     }
12658     return false;
12659 }
12660 
QueryPreLoadUIExtensionRecord(const AppExecFwk::ElementName & element,const std::string & moduleName,const std::string & hostBundleName,int32_t & recordNum,int32_t userId)12661 int32_t AbilityManagerService::QueryPreLoadUIExtensionRecord(const AppExecFwk::ElementName &element,
12662                                                              const std::string &moduleName,
12663                                                              const std::string &hostBundleName,
12664                                                              int32_t &recordNum,
12665                                                              int32_t userId)
12666 {
12667   // check preload ui extension permission.
12668   CHECK_CALLER_IS_SYSTEM_APP;
12669   if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
12670           PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
12671       TAG_LOGE(AAFwkTag::UI_EXT, "permission %{public}s verification failed",
12672                PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
12673       return ERR_PERMISSION_DENIED;
12674   }
12675   int32_t validUserId = GetValidUserId(userId);
12676   auto connectManager = GetConnectManagerByUserId(validUserId);
12677   if (!connectManager) {
12678       TAG_LOGE(AAFwkTag::UI_EXT, "connectManager null. userId=%{public}d", userId);
12679       return ERR_INVALID_VALUE;
12680   }
12681   return connectManager->QueryPreLoadUIExtensionRecordInner(
12682       element, moduleName, hostBundleName, recordNum);
12683 }
12684 }  // namespace AAFwk
12685 }  // namespace OHOS
12686