• 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 <sys/epoll.h>
19 
20 #include "ability_background_connection.h"
21 #include "ability_connect_manager.h"
22 #include "ability_manager_radar.h"
23 #include "ability_start_by_call_helper.h"
24 #include "accesstoken_kit.h"
25 #include "ability_manager_xcollie.h"
26 #include "app_utils.h"
27 #include "app_exit_reason_data_manager.h"
28 #include "application_util.h"
29 #include "app_mgr_util.h"
30 #include "recovery_info_timer.h"
31 #include "assert_fault_callback_death_mgr.h"
32 #include "concurrent_task_client.h"
33 #include "connection_state_manager.h"
34 #include "c/executor_task.h"
35 #include "display_manager.h"
36 #include "display_util.h"
37 #include "distributed_client.h"
38 #ifdef WITH_DLP
39 #include "dlp_utils.h"
40 #endif // WITH_DLP
41 #include "exit_info_data_manager.h"
42 #include "ffrt.h"
43 #include "ffrt_inner.h"
44 #include "freeze_util.h"
45 #include "global_constant.h"
46 #include "hitrace_meter.h"
47 #include "insight_intent_execute_manager.h"
48 #include "interceptor/ability_jump_interceptor.h"
49 #include "interceptor/block_all_app_start_interceptor.h"
50 #include "interceptor/control_interceptor.h"
51 #include "interceptor/crowd_test_interceptor.h"
52 #include "interceptor/disposed_rule_interceptor.h"
53 #include "interceptor/ecological_rule_interceptor.h"
54 #include "interceptor/extension_control_interceptor.h"
55 #include "interceptor/screen_unlock_interceptor.h"
56 #include "interceptor/start_other_app_interceptor.h"
57 #include "int_wrapper.h"
58 #include "ipc_skeleton.h"
59 #include "iservice_registry.h"
60 #include "keep_alive_process_manager.h"
61 #include "keep_alive_utils.h"
62 #include "mock_session_manager_service.h"
63 #include "modal_system_dialog/modal_system_dialog_ui_extension.h"
64 #include "modal_system_ui_extension.h"
65 #include "multi_app_utils.h"
66 #include "os_account_manager_wrapper.h"
67 #include "permission_constants.h"
68 #include "process_options.h"
69 #include "recovery_param.h"
70 #include "res_sched_util.h"
71 #include "restart_app_manager.h"
72 #include "scene_board_judgement.h"
73 #include "server_constant.h"
74 #include "session_manager_lite.h"
75 #include "softbus_bus_center.h"
76 #include "start_ability_handler/start_ability_sandbox_savefile.h"
77 #include "start_ability_utils.h"
78 #include "hidden_start_utils.h"
79 #include "startup_util.h"
80 #include "status_bar_delegate_interface.h"
81 #include "string_wrapper.h"
82 #include "ui_extension_utils.h"
83 #include "ui_service_extension_connection_constants.h"
84 #include "unlock_screen_manager.h"
85 #ifdef SUPPORT_UPMS
86 #include "uri_permission_manager_client.h"
87 #endif // SUPPORT_UPMS
88 #include "uri_utils.h"
89 #include "view_data.h"
90 #include "xcollie/watchdog.h"
91 #include "config_policy_utils.h"
92 #include "uri_utils.h"
93 #include "utils/ability_permission_util.h"
94 #include "utils/dump_utils.h"
95 #include "utils/extension_permissions_util.h"
96 #include "utils/modal_system_dialog_util.h"
97 #include "utils/update_caller_info_util.h"
98 #include "utils/want_utils.h"
99 #include "utils/window_options_utils.h"
100 #include "insight_intent_execute_manager.h"
101 #ifdef SUPPORT_GRAPHICS
102 #include "dialog_session_manager.h"
103 #include "application_anr_listener.h"
104 #include "input_manager.h"
105 #include "ability_first_frame_state_observer_manager.h"
106 #include "session_manager_lite.h"
107 #include "session/host/include/zidl/session_interface.h"
108 #include "window_focus_changed_listener.h"
109 #include "wm_common.h"
110 #endif
111 #include "query_erms_manager.h"
112 #include "window_visibility_changed_listener.h"
113 #ifdef SUPPORT_SCREEN
114 #include "utils/dms_util.h"
115 #endif
116 #include "hidden_start_observer_manager.h"
117 
118 using OHOS::AppExecFwk::ElementName;
119 using OHOS::Security::AccessToken::AccessTokenKit;
120 
121 namespace OHOS {
122 using AbilityRuntime::FreezeUtil;
123 using namespace AbilityRuntime::ServerConstant;
124 namespace AAFwk {
125 using AutoStartupInfo = AbilityRuntime::AutoStartupInfo;
126 using GetExtensionAbilityInfoFlag = AppExecFwk::GetExtensionAbilityInfoFlag;
127 namespace {
128 #define CHECK_CALLER_IS_SYSTEM_APP                                                             \
129     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
130         TAG_LOGE(AAFwkTag::ABILITYMGR,                                                         \
131         "caller no system-app, can not use system-api");                               \
132         return ERR_NOT_SYSTEM_APP;                                                             \
133     }
134 
135 constexpr const char* ARGS_USER_ID = "-u";
136 constexpr const char* ARGS_CLIENT = "-c";
137 constexpr const char* ILLEGAL_INFOMATION = "The arguments are illegal and you can enter '-h' for help.";
138 
139 constexpr int32_t NEW_RULE_VALUE_SIZE = 6;
140 constexpr int32_t APP_ALIVE_TIME_MS = 1000;  // Allow background startup within 1 second after application startup
141 constexpr int32_t REGISTER_FOCUS_DELAY = 5000;
142 constexpr size_t OFFSET = 32;
143 constexpr const char* IS_DELEGATOR_CALL = "isDelegatorCall";
144 
145 // Startup rule switch
146 constexpr const char* COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
147 constexpr const char* NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI = "component.startup.newRules.except.LauncherSystemUI";
148 constexpr const char* BACKGROUND_JUDGE_FLAG = "component.startup.backgroundJudge.flag";
149 constexpr const char* WHITE_LIST_ASS_WAKEUP_FLAG = "component.startup.whitelist.associatedWakeUp";
150 
151 // White list app
152 constexpr const char* BUNDLE_NAME_SETTINGSDATA = "com.ohos.settingsdata";
153 // UIExtension type
154 constexpr const char* UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType";
155 constexpr const char* UIEXTENSION_TARGET_TYPE_KEY = "ability.want.params.uiExtensionTargetType";
156 // Share picker params
157 constexpr char SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY[] = "const.system.sharePicker.bundleName";
158 constexpr char SHARE_PICKER_DIALOG_ABILITY_NAME_KEY[] = "const.system.sharePicker.abilityName";
159 constexpr char SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME[] = "com.ohos.sharepickerdialog";
160 constexpr char SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME[] = "PickerDialog";
161 constexpr char TOKEN_KEY[] = "ohos.ability.params.token";
162 // Developer mode param
163 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
164 constexpr char PRODUCT_APPBOOT_SETTING_ENABLED[] = "const.product.appboot.setting.enabled";
165 // Broker params key
166 constexpr const char* KEY_VISIBLE_ID = "ohos.anco.param.visible";
167 constexpr const char* START_ABILITY_TYPE = "ABILITY_INNER_START_WITH_ACCOUNT";
168 constexpr const char* BUNDLE_NAME_DIALOG = "com.ohos.amsdialog";
169 constexpr const char* STR_PHONE = "phone";
170 constexpr const char* PARAM_RESV_ANCO_CALLER_UID = "ohos.anco.param.callerUid";
171 constexpr const char* PARAM_RESV_ANCO_CALLER_BUNDLENAME = "ohos.anco.param.callerBundleName";
172 constexpr const char* PARAM_RESV_ANCO_IS_NEED_UPDATE_NAME = "ohos.anco.param.isNeedUpdateName";
173 constexpr const char* PARAM_ANCO_APP_IDENTIFIER = "persist.hmos_fusion_mgr.anco_identifier";
174 // Distributed continued session Id
175 constexpr const char* DMS_CONTINUED_SESSION_ID = "ohos.dms.continueSessionId";
176 constexpr const char* DMS_PERSISTENT_ID = "ohos.dms.persistentId";
177 constexpr const char* DMS_CALLING_UID = "ohos.dms.callingUid";
178 
179 constexpr const char* DEBUG_APP = "debugApp";
180 constexpr const char* NATIVE_DEBUG = "nativeDebug";
181 constexpr const char* DEBUG_FROM = "ohos.param.debugFrom";
182 constexpr const char* AUTO_FILL_PASSWORD_TYPE = "autoFill/password";
183 constexpr const char* AUTO_FILL_SMART_TYPE = "autoFill/smart";
184 constexpr size_t INDEX_ZERO = 0;
185 constexpr size_t INDEX_ONE = 1;
186 constexpr size_t INDEX_TWO = 2;
187 constexpr size_t ARGC_THREE = 3;
188 constexpr static char WANT_PARAMS_VIEW_DATA_KEY[] = "ohos.ability.params.viewData";
189 constexpr const char* WANT_PARAMS_HOST_WINDOW_ID_KEY = "ohos.extra.param.key.hostwindowid";
190 
191 constexpr int32_t FOUNDATION_UID = 5523;
192 constexpr const char* FRS_BUNDLE_NAME = "com.ohos.formrenderservice";
193 constexpr const char* FOUNDATION_PROCESS_NAME = "foundation";
194 constexpr const char* RSS_PROCESS_NAME = "resource_schedule_service";
195 constexpr const char* IS_PRELOAD_UIEXTENSION_ABILITY = "ability.want.params.is_preload_uiextension_ability";
196 constexpr const char* UIEXTENSION_MODAL_TYPE = "ability.want.params.modalType";
197 constexpr const char* SUPPORT_CLOSE_ON_BLUR = "supportCloseOnBlur";
198 constexpr const char* ATOMIC_SERVICE_PREFIX = "com.atomicservice.";
199 constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohosSpecifiedProcessFlag";
200 
201 constexpr char ASSERT_FAULT_DETAIL[] = "assertFaultDialogDetail";
202 constexpr char PRODUCT_ASSERT_FAULT_DIALOG_ENABLED[] = "persisit.sys.abilityms.support_assert_fault_dialog";
203 constexpr const char* ABILITYMS_ENABLE_UISERVICE = "const.abilityms.enable_uiservice";
204 
205 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
206 
207 constexpr char PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED[] = "const.product.enterprisefeature.setting.enabled";
208 
209 constexpr int32_t RESOURCE_SCHEDULE_UID = 1096;
210 constexpr int32_t HIVIEW_UID = 1201;
211 constexpr int32_t UPDATE_CONFIG_FLAG_COVER = 1;
212 constexpr int32_t UPDATE_CONFIG_FLAG_APPEND = 2;
213 constexpr int32_t START_AUTO_START_APP_DELAY_TIME = 200;
214 constexpr int32_t START_AUTO_START_APP_RETRY_MAX_TIMES = 5;
215 constexpr int32_t RETRY_COUNT = 20;
216 
217 const std::unordered_set<std::string> COMMON_PICKER_TYPE = {
218     "share", "action"
219 };
220 std::atomic<bool> g_isDmsAlive = false;
221 constexpr int32_t PIPE_MSG_READ_BUFFER = 1024;
222 constexpr const char* APPSPAWN_STARTED = "startup.service.ctl.appspawn.pid";
223 
SendAbilityEvent(const EventName & eventName,HiSysEventType type,const EventInfo & eventInfo)224 void SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo)
225 {
226     auto taskHandler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
227     if (taskHandler == nullptr) {
228         TAG_LOGI(AAFwkTag::ABILITYMGR, "task handler null");
229         return;
230     }
231     taskHandler->SubmitTask([eventName, type, eventInfo]() {
232         EventReport::SendAbilityEvent(eventName, type, eventInfo);
233         });
234 }
235 
IsEmbeddableStart(int32_t screenMode)236 bool IsEmbeddableStart(int32_t screenMode)
237 {
238     return screenMode == AAFwk::EMBEDDED_FULL_SCREEN_MODE ||
239         screenMode == AAFwk::EMBEDDED_HALF_SCREEN_MODE;
240 }
241 } // namespace
242 
243 using namespace std::chrono;
244 using namespace std::chrono_literals;
245 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
246 using namespace BackgroundTaskMgr;
247 #endif
248 const bool CONCURRENCY_MODE_FALSE = false;
249 constexpr int32_t MAIN_USER_ID = 100;
250 constexpr auto DATA_ABILITY_START_TIMEOUT = 5s;
251 constexpr int32_t NON_ANONYMIZE_LENGTH = 6;
252 constexpr uint32_t SCENE_FLAG_NORMAL = 0;
253 constexpr int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20;
254 constexpr int32_t SWITCH_ACCOUNT_TRY = 3;
255 constexpr const char* EMPTY_DEVICE_ID = "";
256 constexpr int32_t APP_MEMORY_SIZE = 512;
257 constexpr int32_t GET_PARAMETER_INCORRECT = -9;
258 constexpr int32_t GET_PARAMETER_OTHER = -1;
259 constexpr int32_t SIZE_10 = 10;
260 constexpr int32_t HIDUMPER_SERVICE_UID = 1212;
261 constexpr int32_t ACCOUNT_MGR_SERVICE_UID = 3058;
262 constexpr int32_t DMS_UID = 5522;
263 constexpr int32_t BOOTEVENT_COMPLETED_DELAY_TIME = 1000;
264 constexpr int32_t BOOTEVENT_BOOT_ANIMATION_READY_SIZE = 6;
265 constexpr const char* BUNDLE_NAME_KEY = "bundleName";
266 constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager";
267 constexpr const char* ACTION_CHOOSE = "ohos.want.action.select";
268 constexpr const char* HIGHEST_PRIORITY_ABILITY_ENTITY = "flag.home.intent.from.system";
269 constexpr const char* DMS_API_VERSION = "dmsApiVersion";
270 constexpr const char* DMS_IS_CALLER_BACKGROUND = "dmsIsCallerBackGround";
271 constexpr const char* DMS_PROCESS_NAME = "distributedsched";
272 constexpr const char* DMS_MISSION_ID = "dmsMissionId";
273 constexpr const char* BOOTEVENT_APPFWK_READY = "bootevent.appfwk.ready";
274 constexpr const char* BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed";
275 constexpr const char* BOOTEVENT_BOOT_ANIMATION_STARTED = "bootevent.bootanimation.started";
276 constexpr const char* BOOTEVENT_BOOT_ANIMATION_READY = "bootevent.bootanimation.ready";
277 constexpr const char* NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
278 constexpr const char* PERMISSIONMGR_BUNDLE_NAME = "com.ohos.permissionmanager";
279 constexpr const char* PERMISSIONMGR_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility";
280 constexpr const char* SCENEBOARD_BUNDLE_NAME = "com.ohos.sceneboard";
281 constexpr const char* SPECIFY_TOKEN_ID = "specifyTokenId";
282 constexpr const char* PROCESS_SUFFIX = "embeddable";
283 constexpr int32_t DEFAULT_DMS_MISSION_ID = -1;
284 constexpr const char* PARAM_PREVENT_STARTABILITY = "persist.sys.abilityms.prevent_startability";
285 constexpr const char* SUSPEND_SERVICE_CONFIG_FILE = "/etc/efficiency_manager/prevent_startability_whitelist.json";
286 constexpr int32_t MAX_BUFFER = 2048;
287 constexpr int32_t API12 = 12;
288 constexpr int32_t API_VERSION_MOD = 100;
289 constexpr const char* WHITE_LIST = "white_list";
290 constexpr const char* SUPPORT_COLLABORATE_INDEX = "ohos.extra.param.key.supportCollaborateIndex";
291 constexpr const char* COLLABORATE_KEY = "ohos.dms.collabToken";
292 constexpr const char* IS_CALLING_FROM_DMS = "supportCollaborativeCallingFromDmsInAAFwk";
293 constexpr int32_t CLEAR_REASON_DELAY_TIME = 3000;  // 3s
294 
295 const bool REGISTER_RESULT =
296     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<AbilityManagerService>::GetInstance().get());
297 sptr<AbilityManagerService> AbilityManagerService::instance_;
298 
AbilityManagerService()299 AbilityManagerService::AbilityManagerService()
300     : SystemAbility(ABILITY_MGR_SERVICE_ID, true),
301       state_(ServiceRunningState::STATE_NOT_START)
302 {}
303 
~AbilityManagerService()304 AbilityManagerService::~AbilityManagerService()
305 {}
306 
GetPubInstance()307 std::shared_ptr<AbilityManagerService> AbilityManagerService::GetPubInstance()
308 {
309     return DelayedSingleton<AbilityManagerService>::GetInstance();
310 }
311 
OnStart()312 void AbilityManagerService::OnStart()
313 {
314     if (state_ == ServiceRunningState::STATE_RUNNING) {
315         TAG_LOGI(AAFwkTag::ABILITYMGR, "started");
316         return;
317     }
318     TAG_LOGI(AAFwkTag::ABILITYMGR, "starting");
319     if (!Init()) {
320         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed  init");
321         return;
322     }
323     state_ = ServiceRunningState::STATE_RUNNING;
324     /* Publish service maybe failed, so we need call this function at the last,
325      * so it can't affect the TDD test program */
326     instance_ = DelayedSingleton<AbilityManagerService>::GetInstance().get();
327     if (instance_ == nullptr) {
328         TAG_LOGE(AAFwkTag::ABILITYMGR, "instance_ null");
329         return;
330     }
331     auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
332     if (bundleMgrHelper) {
333         bundleMgrHelper->SetBmsReady(false);
334     }
335     bool ret = Publish(instance_);
336     if (!ret) {
337         TAG_LOGE(AAFwkTag::ABILITYMGR, "publish failed");
338         return;
339     }
340 
341     SetParameter(BOOTEVENT_APPFWK_READY, "true");
342     bool bgTaskMgr = AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
343     bool distributedMgr = AddSystemAbilityListener(DISTRIBUTED_SCHED_SA_ID);
344     bool bundleMgr = AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
345 #ifdef SUPPORT_SCREEN
346     if (!AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID)) {
347         TAG_LOGE(AAFwkTag::ABILITYMGR, "OnStart, add listener err");
348     }
349 #endif
350     bool windowMgr = AddSystemAbilityListener(WINDOW_MANAGER_SERVICE_ID);
351     if (!bgTaskMgr || !distributedMgr || !bundleMgr || !windowMgr) {
352         TAG_LOGE(AAFwkTag::ABILITYMGR, "OnStart, add listeners err");
353     }
354     TAG_LOGI(AAFwkTag::ABILITYMGR, "onStart success");
355     auto pid = getpid();
356     std::unordered_map<std::string, std::string> payload;
357     payload["pid"] = std::to_string(pid);
358     OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload);
359 }
360 
Init()361 bool AbilityManagerService::Init()
362 {
363     HiviewDFX::Watchdog::GetInstance().InitFfrtWatchdog(); // For ffrt watchdog available in foundation
364     taskHandler_ = TaskHandlerWrap::CreateQueueHandler(AbilityConfig::NAME_ABILITY_MGR_SERVICE);
365     delayClearReasonHandler_ = TaskHandlerWrap::CreateQueueHandler("delay_clear_reason_queue");
366     eventHandler_ = std::make_shared<AbilityEventHandler>(taskHandler_, weak_from_this());
367     freeInstallManager_ = std::make_shared<FreeInstallManager>(weak_from_this());
368     CHECK_POINTER_RETURN_BOOL(freeInstallManager_);
369 
370     // init user controller.
371     userController_ = std::make_shared<UserController>();
372     userController_->Init();
373     AmsConfigurationParameter::GetInstance().Parse();
374     TAG_LOGI(AAFwkTag::ABILITYMGR, "config parse");
375     subManagersHelper_ = std::make_shared<SubManagersHelper>(taskHandler_, eventHandler_);
376     subManagersHelper_->InitSubManagers(MAIN_USER_ID, true);
377     SwitchManagers(U0_USER_ID, false);
378 #ifdef SUPPORT_SCREEN
379     implicitStartProcessor_ = std::make_shared<ImplicitStartProcessor>();
380     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
381         InitFocusListener();
382     }
383     AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().Init();
384 #endif
385 
386     DelayedSingleton<ConnectionStateManager>::GetInstance()->Init(taskHandler_);
387 
388     InitInterceptor();
389     InitStartAbilityChain();
390     InitDeepLinkReserve();
391 
392     abilityAutoStartupService_ = std::make_shared<AbilityRuntime::AbilityAutoStartupService>();
393     InitPushTask();
394     AbilityCacheManager::GetInstance().Init(AppUtils::GetInstance().GetLimitMaximumExtensionsPerDevice(),
395         AppUtils::GetInstance().GetLimitMaximumExtensionsPerProc());
396 
397     SubscribeScreenUnlockedEvent();
398     appExitReasonHelper_ = std::make_shared<AppExitReasonHelper>(subManagersHelper_);
399     TAG_LOGI(AAFwkTag::ABILITYMGR, "init success");
400     return true;
401 }
402 
InitDeepLinkReserve()403 void AbilityManagerService::InitDeepLinkReserve()
404 {
405     if (!DeepLinkReserveConfig::GetInstance().LoadConfiguration()) {
406         TAG_LOGE(AAFwkTag::ABILITYMGR, "initDeepLinkReserve failed");
407     }
408 }
409 
InitInterceptor()410 void AbilityManagerService::InitInterceptor()
411 {
412     interceptorExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
413     interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
414     interceptorExecuter_->AddInterceptor("CrowdTest", std::make_shared<CrowdTestInterceptor>());
415     interceptorExecuter_->AddInterceptor("Control", std::make_shared<ControlInterceptor>());
416     afterCheckExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
417     afterCheckExecuter_->AddInterceptor("ExtensionControl", std::make_shared<ExtensionControlInterceptor>());
418     afterCheckExecuter_->AddInterceptor("StartOtherApp", std::make_shared<StartOtherAppInterceptor>());
419     afterCheckExecuter_->AddInterceptor("DisposedRule", std::make_shared<DisposedRuleInterceptor>());
420     afterCheckExecuter_->AddInterceptor("EcologicalRule", std::make_shared<EcologicalRuleInterceptor>());
421     afterCheckExecuter_->SetTaskHandler(taskHandler_);
422     bool isAppJumpEnabled = OHOS::system::GetBoolParameter(
423         OHOS::AppExecFwk::PARAMETER_APP_JUMP_INTERCEPTOR_ENABLE, false);
424     if (isAppJumpEnabled) {
425         TAG_LOGI(AAFwkTag::ABILITYMGR, "app jump enabled, add abilityJumpInterceptor");
426         interceptorExecuter_->AddInterceptor("AbilityJump", std::make_shared<AbilityJumpInterceptor>());
427     }
428     if (AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
429         TAG_LOGI(AAFwkTag::ABILITYMGR, "add BlockAllAppStartInterceptor");
430         interceptorExecuter_->AddInterceptor("BlockAllAppStart", std::make_shared<BlockAllAppStartInterceptor>());
431     }
432 }
433 
InitInterceptorForScreenUnlock()434 void AbilityManagerService::InitInterceptorForScreenUnlock()
435 {
436     if (interceptorExecuter_) {
437         interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
438     }
439 }
440 
InitPushTask()441 void AbilityManagerService::InitPushTask()
442 {
443     if (taskHandler_ == nullptr) {
444         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler_ null");
445         return;
446     }
447 
448     auto initStartupFlagTask = [aams = shared_from_this()]() { aams->InitStartupFlag(); };
449     taskHandler_->SubmitTask(initStartupFlagTask, "InitStartupFlag");
450 
451     auto initExtensionConfigTask = []() {
452         DelayedSingleton<ExtensionConfig>::GetInstance()->LoadExtensionConfiguration();
453     };
454     taskHandler_->SubmitTask(initExtensionConfigTask, "InitExtensionConfigTask");
455 
456     auto bootCompletedTask = [handler = taskHandler_]() {
457         if (ApplicationUtil::IsBootCompleted()) {
458             auto task = []() {
459                 ApplicationUtil::AppFwkBootEventCallback(BOOTEVENT_BOOT_COMPLETED, "true", nullptr);
460             };
461             CHECK_POINTER(handler);
462             handler->SubmitTaskJust(task, "BootCompletedDelayTask", BOOTEVENT_COMPLETED_DELAY_TIME);
463         } else {
464             WatchParameter(BOOTEVENT_BOOT_COMPLETED, ApplicationUtil::AppFwkBootEventCallback, nullptr);
465             TAG_LOGI(AAFwkTag::ABILITYMGR, "init call, InitPushTask suc");
466         }
467     };
468     if (!ParseJsonFromBoot(SUSPEND_SERVICE_CONFIG_FILE)) {
469         TAG_LOGE(AAFwkTag::ABILITYMGR, "parse json fail");
470     }
471     isParamStartAbilityEnable_ = system::GetBoolParameter(PARAM_PREVENT_STARTABILITY, false);
472     taskHandler_->SubmitTask(bootCompletedTask, "BootCompletedTask");
473 }
474 
InitStartupFlag()475 void AbilityManagerService::InitStartupFlag()
476 {
477     startUpNewRule_ = CheckNewRuleSwitchState(COMPONENT_STARTUP_NEW_RULES);
478     newRuleExceptLauncherSystemUI_ = CheckNewRuleSwitchState(NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI);
479     backgroundJudgeFlag_ = CheckNewRuleSwitchState(BACKGROUND_JUDGE_FLAG);
480     whiteListassociatedWakeUpFlag_ = CheckNewRuleSwitchState(WHITE_LIST_ASS_WAKEUP_FLAG);
481 }
482 
InitStartAbilityChain()483 void AbilityManagerService::InitStartAbilityChain()
484 {
485     auto startSandboxSaveFile = std::make_shared<StartAbilitySandboxSavefile>();
486     startAbilityChain_.emplace(startSandboxSaveFile->GetPriority(), startSandboxSaveFile);
487 }
488 
OnStop()489 void AbilityManagerService::OnStop()
490 {
491     TAG_LOGI(AAFwkTag::ABILITYMGR, "stop");
492 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
493     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
494     if (bgtaskObserver_) {
495         int ret = BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver_);
496         if (ret != ERR_OK) {
497             TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bgtask failed, err:%{public}d", ret);
498         }
499     }
500 #endif
501     if (abilityBundleEventCallback_) {
502         auto bms = AbilityUtil::GetBundleManagerHelper();
503         if (bms) {
504             bool ret = IN_PROCESS_CALL(bms->UnregisterBundleEventCallback(abilityBundleEventCallback_));
505             if (ret != ERR_OK) {
506                 TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bundle event failed, err:%{public}d", ret);
507             }
508         }
509     }
510     eventHandler_.reset();
511     taskHandler_.reset();
512     state_ = ServiceRunningState::STATE_NOT_START;
513 }
514 
QueryServiceState() const515 ServiceRunningState AbilityManagerService::QueryServiceState() const
516 {
517     return state_;
518 }
519 
StartAbility(const Want & want,int32_t userId,int requestCode)520 int AbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode)
521 {
522     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
523     bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
524     bool isNativeDebugApp = want.GetBoolParam(NATIVE_DEBUG, false);
525     bool hasWindowOptions = (want.HasParameter(Want::PARAM_RESV_WINDOW_LEFT) ||
526         want.HasParameter(Want::PARAM_RESV_WINDOW_TOP) ||
527         want.HasParameter(Want::PARAM_RESV_WINDOW_HEIGHT) ||
528         want.HasParameter(Want::PARAM_RESV_WINDOW_WIDTH));
529     bool isDebugFromLocal = want.GetBoolParam(DEBUG_FROM, false);
530     TAG_LOGD(AAFwkTag::ABILITYMGR,
531         "isDebugApp=%{public}d, hasWindowOptions=%{public}d, isNativeDebugApp=%{public}d, isDebugFromLocal=%{public}d",
532         static_cast<int>(isDebugApp), static_cast<int>(hasWindowOptions), static_cast<int>(isNativeDebugApp),
533         isDebugFromLocal);
534     bool checkDeveloperModeFlag = (isDebugApp || hasWindowOptions || isNativeDebugApp || isDebugFromLocal);
535     if (checkDeveloperModeFlag) {
536         if (isDebugFromLocal && !AAFwk::PermissionVerification::GetInstance()-> VerifyStartLocalDebug()) {
537             TAG_LOGE(AAFwkTag::ABILITYMGR, "local debugging, permission denied");
538             return CHECK_PERMISSION_FAILED;
539         } else if (!isDebugFromLocal && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
540             TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
541             return ERR_NOT_DEVELOPER_MODE;
542         }
543         int32_t err = ERR_OK;
544         if (userId == DEFAULT_INVAL_VALUE) {
545             userId = GetValidUserId(userId);
546         }
547         if ((err = StartAbilityUtils::CheckAppProvisionMode(want, userId)) != ERR_OK) {
548             TAG_LOGE(AAFwkTag::ABILITYMGR, "checkAppProvisionMode returns errcode=%{public}d", err);
549             return err;
550         }
551     }
552     if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
553         TAG_LOGE(AAFwkTag::ABILITYMGR, "need passord to unlock");
554         return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
555     }
556     TAG_LOGD(AAFwkTag::ABILITYMGR, "coldStart:%{public}d", want.GetBoolParam("coldStart", false));
557     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
558     if (startWithAccount || IsCrossUserCall(userId)) {
559         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
560         CHECK_CALLER_IS_SYSTEM_APP;
561     }
562     if (hasWindowOptions && !AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
563         TAG_LOGE(AAFwkTag::ABILITYMGR, "window options not supported");
564         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
565     }
566     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
567     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
568     EventInfo eventInfo = BuildEventInfo(want, userId);
569     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
570     auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId), 0);
571     if (checkFileShareRet != ERR_OK) {
572         return checkFileShareRet;
573     }
574 #ifdef SUPPORT_SCREEN
575     DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
576 #endif
577     int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
578     AAFWK::ContinueRadar::GetInstance().ClickIconStartAbility("StartAbilityWrap", want.GetFlags(), ret);
579     if (ret != ERR_OK) {
580         eventInfo.errCode = ret;
581         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
582     }
583     return ret;
584 }
585 
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)586 int AbilityManagerService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
587     int32_t userId, int requestCode)
588 {
589     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
590     TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability with caller");
591     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
592     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
593     auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId), 0);
594     if (checkFileShareRet != ERR_OK) {
595         return checkFileShareRet;
596     }
597 #ifdef SUPPORT_SCREEN
598     DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
599 #endif
600     return StartAbilityByFreeInstall(want, callerToken, userId, requestCode);
601 }
602 
StartAbilityByFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int32_t requestCode)603 int32_t AbilityManagerService::StartAbilityByFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
604     int32_t userId, int32_t requestCode)
605 {
606     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
607     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
608     if (startWithAccount || IsCrossUserCall(userId)) {
609         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
610         CHECK_CALLER_IS_SYSTEM_APP;
611     }
612     auto flags = want.GetFlags();
613     EventInfo eventInfo = BuildEventInfo(want, userId);
614     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
615     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
616         TAG_LOGE(AAFwkTag::ABILITYMGR, "not allow startAbility with continuation flags");
617         eventInfo.errCode = ERR_INVALID_VALUE;
618         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
619         return ERR_INVALID_CONTINUATION_FLAG;
620     }
621 
622     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d",
623         want.GetElement().GetAbilityName().c_str(), userId);
624 
625     int32_t ret = StartAbilityWrap(want, callerToken, requestCode, false, userId);
626     if (ret != ERR_OK) {
627         eventInfo.errCode = ret;
628         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
629     }
630     return ret;
631 }
632 
StartAbilityWithSpecifyTokenId(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,int32_t userId,int requestCode)633 int AbilityManagerService::StartAbilityWithSpecifyTokenId(const Want &want, const sptr<IRemoteObject> &callerToken,
634     uint32_t specifyTokenId, int32_t userId, int requestCode)
635 {
636     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
637         TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with specialId, current process not foundation process");
638         return CHECK_PERMISSION_FAILED;
639     }
640     return StartAbilityWithSpecifyTokenIdInner(want, callerToken, specifyTokenId, false, userId, requestCode);
641 }
642 
StartAbilityWithSpecifyTokenIdInner(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,bool isPendingWantCaller,int32_t userId,int requestCode)643 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const sptr<IRemoteObject> &callerToken,
644     uint32_t specifyTokenId, bool isPendingWantCaller, int32_t userId, int requestCode)
645 {
646     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
647     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
648     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
649     auto flags = want.GetFlags();
650     EventInfo eventInfo = BuildEventInfo(want, userId);
651     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
652     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
653         TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with continuation flags not allowed");
654         eventInfo.errCode = ERR_INVALID_VALUE;
655         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
656         return ERR_INVALID_CONTINUATION_FLAG;
657     }
658 
659     TAG_LOGI(AAFwkTag::ABILITYMGR,
660         "start ability come, ability:%{public}s, userId:%{public}d, specifyTokenId:%{public}u",
661         want.GetElement().GetAbilityName().c_str(), userId, specifyTokenId);
662     auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId),
663         specifyTokenId);
664     if (checkFileShareRet != ERR_OK) {
665         return checkFileShareRet;
666     }
667     int32_t ret = StartAbilityWrap(want, callerToken, requestCode, isPendingWantCaller, userId, false, specifyTokenId);
668     if (ret != ERR_OK) {
669         eventInfo.errCode = ret;
670         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
671     }
672     return ret;
673 }
674 
StartAbilityWithSpecifyTokenIdInner(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId)675 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const StartOptions &startOptions,
676     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller,
677     int32_t userId, int requestCode, uint32_t callerTokenId)
678 {
679     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions by trigger.");
680     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
681     auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId),
682         callerTokenId);
683     if (checkFileShareRet != ERR_OK) {
684         return checkFileShareRet;
685     }
686     return StartUIAbilityForOptionWrap(
687         want, startOptions, callerToken, isPendingWantCaller, userId, requestCode, callerTokenId);
688 }
689 
StartAbilityByInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,uint64_t intentId,int32_t userId)690 int32_t AbilityManagerService::StartAbilityByInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken,
691     uint64_t intentId, int32_t userId)
692 {
693     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
694     std::string bundleNameFromWant = want.GetElement().GetBundleName();
695     std::string bundleNameFromIntentMgr = "";
696     if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->
697         GetBundleName(intentId, bundleNameFromIntentMgr) != ERR_OK) {
698         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched intentId");
699         return ERR_INVALID_VALUE;
700     }
701     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
702     if (abilityRecord == nullptr) {
703         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched token");
704         return ERR_INVALID_VALUE;
705     }
706     std::string bundleNameFromAbilityRecord = abilityRecord->GetAbilityInfo().bundleName;
707     if (!bundleNameFromWant.empty() && bundleNameFromWant == bundleNameFromIntentMgr &&
708         bundleNameFromWant == bundleNameFromAbilityRecord) {
709         AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
710         TAG_LOGI(AAFwkTag::ABILITYMGR, "bundleName match");
711         return StartAbility(want, callerToken, userId, -1);
712     }
713     TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleName not match");
714     return ERR_INSIGHT_INTENT_START_INVALID_COMPONENT;
715 }
716 
StartAbilityByUIContentSession(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)717 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const sptr<IRemoteObject> &callerToken,
718     const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
719 {
720     if (!callerToken || !sessionInfo) {
721         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo null");
722         return ERR_INVALID_VALUE;
723     }
724     sptr<IRemoteObject> token;
725 #ifdef SUPPORT_SCREEN
726     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
727         Rosen::FocusChangeInfo focusChangeInfo;
728         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
729         token = focusChangeInfo.abilityToken_;
730     } else {
731         if (!wmsHandler_) {
732             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
733             return ERR_INVALID_VALUE;
734         }
735         wmsHandler_->GetFocusWindow(token);
736     }
737 #endif // SUPPORT_SCREEN
738     if (!token) {
739         TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
740         return ERR_INVALID_VALUE;
741     }
742 
743     if (token != sessionInfo->callerToken) {
744         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken unequal to top ability token");
745         return NOT_TOP_ABILITY;
746     }
747     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
748     return StartAbility(want, callerToken, userId, requestCode);
749 }
750 
StartAbilityByUIContentSession(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)751 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const StartOptions &startOptions,
752     const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
753 {
754     if (!callerToken || !sessionInfo) {
755         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo null");
756         return ERR_INVALID_VALUE;
757     }
758     sptr<IRemoteObject> token;
759 #ifdef SUPPORT_SCREEN
760     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
761         Rosen::FocusChangeInfo focusChangeInfo;
762         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
763         token = focusChangeInfo.abilityToken_;
764     } else {
765         if (!wmsHandler_) {
766             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
767             return ERR_INVALID_VALUE;
768         }
769         wmsHandler_->GetFocusWindow(token);
770     }
771 #endif // SUPPORT_SCREEN
772 
773     if (!token) {
774         TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
775         return ERR_INVALID_VALUE;
776     }
777 
778     if (token != sessionInfo->callerToken) {
779         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken unequal to top ability token");
780         return NOT_TOP_ABILITY;
781     }
782     return StartAbility(want, startOptions, callerToken, userId, requestCode);
783 }
784 
StartAbilityOnlyUIAbility(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId)785 int AbilityManagerService::StartAbilityOnlyUIAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
786     uint32_t specifyTokenId)
787 {
788     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
789         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with specialId, process not foundation process");
790         return CHECK_PERMISSION_FAILED;
791     }
792 
793     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
794     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
795     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
796     auto flags = want.GetFlags();
797     EventInfo eventInfo = BuildEventInfo(want, DEFAULT_INVAL_VALUE);
798     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
799     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
800         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility not allowed");
801         eventInfo.errCode = ERR_INVALID_VALUE;
802         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
803         return ERR_INVALID_CONTINUATION_FLAG;
804     }
805 
806     TAG_LOGI(AAFwkTag::ABILITYMGR,
807         "start, ability: %{public}s, userId: %{public}d, specifyTokenId: %{public}u",
808         want.GetElement().GetAbilityName().c_str(), DEFAULT_INVAL_VALUE, specifyTokenId);
809 
810     int32_t ret = StartAbilityWrap(want, callerToken, DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, specifyTokenId, false, false, true);
811     if (ret != ERR_OK) {
812         eventInfo.errCode = ret;
813         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
814     }
815     return ret;
816 }
817 
StartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)818 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
819     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
820 {
821     return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, requestCode);
822 }
823 
ImplicitStartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)824 int AbilityManagerService::ImplicitStartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
825     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
826 {
827     return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId,
828         requestCode, true);
829 }
830 
StartAbilityAsCallerDetails(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode,bool isImplicit)831 int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const sptr<IRemoteObject> &callerToken,
832     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode, bool isImplicit)
833 {
834     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
835     CHECK_CALLER_IS_SYSTEM_APP;
836     auto flags = want.GetFlags();
837     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
838     EventInfo eventInfo = BuildEventInfo(want, userId);
839     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
840     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
841         TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with continuation flags not allowed");
842         eventInfo.errCode = ERR_INVALID_VALUE;
843         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
844         return ERR_INVALID_CONTINUATION_FLAG;
845     }
846 
847     AAFwk::Want newWant = want;
848     UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
849     TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability come, ability:%{public}s, userId:%{public}d",
850         want.GetElement().GetAbilityName().c_str(), userId);
851     std::string callerPkg;
852     std::string targetPkg;
853     if (AbilityUtil::CheckJumpInterceptorWant(newWant, callerPkg, targetPkg)) {
854         TAG_LOGI(AAFwkTag::ABILITYMGR,
855             "call from interceptor dialog, callerPkg:%{public}s, targetPkg:%{public}s",
856             callerPkg.c_str(), targetPkg.c_str());
857         AbilityUtil::AddAbilityJumpRuleToBms(callerPkg, targetPkg, GetUserId());
858     }
859     int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true,
860         0, false, isImplicit, false);
861     if (ret != ERR_OK) {
862         eventInfo.errCode = ret;
863         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
864     }
865     return ret;
866 }
867 
StartAbilityPublicPrechainCheck(StartAbilityParams & params)868 int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams &params)
869 {
870     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
871     // 1. CheckCallerToken
872     if (params.callerToken != nullptr && !VerificationAllToken(params.callerToken)) {
873         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
874             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
875         if (!isSpecificSA) {
876             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
877             return ERR_INVALID_CALLER;
878         }
879         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: caller specific system ability", __func__);
880     }
881 
882     // 2. validUserId, multi-user
883     if (!JudgeMultiUserConcurrency(params.GetValidUserId())) {
884         TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
885         return ERR_CROSS_USER;
886     }
887 
888     return ERR_OK;
889 }
890 
StartAbilityPrechainInterceptor(StartAbilityParams & params)891 int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams &params)
892 {
893     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
894     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
895     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(params.want, params.requestCode,
896         GetUserId(), true, nullptr, shouldBlockFunc);
897     auto interceptorResult = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
898         interceptorExecuter_->DoProcess(interceptorParam);
899     if (interceptorResult != ERR_OK) {
900         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
901         return interceptorResult;
902     }
903 
904     return ERR_OK;
905 }
906 
StartAbilityInChain(StartAbilityParams & params,int & result)907 bool AbilityManagerService::StartAbilityInChain(StartAbilityParams &params, int &result)
908 {
909     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
910     std::shared_ptr<StartAbilityHandler> reqHandler;
911     for (const auto &item : startAbilityChain_) {
912         if (item.second != nullptr && item.second->MatchStartRequest(params)) {
913             reqHandler = item.second;
914             break;
915         }
916     }
917 
918     if (!reqHandler) {
919         return false;
920     }
921 
922     result = StartAbilityPublicPrechainCheck(params);
923     if (result != ERR_OK) {
924         return true;
925     }
926     result = StartAbilityPrechainInterceptor(params);
927     if (result != ERR_OK) {
928         return true;
929     }
930     result = reqHandler->HandleStartRequest(params);
931     return true;
932 }
933 
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)934 int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr<IRemoteObject> &callerToken,
935     int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyToken,
936     bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
937 {
938     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
939     StartAbilityParams startParams(const_cast<Want &>(want));
940     startParams.callerToken = callerToken;
941     startParams.userId = userId;
942     startParams.requestCode = requestCode;
943     startParams.isStartAsCaller = isStartAsCaller;
944     startParams.SetValidUserId(GetValidUserId(userId));
945 
946     int result = ERR_OK;
947     if (StartAbilityInChain(startParams, result)) {
948         return result;
949     }
950 
951     return StartAbilityInner(want, callerToken, requestCode, isPendingWantCaller, userId, isStartAsCaller, specifyToken,
952         isForegroundToRestartApp, isImplicit, isUIAbilityOnly);
953 }
954 
SetReserveInfo(const std::string & linkString,AbilityRequest & abilityRequest)955 void AbilityManagerService::SetReserveInfo(const std::string &linkString, AbilityRequest& abilityRequest)
956 {
957     if (!linkString.size()) {
958         return;
959     }
960 
961 #ifdef SUPPORT_SCREEN
962     abilityRequest.uriReservedFlag =
963         DeepLinkReserveConfig::GetInstance().IsLinkReserved(linkString, abilityRequest.reservedBundleName);
964 #endif // SUPPORT_SCREEN
965 }
966 
CheckExtensionCallPermission(const Want & want,const AbilityRequest & abilityRequest,uint32_t specifyTokenId)967 int AbilityManagerService::CheckExtensionCallPermission(const Want& want, const AbilityRequest& abilityRequest,
968     uint32_t specifyTokenId)
969 {
970     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "startExtensionCheck");
971     auto isSACall = AAFwk::PermissionVerification::GetInstance()->IsSACallByTokenId(specifyTokenId);
972     auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCallByTokenId(specifyTokenId);
973     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCallByTokenId(specifyTokenId);
974     auto isToPermissionMgr = IsTargetPermission(want);
975     if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) {
976         TAG_LOGE(AAFwkTag::ABILITYMGR,
977             "cannot start, use startServiceExtensionAbility");
978         return ERR_WRONG_INTERFACE_CALL;
979     }
980     int result = CheckCallServicePermission(abilityRequest);
981     if (result != ERR_OK) {
982         TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
983     }
984     return result;
985 }
986 
CheckServiceCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)987 int AbilityManagerService::CheckServiceCallPermission(const AbilityRequest& abilityRequest,
988     const AppExecFwk::AbilityInfo& abilityInfo)
989 {
990     TAG_LOGD(AAFwkTag::ABILITYMGR,
991         "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
992     int result = CheckCallServicePermission(abilityRequest);
993     if (result != ERR_OK) {
994         TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
995     }
996     return result;
997 }
998 
CheckBrokerCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)999 int AbilityManagerService::CheckBrokerCallPermission(const AbilityRequest& abilityRequest,
1000     const AppExecFwk::AbilityInfo& abilityInfo)
1001 {
1002     // temp add for broker, remove when delete issacall
1003     if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) {
1004         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check permission failed");
1005         return CHECK_PERMISSION_FAILED;
1006     }
1007     TAG_LOGD(AAFwkTag::ABILITYMGR,
1008         "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
1009     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
1010     if (collaborator == nullptr) {
1011         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator null");
1012         return CHECK_PERMISSION_FAILED;
1013     }
1014     int result = collaborator->CheckCallAbilityPermission(abilityRequest.want);
1015     if (result != ERR_OK) {
1016         TAG_LOGE(AAFwkTag::ABILITYMGR, "check broker permission failed");
1017         return CHECK_PERMISSION_FAILED;
1018     }
1019     return result;
1020 }
1021 
CheckAbilityCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,uint32_t specifyTokenId)1022 int AbilityManagerService::CheckAbilityCallPermission(const AbilityRequest& abilityRequest,
1023     const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId)
1024 {
1025     TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
1026     if (AbilityPermissionUtil::GetInstance().IsStartSelfUIAbility()) {
1027         TAG_LOGI(AAFwkTag::ABILITYMGR, "call from capi, already checked");
1028         return ERR_OK;
1029     }
1030     int result = CheckCallAbilityPermission(abilityRequest, specifyTokenId);
1031     if (result != ERR_OK) {
1032         TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
1033     }
1034     return result;
1035 }
1036 
CheckCallPermission(const Want & want,const AppExecFwk::AbilityInfo & abilityInfo,const AbilityRequest & abilityRequest,bool isForegroundToRestartApp,bool isSendDialogResult,uint32_t specifyTokenId,const std::string & callerBundleName)1037 int AbilityManagerService::CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
1038     const AbilityRequest& abilityRequest, bool isForegroundToRestartApp,
1039     bool isSendDialogResult, uint32_t specifyTokenId,
1040     const std::string& callerBundleName)
1041 {
1042     auto type = abilityInfo.type;
1043     if (type == AppExecFwk::AbilityType::DATA) {
1044         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot start data ability by start ability");
1045         return ERR_WRONG_INTERFACE_CALL;
1046     }
1047     if (type == AppExecFwk::AbilityType::EXTENSION) {
1048         return CheckExtensionCallPermission(want, abilityRequest, specifyTokenId);
1049     }
1050     if (type == AppExecFwk::AbilityType::SERVICE) {
1051         return CheckServiceCallPermission(abilityRequest, abilityInfo);
1052     }
1053     if ((callerBundleName == AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
1054         AppUtils::GetInstance().IsSupportAncoApp()) ||
1055         IPCSkeleton::GetCallingUid() == AppUtils::GetInstance().GetCollaboratorBrokerUID()) {
1056         return CheckBrokerCallPermission(abilityRequest, abilityInfo);
1057     }
1058     if (!isForegroundToRestartApp && (!isSendDialogResult || want.GetBoolParam("isSelector", false))) {
1059         return CheckAbilityCallPermission(abilityRequest, abilityInfo, specifyTokenId);
1060     }
1061     return ERR_OK;
1062 }
1063 
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)1064 int AbilityManagerService::StartAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
1065     int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyTokenId,
1066     bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
1067 {
1068     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1069     if (!isStartAsCaller || isImplicit) {
1070         (const_cast<Want &>(want)).RemoveParam("ability.params.picker.erms.policy");
1071     }
1072     std::string dialogSessionId = want.GetStringParam("dialogSessionId");
1073     bool isSendDialogResult = false;
1074 #ifdef SUPPORT_SCREEN
1075     if (!dialogSessionId.empty() &&
1076         DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId) != nullptr) {
1077         isSendDialogResult = true;
1078     }
1079 #endif // SUPPORT_SCREEN
1080 
1081     // prevent the app from dominating the screen
1082     if (callerToken == nullptr && !IsCallerSceneBoard() && !isSendDialogResult && !isForegroundToRestartApp &&
1083         AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1084         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
1085         return ERR_INVALID_CALLER;
1086     }
1087     {
1088 #ifdef WITH_DLP
1089         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1090         if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1091             VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1092             !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1093             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
1094             return CHECK_PERMISSION_FAILED;
1095         }
1096 
1097         if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1098             InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1099             return StartExtensionAbilityInner(want, callerToken, userId,
1100                 AppExecFwk::ExtensionAbilityType::SERVICE, false, false, true, isStartAsCaller);
1101         }
1102 #endif // WITH_DLP
1103     }
1104 
1105     AbilityUtil::RemoveWindowModeKey(const_cast<Want &>(want));
1106     if (callerToken != nullptr && !VerificationAllToken(callerToken) && !isSendDialogResult) {
1107         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
1108             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME) ||
1109             AAFwk::PermissionVerification::GetInstance()->VerifyFusionAccessPermission();
1110         if (!isSpecificSA) {
1111             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
1112             return ERR_INVALID_CALLER;
1113         }
1114         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:caller specific system ability", __func__);
1115     }
1116 
1117     int32_t oriValidUserId = GetValidUserId(userId);
1118     int32_t validUserId = oriValidUserId;
1119     SetTargetCloneIndexInSameBundle(want, callerToken);
1120     int32_t appIndex = 0;
1121     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1122         return ERR_APP_CLONE_INDEX_INVALID;
1123     }
1124     if (!isForegroundToRestartApp) {
1125         auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1126             validUserId, appIndex, callerToken);
1127         if (checkRet != ERR_OK) {
1128             return checkRet;
1129         }
1130     }
1131     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1132     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1133     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1134         true, nullptr, shouldBlockFunc);
1135     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1136         interceptorExecuter_->DoProcess(interceptorParam);
1137     if (result != ERR_OK) {
1138         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
1139         return result;
1140     }
1141 
1142     if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1143         IPCSkeleton::GetCallingUid() != DMS_UID) {
1144         TAG_LOGE(AAFwkTag::ABILITYMGR, "flag only support DMS, flag:%{public}d", want.GetFlags());
1145         return ERR_INVALID_CONTINUATION_FLAG;
1146     }
1147 
1148     if (callerToken != nullptr && CheckIfOperateRemote(want)) {
1149         TAG_LOGI(AAFwkTag::ABILITYMGR, "try to StartRemoteAbility");
1150         return StartRemoteAbility(want, requestCode, validUserId, callerToken);
1151     }
1152 
1153     if (!JudgeMultiUserConcurrency(validUserId)) {
1154         TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
1155         return ERR_CROSS_USER;
1156     }
1157 
1158     AbilityRequest abilityRequest;
1159 #ifdef SUPPORT_SCREEN
1160     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1161         TAG_LOGD(AAFwkTag::ABILITYMGR, "is implicit start action");
1162         auto checkResult = AbilityUtil::CheckInstanceKey(want);
1163         if (checkResult != ERR_OK) {
1164             return checkResult;
1165         }
1166         abilityRequest.Voluation(want, requestCode, callerToken);
1167         if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1168             UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1169         } else if (!isStartAsCaller) {
1170             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1171             UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1172         } else {
1173             TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1174         }
1175         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1176         SetReserveInfo(want.GetUriString(), abilityRequest);
1177         return implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1178     }
1179     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1180         return ShowPickerDialog(want, validUserId, callerToken);
1181     }
1182 #endif
1183     std::string identifier = system::GetParameter(PARAM_ANCO_APP_IDENTIFIER, "");
1184     std::string targetBundleName = want.GetBundle();
1185     if (!identifier.empty() && !targetBundleName.empty() && identifier.find(targetBundleName) != std::string::npos) {
1186         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
1187         if (collaborator != nullptr) {
1188             Want tempWant = want;
1189             int32_t ret = collaborator->UpdateTargetIfNeed(tempWant);
1190             TAG_LOGI(AAFwkTag::ABILITYMGR, "UpdateTargetIfNeed end,ret:%{public}d", ret);
1191             (const_cast<Want &>(want)).SetElement(tempWant.GetElement());
1192         } else {
1193             TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateTargetIfNeed error due to collaborator is nullptr");
1194         }
1195     }
1196     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1197     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1198     std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
1199     bool selfFreeInstallEnable = (result == RESOLVE_ABILITY_ERR && want.GetElement().GetModuleName() != "" &&
1200                                   want.GetElement().GetBundleName() == callerBundleName);
1201     bool isStartFreeInstallByWant = AbilityUtil::IsStartFreeInstall(want);
1202     if (isStartFreeInstallByWant || selfFreeInstallEnable) {
1203         TAG_LOGD(AAFwkTag::ABILITYMGR, "selfFreeInstallEnable: %{public}d, isStartFreeInstallByWant: %{public}d",
1204             selfFreeInstallEnable, isStartFreeInstallByWant);
1205         Want localWant;
1206         auto freeInstallResult = PreStartFreeInstall(want, callerToken, specifyTokenId, isStartAsCaller, localWant);
1207         if (freeInstallResult != ERR_OK) {
1208             TAG_LOGE(AAFwkTag::ABILITYMGR, "preStartFreeInstall failed");
1209             return freeInstallResult;
1210         }
1211         CHECK_POINTER_AND_RETURN(freeInstallManager_, ERR_INVALID_VALUE);
1212 
1213         if (isStartFreeInstallByWant) {
1214             auto param = std::make_shared<FreeInstallParams>();
1215             param->isAsync = true;
1216             param->specifyTokenId = specifyTokenId;
1217             return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, param);
1218         }
1219         int32_t ret = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken);
1220         if (ret == ERR_OK) {
1221             result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1222         }
1223     }
1224 
1225     if (result != ERR_OK) {
1226         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
1227         return result;
1228     }
1229 
1230     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1231         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1232     } else if (!isStartAsCaller) {
1233         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1234         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1235     } else if (callerBundleName == BUNDLE_NAME_DIALOG ||
1236         (isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1237 #ifdef SUPPORT_SCREEN
1238         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1239         int32_t flag = false;
1240         if (callerBundleName == BUNDLE_NAME_DIALOG) {
1241             flag = true;
1242         }
1243         implicitStartProcessor_->ResetCallingIdentityAsCaller(
1244             abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), flag);
1245 #endif // SUPPORT_SCREEN
1246     }
1247 
1248     auto abilityInfo = abilityRequest.abilityInfo;
1249     if (isUIAbilityOnly && abilityInfo.type != AbilityType::PAGE) {
1250         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability type no UIAbility");
1251         return ERR_INVALID_VALUE;
1252     }
1253     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1254     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
1255         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1256 
1257     if ((isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1258         isImplicit = true;
1259     }
1260     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1261         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1262     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1263         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
1264         return ERR_STATIC_CFG_PERMISSION;
1265     }
1266 
1267     if (!isSendDialogResult || !want.GetBoolParam("isSelector", false)) {
1268         result = CheckCallPermission(want, abilityInfo, abilityRequest, isForegroundToRestartApp,
1269             isSendDialogResult, specifyTokenId, callerBundleName);
1270         if (result != ERR_OK) {
1271             TAG_LOGE(AAFwkTag::ABILITYMGR, "checkCallPermission error, result:%{public}d", result);
1272             return result;
1273         }
1274     }
1275     Want newWant = abilityRequest.want;
1276     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1277         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1278     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1279         afterCheckExecuter_->DoProcess(afterCheckParam);
1280     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1281     newWant.RemoveParam("queryWantFromErms");
1282     if (result != ERR_OK && isReplaceWantExist == false) {
1283         TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
1284         return result;
1285     }
1286 #ifdef SUPPORT_SCREEN
1287     if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
1288         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1289     }
1290     if (result == ERR_OK &&
1291         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1292         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1293         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
1294     }
1295 #endif // SUPPORT_SCREEN
1296 
1297     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1298         TAG_LOGD(AAFwkTag::ABILITYMGR, "PreLoadAppDataAbilities:%{public}s.", abilityInfo.bundleName.c_str());
1299         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1300         if (result != ERR_OK) {
1301             TAG_LOGE(AAFwkTag::ABILITYMGR,
1302                 "startAbility:app data ability preloading failed, '%{public}s', %{public}d",
1303                 abilityInfo.bundleName.c_str(), result);
1304             return result;
1305         }
1306     }
1307 
1308     RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerToken);
1309     if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
1310         abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
1311         SendStartAbilityOtherExtensionEvent(abilityInfo, abilityRequest.want, specifyTokenId);
1312         return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
1313     }
1314 
1315     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1316         TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", abilityInfo.bundleName.c_str());
1317         return ERR_WOULD_BLOCK;
1318     }
1319 
1320     auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1321     UpdateCallerInfoUtil::GetInstance().UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1322     StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1323 
1324     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1325     if (specifyTokenId > 0) {
1326         TAG_LOGD(AAFwkTag::ABILITYMGR, "set specifyTokenId, the specifyTokenId is %{public}d", specifyTokenId);
1327         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1328         abilityRequest.specifyTokenId = specifyTokenId;
1329     }
1330     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1331     // sceneboard
1332     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1333         ReportEventToRSS(abilityInfo, abilityRequest.callerToken);
1334         abilityRequest.userId = oriValidUserId;
1335         abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
1336         // other sa or shell can not use continueSessionId and persistentId
1337         auto abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
1338         if (abilityRecord == nullptr &&
1339             !PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
1340             TAG_LOGW(AAFwkTag::ABILITYMGR, "startAbilityInner, remove continueSessionId and persistentId");
1341             abilityRequest.want.RemoveParam(DMS_CONTINUED_SESSION_ID);
1342             abilityRequest.want.RemoveParam(DMS_PERSISTENT_ID);
1343         }
1344         if (abilityRequest.want.GetBoolParam(PARAM_RESV_ANCO_IS_NEED_UPDATE_NAME, false) &&
1345                 PermissionVerification::GetInstance()->VerifyFusionAccessPermission()) {
1346             TAG_LOGI(AAFwkTag::ABILITYMGR, "startAbilityInner, update name for fusion");
1347             abilityRequest.want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, std::string(""));
1348             abilityRequest.want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, std::string(""));
1349         }
1350         if (StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
1351             auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
1352             if (collaborator != nullptr) {
1353                 int32_t ret = collaborator->UpdateCallerIfNeed(abilityRequest.want);
1354                 TAG_LOGI(AAFwkTag::ABILITYMGR, "UpdateCallerIfNeed end,ret:%{public}d", ret);
1355             } else {
1356                 TAG_LOGI(AAFwkTag::ABILITYMGR, "UpdateCallerIfNeed error due to collaborator is nullptr");
1357             }
1358         }
1359         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1360         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1361         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1362     }
1363 
1364     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1365     if (missionListManager == nullptr) {
1366         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", validUserId);
1367         return ERR_INVALID_VALUE;
1368     }
1369 
1370     ReportAbilityStartInfoToRSS(abilityInfo);
1371     ReportEventToRSS(abilityInfo, callerToken);
1372     TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability, name is %{public}s", abilityInfo.name.c_str());
1373     return missionListManager->StartAbility(abilityRequest);
1374 }
1375 
PreStartFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,uint32_t specifyTokenId,bool isStartAsCaller,Want & localWant)1376 int AbilityManagerService::PreStartFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
1377     uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant)
1378 {
1379     if (freeInstallManager_ == nullptr) {
1380         return ERR_INVALID_VALUE;
1381     }
1382     (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1383     localWant = want;
1384     if (!localWant.GetDeviceId().empty()) {
1385         localWant.SetDeviceId("");
1386     }
1387     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1388         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(localWant, callerToken);
1389     } else if (!isStartAsCaller) {
1390         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1391         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1392     } else {
1393         TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1394     }
1395     return ERR_OK;
1396 }
1397 
StartAbilityByConnectManager(const Want & want,const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,int validUserId,sptr<IRemoteObject> callerToken)1398 int AbilityManagerService::StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest,
1399     const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr<IRemoteObject> callerToken)
1400 {
1401     auto connectManager = GetConnectManagerByUserId(validUserId);
1402     if (!connectManager) {
1403         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
1404         return ERR_INVALID_VALUE;
1405     }
1406     TAG_LOGD(AAFwkTag::ABILITYMGR, "start service or extension, name is %{public}s", abilityInfo.name.c_str());
1407     ReportEventToRSS(abilityInfo, callerToken);
1408     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1409     return connectManager->StartAbility(abilityRequest);
1410 }
1411 
StartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1412 int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1413     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1414 {
1415     auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId), 0);
1416     if (checkFileShareRet != ERR_OK) {
1417         return checkFileShareRet;
1418     }
1419 #ifdef SUPPORT_SCREEN
1420     DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
1421 #endif
1422     return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode);
1423 }
1424 
ImplicitStartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1425 int AbilityManagerService::ImplicitStartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1426     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1427 {
1428     return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode, true);
1429 }
1430 
StartAbilityDetails(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode,bool isImplicit)1431 int AbilityManagerService::StartAbilityDetails(const Want &want, const AbilityStartSetting &abilityStartSetting,
1432     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isImplicit)
1433 {
1434     if (want.GetBoolParam(DEBUG_APP, false)) {
1435         if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
1436             TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
1437             return ERR_NOT_DEVELOPER_MODE;
1438         }
1439         int32_t err = ERR_OK;
1440         if (userId == DEFAULT_INVAL_VALUE) {
1441             userId = GetValidUserId(userId);
1442         }
1443         if ((err = StartAbilityUtils::CheckAppProvisionMode(want, userId)) != ERR_OK) {
1444             TAG_LOGE(AAFwkTag::ABILITYMGR, "checkAppProvisionMode returns errcode=%{public}d", err);
1445             return err;
1446         }
1447     }
1448     if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
1449         TAG_LOGE(AAFwkTag::ABILITYMGR, "screen need passord unlock");
1450         return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
1451     }
1452     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1453     StartAbilityParams startParams(const_cast<Want &>(want));
1454     startParams.callerToken = callerToken;
1455     startParams.userId = userId;
1456     startParams.requestCode = requestCode;
1457     startParams.SetValidUserId(GetValidUserId(userId));
1458 
1459     int result = ERR_OK;
1460     if (StartAbilityInChain(startParams, result)) {
1461         return result;
1462     }
1463 
1464     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1465     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability setting.");
1466     if (IsCrossUserCall(userId)) {
1467         CHECK_CALLER_IS_SYSTEM_APP;
1468     }
1469     EventInfo eventInfo = BuildEventInfo(want, userId);
1470     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1471 
1472 #ifdef WITH_DLP
1473     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1474         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1475         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1476         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
1477         eventInfo.errCode = CHECK_PERMISSION_FAILED;
1478         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1479         return CHECK_PERMISSION_FAILED;
1480     }
1481 #endif // WITH_DLP
1482 
1483     if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1484         IPCSkeleton::GetCallingUid() != DMS_UID) {
1485         TAG_LOGE(AAFwkTag::ABILITYMGR, "The flag only support for DMS, flag is %{public}d", want.GetFlags());
1486         eventInfo.errCode = ERR_INVALID_VALUE;
1487         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1488         return ERR_INVALID_CONTINUATION_FLAG;
1489     }
1490 
1491     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1492         eventInfo.errCode = ERR_INVALID_VALUE;
1493         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1494         return ERR_INVALID_CALLER;
1495     }
1496 
1497     int32_t oriValidUserId = GetValidUserId(userId);
1498     int32_t validUserId = oriValidUserId;
1499     int32_t appIndex = 0;
1500     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1501         return ERR_APP_CLONE_INDEX_INVALID;
1502     }
1503     auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1504         validUserId, appIndex, callerToken);
1505     if (checkRet != ERR_OK) {
1506         return checkRet;
1507     }
1508     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1509     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1510     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1511         true, nullptr, shouldBlockFunc);
1512     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1513         interceptorExecuter_->DoProcess(interceptorParam);
1514     if (result != ERR_OK) {
1515         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
1516         eventInfo.errCode = result;
1517         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1518         return result;
1519     }
1520 
1521     if (AbilityUtil::IsStartFreeInstall(want)) {
1522         if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1523             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1524             return ERR_INVALID_VALUE;
1525         }
1526         (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1527         Want localWant = want;
1528         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1529         auto param = std::make_shared<FreeInstallParams>();
1530         param->isAsync = true;
1531         return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, param);
1532     }
1533 
1534     if (!JudgeMultiUserConcurrency(validUserId)) {
1535         TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
1536         eventInfo.errCode = ERR_INVALID_VALUE;
1537         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1538         return ERR_CROSS_USER;
1539     }
1540 
1541     AbilityRequest abilityRequest;
1542 #ifdef SUPPORT_SCREEN
1543     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1544         TAG_LOGD(AAFwkTag::ABILITYMGR, "is implicit start action");
1545         auto checkResult = AbilityUtil::CheckInstanceKey(want);
1546         if (checkResult != ERR_OK) {
1547             return checkResult;
1548         }
1549         abilityRequest.Voluation(
1550             want, requestCode, callerToken, std::make_shared<AbilityStartSetting>(abilityStartSetting));
1551         abilityRequest.callType = AbilityCallType::START_SETTINGS_TYPE;
1552         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1553         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1554         if (result != ERR_OK) {
1555             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error");
1556             eventInfo.errCode = result;
1557             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1558         }
1559         return result;
1560     }
1561     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1562         return ShowPickerDialog(want, validUserId, callerToken);
1563     }
1564 #endif
1565     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1566     if (result != ERR_OK) {
1567         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
1568         eventInfo.errCode = result;
1569         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1570         return result;
1571     }
1572     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1573 
1574     auto abilityInfo = abilityRequest.abilityInfo;
1575     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1576     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1577         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1578 
1579     result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
1580     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1581         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
1582         eventInfo.errCode = result;
1583         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1584         return ERR_STATIC_CFG_PERMISSION;
1585     }
1586     result = CheckCallAbilityPermission(abilityRequest);
1587     if (result != ERR_OK) {
1588         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s checkCallAbilityPermission error", __func__);
1589         eventInfo.errCode = result;
1590         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1591         return result;
1592     }
1593 
1594     abilityRequest.startSetting = std::make_shared<AbilityStartSetting>(abilityStartSetting);
1595 
1596     if (abilityInfo.type == AppExecFwk::AbilityType::DATA) {
1597         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot start data ability, use 'AcquireDataAbility()'");
1598         eventInfo.errCode = ERR_INVALID_VALUE;
1599         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1600         return ERR_WRONG_INTERFACE_CALL;
1601     }
1602 
1603     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
1604         GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
1605     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1606         afterCheckExecuter_->DoProcess(afterCheckParam);
1607     if (result != ERR_OK) {
1608         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
1609         return result;
1610     }
1611 
1612     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1613         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1614         if (result != ERR_OK) {
1615             TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility: app data ability preloading failed, '%{public}s', %{public}d",
1616                 abilityInfo.bundleName.c_str(),
1617                 result);
1618             eventInfo.errCode = result;
1619             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1620             return result;
1621         }
1622     }
1623 #ifdef SUPPORT_GRAPHICS
1624     if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1625         TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability");
1626         eventInfo.errCode = ERR_INVALID_VALUE;
1627         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1628         return ERR_WRONG_INTERFACE_CALL;
1629     }
1630 #endif
1631     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1632         eventInfo.errCode = ERR_WOULD_BLOCK;
1633         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1634         return ERR_WOULD_BLOCK;
1635     }
1636 
1637     RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerToken);
1638     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1639         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1640         abilityRequest.userId = oriValidUserId;
1641         abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
1642         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1643         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1644         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1645     }
1646     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1647     if (missionListManager == nullptr) {
1648         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", validUserId);
1649         eventInfo.errCode = ERR_INVALID_VALUE;
1650         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1651         return ERR_INVALID_VALUE;
1652     }
1653     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1654     auto ret = missionListManager->StartAbility(abilityRequest);
1655     if (ret != ERR_OK) {
1656         eventInfo.errCode = ret;
1657         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1658     }
1659     return ret;
1660 }
1661 
StartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1662 int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions,
1663     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1664 {
1665     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1666     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions.");
1667     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1668     auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId), 0);
1669     if (checkFileShareRet != ERR_OK) {
1670         return checkFileShareRet;
1671     }
1672 #ifdef SUPPORT_SCREEN
1673     DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
1674 #endif
1675     return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode);
1676 }
1677 
ImplicitStartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1678 int AbilityManagerService::ImplicitStartAbility(const Want &want, const StartOptions &startOptions,
1679     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1680 {
1681     TAG_LOGD(AAFwkTag::ABILITYMGR, "Implicit Start ability with startOptions.");
1682     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1683     return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode, 0, true);
1684 }
1685 
StartUIAbilityForOptionWrap(const Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId,bool isImplicit,bool isCallByShortcut)1686 int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options,
1687     sptr<IRemoteObject> callerToken, bool isPendingWantCaller, int32_t userId,
1688     int requestCode, uint32_t callerTokenId, bool isImplicit,
1689     bool isCallByShortcut)
1690 {
1691     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1692     int32_t ret = ERR_OK;
1693 
1694     if (HiddenStartUtils::IsHiddenStart(want, options)) {
1695         ret = HiddenStartUtils::CheckHiddenStartSupported(want, options);
1696     } else if (AbilityPermissionUtil::GetInstance().IsStartSelfUIAbility() &&
1697                options.processOptions != nullptr &&
1698                options.processOptions->isStartFromNDK) {
1699         ret = CheckStartSelfUIAbilityStartOptions(want, options);
1700     } else {
1701         ret = CheckProcessOptions(want, options, userId);
1702     }
1703 
1704     if (ret != ERR_OK) {
1705         return ret;
1706     }
1707     return StartAbilityForOptionWrap(want, options, callerToken, isPendingWantCaller, userId, requestCode, false,
1708         callerTokenId, isImplicit, isCallByShortcut);
1709 }
1710 
StartAbilityAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)1711 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOptions &startOptions,
1712     const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken,
1713     int32_t userId, int requestCode)
1714 {
1715     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability as caller with startOptions.");
1716     CHECK_CALLER_IS_SYSTEM_APP;
1717 
1718     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1719     AAFwk::Want newWant = want;
1720     UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1721     return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1722 }
1723 
StartAbilityForResultAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1724 int AbilityManagerService::StartAbilityForResultAsCaller(
1725     const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1726 {
1727     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1728     CHECK_CALLER_IS_SYSTEM_APP;
1729 
1730     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1731     AAFwk::Want newWant = want;
1732     auto connectManager = GetCurrentConnectManager();
1733     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1734     auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1735     UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1736     return StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true);
1737 }
1738 
StartAbilityForResultAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1739 int AbilityManagerService::StartAbilityForResultAsCaller(const Want &want, const StartOptions &startOptions,
1740     const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1741 {
1742     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1743     CHECK_CALLER_IS_SYSTEM_APP;
1744 
1745     AAFwk::Want newWant = want;
1746     auto connectManager = GetCurrentConnectManager();
1747     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1748     auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1749     UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1750     return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1751 }
1752 
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)1753 int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const StartOptions &startOptions,
1754     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1755     bool isStartAsCaller, uint32_t callerTokenId, bool isImplicit, bool isCallByShortcut)
1756 {
1757     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1758     StartAbilityParams startParams(const_cast<Want &>(want));
1759     startParams.callerToken = callerToken;
1760     startParams.userId = userId;
1761     startParams.requestCode = requestCode;
1762     startParams.isStartAsCaller = isStartAsCaller;
1763     startParams.startOptions = &startOptions;
1764     startParams.SetValidUserId(GetValidUserId(userId));
1765 
1766     int result = ERR_OK;
1767     if (StartAbilityInChain(startParams, result)) {
1768         return result;
1769     }
1770 
1771     return StartAbilityForOptionInner(want, startOptions, callerToken, isPendingWantCaller, userId, requestCode,
1772         isStartAsCaller, callerTokenId, isImplicit, isCallByShortcut);
1773 }
1774 
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)1775 int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const StartOptions &startOptions,
1776     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1777     bool isStartAsCaller, uint32_t specifyTokenId, bool isImplicit, bool isCallByShortcut)
1778 {
1779     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1780     // prevent the app from dominating the screen
1781     if (callerToken == nullptr && !IsCallerSceneBoard() && !isCallByShortcut &&
1782         AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1783         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
1784         return ERR_INVALID_CALLER;
1785     }
1786 
1787     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
1788     if (startWithAccount || IsCrossUserCall(userId)) {
1789         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
1790         CHECK_CALLER_IS_SYSTEM_APP;
1791     }
1792     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1793     EventInfo eventInfo = BuildEventInfo(want, userId);
1794     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1795 
1796 #ifdef WITH_DLP
1797     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1798         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1799         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1800         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
1801         eventInfo.errCode = CHECK_PERMISSION_FAILED;
1802         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1803         return CHECK_PERMISSION_FAILED;
1804     }
1805 #endif // WITH_DLP
1806 
1807     if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1808         IPCSkeleton::GetCallingUid() != DMS_UID) {
1809         TAG_LOGE(AAFwkTag::ABILITYMGR, "The flag only support for DMS, flag is %{public}d", want.GetFlags());
1810         eventInfo.errCode = ERR_INVALID_VALUE;
1811         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1812         return ERR_INVALID_CONTINUATION_FLAG;
1813     }
1814 
1815     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1816         eventInfo.errCode = ERR_INVALID_VALUE;
1817         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1818         return ERR_INVALID_CALLER;
1819     }
1820 
1821     int32_t oriValidUserId = GetValidUserId(userId);
1822     int32_t validUserId = oriValidUserId;
1823     SetTargetCloneIndexInSameBundle(want, callerToken);
1824     int32_t appIndex = 0;
1825     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1826         return ERR_APP_CLONE_INDEX_INVALID;
1827     }
1828     auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1829         validUserId, appIndex, callerToken);
1830     if (checkRet != ERR_OK) {
1831         return checkRet;
1832     }
1833     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1834     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1835     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1836         true, nullptr, shouldBlockFunc);
1837     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1838         interceptorExecuter_->DoProcess(interceptorParam);
1839     if (result != ERR_OK) {
1840         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
1841         eventInfo.errCode = result;
1842         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1843         return result;
1844     }
1845 
1846     if (AbilityUtil::IsStartFreeInstall(want)) {
1847         if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1848             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1849             return ERR_INVALID_VALUE;
1850         }
1851         (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1852         Want localWant = want;
1853         if (!isStartAsCaller) {
1854             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1855             UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1856         }
1857         TAG_LOGD(AAFwkTag::ABILITYMGR, "is start free install");
1858         auto param = std::make_shared<FreeInstallParams>();
1859         param->isAsync = true;
1860         param->specifyTokenId = specifyTokenId;
1861         param->startOptions = std::make_shared<AAFwk::StartOptions>(startOptions);
1862         return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, param);
1863     }
1864     if (!JudgeMultiUserConcurrency(validUserId)) {
1865         TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
1866         eventInfo.errCode = ERR_INVALID_VALUE;
1867         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1868         return ERR_CROSS_USER;
1869     }
1870 
1871     AbilityRequest abilityRequest;
1872 #ifdef SUPPORT_SCREEN
1873     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1874         TAG_LOGD(AAFwkTag::ABILITYMGR, "is implicit start action");
1875         auto checkResult = AbilityUtil::CheckInstanceKey(want);
1876         if (checkResult != ERR_OK) {
1877             return checkResult;
1878         }
1879         abilityRequest.Voluation(want, requestCode, callerToken);
1880         if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
1881             bool windowFocused = startOptions.GetWindowFocused();
1882             abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowFocused);
1883         } else {
1884             abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
1885         }
1886         if (startOptions.GetDisplayID() == 0) {
1887             abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1888                 DisplayUtil::GetDefaultDisplayId());
1889         } else {
1890             abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1891         }
1892         WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
1893         abilityRequest.callType = AbilityCallType::START_OPTIONS_TYPE;
1894         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1895         if (specifyTokenId > 0 && callerToken) { // for sa specify tokenId and caller token
1896             UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1897         } else if (!isStartAsCaller) {
1898             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1899             UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1900         }
1901         TAG_LOGD(AAFwkTag::ABILITYMGR, "implicit start ability");
1902         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId,
1903             startOptions.GetWindowMode());
1904         if (result != ERR_OK) {
1905             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error");
1906             eventInfo.errCode = result;
1907             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1908         }
1909         return result;
1910     }
1911     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1912         return ShowPickerDialog(want, validUserId, callerToken);
1913     }
1914 #endif
1915     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1916     if (result != ERR_OK) {
1917         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
1918         eventInfo.errCode = result;
1919         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1920         return result;
1921     }
1922 
1923     if (!isStartAsCaller) {
1924         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1925         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1926     }
1927     auto abilityInfo = abilityRequest.abilityInfo;
1928     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1929     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1930         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1931 
1932     if (startOptions.processOptions != nullptr &&
1933         abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
1934         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
1935         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1936         auto abilityRecords = uiAbilityManager->GetAbilityRecordsByName(want.GetElement());
1937         if (!abilityRecords.empty() && abilityRecords[0] &&
1938             !startOptions.processOptions->isRestartKeepAlive &&
1939             !ProcessOptions::IsAttachToStatusBarItemMode(startOptions.processOptions->processMode) &&
1940             !startOptions.processOptions->isStartFromNDK) {
1941             TAG_LOGE(AAFwkTag::ABILITYMGR, "processMode is not attach to status bar item.");
1942             return ERR_ABILITY_ALREADY_RUNNING;
1943         }
1944     }
1945 
1946     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1947         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1948     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1949         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result=%{public}d", result);
1950         eventInfo.errCode = result;
1951         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1952         return ERR_STATIC_CFG_PERMISSION;
1953     }
1954     result = CheckCallAbilityPermission(abilityRequest, 0, isCallByShortcut);
1955     if (result != ERR_OK) {
1956         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error", __func__);
1957         eventInfo.errCode = result;
1958         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1959         return result;
1960     }
1961 
1962     if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1963         TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability");
1964         eventInfo.errCode = ERR_INVALID_VALUE;
1965         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1966         return ERR_INVALID_VALUE;
1967     }
1968 
1969     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1970         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1971         if (result != ERR_OK) {
1972             TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility:app data ability preloading failed, '%{public}s', %{public}d",
1973                 abilityInfo.bundleName.c_str(),
1974                 result);
1975             eventInfo.errCode = result;
1976             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1977             return result;
1978         }
1979     }
1980 
1981     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1982         eventInfo.errCode = ERR_WOULD_BLOCK;
1983         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1984         return ERR_WOULD_BLOCK;
1985     }
1986 #ifdef SUPPORT_SCREEN
1987     if (abilityInfo.isStageBasedModel && !CheckWindowMode(startOptions.GetWindowMode(), abilityInfo.windowModes)) {
1988         return ERR_AAFWK_INVALID_WINDOW_MODE;
1989     }
1990 #endif
1991     if (startOptions.GetDisplayID() == 0) {
1992         abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1993             DisplayUtil::GetDefaultDisplayId());
1994     } else {
1995         abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1996     }
1997     AbilityUtil::ProcessWindowMode(abilityRequest.want, abilityInfo.applicationInfo.accessTokenId,
1998         startOptions.GetWindowMode());
1999 
2000     WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
2001 
2002     if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
2003         bool focused = abilityRequest.want.GetBoolParam(Want::PARAM_RESV_WINDOW_FOCUSED, true);
2004         if (focused) {
2005             bool windowfocused = startOptions.GetWindowFocused();
2006             abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowfocused);
2007         }
2008     } else {
2009         abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
2010     }
2011 
2012     Want newWant = abilityRequest.want;
2013     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
2014         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
2015     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2016         afterCheckExecuter_->DoProcess(afterCheckParam);
2017     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2018     newWant.RemoveParam("queryWantFromErms");
2019     if (result != ERR_OK && isReplaceWantExist == false) {
2020         TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
2021         return result;
2022     }
2023 #ifdef SUPPORT_SCREEN
2024     if (result != ERR_OK && isReplaceWantExist) {
2025         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
2026     }
2027     if (result == ERR_OK &&
2028         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
2029         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
2030         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
2031     }
2032 #endif // SUPPORT_GRAPHICS
2033     auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
2034     UpdateCallerInfoUtil::GetInstance().UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
2035     StartAbilityUtils::ermsSupportBackToCallerFlag = false;
2036 
2037     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
2038     if (specifyTokenId > 0) {
2039         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
2040         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
2041         abilityRequest.specifyTokenId = specifyTokenId;
2042     }
2043 
2044     RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerToken);
2045     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
2046     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2047         abilityRequest.userId = oriValidUserId;
2048         abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
2049         abilityRequest.processOptions = startOptions.processOptions;
2050         if (IPCSkeleton::GetCallingTokenID() == abilityRequest.appInfo.accessTokenId ||
2051             AbilityPermissionUtil::GetInstance().IsStartSelfUIAbility()) {
2052             abilityRequest.startWindowOption = startOptions.startWindowOption;
2053         }
2054         abilityRequest.supportWindowModes = startOptions.supportWindowModes_;
2055         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
2056         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2057         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
2058     }
2059     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
2060     if (missionListManager == nullptr) {
2061         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", oriValidUserId);
2062         eventInfo.errCode = ERR_INVALID_VALUE;
2063         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2064         return ERR_INVALID_VALUE;
2065     }
2066     if (startOptions.GetDisplayID() == -1) {
2067         abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
2068             DisplayUtil::GetDefaultDisplayId());
2069     }
2070     auto ret = missionListManager->StartAbility(abilityRequest);
2071     if (ret != ERR_OK) {
2072         eventInfo.errCode = ret;
2073         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2074     }
2075     return ret;
2076 }
2077 
RequestDialogService(const Want & want,const sptr<IRemoteObject> & callerToken)2078 int32_t AbilityManagerService::RequestDialogService(const Want &want, const sptr<IRemoteObject> &callerToken)
2079 {
2080     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2081     auto flags = want.GetFlags();
2082     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
2083         TAG_LOGE(AAFwkTag::ABILITYMGR, "requestDialogService with continuation flags not allowed");
2084         return ERR_INVALID_CONTINUATION_FLAG;
2085     }
2086 
2087     TAG_LOGI(AAFwkTag::ABILITYMGR, "request dialog service, target:%{public}s", want.GetElement().GetURI().c_str());
2088     return RequestDialogServiceInner(want, callerToken, -1, -1);
2089 }
2090 
ReportDrawnCompleted(const sptr<IRemoteObject> & callerToken)2091 int32_t AbilityManagerService::ReportDrawnCompleted(const sptr<IRemoteObject> &callerToken)
2092 {
2093     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
2094     if (callerToken == nullptr) {
2095         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken null");
2096         return INNER_ERR;
2097     }
2098 
2099     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2100     if (abilityRecord == nullptr) {
2101         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
2102         return INNER_ERR;
2103     }
2104     auto abilityInfo = abilityRecord->GetAbilityInfo();
2105 
2106     EventInfo eventInfo;
2107     eventInfo.userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2108     eventInfo.pid = IPCSkeleton::GetCallingPid();
2109     eventInfo.bundleName = abilityInfo.bundleName;
2110     eventInfo.moduleName = abilityInfo.moduleName;
2111     eventInfo.abilityName = abilityInfo.name;
2112     EventReport::SendAppEvent(EventName::DRAWN_COMPLETED, HiSysEventType::BEHAVIOR, eventInfo);
2113     return ERR_OK;
2114 }
2115 
RequestDialogServiceInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)2116 int32_t AbilityManagerService::RequestDialogServiceInner(const Want &want, const sptr<IRemoteObject> &callerToken,
2117     int requestCode, int32_t userId)
2118 {
2119     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2120     if (callerToken == nullptr || !VerificationAllToken(callerToken)) {
2121         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller invalid");
2122         return ERR_INVALID_CALLER;
2123     }
2124 
2125     {
2126 #ifdef WITH_DLP
2127         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
2128         if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
2129             !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
2130             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
2131             return CHECK_PERMISSION_FAILED;
2132         }
2133 
2134         if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
2135             TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot handle dlp by requestDialogService");
2136             return ERR_WRONG_INTERFACE_CALL;
2137         }
2138 #endif // WITH_DLP
2139     }
2140 
2141     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
2142     int32_t validUserId = GetValidUserId(userId);
2143     StartAbilityInfoWrap threadLocalInfo;
2144     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2145     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
2146         true, nullptr, shouldBlockFunc);
2147     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2148         interceptorExecuter_->DoProcess(interceptorParam);
2149     if (result != ERR_OK) {
2150         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
2151         return result;
2152     }
2153 
2154     if (!JudgeMultiUserConcurrency(validUserId)) {
2155         TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
2156         return ERR_CROSS_USER;
2157     }
2158     AbilityRequest abilityRequest;
2159     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2160     if (result != ERR_OK) {
2161         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error when requestDialogService");
2162         return result;
2163     }
2164     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
2165 
2166     auto abilityInfo = abilityRequest.abilityInfo;
2167     threadLocalInfo.SetStartAbilityInfo(abilityInfo);
2168     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2169     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
2170         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2171 
2172     result = CheckStaticCfgPermission(abilityRequest, false, -1);
2173     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2174         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
2175         return ERR_STATIC_CFG_PERMISSION;
2176     }
2177 
2178     auto type = abilityInfo.type;
2179     if (type == AppExecFwk::AbilityType::EXTENSION &&
2180         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
2181         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
2182         result = CheckCallServicePermission(abilityRequest);
2183         if (result != ERR_OK) {
2184             TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
2185             return result;
2186         }
2187     } else {
2188         TAG_LOGE(AAFwkTag::ABILITYMGR, "requestDialogService no support other component");
2189         return ERR_WRONG_INTERFACE_CALL;
2190     }
2191 
2192     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
2193         GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
2194     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2195         afterCheckExecuter_->DoProcess(afterCheckParam);
2196     if (result != ERR_OK) {
2197         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or DoProcess error");
2198         return result;
2199     }
2200 
2201     auto connectManager = GetConnectManagerByUserId(validUserId);
2202     if (!connectManager) {
2203         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
2204         return ERR_INVALID_VALUE;
2205     }
2206     TAG_LOGD(AAFwkTag::ABILITYMGR,
2207         "request dialog service, start service extension,name is %{public}s.", abilityInfo.name.c_str());
2208     ReportEventToRSS(abilityInfo, callerToken);
2209     return connectManager->StartAbility(abilityRequest);
2210 }
2211 
OpenAtomicService(AAFwk::Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,int32_t requestCode,int32_t userId)2212 int32_t AbilityManagerService::OpenAtomicService(AAFwk::Want& want, const StartOptions &options,
2213     sptr<IRemoteObject> callerToken, int32_t requestCode, int32_t userId)
2214 {
2215     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2216     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
2217     if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
2218         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not hap");
2219         return CHECK_PERMISSION_FAILED;
2220     }
2221     want.SetParam(AAFwk::SCREEN_MODE_KEY, AAFwk::ScreenMode::JUMP_SCREEN_MODE);
2222     return StartUIAbilityForOptionWrap(want, options, callerToken, false, userId, requestCode);
2223 }
2224 
SetWantForSessionInfo(sptr<SessionInfo> sessionInfo)2225 int AbilityManagerService::SetWantForSessionInfo(sptr<SessionInfo> sessionInfo)
2226 {
2227     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
2228     if (!(sessionInfo->want).GetElement().GetAbilityName().empty() &&
2229         !(sessionInfo->want).GetElement().GetModuleName().empty()) {
2230         return ERR_OK;
2231     }
2232     auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
2233     CHECK_POINTER_AND_RETURN(bundleMgrHelper, ERR_INVALID_VALUE);
2234     Want launchWant;
2235     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName:%{public}s, userId:%{public}d", sessionInfo->want.GetBundle().c_str(),
2236         GetValidUserId(sessionInfo->userId));
2237     auto errCode = IN_PROCESS_CALL(bundleMgrHelper->GetLaunchWantForBundle(
2238         (sessionInfo->want).GetBundle(), launchWant, GetValidUserId(sessionInfo->userId)));
2239     if (errCode != ERR_OK) {
2240         TAG_LOGE(AAFwkTag::ABILITYMGR, "getLaunchWantForBundle returns %{public}d", errCode);
2241         return errCode;
2242     }
2243     (sessionInfo->want).SetElement(launchWant.GetElement());
2244     return ERR_OK;
2245 }
2246 
StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo,bool & isColdStart,uint32_t sceneFlag)2247 int AbilityManagerService::StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo, bool &isColdStart, uint32_t sceneFlag)
2248 {
2249     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2250     TAG_LOGI(AAFwkTag::ABILITYMGR, "call, sceneFlag:%{public}u", sceneFlag);
2251     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
2252         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
2253         return ERR_INVALID_VALUE;
2254     }
2255 
2256     if (!IsCallerSceneBoard()) {
2257         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
2258         return ERR_WRONG_INTERFACE_CALL;
2259     }
2260 
2261     if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
2262         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2263     }
2264 
2265     std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
2266     if (sessionId.empty()) {
2267         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2268     }
2269 
2270     TAG_LOGI(AAFwkTag::ABILITYMGR, "sessionId=%{public}s", sessionId.c_str());
2271 
2272     if (freeInstallManager_ == nullptr) {
2273         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
2274         return ERR_INVALID_VALUE;
2275     }
2276     FreeInstallInfo taskInfo;
2277     if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
2278         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed find free install task");
2279         auto err = SetWantForSessionInfo(sessionInfo);
2280         if (err != ERR_OK) {
2281             TAG_LOGE(AAFwkTag::ABILITYMGR, "SetWantForSessionInfo failed");
2282             return err;
2283         }
2284         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2285         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2286         if (uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo) == nullptr) {
2287             TAG_LOGI(AAFwkTag::ABILITYMGR, "first time open");
2288             return StartUIAbilityByPreInstallInner(sessionInfo, 0, sceneFlag, isColdStart);
2289         }
2290         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2291     }
2292 
2293     if (taskInfo.isFreeInstallFinished) {
2294         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
2295         if (!taskInfo.isInstalled) {
2296             TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
2297                 taskInfo.resultCode);
2298             return taskInfo.resultCode;
2299         }
2300         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeds");
2301         return StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, sceneFlag, isColdStart);
2302     }
2303 
2304     {
2305         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
2306         preStartSessionMap_[sessionId] = sessionInfo;
2307     }
2308 
2309     TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task in progress");
2310     const Want& want = sessionInfo->want;
2311     freeInstallManager_->SetSCBCallStatus(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(),
2312         want.GetStringParam(Want::PARAM_RESV_START_TIME), true);
2313     return ERR_OK;
2314 }
2315 
StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2316 int AbilityManagerService::StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo, uint32_t sceneFlag,
2317     bool &isColdStart)
2318 {
2319     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2320     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
2321 
2322     auto currentUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2323     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
2324     if (sessionInfo->userId == DEFAULT_INVAL_VALUE) {
2325         sessionInfo->userId = currentUserId;
2326     }
2327 
2328     (sessionInfo->want).RemoveParam(AAFwk::SCREEN_MODE_KEY);
2329     EventInfo eventInfo = BuildEventInfo(sessionInfo->want, currentUserId);
2330     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
2331 
2332     auto requestCode = sessionInfo->requestCode;
2333     int32_t appIndex = 0;
2334     if (!StartAbilityUtils::GetAppIndex(sessionInfo->want, sessionInfo->callerToken, appIndex)) {
2335         return ERR_APP_CLONE_INDEX_INVALID;
2336     }
2337     StartAbilityInfoWrap threadLocalInfo(sessionInfo->want, currentUserId, appIndex, sessionInfo->callerToken);
2338     if (sessionInfo->want.GetBoolParam(ServerConstant::IS_CALL_BY_SCB, true)) {
2339         TAG_LOGD(AAFwkTag::ABILITYMGR, "interceptorExecuter_ called");
2340         (sessionInfo->want).RemoveParam(IS_CALLING_FROM_DMS);
2341         auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2342         AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(sessionInfo->want, requestCode,
2343             currentUserId, true, nullptr, shouldBlockFunc);
2344         auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2345         interceptorExecuter_->DoProcess(interceptorParam);
2346         if (result != ERR_OK) {
2347             TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
2348             eventInfo.errCode = result;
2349             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2350             return result;
2351         }
2352     }
2353 
2354     AbilityRequest abilityRequest;
2355     auto result = GenerateAbilityRequest(sessionInfo->want, requestCode, abilityRequest,
2356         sessionInfo->callerToken, currentUserId);
2357     if (result != ERR_OK) {
2358         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
2359         return result;
2360     }
2361 
2362     if (sessionInfo->want.GetBoolParam(ServerConstant::IS_CALL_BY_SCB, true)) {
2363         if (sessionInfo->startSetting != nullptr) {
2364             TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb, last not.");
2365             sessionInfo->startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2366         }
2367 
2368         if (abilityRequest.startSetting != nullptr) {
2369             TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb.");
2370             abilityRequest.startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2371         }
2372     }
2373 
2374     abilityRequest.collaboratorType = sessionInfo->collaboratorType;
2375     uint32_t specifyTokenId = static_cast<uint32_t>(sessionInfo->want.GetIntParam(SPECIFY_TOKEN_ID, 0));
2376     (sessionInfo->want).RemoveParam(SPECIFY_TOKEN_ID);
2377     abilityRequest.specifyTokenId = specifyTokenId;
2378 
2379     auto abilityInfo = abilityRequest.abilityInfo;
2380     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall() &&
2381         abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
2382         TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability");
2383         return ERR_INVALID_VALUE;
2384     }
2385 
2386     if (sessionInfo->want.GetBoolParam(ServerConstant::IS_CALL_BY_SCB, true)) {
2387         TAG_LOGD(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ called");
2388         if (sessionInfo->want.GetBoolParam("ohos.ability.params.isSkipErmsFromSCB", false)) {
2389             abilityRequest.want.RemoveParam("ohos.ability.params.isSkipErmsFromSCB");
2390             StartAbilityUtils::skipErms = true;
2391         }
2392         Want newWant = abilityRequest.want;
2393         RemoveUnauthorizedLaunchReasonMessage(sessionInfo->want, abilityRequest, sessionInfo->callerToken);
2394         AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(), true,
2395             sessionInfo->callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2396         result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2397             afterCheckExecuter_->DoProcess(afterCheckParam);
2398         bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2399         newWant.RemoveParam("queryWantFromErms");
2400         if (result != ERR_OK) {
2401             if (isReplaceWantExist == false) {
2402                 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
2403                 return result;
2404             }
2405             return DialogSessionManager::GetInstance().HandleErmsResultBySCB(abilityRequest, newWant);
2406         }
2407     }
2408 
2409     return StartUIAbilityBySCBDefaultCommon(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2410 }
2411 
StartUIAbilityBySCBDefaultCommon(AbilityRequest & abilityRequest,sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2412 int32_t AbilityManagerService::StartUIAbilityBySCBDefaultCommon(AbilityRequest &abilityRequest,
2413     sptr<SessionInfo> sessionInfo, uint32_t sceneFlag, bool &isColdStart)
2414 {
2415     auto abilityInfo = abilityRequest.abilityInfo;
2416     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
2417         int32_t result = PreLoadAppDataAbilities(abilityInfo.bundleName, IPCSkeleton::GetCallingUid() / BASE_USER_RANGE);
2418         if (result != ERR_OK) {
2419             TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility: app data ability preloading failed, '%{public}s', %{public}d",
2420                 abilityInfo.bundleName.c_str(), result);
2421             return result;
2422         }
2423     }
2424 
2425     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
2426     ReportAbilityStartInfoToRSS(abilityInfo);
2427     ReportAbilityAssociatedStartInfoToRSS(abilityInfo, RES_TYPE_SCB_START_ABILITY, sessionInfo->callerToken);
2428     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2429     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2430     return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2431 }
2432 
NotifySCBToRecoveryAfterInterception(const AbilityRequest & abilityRequest)2433 int32_t AbilityManagerService::NotifySCBToRecoveryAfterInterception(const AbilityRequest &abilityRequest)
2434 {
2435     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2436     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2437     return uiAbilityManager->NotifySCBToRecoveryAfterInterception(abilityRequest);
2438 }
2439 
CheckCallingTokenId(const std::string & bundleName,int32_t userId,int32_t appIndex)2440 bool AbilityManagerService::CheckCallingTokenId(const std::string &bundleName, int32_t userId, int32_t appIndex)
2441 {
2442     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2443     auto bundleMgrHelper = DelayedSingleton<AppExecFwk::BundleMgrHelper>::GetInstance();
2444     CHECK_POINTER_AND_RETURN(bundleMgrHelper, false);
2445     auto validUserId = GetValidUserId(userId);
2446     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, userId: %{public}d, appIndex: %{public}d",
2447         bundleName.c_str(), validUserId, appIndex);
2448     AppExecFwk::ApplicationInfo appInfo;
2449     IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->GetApplicationInfoWithAppIndex(bundleName,
2450         appIndex, validUserId, appInfo));
2451     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2452     if (accessTokenId != appInfo.accessTokenId) {
2453         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
2454         return false;
2455     }
2456     return true;
2457 }
2458 
IsCallerSceneBoard()2459 bool AbilityManagerService::IsCallerSceneBoard()
2460 {
2461     int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2462     auto connectManager = GetConnectManagerByUserId(userId);
2463     CHECK_POINTER_AND_RETURN(connectManager, false);
2464     auto sceneBoardTokenId = connectManager->GetSceneBoardTokenId();
2465     if (sceneBoardTokenId != 0 && IPCSkeleton::GetCallingTokenID() == sceneBoardTokenId) {
2466         return true;
2467     }
2468     return false;
2469 }
2470 
IsBackgroundTaskUid(const int uid)2471 bool AbilityManagerService::IsBackgroundTaskUid(const int uid)
2472 {
2473 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2474     std::lock_guard<ffrt::mutex> lock(bgtaskObserverMutex_);
2475     if (bgtaskObserver_) {
2476         return bgtaskObserver_->IsBackgroundTaskUid(uid);
2477     }
2478     return false;
2479 #else
2480     return false;
2481 #endif
2482 }
2483 
IsDmsAlive() const2484 bool AbilityManagerService::IsDmsAlive() const
2485 {
2486     return g_isDmsAlive.load();
2487 }
2488 
AppUpgradeCompleted(int32_t uid)2489 void AbilityManagerService::AppUpgradeCompleted(int32_t uid)
2490 {
2491     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2492         TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
2493         return;
2494     }
2495 
2496     auto bms = AbilityUtil::GetBundleManagerHelper();
2497     CHECK_POINTER(bms);
2498     auto userId = uid / BASE_USER_RANGE;
2499     if (userId != U0_USER_ID && userId != GetUserId()) {
2500         TAG_LOGI(AAFwkTag::ABILITYMGR, "not current user");
2501         return;
2502     }
2503 
2504     AppExecFwk::BundleInfo bundleInfo;
2505     std::string bundleName;
2506     int32_t appIndex;
2507     if (IN_PROCESS_CALL(bms->GetNameAndIndexForUid(uid, bundleName, appIndex)) != ERR_OK) {
2508         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get appIndex for %{public}s", bundleName.c_str());
2509         return;
2510     }
2511     auto flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION)
2512         | static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE)
2513         | static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY)
2514         | static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY);
2515     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, userId: %{public}d, appIndex: %{public}d",
2516         bundleName.c_str(), userId, appIndex);
2517     if (IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName, flags, appIndex, bundleInfo, userId)) != ERR_OK) {
2518         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundle info for %{public}s", bundleName.c_str());
2519         return;
2520     }
2521 
2522     KeepAliveType type = KeepAliveType::UNSPECIFIED;
2523     if (!KeepAliveUtils::IsKeepAliveBundle(bundleInfo, userId, type)) {
2524         TAG_LOGW(AAFwkTag::ABILITYMGR, "not keep-alive application");
2525         return;
2526     }
2527 
2528     std::vector<AppExecFwk::BundleInfo> bundleInfos = { bundleInfo };
2529     if (type == KeepAliveType::THIRD_PARTY) {
2530         KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfos, userId);
2531     } else if (type == KeepAliveType::RESIDENT_PROCESS) {
2532         auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
2533         CHECK_POINTER(residentProcessManager);
2534         residentProcessManager->StartResidentProcessWithMainElement(bundleInfos, userId);
2535         if (!bundleInfos.empty()) {
2536             residentProcessManager->StartResidentProcess(bundleInfos);
2537         }
2538     }
2539 }
2540 
RecordAppExitReason(const ExitReason & exitReason)2541 int32_t AbilityManagerService::RecordAppExitReason(const ExitReason &exitReason)
2542 {
2543     TAG_LOGD(AAFwkTag::ABILITYMGR, "recordAppExitReason reason:%{public}d, exitMsg:%{public}s", exitReason.reason,
2544         exitReason.exitMsg.c_str());
2545 
2546     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2547     return appExitReasonHelper_->RecordAppExitReason(exitReason);
2548 }
2549 
RecordProcessExitReason(const int32_t pid,const ExitReason & exitReason)2550 int32_t AbilityManagerService::RecordProcessExitReason(const int32_t pid, const ExitReason &exitReason)
2551 {
2552     TAG_LOGI(AAFwkTag::ABILITYMGR, "recordProcessExitReason pid:%{public}d, reason:%{public}d, exitMsg:%{public}s",
2553         pid, exitReason.reason, exitReason.exitMsg.c_str());
2554 
2555     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
2556         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
2557         TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
2558         return ERR_PERMISSION_DENIED;
2559     }
2560 
2561     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2562     return appExitReasonHelper_->RecordProcessExitReason(pid, exitReason, false);
2563 }
2564 
RecordProcessExitReason(int32_t pid,int32_t uid,const ExitReason & exitReason)2565 int32_t AbilityManagerService::RecordProcessExitReason(int32_t pid, int32_t uid, const ExitReason &exitReason)
2566 {
2567     if (IPCSkeleton::GetCallingUid() != HIVIEW_UID) {
2568         TAG_LOGE(AAFwkTag::ABILITYMGR, "not expected caller");
2569         return ERR_NO_PERMISSION_CALLER;
2570     }
2571 
2572     TAG_LOGI(AAFwkTag::ABILITYMGR, "[EXIT_REASON_TAG] pid:%{public}d, reason:%{public}d, exitMsg:%{public}s",
2573         pid, exitReason.reason, exitReason.exitMsg.c_str());
2574 
2575     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_APP_EXIT_REASON_HELPER);
2576     return appExitReasonHelper_->RecordProcessExitReason(pid, uid, exitReason);
2577 }
2578 
ForceExitApp(const int32_t pid,const ExitReason & exitReason)2579 int32_t AbilityManagerService::ForceExitApp(const int32_t pid, const ExitReason &exitReason)
2580 {
2581     TAG_LOGI(AAFwkTag::ABILITYMGR, "forceExitApp pid:%{public}d, reason:%{public}d, exitMsg:%{public}s",
2582         pid, exitReason.reason, exitReason.exitMsg.c_str());
2583 
2584     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
2585         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
2586         TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa or shell call");
2587         return ERR_PERMISSION_DENIED;
2588     }
2589 
2590     AppExecFwk::ApplicationInfo application;
2591     bool debug = false;
2592     auto ret = IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->GetApplicationInfoByProcessID(pid,
2593         application, debug));
2594     if (ret != ERR_OK) {
2595         TAG_LOGE(AAFwkTag::ABILITYMGR, "getApplicationInfoByProcessID failed");
2596         return ret;
2597     }
2598 
2599     std::string bundleName = application.bundleName;
2600     int32_t uid = application.uid;
2601     int32_t appIndex = application.appIndex;
2602 
2603     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2604     appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
2605 
2606     return DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName, false, appIndex);
2607 }
2608 
GetConfiguration(AppExecFwk::Configuration & config)2609 int32_t AbilityManagerService::GetConfiguration(AppExecFwk::Configuration& config)
2610 {
2611     auto appMgr = AppMgrUtil::GetAppMgr();
2612     if (appMgr == nullptr) {
2613         TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
2614         return -1;
2615     }
2616 
2617     return appMgr->GetConfiguration(config);
2618 }
2619 
CheckOptExtensionAbility(const Want & want,AbilityRequest & abilityRequest,int32_t validUserId,AppExecFwk::ExtensionAbilityType extensionType,bool isImplicit,bool isStartAsCaller)2620 int AbilityManagerService::CheckOptExtensionAbility(const Want &want, AbilityRequest &abilityRequest,
2621     int32_t validUserId, AppExecFwk::ExtensionAbilityType extensionType, bool isImplicit, bool isStartAsCaller)
2622 {
2623     auto abilityInfo = abilityRequest.abilityInfo;
2624     auto type = abilityInfo.type;
2625     if (type != AppExecFwk::AbilityType::EXTENSION) {
2626         TAG_LOGE(AAFwkTag::ABILITYMGR, "not extension ability");
2627         return ERR_WRONG_INTERFACE_CALL;
2628     }
2629     if (extensionType != AppExecFwk::ExtensionAbilityType::UNSPECIFIED &&
2630         extensionType != abilityInfo.extensionAbilityType) {
2631         TAG_LOGE(AAFwkTag::ABILITYMGR, "extension ability type not match, set type:%{public}d, real type: %{public}d",
2632             static_cast<int32_t>(extensionType), static_cast<int32_t>(abilityInfo.extensionAbilityType));
2633         return ERR_WRONG_INTERFACE_CALL;
2634     }
2635 
2636     auto result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
2637     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2638         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result=%{public}d", result);
2639         return ERR_STATIC_CFG_PERMISSION;
2640     }
2641 
2642     if (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
2643         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE ||
2644         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2645         result = CheckCallServiceExtensionPermission(abilityRequest);
2646         if (result != ERR_OK) {
2647             return result;
2648         }
2649     } else {
2650         result = CheckCallOtherExtensionPermission(abilityRequest);
2651         if (result != ERR_OK) {
2652             return result;
2653         }
2654     }
2655     if (!isStartAsCaller) {
2656         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
2657     }
2658     return ERR_OK;
2659 }
2660 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2661 void AbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2662 {
2663     TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d add", systemAbilityId);
2664     switch (systemAbilityId) {
2665         case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2666             SubscribeBackgroundTask();
2667             break;
2668         }
2669         case DISTRIBUTED_SCHED_SA_ID: {
2670             g_isDmsAlive.store(true);
2671             break;
2672         }
2673         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2674             auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
2675             if (bundleMgrHelper) {
2676                 bundleMgrHelper->SetBmsReady(true);
2677             }
2678             SubscribeBundleEventCallback();
2679             break;
2680         }
2681 #ifdef SUPPORT_SCREEN
2682         case MULTIMODAL_INPUT_SERVICE_ID: {
2683             auto anrListener = std::make_shared<ApplicationAnrListener>();
2684             MMI::InputManager::GetInstance()->SetAnrObserver(anrListener);
2685             break;
2686         }
2687 #endif
2688         case WINDOW_MANAGER_SERVICE_ID: {
2689             InitWindowVisibilityChangedListener();
2690             break;
2691         }
2692         default:
2693             break;
2694     }
2695 }
2696 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2697 void AbilityManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2698 {
2699     TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d remove", systemAbilityId);
2700     switch (systemAbilityId) {
2701         case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2702             UnSubscribeBackgroundTask();
2703             break;
2704         }
2705         case DISTRIBUTED_SCHED_SA_ID: {
2706             g_isDmsAlive.store(false);
2707             break;
2708         }
2709         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2710             UnsubscribeBundleEventCallback();
2711             break;
2712         }
2713         case WINDOW_MANAGER_SERVICE_ID: {
2714             FreeWindowVisibilityChangedListener();
2715             break;
2716         }
2717         default:
2718             break;
2719     }
2720 }
2721 
SubscribeBackgroundTask()2722 void AbilityManagerService::SubscribeBackgroundTask()
2723 {
2724 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2725     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2726     if (!bgtaskObserver_) {
2727         bgtaskObserver_ = std::make_shared<BackgroundTaskObserver>();
2728     }
2729     int ret = BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver_);
2730     if (ret != ERR_OK) {
2731         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s failed, err:%{public}d", __func__, ret);
2732         return;
2733     }
2734     bgtaskObserver_->GetContinuousTaskApps();
2735     bgtaskObserver_->GetEfficiencyResourcesTaskApps();
2736     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success", __func__);
2737 #endif
2738 }
2739 
UnSubscribeBackgroundTask()2740 void AbilityManagerService::UnSubscribeBackgroundTask()
2741 {
2742 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2743     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2744     if (!bgtaskObserver_) {
2745         return;
2746     }
2747     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success", __func__);
2748 #endif
2749 }
2750 
SubscribeBundleEventCallback()2751 void AbilityManagerService::SubscribeBundleEventCallback()
2752 {
2753     TAG_LOGI(AAFwkTag::ABILITYMGR, "subscribeBundleEventCallback begin");
2754     if (taskHandler_) {
2755         TAG_LOGI(AAFwkTag::ABILITYMGR, "submit startResidentApps task");
2756         auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(U0_USER_ID); };
2757         taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps");
2758     }
2759 
2760     if (abilityBundleEventCallback_) {
2761         return;
2762     }
2763 
2764     // Register abilityBundleEventCallback to receive hap updates
2765     abilityBundleEventCallback_ =
2766         new (std::nothrow) AbilityBundleEventCallback(taskHandler_, abilityAutoStartupService_);
2767     auto bms = AbilityUtil::GetBundleManagerHelper();
2768     if (bms) {
2769         bool ret = IN_PROCESS_CALL(bms->RegisterBundleEventCallback(abilityBundleEventCallback_));
2770         if (!ret) {
2771             TAG_LOGE(AAFwkTag::ABILITYMGR, "registerBundleEventCallback failed");
2772         }
2773     } else {
2774         TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundleManager failed");
2775     }
2776     TAG_LOGD(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback success.");
2777 }
2778 
UnsubscribeBundleEventCallback()2779 void AbilityManagerService::UnsubscribeBundleEventCallback()
2780 {
2781     if (!abilityBundleEventCallback_) {
2782         return;
2783     }
2784     abilityBundleEventCallback_ = nullptr;
2785     TAG_LOGD(AAFwkTag::ABILITYMGR, "UnsubscribeBundleEventCallback success.");
2786 }
2787 
ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo)2788 void AbilityManagerService::ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo)
2789 {
2790     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2791     if (abilityInfo.type == AppExecFwk::AbilityType::PAGE &&
2792         abilityInfo.launchMode != AppExecFwk::LaunchMode::SPECIFIED) {
2793         std::vector<AppExecFwk::RunningProcessInfo> runningProcessInfos;
2794         if (IN_PROCESS_CALL(GetProcessRunningInfos(runningProcessInfos)) != ERR_OK) {
2795             return;
2796         }
2797         bool isColdStart = true;
2798         int32_t pid = 0;
2799         int32_t warmStartType = -1;
2800         for (auto const &info : runningProcessInfos) {
2801             if (info.uid_ == abilityInfo.applicationInfo.uid) {
2802                 isColdStart = false;
2803                 pid = info.pid_;
2804                 warmStartType = static_cast<int32_t>(info.preloadMode_);
2805                 break;
2806             }
2807         }
2808         ResSchedUtil::GetInstance().ReportAbilityStartInfoToRSS(abilityInfo, pid, isColdStart, warmStartType);
2809     }
2810 }
2811 
ReportAbilityAssociatedStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo,int64_t type,const sptr<IRemoteObject> & callerToken)2812 void AbilityManagerService::ReportAbilityAssociatedStartInfoToRSS(
2813     const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr<IRemoteObject> &callerToken)
2814 {
2815     CHECK_POINTER_LOG(callerToken, "null callerToken");
2816     auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2817     CHECK_POINTER_LOG(callerAbility, "null callerAbility");
2818     int32_t callerUid = callerAbility->GetUid();
2819     int32_t callerPid = callerAbility->GetPid();
2820     ResSchedUtil::GetInstance().ReportAbilityAssociatedStartInfoToRSS(abilityInfo, type, callerUid, callerPid);
2821 }
2822 
ReportEventToRSS(const AppExecFwk::AbilityInfo & abilityInfo,sptr<IRemoteObject> callerToken)2823 void AbilityManagerService::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo,
2824     sptr<IRemoteObject> callerToken)
2825 {
2826     CHECK_POINTER_LOG(taskHandler_, "taskhandler null");
2827     std::string reason = ResSchedUtil::GetInstance().GetThawReasonByAbilityType(abilityInfo);
2828     const auto uid = abilityInfo.applicationInfo.uid;
2829     const auto bundleName = abilityInfo.applicationInfo.bundleName;
2830     auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2831     const int32_t callerPid = (callerAbility != nullptr) ? callerAbility->GetPid() : IPCSkeleton::GetCallingPid();
2832     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}d_%{public}s reason=%{public}s callerPid=%{public}d", uid,
2833         bundleName.c_str(), reason.c_str(), callerPid);
2834     taskHandler_->SubmitTask([reason, uid, bundleName, callerPid]() {
2835         ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason, -1, callerPid);
2836     });
2837 }
2838 
ReportAppConnectOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want)2839 void AbilityManagerService::ReportAppConnectOtherExtensionEvent(const AppExecFwk::AbilityInfo &abilityInfo,
2840     const Want &want)
2841 {
2842     if (PermissionVerification::GetInstance()->IsSACall()) {
2843         return;
2844     }
2845     const std::unordered_set<AppExecFwk::ExtensionAbilityType> extensionSet {
2846         AppExecFwk::ExtensionAbilityType::FORM,
2847         AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER,
2848         AppExecFwk::ExtensionAbilityType::INPUTMETHOD,
2849         AppExecFwk::ExtensionAbilityType::ACCESSIBILITY,
2850         AppExecFwk::ExtensionAbilityType::STATICSUBSCRIBER,
2851         AppExecFwk::ExtensionAbilityType::WALLPAPER,
2852         AppExecFwk::ExtensionAbilityType::BACKUP,
2853         AppExecFwk::ExtensionAbilityType::ENTERPRISE_ADMIN,
2854         AppExecFwk::ExtensionAbilityType::PRINT,
2855         AppExecFwk::ExtensionAbilityType::VPN,
2856         AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION,
2857         AppExecFwk::ExtensionAbilityType::REMOTE_NOTIFICATION,
2858         AppExecFwk::ExtensionAbilityType::REMOTE_LOCATION,
2859         AppExecFwk::ExtensionAbilityType::PUSH,
2860         AppExecFwk::ExtensionAbilityType::VOIP
2861     };
2862     if (extensionSet.find(abilityInfo.extensionAbilityType) != extensionSet.end()) {
2863         EventInfo eventInfo;
2864         eventInfo.bundleName = abilityInfo.bundleName;
2865         eventInfo.moduleName = abilityInfo.moduleName;
2866         eventInfo.abilityName = abilityInfo.name;
2867         eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
2868         eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
2869         if (eventInfo.callerBundleName.empty()) {
2870             eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
2871         }
2872         // Add prefix to distinguish reporting scenarios
2873         eventInfo.callerBundleName = "Connect:" + eventInfo.callerBundleName;
2874         EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
2875     }
2876 }
2877 
StartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2878 int32_t AbilityManagerService::StartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2879     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2880 {
2881     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2882     if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2883         if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
2884             TAG_LOGE(AAFwkTag::SERVICE_EXT, "uiServiceExtensionAbility disable");
2885             return ERR_CAPABILITY_NOT_SUPPORT;
2886         }
2887     }
2888     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2889     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN ||
2890         extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2891         return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false);
2892     }
2893     return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true);
2894 }
2895 
ImplicitStartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2896 int AbilityManagerService::ImplicitStartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2897     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2898 {
2899     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2900     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
2901         return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false, true);
2902     }
2903     return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true, true);
2904 }
2905 
PreloadUIExtensionAbility(const Want & want,std::string & bundleName,int32_t userId,int32_t hostPid)2906 int AbilityManagerService::PreloadUIExtensionAbility(const Want &want, std::string &bundleName,
2907     int32_t userId, int32_t hostPid)
2908 {
2909     TAG_LOGI(AAFwkTag::UI_EXT, "PreloadUIExtensionAbility callerBundle: %{public}s", bundleName.c_str());
2910     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2911     // check preload ui extension permission.
2912     CHECK_CALLER_IS_SYSTEM_APP;
2913     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
2914         PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
2915         TAG_LOGE(AAFwkTag::UI_EXT, "permission %{public}s verification failed",
2916             PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
2917         return ERR_PERMISSION_DENIED;
2918     }
2919     return PreloadUIExtensionAbilityInner(want, bundleName, userId, hostPid);
2920 }
2921 
PreloadUIExtensionAbilityInner(const Want & want,std::string & hostBundleName,int32_t userId,int32_t hostPid)2922 int AbilityManagerService::PreloadUIExtensionAbilityInner(const Want &want, std::string &hostBundleName,
2923     int32_t userId, int32_t hostPid)
2924 {
2925     TAG_LOGD(AAFwkTag::UI_EXT, "PreloadUIExtension called, elementName: %{public}s.",
2926         want.GetElement().GetURI().c_str());
2927     int32_t validUserId = GetValidUserId(userId);
2928     AbilityRequest abilityRequest;
2929     ErrCode result = ERR_OK;
2930     result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, validUserId);
2931     if (result != ERR_OK) {
2932         TAG_LOGE(AAFwkTag::UI_EXT, "generate abilityReq error");
2933         return result;
2934     }
2935     abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
2936     abilityRequest.want.SetParam(IS_PRELOAD_UIEXTENSION_ABILITY, true);
2937     auto abilityInfo = abilityRequest.abilityInfo;
2938     auto res = JudgeAbilityVisibleControl(abilityInfo);
2939     if (res != ERR_OK) {
2940         TAG_LOGE(AAFwkTag::UI_EXT, "target ability invisible");
2941         return res;
2942     }
2943     auto connectManager = GetConnectManagerByUserId(validUserId);
2944     if (connectManager == nullptr) {
2945         TAG_LOGE(AAFwkTag::UI_EXT, "connectManager null, userId:%{public}d", validUserId);
2946         return ERR_INVALID_VALUE;
2947     }
2948     return connectManager->PreloadUIExtensionAbilityLocked(abilityRequest, hostBundleName, hostPid);
2949 }
2950 
UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> & abilityRecord,std::string & hostBundleName)2951 int AbilityManagerService::UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> &abilityRecord,
2952     std::string &hostBundleName)
2953 {
2954     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
2955     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2956     auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
2957     if (connectManager == nullptr) {
2958         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null");
2959         return ERR_INVALID_VALUE;
2960     }
2961     return connectManager->UnloadUIExtensionAbility(abilityRecord, hostBundleName);
2962 }
2963 
RequestModalUIExtension(const Want & want)2964 int AbilityManagerService::RequestModalUIExtension(const Want &want)
2965 {
2966     CHECK_CALLER_IS_SYSTEM_APP;
2967     return RequestModalUIExtensionInner(want);
2968 }
2969 
RequestModalUIExtensionInner(Want want)2970 int AbilityManagerService::RequestModalUIExtensionInner(Want want)
2971 {
2972     sptr<IRemoteObject> token = nullptr;
2973     int ret = IN_PROCESS_CALL(GetTopAbility(token));
2974     if (ret == ERR_OK && token != nullptr) {
2975         // Gets the record corresponding to the current focus appliaction
2976         auto record = Token::GetAbilityRecordByToken(token);
2977         if (!record) {
2978             TAG_LOGE(AAFwkTag::ABILITYMGR, "record null");
2979             return ERR_INVALID_VALUE;
2980         }
2981 
2982         // Gets the bundleName corresponding to the
2983         // current focus appliaction
2984         std::string focusName = record->GetAbilityInfo().bundleName;
2985 
2986         // Gets the bundleName corresponding to the
2987         // current focus appliaction
2988         std::string callerName = want.GetParams().GetStringParam("bundleName");
2989 
2990         TAG_LOGI(AAFwkTag::ABILITYMGR,
2991                "focusbundlename: %{public}s, callerbundlename: %{public}s",
2992                focusName.c_str(), callerName.c_str());
2993 
2994         // Compare
2995         if (record->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
2996             focusName == callerName) {
2997             TAG_LOGD(AAFwkTag::ABILITYMGR, "CreateModalUIExtension is called!");
2998             return record->CreateModalUIExtension(want);
2999         }
3000     } else {
3001         TAG_LOGW(AAFwkTag::ABILITYMGR, "token null");
3002     }
3003 
3004     TAG_LOGD(AAFwkTag::ABILITYMGR, "Window Modal System Create UIExtension is called!");
3005     want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
3006     auto connection = std::make_shared<Rosen::ModalSystemUiExtension>();
3007     return connection->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR;
3008 }
3009 
ChangeAbilityVisibility(sptr<IRemoteObject> token,bool isShow)3010 int AbilityManagerService::ChangeAbilityVisibility(sptr<IRemoteObject> token, bool isShow)
3011 {
3012     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
3013     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
3014         TAG_LOGE(AAFwkTag::ABILITYMGR, "capability not support");
3015         return ERR_CAPABILITY_NOT_SUPPORT;
3016     }
3017     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3018     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3019     return uiAbilityManager->ChangeAbilityVisibility(token, isShow);
3020 }
3021 
ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo,bool isShow)3022 int AbilityManagerService::ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo, bool isShow)
3023 {
3024     if (!IsCallerSceneBoard()) {
3025         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3026         return ERR_WRONG_INTERFACE_CALL;
3027     }
3028     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3029     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3030     return uiAbilityManager->ChangeUIAbilityVisibilityBySCB(sessionInfo, isShow);
3031 }
3032 
CheckWorkSchedulerPermission(const sptr<IRemoteObject> & callerToken,const uint32_t uid)3033 bool AbilityManagerService::CheckWorkSchedulerPermission(const sptr<IRemoteObject> &callerToken, const uint32_t uid)
3034 {
3035 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
3036     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
3037     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
3038     if (bgtaskObserver_ && abilityRecord) {
3039         auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
3040         if (callerAbilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER) {
3041             return true;
3042         }
3043 
3044         if (!bgtaskObserver_->IsEfficiencyResourcesTaskUid(uid)) {
3045             TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to start extension by WorkScheduler");
3046             return false;
3047         }
3048     }
3049 #endif
3050     return true;
3051 }
3052 
StartExtensionAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType,bool checkSystemCaller,bool isImplicit,bool isDlp,bool isStartAsCaller)3053 int32_t AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
3054     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller, bool isImplicit,
3055     bool isDlp, bool isStartAsCaller)
3056 {
3057     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3058     TAG_LOGI(AAFwkTag::SERVICE_EXT,
3059         "Start extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
3060         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3061     if (checkSystemCaller) {
3062         CHECK_CALLER_IS_SYSTEM_APP;
3063     }
3064     EventInfo eventInfo = BuildEventInfo(want, userId);
3065     eventInfo.extensionType = static_cast<int32_t>(extensionType);
3066 
3067     int result;
3068 #ifdef WITH_DLP
3069     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::START_EXTENSION_ERROR);
3070     if (result != ERR_OK) {
3071         TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckDlpForExtension error");
3072         return result;
3073     }
3074 #endif // WITH_DLP
3075 
3076     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3077         TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s verificationAllToken failed", __func__);
3078         eventInfo.errCode = ERR_INVALID_VALUE;
3079         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3080         return ERR_INVALID_CALLER;
3081     }
3082 
3083     int32_t validUserId = GetValidUserId(userId);
3084     int32_t appIndex = 0;
3085     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
3086         eventInfo.errCode = ERR_APP_CLONE_INDEX_INVALID;
3087         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3088         return ERR_APP_CLONE_INDEX_INVALID;
3089     }
3090     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken, true);
3091     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
3092     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
3093         shouldBlockFunc);
3094     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3095         interceptorExecuter_->DoProcess(interceptorParam);
3096     if (result != ERR_OK) {
3097         TAG_LOGE(AAFwkTag::SERVICE_EXT, "interceptorExecuter_ null or doProcess error");
3098         eventInfo.errCode = result;
3099         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3100         return result;
3101     }
3102 
3103     if (!JudgeMultiUserConcurrency(validUserId)) {
3104         TAG_LOGE(AAFwkTag::SERVICE_EXT, "multi-user non-concurrent unsatisfied");
3105         eventInfo.errCode = ERR_CROSS_USER;
3106         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3107         return ERR_CROSS_USER;
3108     }
3109 
3110     AbilityRequest abilityRequest;
3111 #ifdef SUPPORT_SCREEN
3112     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
3113         TAG_LOGD(AAFwkTag::SERVICE_EXT, "is implicit start action");
3114         abilityRequest.Voluation(want, DEFAULT_INVAL_VALUE, callerToken);
3115         abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
3116         abilityRequest.extensionType = extensionType;
3117         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
3118         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
3119         if (result != ERR_OK) {
3120             TAG_LOGE(AAFwkTag::SERVICE_EXT, "implicit start ability error");
3121             eventInfo.errCode = result;
3122             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3123         }
3124         return result;
3125     }
3126 #endif
3127     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
3128     if (result != ERR_OK) {
3129         TAG_LOGE(AAFwkTag::SERVICE_EXT, "generate ability request local error");
3130         eventInfo.errCode = result;
3131         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3132         return result;
3133     }
3134 
3135     if (!CheckWorkSchedulerPermission(callerToken, abilityRequest.abilityInfo.applicationInfo.uid)) {
3136         return CHECK_PERMISSION_FAILED;
3137     }
3138     auto abilityInfo = abilityRequest.abilityInfo;
3139     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3140     TAG_LOGD(AAFwkTag::SERVICE_EXT, "userId is : %{public}d, singleton is : %{public}d",
3141         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3142 
3143     result = isDlp ? IN_PROCESS_CALL(
3144         CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller)) :
3145         CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller);
3146     if (result != ERR_OK) {
3147         TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkOptExtensionAbility error");
3148         eventInfo.errCode = result;
3149         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3150         return result;
3151     }
3152 
3153     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
3154         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
3155     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
3156         afterCheckExecuter_->DoProcess(afterCheckParam);
3157     if (result != ERR_OK) {
3158         TAG_LOGE(AAFwkTag::SERVICE_EXT, "afterCheckExecuter_ null or doProcess error");
3159         eventInfo.errCode = result;
3160         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3161         return result;
3162     }
3163 
3164     auto connectManager = GetConnectManagerByUserId(validUserId);
3165     if (!connectManager) {
3166         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", validUserId);
3167         eventInfo.errCode = ERR_INVALID_VALUE;
3168         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3169         return ERR_INVALID_VALUE;
3170     }
3171     if (!isStartAsCaller) {
3172         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
3173     }
3174 
3175     TAG_LOGD(AAFwkTag::SERVICE_EXT, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
3176     SetAbilityRequestSessionInfo(abilityRequest, extensionType);
3177     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
3178     if (eventInfo.errCode != ERR_OK) {
3179         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3180     }
3181     ReportAbilityAssociatedStartInfoToRSS(abilityRequest.abilityInfo, RES_TYPE_EXTENSION_START_ABILITY, callerToken);
3182     return eventInfo.errCode;
3183 }
3184 
SetPickerElementName(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)3185 void AbilityManagerService::SetPickerElementName(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
3186 {
3187     CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
3188     std::string targetType = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TARGET_TYPE_KEY);
3189     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
3190         extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
3191         extensionSessionInfo->want.GetElement().GetAbilityName().empty() &&
3192         COMMON_PICKER_TYPE.find(targetType) != COMMON_PICKER_TYPE.end()) {
3193         std::string abilityName = "CommonSelectPickerAbility";
3194         std::string bundleName = "com.ohos.amsdialog";
3195         extensionSessionInfo->want.SetElementName(bundleName, abilityName);
3196         WantParams &parameters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
3197         parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box("sys/commonUI"));
3198         extensionSessionInfo->want.SetParams(parameters);
3199         return;
3200     }
3201     if (extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
3202         extensionSessionInfo->want.GetElement().GetAbilityName().empty() && !targetType.empty()) {
3203         std::string abilityName;
3204         std::string bundleName;
3205         std::string pickerType;
3206         std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
3207         auto pickerMap = AmsConfigurationParameter::GetInstance().GetPickerMap();
3208         auto it = pickerMap.find(targetType);
3209         if (it == pickerMap.end()) {
3210             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not find targetType:%{public}s", targetType.c_str());
3211             return;
3212         }
3213         pickerType = it->second;
3214         auto bms = AbilityUtil::GetBundleManagerHelper();
3215         CHECK_POINTER(bms);
3216         int32_t validUserId = GetValidUserId(userId);
3217         TAG_LOGI(AAFwkTag::ABILITYMGR, "targetType: %{public}s, pickerType: %{public}s, userId: %{public}d",
3218             targetType.c_str(), pickerType.c_str(), validUserId);
3219         auto flags = static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION) |
3220             static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_BY_TYPE_NAME);
3221         auto ret = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfosOnlyWithTypeName(pickerType,
3222             flags,
3223             validUserId,
3224             extensionInfos));
3225         if (ret != ERR_OK) {
3226             TAG_LOGE(AAFwkTag::ABILITYMGR, "queryExtensionAbilityInfosOnlyWithTypeName failed");
3227             return;
3228         }
3229         abilityName = extensionInfos[0].name;
3230         bundleName = extensionInfos[0].bundleName;
3231         TAG_LOGI(AAFwkTag::ABILITYMGR,
3232             "abilityName: %{public}s, bundleName: %{public}s", abilityName.c_str(), bundleName.c_str());
3233         extensionSessionInfo->want.SetElementName(bundleName, abilityName);
3234         WantParams &parameters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
3235         parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box(pickerType));
3236         extensionSessionInfo->want.SetParams(parameters);
3237     }
3238 }
3239 
SetAutoFillElementName(const sptr<SessionInfo> & extensionSessionInfo)3240 void AbilityManagerService::SetAutoFillElementName(const sptr<SessionInfo> &extensionSessionInfo)
3241 {
3242 #ifdef SUPPORT_AUTO_FILL
3243     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
3244     CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
3245     std::vector<std::string> argList;
3246     if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_PASSWORD_TYPE) {
3247         SplitStr(KEY_AUTO_FILL_ABILITY, "/", argList);
3248     } else if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_SMART_TYPE) {
3249         SplitStr(KEY_SMART_AUTO_FILL_ABILITY, "/", argList);
3250     } else {
3251         TAG_LOGW(AAFwkTag::ABILITYMGR, "not autofill");
3252         return;
3253     }
3254 
3255     if (argList.size() != ARGC_THREE) {
3256         TAG_LOGE(AAFwkTag::ABILITYMGR, "parse extension element name failed");
3257         return;
3258     }
3259     extensionSessionInfo->want.SetElementName(argList[INDEX_ZERO], argList[INDEX_TWO]);
3260     extensionSessionInfo->want.SetModuleName(argList[INDEX_ONE]);
3261 #endif // SUPPORT_AUTO_FILL
3262 }
3263 
CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,AppExecFwk::ExtensionAbilityType extensionType)3264 int AbilityManagerService::CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,
3265     AppExecFwk::ExtensionAbilityType extensionType)
3266 {
3267     if (uiExtensionUsage == UIExtensionUsage::EMBEDDED &&
3268         !AAFwk::UIExtensionUtils::IsPublicForEmbedded(extensionType)) {
3269         CHECK_CALLER_IS_SYSTEM_APP;
3270     }
3271 
3272     if (uiExtensionUsage == UIExtensionUsage::CONSTRAINED_EMBEDDED &&
3273         !AAFwk::UIExtensionUtils::IsPublicForConstrainedEmbedded(extensionType)) {
3274         TAG_LOGE(AAFwkTag::ABILITYMGR, "secureConstrainedEmbedded extension type error:%u.", extensionType);
3275         return ERR_INVALID_VALUE;
3276     }
3277 
3278     if (AAFwk::UIExtensionUtils::IsOnlyForModal(extensionType) &&
3279         uiExtensionUsage != UIExtensionUsage::MODAL) {
3280         TAG_LOGE(AAFwkTag::ABILITYMGR, "secureModal extension type error:%u.", extensionType);
3281         return ERR_INVALID_VALUE;
3282     }
3283 
3284     return ERR_OK;
3285 }
3286 
StartUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)3287 int AbilityManagerService::StartUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
3288 {
3289     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3290     TAG_LOGD(AAFwkTag::UI_EXT, "StartUIExtensionAbility begin");
3291     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3292     SetPickerElementName(extensionSessionInfo, userId);
3293     SetAutoFillElementName(extensionSessionInfo);
3294 
3295     if (extensionSessionInfo->want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
3296         int32_t screenMode = extensionSessionInfo->want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
3297         if (!IsEmbeddableStart(screenMode)) {
3298             TAG_LOGE(AAFwkTag::UI_EXT, "only support embedded pull-ups");
3299             return ERR_INVALID_VALUE;
3300         }
3301         auto bms = AbilityUtil::GetBundleManagerHelper();
3302         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3303         TAG_LOGD(AAFwkTag::UI_EXT, "bundleName: %{public}s, userId: %{public}d",
3304             extensionSessionInfo->want.GetBundle().c_str(), GetValidUserId(userId));
3305         AppExecFwk::BundleInfo bundleInfo;
3306         if (!IN_PROCESS_CALL(bms->GetBundleInfo(extensionSessionInfo->want.GetBundle(),
3307             AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, GetValidUserId(userId)))) {
3308             TAG_LOGE(AAFwkTag::UI_EXT, "verifyPermission failed get application info");
3309             return CHECK_PERMISSION_FAILED;
3310         }
3311         if (bundleInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE) {
3312             TAG_LOGE(AAFwkTag::UI_EXT, "only support atomicService");
3313             return ERR_INVALID_CALLER;
3314         }
3315         if (extensionSessionInfo->want.GetElement().GetAbilityName().empty()) {
3316             if (bundleInfo.abilityInfos.empty()) {
3317                 TAG_LOGE(AAFwkTag::UI_EXT, "failed get abilityInfos");
3318                 return ERR_INVALID_VALUE;
3319             }
3320             extensionSessionInfo->want.SetElementName(bundleInfo.name, bundleInfo.abilityInfos.begin()->name);
3321         }
3322         extensionSessionInfo->want.SetParam("send_to_erms_embedded", 1);
3323     }
3324     std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY);
3325     AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ?
3326         AppExecFwk::ExtensionAbilityType::UI : AppExecFwk::ConvertToExtensionAbilityType(extensionTypeStr);
3327     if (extensionType == AppExecFwk::ExtensionAbilityType::UNSPECIFIED) {
3328         TAG_LOGE(AAFwkTag::UI_EXT, "input extension ability type invalid");
3329         return ERR_INVALID_VALUE;
3330     }
3331     EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, userId);
3332     eventInfo.extensionType = static_cast<int32_t>(extensionType);
3333 
3334     auto ret = CheckUIExtensionUsage(extensionSessionInfo->uiExtensionUsage, extensionType);
3335     if (ret != ERR_OK) {
3336         TAG_LOGE(AAFwkTag::UI_EXT, "check usage failed");
3337         return ret;
3338     }
3339 
3340     if (InsightIntentExecuteParam::IsInsightIntentExecute(extensionSessionInfo->want)) {
3341         auto callerBundlename = InsightIntentGetcallerBundleName();
3342         if (callerBundlename.empty()) {
3343             TAG_LOGD(AAFwkTag::ABILITYMGR, "insightIntent get callerBundlename failed");
3344         }
3345         int32_t result = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateWant(
3346             extensionSessionInfo->want, AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY, callerBundlename);
3347         if (result != ERR_OK) {
3348             eventInfo.errCode = ERR_INVALID_VALUE;
3349             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3350             return result;
3351         }
3352     }
3353 
3354     sptr<IRemoteObject> callerToken = extensionSessionInfo->callerToken;
3355 
3356 #ifdef WITH_DLP
3357     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, extensionSessionInfo->want) ||
3358         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
3359         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, extensionSessionInfo->want)) {
3360         TAG_LOGE(AAFwkTag::UI_EXT, "startUIExtensionAbility: permission verification failed");
3361         eventInfo.errCode = CHECK_PERMISSION_FAILED;
3362         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3363         return CHECK_PERMISSION_FAILED;
3364     }
3365 #endif // WITH_DLP
3366 
3367     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3368         TAG_LOGE(AAFwkTag::UI_EXT, "startUIExtensionAbility verificationAllToken failed");
3369         eventInfo.errCode = ERR_INVALID_VALUE;
3370         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3371         return ERR_INVALID_CALLER;
3372     }
3373 
3374     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
3375     if (callerRecord == nullptr || !JudgeSelfCalled(callerRecord)) {
3376         TAG_LOGE(AAFwkTag::UI_EXT, "invalid callerToken");
3377         eventInfo.errCode = ERR_INVALID_VALUE;
3378         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3379         return ERR_INVALID_CALLER;
3380     }
3381     StartAbilityInfoWrap threadLocalInfo;
3382 
3383     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
3384     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(extensionSessionInfo->want, 0, GetUserId(),
3385         true, nullptr, shouldBlockFunc);
3386     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3387         interceptorExecuter_->DoProcess(interceptorParam);
3388     if (result != ERR_OK) {
3389         TAG_LOGE(AAFwkTag::UI_EXT, "interceptorExecuter_ null or doProcess error");
3390         eventInfo.errCode = result;
3391         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3392         return result;
3393     }
3394 
3395     int32_t validUserId = GetValidUserId(userId);
3396     if (!JudgeMultiUserConcurrency(validUserId)) {
3397         TAG_LOGE(AAFwkTag::UI_EXT, "multi-user non-concurrent unsatisfied");
3398         eventInfo.errCode = ERR_INVALID_VALUE;
3399         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3400         return ERR_INVALID_VALUE;
3401     }
3402 #ifdef SUPPORT_GRAPHICS
3403     if (ImplicitStartProcessor::IsImplicitStartAction(extensionSessionInfo->want)) {
3404         TAG_LOGE(AAFwkTag::UI_EXT, "UI extension ability not support implicit start");
3405         eventInfo.errCode = ERR_INVALID_VALUE;
3406         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3407         return ERR_INVALID_VALUE;
3408     }
3409 #endif // SUPPORT_GRAPHICS
3410     AbilityRequest abilityRequest;
3411     abilityRequest.Voluation(extensionSessionInfo->want, DEFAULT_INVAL_VALUE, callerToken);
3412     abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
3413     abilityRequest.sessionInfo = extensionSessionInfo;
3414     result = GenerateEmbeddableUIAbilityRequest(extensionSessionInfo->want, abilityRequest, callerToken, validUserId);
3415     CHECK_POINTER_AND_RETURN(abilityRequest.sessionInfo, ERR_INVALID_VALUE);
3416     abilityRequest.sessionInfo->uiExtensionComponentId = (
3417         static_cast<uint64_t>(callerRecord->GetRecordId()) << OFFSET) |
3418         static_cast<uint64_t>(abilityRequest.sessionInfo->persistentId);
3419     TAG_LOGI(AAFwkTag::UI_EXT, "StartUIExtension: persistentId: %{public}d, element: %{public}s.",
3420         abilityRequest.sessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3421     if (result != ERR_OK) {
3422         TAG_LOGE(AAFwkTag::UI_EXT, "generate ability request local error");
3423         eventInfo.errCode = result;
3424         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3425         return result;
3426     }
3427     abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
3428 
3429     auto abilityInfo = abilityRequest.abilityInfo;
3430     threadLocalInfo.SetStartAbilityInfo(abilityInfo);
3431     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3432     TAG_LOGD(AAFwkTag::UI_EXT, "userId is : %{public}d, singleton is : %{public}d",
3433         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3434 
3435     result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType);
3436     if (result != ERR_OK) {
3437         TAG_LOGE(AAFwkTag::UI_EXT, "checkOptExtensionAbility error");
3438         eventInfo.errCode = result;
3439         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3440         return result;
3441     }
3442 
3443     sptr<IRemoteObject> parentToken = extensionSessionInfo->parentToken;
3444     if (parentToken && parentToken != callerToken) {
3445         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, parentToken);
3446     }
3447 
3448     result = JudgeAbilityVisibleControl(abilityInfo);
3449     if (result != ERR_OK) {
3450         TAG_LOGE(AAFwkTag::UI_EXT, "judgeAbilityVisibleControl error");
3451         eventInfo.errCode = result;
3452         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3453         return result;
3454     }
3455 
3456     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
3457         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
3458     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
3459         afterCheckExecuter_->DoProcess(afterCheckParam);
3460     if (result != ERR_OK) {
3461         TAG_LOGE(AAFwkTag::UI_EXT, "afterCheckExecuter_ null or doProcess error");
3462         return result;
3463     }
3464 
3465     auto connectManager = GetConnectManagerByUserId(validUserId);
3466     if (!connectManager) {
3467         TAG_LOGE(AAFwkTag::UI_EXT, "connectManager null userId=%{public}d", validUserId);
3468         eventInfo.errCode = ERR_INVALID_VALUE;
3469         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3470         return ERR_INVALID_VALUE;
3471     }
3472     ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
3473     TAG_LOGD(AAFwkTag::UI_EXT, "name:%{public}s", abilityInfo.name.c_str());
3474 #ifdef SUPPORT_GRAPHICS
3475     // for implicit system selector modal dialog
3476     bool isSCBCall = (callerRecord->GetApplicationInfo().bundleName == AbilityConfig::SCENEBOARD_BUNDLE_NAME);
3477     DialogSessionManager::GetInstance().UpdateExtensionWantWithDialogCallerInfo(abilityRequest, callerToken,
3478         isSCBCall);
3479 #endif // SUPPORT_GRAPHICS
3480     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
3481     if (eventInfo.errCode != ERR_OK) {
3482         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3483     }
3484     return eventInfo.errCode;
3485 }
3486 
StopExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)3487 int AbilityManagerService::StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
3488     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
3489 {
3490     TAG_LOGI(AAFwkTag::SERVICE_EXT,
3491         "bundlename:%{public}s, ability:%{public}s, userId:%{public}d",
3492         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3493     if (extensionType != AppExecFwk::ExtensionAbilityType::VPN) {
3494         CHECK_CALLER_IS_SYSTEM_APP;
3495     }
3496     EventInfo eventInfo = BuildEventInfo(want, userId);
3497     eventInfo.extensionType = static_cast<int32_t>(extensionType);
3498 
3499     int result;
3500 #ifdef WITH_DLP
3501     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::STOP_EXTENSION_ERROR);
3502     if (result != ERR_OK) {
3503         TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckDlpForExtension error");
3504         return result;
3505     }
3506 #endif // WITH_DLP
3507 
3508     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3509         TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s verificationAllToken failed", __func__);
3510         if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
3511             TAG_LOGE(AAFwkTag::SERVICE_EXT, "verificationAllToken failed");
3512             eventInfo.errCode = ERR_INVALID_VALUE;
3513             EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3514             return ERR_INVALID_CALLER;
3515         }
3516         TAG_LOGD(AAFwkTag::SERVICE_EXT, "Caller is specific system ability.");
3517     }
3518 
3519     int32_t validUserId = GetValidUserId(userId);
3520     if (!JudgeMultiUserConcurrency(validUserId)) {
3521         TAG_LOGE(AAFwkTag::SERVICE_EXT, "multi-user non-concurrent unsatisfied");
3522         eventInfo.errCode = ERR_INVALID_VALUE;
3523         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3524         return ERR_CROSS_USER;
3525     }
3526 
3527     if (callerToken != nullptr && CheckIfOperateRemote(want)) {
3528         auto callerUid = IPCSkeleton::GetCallingUid();
3529         uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3530         DistributedClient dmsClient;
3531         return dmsClient.StopRemoteExtensionAbility(want, callerUid, accessToken, eventInfo.extensionType);
3532     }
3533 
3534     AbilityRequest abilityRequest;
3535     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
3536     if (result != ERR_OK) {
3537         TAG_LOGE(AAFwkTag::SERVICE_EXT, "generate ability request local error");
3538         eventInfo.errCode = result;
3539         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3540         return result;
3541     }
3542 
3543     auto abilityInfo = abilityRequest.abilityInfo;
3544     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3545     TAG_LOGD(AAFwkTag::SERVICE_EXT, "userId is : %{public}d, singleton is : %{public}d",
3546         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3547 
3548     result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
3549     if (result != ERR_OK) {
3550         TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkOptExtensionAbility error");
3551         eventInfo.errCode = result;
3552         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3553         return result;
3554     }
3555 
3556     auto connectManager = GetConnectManagerByUserId(validUserId);
3557     if (!connectManager) {
3558         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", validUserId);
3559         eventInfo.errCode = ERR_INVALID_VALUE;
3560         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3561         return ERR_INVALID_VALUE;
3562     }
3563     TAG_LOGD(AAFwkTag::SERVICE_EXT, "Stop extension begin, name:%{public}s", abilityInfo.name.c_str());
3564     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3565     if (eventInfo.errCode != ERR_OK) {
3566         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3567     }
3568     return eventInfo.errCode;
3569 }
3570 
StopSwitchUserDialog()3571 void AbilityManagerService::StopSwitchUserDialog()
3572 {
3573     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog extension ability come");
3574     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3575         TAG_LOGE(AAFwkTag::ABILITYMGR, "scene board enabled");
3576         return;
3577     }
3578 
3579     if (userController_ == nullptr || userController_->GetFreezingNewUserId() == DEFAULT_INVAL_VALUE) {
3580         TAG_LOGE(AAFwkTag::ABILITYMGR, "get last userId error");
3581         return;
3582     }
3583 #ifdef SUPPORT_GRAPHICS
3584     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
3585     if (sysDialog == nullptr) {
3586         TAG_LOGE(AAFwkTag::ABILITYMGR, "system dialog scheduler instance null");
3587         return;
3588     }
3589     Want stopWant = sysDialog->GetSwitchUserDialogWant();
3590     StopSwitchUserDialogInner(stopWant, userController_->GetFreezingNewUserId());
3591 #endif // SUPPORT_GRAPHICS
3592     userController_->SetFreezingNewUserId(DEFAULT_INVAL_VALUE);
3593     return;
3594 }
3595 
StopSwitchUserDialogInner(const Want & want,const int32_t lastUserId)3596 void AbilityManagerService::StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)
3597 {
3598     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog inner come");
3599     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
3600     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
3601     AbilityRequest abilityRequest;
3602     auto result =
3603         GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
3604     if (result != ERR_OK) {
3605         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
3606         eventInfo.errCode = result;
3607         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3608         return;
3609     }
3610 
3611     auto abilityInfo = abilityRequest.abilityInfo;
3612     auto stopUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
3613     result = CheckOptExtensionAbility(want, abilityRequest, stopUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
3614     if (result != ERR_OK) {
3615         TAG_LOGE(AAFwkTag::ABILITYMGR, "check extensionAbility type error");
3616         eventInfo.errCode = result;
3617         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3618         return;
3619     }
3620 
3621     auto connectManager = GetConnectManagerByUserId(stopUserId);
3622     if (connectManager == nullptr) {
3623         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId:%{public}d", stopUserId);
3624         eventInfo.errCode = ERR_INVALID_VALUE;
3625         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3626         return;
3627     }
3628 
3629     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3630     if (eventInfo.errCode != ERR_OK) {
3631         TAG_LOGE(AAFwkTag::ABILITYMGR, "eventInfo errCode=%{public}d", eventInfo.errCode);
3632         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3633     }
3634 }
3635 
MoveAbilityToBackground(const sptr<IRemoteObject> & token)3636 int AbilityManagerService::MoveAbilityToBackground(const sptr<IRemoteObject> &token)
3637 {
3638     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3639     TAG_LOGD(AAFwkTag::ABILITYMGR, "Move ability to background begin");
3640     if (!VerificationAllToken(token)) {
3641         return ERR_INVALID_VALUE;
3642     }
3643     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3644     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3645     if (!JudgeSelfCalled(abilityRecord)) {
3646         return CHECK_PERMISSION_FAILED;
3647     }
3648 
3649     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3650         return ERR_WOULD_BLOCK;
3651     }
3652 
3653     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3654     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3655     if (!missionListManager) {
3656         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null ownerUserId=%{public}d", ownerUserId);
3657         return ERR_INVALID_VALUE;
3658     }
3659     return missionListManager->MoveAbilityToBackground(abilityRecord);
3660 }
3661 
MoveUIAbilityToBackground(const sptr<IRemoteObject> token)3662 int32_t AbilityManagerService::MoveUIAbilityToBackground(const sptr<IRemoteObject> token)
3663 {
3664     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3665     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
3666     if (!AppUtils::GetInstance().EnableMoveUIAbilityToBackgroundApi()) {
3667         return ERR_OPERATION_NOT_SUPPORTED_ON_CURRENT_DEVICE;
3668     }
3669     if (!VerificationAllToken(token)) {
3670         return ERR_INVALID_VALUE;
3671     }
3672     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3673     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3674     if (!IsAppSelfCalled(abilityRecord)) {
3675         return CHECK_PERMISSION_FAILED;
3676     }
3677     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3678         TAG_LOGE(AAFwkTag::ABILITYMGR, "move ability background failed in wukong mode");
3679         return ERR_WUKONG_MODE_CANT_MOVE_STATE;
3680     }
3681     if (!abilityRecord->IsAbilityState(FOREGROUND) && !abilityRecord->IsAbilityState(FOREGROUNDING)) {
3682         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability not foregorund state");
3683         return ERR_ABILITY_NOT_FOREGROUND;
3684     }
3685     if (abilityRecord->GetAbilityInfo().type != AppExecFwk::AbilityType::PAGE) {
3686         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot background non UIAbility");
3687         return RESOLVE_CALL_ABILITY_TYPE_ERR;
3688     }
3689     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3690     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3691         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3692         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3693         return uiAbilityManager->NotifySCBToMinimizeUIAbility(token);
3694     }
3695 
3696     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3697     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3698     return missionListManager->MoveAbilityToBackground(abilityRecord);
3699 }
3700 
TerminateAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3701 int AbilityManagerService::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3702 {
3703     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3704     if (!abilityRecord) {
3705         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
3706         return ERR_INVALID_VALUE;
3707     }
3708     auto elementName = abilityRecord->GetWant().GetElement();
3709     if (AppUtils::GetInstance().IsLauncher(elementName.GetBundleName()) &&
3710         AppUtils::GetInstance().IsLauncherAbility(elementName.GetAbilityName())) {
3711         TAG_LOGI(AAFwkTag::ABILITYMGR, "cannot terminate launcher ability");
3712         return ERR_OK;
3713     }
3714     return TerminateAbilityWithFlag(token, resultCode, resultWant, true);
3715 }
3716 
TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> & token)3717 int32_t AbilityManagerService::TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> &token)
3718 {
3719     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3720     if (!VerificationAllToken(token)) {
3721         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
3722         return ERR_INVALID_VALUE;
3723     }
3724 
3725     if (!IsCallerSceneBoard()) {
3726         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3727         return ERR_WRONG_INTERFACE_CALL;
3728     }
3729 
3730     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3731     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3732 
3733     auto type = abilityRecord->GetAbilityInfo().type;
3734     auto extensionAbilityType = abilityRecord->GetAbilityInfo().extensionAbilityType;
3735 
3736     if (type != AppExecFwk::AbilityType::EXTENSION  ||
3737         extensionAbilityType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3738             return ERR_INVALID_VALUE;
3739     }
3740 
3741     auto userId = GetValidUserId(DEFAULT_INVAL_VALUE);
3742     auto connectManager = GetConnectManagerByUserId(userId);
3743     if (!connectManager) {
3744         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
3745         return ERR_INVALID_VALUE;
3746     }
3747     return connectManager->TerminateAbility(token);
3748 }
3749 
BackToCallerAbilityWithResult(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,int64_t callerRequestCode)3750 int AbilityManagerService::BackToCallerAbilityWithResult(const sptr<IRemoteObject> &token, int resultCode,
3751     const Want *resultWant, int64_t callerRequestCode)
3752 {
3753     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3754     if (!abilityRecord) {
3755         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
3756         return ERR_INVALID_VALUE;
3757     }
3758     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3759     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3760         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3761         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3762         return uiAbilityManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant,
3763             callerRequestCode);
3764     }
3765     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3766     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3767     return missionListManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant, callerRequestCode);
3768 }
3769 
CloseAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3770 int AbilityManagerService::CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3771 {
3772     EventInfo eventInfo;
3773     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3774     return TerminateAbilityWithFlag(token, resultCode, resultWant, false);
3775 }
3776 
TerminateAbilityWithFlag(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,bool flag)3777 int AbilityManagerService::TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode,
3778     const Want *resultWant, bool flag)
3779 {
3780     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3781     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ability begin, flag:%{public}d.", flag);
3782     if (!VerificationAllToken(token)) {
3783         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
3784         return ERR_INVALID_VALUE;
3785     }
3786 
3787     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3788     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3789     if (!JudgeSelfCalled(abilityRecord)) {
3790         return CHECK_PERMISSION_FAILED;
3791     }
3792 
3793     if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) {
3794         TAG_LOGE(AAFwkTag::ABILITYMGR, "system ui not allow terminate");
3795         return ERR_INVALID_VALUE;
3796     }
3797 
3798     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
3799     auto type = abilityRecord->GetAbilityInfo().type;
3800     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
3801         auto connectManager = GetConnectManagerByUserId(userId);
3802         if (!connectManager) {
3803             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
3804             return ERR_INVALID_VALUE;
3805         }
3806         return connectManager->TerminateAbility(token);
3807     }
3808 
3809     if (type == AppExecFwk::AbilityType::DATA) {
3810         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot terminate, use 'ReleaseDataAbility()'");
3811         return ERR_WRONG_INTERFACE_CALL;
3812     }
3813 
3814     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3815         return ERR_WOULD_BLOCK;
3816     }
3817 
3818     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3819     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3820     if (missionListManager) {
3821         return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag);
3822     }
3823     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListManager null ownerUserId=%{public}d", ownerUserId);
3824     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3825         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3826         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3827         return uiAbilityManager->CloseUIAbility(abilityRecord, resultCode, resultWant, false);
3828     }
3829     return ERR_INVALID_VALUE;
3830 }
3831 
TerminateUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int resultCode,const Want * resultWant)3832 int AbilityManagerService::TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode,
3833     const Want *resultWant)
3834 {
3835     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3836     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ui extension ability begin.");
3837     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3838     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3839     std::shared_ptr<AbilityConnectManager> connectManager;
3840     std::shared_ptr<AbilityRecord> targetRecord;
3841     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord, true);
3842     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3843     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3844 
3845     // self terminate or caller terminate is allowed.
3846     if (!(JudgeSelfCalled(targetRecord) || (abilityRecord != nullptr && JudgeSelfCalled(abilityRecord)))) {
3847         return CHECK_PERMISSION_FAILED;
3848     }
3849 
3850     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3851     if (result != ERR_OK) {
3852         TAG_LOGE(AAFwkTag::ABILITYMGR, "judgeAbilityVisibleControl error");
3853         return result;
3854     }
3855 
3856     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3857         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot terminate except ui extension ability");
3858         return ERR_WRONG_INTERFACE_CALL;
3859     }
3860 
3861     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension persistentId: %{public}d, element: %{public}s.",
3862         extensionSessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3863     connectManager->TerminateAbilityWindowLocked(targetRecord, extensionSessionInfo);
3864     return ERR_OK;
3865 }
3866 
CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)3867 int AbilityManagerService::CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)
3868 {
3869     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3870     TAG_LOGD(AAFwkTag::ABILITYMGR, "close uiextensionability by scb");
3871     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
3872 
3873     if (!IsCallerSceneBoard()) {
3874         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
3875         return ERR_PERMISSION_DENIED;
3876     }
3877 
3878     if (!VerificationAllToken(token)) {
3879         TAG_LOGE(AAFwkTag::ABILITYMGR, "verificationAllToken failed");
3880         return ERR_INVALID_VALUE;
3881     }
3882 
3883     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3884     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3885     if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
3886         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability %{public}s not an uiextensionability",
3887             abilityRecord->GetURI().c_str());
3888         return ERR_INVALID_VALUE;
3889     }
3890 
3891     auto sessionInfo = abilityRecord->GetSessionInfo();
3892     if (sessionInfo == nullptr) {
3893         TAG_LOGE(AAFwkTag::ABILITYMGR, "target session info is null, ability: %{public}s",
3894             abilityRecord->GetURI().c_str());
3895         return ERR_INVALID_VALUE;
3896     }
3897 
3898     std::shared_ptr<AbilityConnectManager> connectManager;
3899     std::shared_ptr<AbilityRecord> targetRecord;
3900     GetConnectManagerAndUIExtensionBySessionInfo(sessionInfo, connectManager, targetRecord, true);
3901     if (connectManager == nullptr) {
3902         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null, ability: %{public}s", abilityRecord->GetURI().c_str());
3903         return ERR_INVALID_VALUE;
3904     }
3905 
3906     sptr<Rosen::ISession> sessionProxy = iface_cast<Rosen::ISession>(sessionInfo->sessionToken);
3907     if (sessionProxy == nullptr) {
3908         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get session proxy failed, ability: %{public}s",
3909             abilityRecord->GetURI().c_str());
3910         return ERR_INVALID_VALUE;
3911     }
3912 
3913     // notify caller sync detach
3914     sessionProxy->NotifyExtensionDetachToDisplay();
3915     connectManager->TerminateAbilityWindowLocked(abilityRecord, sessionInfo);
3916     return ERR_OK;
3917 }
3918 
CloseUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool isUserRequestedExit,uint32_t sceneFlag)3919 int AbilityManagerService::CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool isUserRequestedExit,
3920     uint32_t sceneFlag)
3921 {
3922     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3923     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3924         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
3925         return ERR_INVALID_VALUE;
3926     }
3927 
3928     if (!IsCallerSceneBoard()) {
3929         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3930         return ERR_WRONG_INTERFACE_CALL;
3931     }
3932 
3933     SetMinimizedDuringFreeInstall(sessionInfo);
3934 
3935     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3936     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3937     TAG_LOGI(AAFwkTag::ABILITYMGR, "close session: %{public}d, resultCode: %{public}d, isClearSession: %{public}d",
3938         sessionInfo->persistentId, sessionInfo->resultCode, sessionInfo->isClearSession);
3939     if (sessionInfo->isClearSession) {
3940         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
3941             DeleteAbilityRecoverInfoBySessionId(sessionInfo->persistentId);
3942     }
3943     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3944     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3945     abilityRecord->SetSceneFlag(sceneFlag);
3946     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3947         return ERR_WOULD_BLOCK;
3948     }
3949 
3950     EventInfo eventInfo;
3951     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
3952     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
3953     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3954     if (isUserRequestedExit) {
3955         CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
3956         AAFwk::ExitReason exitReason = { REASON_USER_REQUEST, "User Request" };
3957         appExitReasonHelper_->RecordUIAbilityExitReason(abilityRecord->GetPid(), abilityRecord->GetAbilityInfo().name,
3958             exitReason);
3959     }
3960     eventInfo.errCode = uiAbilityManager->CloseUIAbility(abilityRecord, sessionInfo->resultCode,
3961         &(sessionInfo->want), sessionInfo->isClearSession);
3962     if (eventInfo.errCode != ERR_OK) {
3963         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
3964     }
3965     return eventInfo.errCode;
3966 }
3967 
SendResultToAbility(int32_t requestCode,int32_t resultCode,Want & resultWant)3968 int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)
3969 {
3970     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3971     if (!CheckCallerIsDmsProcess()) {
3972         TAG_LOGE(AAFwkTag::ABILITYMGR, "check processName failed");
3973         return ERR_INVALID_VALUE;
3974     }
3975     int missionId = resultWant.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
3976     resultWant.RemoveParam(DMS_MISSION_ID);
3977     if (missionId == DEFAULT_DMS_MISSION_ID) {
3978         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionId empty");
3979         return ERR_INVALID_VALUE;
3980     }
3981     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
3982     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3983         auto uiAbilityManager = GetCurrentUIAbilityManager();
3984         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3985         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
3986     } else {
3987         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
3988         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3989         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
3990     }
3991     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3992 
3993     abilityRecord->SetResult(std::make_shared<AbilityResult>(requestCode, resultCode, resultWant));
3994     abilityRecord->SendResult(0, 0);
3995     return ERR_OK;
3996 }
3997 
StartRemoteAbility(const Want & want,int requestCode,int32_t validUserId,const sptr<IRemoteObject> & callerToken)3998 int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId,
3999     const sptr<IRemoteObject> &callerToken)
4000 {
4001     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4002     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
4003     Want remoteWant = want;
4004     UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(remoteWant, callerToken);
4005     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
4006         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
4007         return ERR_INVALID_VALUE;
4008     }
4009     if (AbilityUtil::IsStartFreeInstall(remoteWant)) {
4010         return freeInstallManager_ == nullptr ? ERR_INVALID_VALUE :
4011             freeInstallManager_->StartRemoteFreeInstall(remoteWant, requestCode, validUserId, callerToken);
4012     }
4013     if (remoteWant.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
4014         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: try startAbilityForResult", __func__);
4015         int32_t missionId = -1;
4016         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4017             missionId = GetMissionIdByAbilityTokenInner(callerToken);
4018             if (!missionId) {
4019                 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
4020                 return ERR_INVALID_VALUE;
4021             }
4022         } else {
4023             missionId = GetMissionIdByAbilityToken(callerToken);
4024         }
4025         if (missionId < 0) {
4026             return ERR_INVALID_VALUE;
4027         }
4028         remoteWant.SetParam(DMS_MISSION_ID, missionId);
4029     }
4030 
4031     int32_t callerUid = IPCSkeleton::GetCallingUid();
4032     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4033 #ifdef SUPPORT_UPMS
4034     UriUtils::GetInstance().CheckUriPermission(accessToken, remoteWant);
4035 #endif // SUPPORT_UPMS
4036     DistributedClient dmsClient;
4037     int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken);
4038     if (result != ERR_NONE) {
4039         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManagerService::startRemoteAbility failed, result=%{public}d", result);
4040     }
4041     return result;
4042 }
4043 
CheckIsRemote(const std::string & deviceId)4044 bool AbilityManagerService::CheckIsRemote(const std::string& deviceId)
4045 {
4046     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4047     if (deviceId.empty()) {
4048         TAG_LOGI(AAFwkTag::ABILITYMGR, "checkIsRemote:deviceId empty");
4049         return false;
4050     }
4051     std::string localDeviceId;
4052     if (!GetLocalDeviceId(localDeviceId)) {
4053         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkIsRemote:get local deviceId failed");
4054         return false;
4055     }
4056     if (localDeviceId == deviceId) {
4057         TAG_LOGI(AAFwkTag::ABILITYMGR, "checkIsRemote:deviceId local");
4058         return false;
4059     }
4060     TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str());
4061     return true;
4062 }
4063 
CheckIfOperateRemote(const Want & want)4064 bool AbilityManagerService::CheckIfOperateRemote(const Want &want)
4065 {
4066     std::string deviceId = want.GetElement().GetDeviceID();
4067     if (deviceId.empty() || want.GetElement().GetBundleName().empty() ||
4068         want.GetElement().GetAbilityName().empty()) {
4069         TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty");
4070         return false;
4071     }
4072     return CheckIsRemote(deviceId);
4073 }
4074 
GetLocalDeviceId(std::string & localDeviceId)4075 bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId)
4076 {
4077     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4078     auto localNode = std::make_unique<NodeBasicInfo>();
4079     int32_t errCode = GetLocalNodeDeviceInfo(DM_PKG_NAME, localNode.get());
4080     if (errCode != ERR_OK) {
4081         TAG_LOGE(AAFwkTag::ABILITYMGR, "err=%{public}d", errCode);
4082         return false;
4083     }
4084     if (localNode != nullptr) {
4085         localDeviceId = localNode->networkId;
4086         TAG_LOGD(AAFwkTag::ABILITYMGR, "get local deviceId, deviceId = %{public}s",
4087             AnonymizeDeviceId(localDeviceId).c_str());
4088         return true;
4089     }
4090     TAG_LOGE(AAFwkTag::ABILITYMGR, "localDeviceId null");
4091     return false;
4092 }
4093 
AnonymizeDeviceId(const std::string & deviceId)4094 std::string AbilityManagerService::AnonymizeDeviceId(const std::string& deviceId)
4095 {
4096     if (deviceId.length() < NON_ANONYMIZE_LENGTH) {
4097         return EMPTY_DEVICE_ID;
4098     }
4099     std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
4100     anonDeviceId.append("******");
4101     return anonDeviceId;
4102 }
4103 
MinimizeAbility(const sptr<IRemoteObject> & token,bool fromUser)4104 int AbilityManagerService::MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)
4105 {
4106     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4107     TAG_LOGI(AAFwkTag::ABILITYMGR, "minimize ability, fromUser:%{public}d", fromUser);
4108     if (!VerificationAllToken(token)) {
4109         return ERR_INVALID_VALUE;
4110     }
4111 
4112     auto abilityRecord = Token::GetAbilityRecordByToken(token);
4113     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4114     if (!JudgeSelfCalled(abilityRecord)) {
4115         return CHECK_PERMISSION_FAILED;
4116     }
4117 
4118     auto type = abilityRecord->GetAbilityInfo().type;
4119     if (type != AppExecFwk::AbilityType::PAGE) {
4120         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except page ability");
4121         return ERR_WRONG_INTERFACE_CALL;
4122     }
4123 
4124     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4125         return ERR_WOULD_BLOCK;
4126     }
4127 
4128     auto missionListManager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
4129     if (!missionListManager) {
4130         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null");
4131         return ERR_INVALID_VALUE;
4132     }
4133     return missionListManager->MinimizeAbility(token, fromUser);
4134 }
4135 
MinimizeUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,bool fromUser)4136 int AbilityManagerService::MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo,
4137     bool fromUser)
4138 {
4139     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4140     TAG_LOGD(AAFwkTag::ABILITYMGR, "Minimize ui extension ability, fromUser:%{public}d.", fromUser);
4141     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
4142     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
4143     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4144     if (!JudgeSelfCalled(abilityRecord)) {
4145         return CHECK_PERMISSION_FAILED;
4146     }
4147 
4148     std::shared_ptr<AbilityConnectManager> connectManager;
4149     std::shared_ptr<AbilityRecord> targetRecord;
4150     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
4151     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
4152     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
4153 
4154     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
4155     if (result != ERR_OK) {
4156         TAG_LOGE(AAFwkTag::ABILITYMGR, "judgeAbilityVisibleControl error");
4157         return result;
4158     }
4159 
4160     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
4161         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except ui extension ability");
4162         return ERR_WRONG_INTERFACE_CALL;
4163     }
4164     extensionSessionInfo->uiExtensionComponentId = (
4165         static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
4166         static_cast<uint64_t>(extensionSessionInfo->persistentId);
4167     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
4168         extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
4169     connectManager->BackgroundAbilityWindowLocked(targetRecord, extensionSessionInfo);
4170     return ERR_OK;
4171 }
4172 
SetMinimizedDuringFreeInstall(const sptr<SessionInfo> & sessionInfo)4173 void AbilityManagerService::SetMinimizedDuringFreeInstall(const sptr<SessionInfo> &sessionInfo)
4174 {
4175     if (sessionInfo == nullptr) {
4176         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
4177         return;
4178     }
4179 
4180     if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
4181         return;
4182     }
4183 
4184     std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
4185     if (sessionId.empty()) {
4186         return;
4187     }
4188 
4189     if (freeInstallManager_ == nullptr) {
4190         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
4191         return;
4192     }
4193     FreeInstallInfo taskInfo;
4194     if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
4195         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task with sessionId=%{public}s does not exist",
4196             sessionId.c_str());
4197         return;
4198     }
4199 
4200     if (taskInfo.isFreeInstallFinished) {
4201         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
4202         return;
4203     }
4204 
4205     {
4206         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
4207         auto it = preStartSessionMap_.find(sessionId);
4208         if (it == preStartSessionMap_.end()) {
4209             TAG_LOGI(AAFwkTag::ABILITYMGR, "session info with sessionId=%{public}s does not exist",
4210                 sessionId.c_str());
4211             return;
4212         }
4213         CHECK_POINTER(it->second);
4214         it->second->isMinimizedDuringFreeInstall = true;
4215     }
4216 }
4217 
MinimizeUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool fromUser,uint32_t sceneFlag)4218 int AbilityManagerService::MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser,
4219     uint32_t sceneFlag)
4220 {
4221     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4222     TAG_LOGI(AAFwkTag::ABILITYMGR, "called, sceneFlag:%{public}u", sceneFlag);
4223     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
4224         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
4225         return ERR_INVALID_VALUE;
4226     }
4227 
4228     if (!IsCallerSceneBoard()) {
4229         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
4230         return ERR_WRONG_INTERFACE_CALL;
4231     }
4232 
4233     SetMinimizedDuringFreeInstall(sessionInfo);
4234 
4235     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4236     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4237     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
4238     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4239     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4240         return ERR_WOULD_BLOCK;
4241     }
4242     return uiAbilityManager->MinimizeUIAbility(abilityRecord, fromUser, sceneFlag);
4243 }
4244 
ConnectAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t userId)4245 int32_t AbilityManagerService::ConnectAbility(
4246     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)
4247 {
4248     return ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::SERVICE, userId);
4249 }
4250 
ConnectAbilityCommon(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,AppExecFwk::ExtensionAbilityType extensionType,int32_t userId,bool isQueryExtensionOnly)4251 int32_t AbilityManagerService::ConnectAbilityCommon(
4252     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
4253     AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)
4254 {
4255     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4256     TAG_LOGI(AAFwkTag::SERVICE_EXT,
4257         "elementUri:%{public}s", want.GetElement().GetURI().c_str());
4258     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4259     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4260     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE && want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
4261         TAG_LOGE(AAFwkTag::SERVICE_EXT, "error to have UISERVICEHOSTPROXY_KEY");
4262         return ERR_WRONG_INTERFACE_CALL;
4263     }
4264     if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && IsCrossUserCall(userId)) {
4265         CHECK_CALLER_IS_SYSTEM_APP;
4266     }
4267     EventInfo eventInfo = BuildEventInfo(want, userId);
4268 
4269     int result;
4270 #ifdef WITH_DLP
4271     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
4272     if (result != ERR_OK) {
4273         TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkDlpForExtension error");
4274         return result;
4275     }
4276 #endif // WITH_DLP
4277 
4278     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
4279     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
4280         shouldBlockFunc);
4281     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4282         interceptorExecuter_->DoProcess(interceptorParam);
4283     if (result != ERR_OK) {
4284         TAG_LOGE(AAFwkTag::SERVICE_EXT, "interceptorExecuter_ null or doProcess error");
4285         eventInfo.errCode = result;
4286         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4287         return result;
4288     }
4289 
4290     int32_t validUserId = GetValidUserId(userId);
4291 
4292     if (AbilityUtil::IsStartFreeInstall(want)) {
4293         CHECK_POINTER_AND_RETURN(freeInstallManager_, ERR_INVALID_VALUE);
4294         TAG_LOGD(AAFwkTag::SERVICE_EXT, "is start free install");
4295         std::string localDeviceId;
4296         if (!GetLocalDeviceId(localDeviceId)) {
4297             TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s:get Local deviceId failed", __func__);
4298             eventInfo.errCode = ERR_INVALID_VALUE;
4299             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4300             return ERR_INVALID_VALUE;
4301         }
4302         result = freeInstallManager_->ConnectFreeInstall(want, validUserId, callerToken, localDeviceId);
4303         if (result != ERR_OK) {
4304             eventInfo.errCode = result;
4305             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4306             return result;
4307         }
4308     }
4309 
4310     Want abilityWant = want;
4311     AbilityRequest abilityRequest;
4312     std::string uri = abilityWant.GetUri().ToString();
4313     bool isFileUri = (abilityWant.GetUri().GetScheme() == "file");
4314     if (!uri.empty() && !isFileUri) {
4315         // if the want include uri, it may only has uri information. it is probably a datashare extension.
4316         TAG_LOGD(AAFwkTag::SERVICE_EXT, "uri: %{public}s, userId: %{public}d", uri.c_str(), validUserId);
4317         AppExecFwk::ExtensionAbilityInfo extensionInfo;
4318         auto bms = AbilityUtil::GetBundleManagerHelper();
4319         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4320 
4321         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4322         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4323             TAG_LOGE(AAFwkTag::SERVICE_EXT, "invalid extension ability info");
4324             eventInfo.errCode = ERR_INVALID_VALUE;
4325             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4326             return ERR_INVALID_VALUE;
4327         }
4328         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4329     }
4330 
4331     if (CheckIfOperateRemote(abilityWant)) {
4332         TAG_LOGD(AAFwkTag::SERVICE_EXT, "AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility");
4333         eventInfo.errCode = ConnectRemoteAbility(abilityWant, callerToken, connect->AsObject());
4334         if (eventInfo.errCode != ERR_OK) {
4335             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4336         }
4337         return eventInfo.errCode;
4338     }
4339     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityWant, callerToken);
4340 
4341     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4342         TAG_LOGD(AAFwkTag::SERVICE_EXT, "invalid Token.");
4343         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr, extensionType);
4344         if (eventInfo.errCode != ERR_OK) {
4345             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4346         }
4347         return eventInfo.errCode;
4348     }
4349     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken, extensionType, nullptr,
4350         isQueryExtensionOnly);
4351     if (eventInfo.errCode != ERR_OK) {
4352         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4353     }
4354     return eventInfo.errCode;
4355 }
4356 
ConnectUIExtensionAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<SessionInfo> & sessionInfo,int32_t userId,sptr<UIExtensionAbilityConnectInfo> connectInfo)4357 int AbilityManagerService::ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect,
4358     const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4359 {
4360     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4361     TAG_LOGI(AAFwkTag::UI_EXT,
4362         "ConnectUIExtensionAbility bundlename: %{public}s, ability is %{public}s, userId is %{private}d",
4363         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
4364     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4365     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4366     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
4367 
4368     if (IsCrossUserCall(userId)) {
4369         CHECK_CALLER_IS_SYSTEM_APP;
4370     }
4371 
4372     EventInfo eventInfo = BuildEventInfo(want, userId);
4373     sptr<IRemoteObject> callerToken = sessionInfo->callerToken;
4374 
4375     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
4376         TAG_LOGE(AAFwkTag::UI_EXT, "connectUIExtensionAbility verificationAllToken failed");
4377         eventInfo.errCode = ERR_INVALID_VALUE;
4378         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4379         return ERR_INVALID_CALLER;
4380     }
4381 
4382     int result;
4383 #ifdef WITH_DLP
4384     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
4385     if (result != ERR_OK) {
4386         TAG_LOGE(AAFwkTag::UI_EXT, "checkDlpForExtension error");
4387         return result;
4388     }
4389 #endif // WITH_DLP
4390 
4391     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
4392     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
4393         shouldBlockFunc);
4394     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4395         interceptorExecuter_->DoProcess(interceptorParam);
4396     if (result != ERR_OK) {
4397         TAG_LOGE(AAFwkTag::UI_EXT, "interceptorExecuter_ null or doProcess error");
4398         eventInfo.errCode = result;
4399         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4400         return result;
4401     }
4402 
4403     int32_t validUserId = GetValidUserId(userId);
4404 
4405     Want abilityWant = want;
4406     AbilityRequest abilityRequest;
4407     std::string uri = abilityWant.GetUri().ToString();
4408     if (!uri.empty()) {
4409         // if the want include uri, it may only has uri information.
4410         TAG_LOGI(AAFwkTag::UI_EXT,
4411             "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
4412         AppExecFwk::ExtensionAbilityInfo extensionInfo;
4413         auto bms = AbilityUtil::GetBundleManagerHelper();
4414         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4415 
4416         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4417         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4418             TAG_LOGE(AAFwkTag::UI_EXT, "invalid extension ability info");
4419             eventInfo.errCode = ERR_INVALID_VALUE;
4420             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4421             return ERR_INVALID_VALUE;
4422         }
4423         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4424     }
4425 
4426     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityWant, callerToken);
4427 
4428     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4429         TAG_LOGI(AAFwkTag::UI_EXT, "%{public}s invalid Token", __func__);
4430         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr,
4431             AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4432         if (eventInfo.errCode != ERR_OK) {
4433             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4434         }
4435         return eventInfo.errCode;
4436     }
4437     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken,
4438         AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4439     if (eventInfo.errCode != ERR_OK) {
4440         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4441     }
4442     return eventInfo.errCode;
4443 }
4444 
BuildEventInfo(const Want & want,int32_t userId)4445 EventInfo AbilityManagerService::BuildEventInfo(const Want &want, int32_t userId)
4446 {
4447     EventInfo eventInfo;
4448     eventInfo.userId = userId;
4449     eventInfo.bundleName = want.GetElement().GetBundleName();
4450     eventInfo.moduleName = want.GetElement().GetModuleName();
4451     eventInfo.abilityName = want.GetElement().GetAbilityName();
4452     return eventInfo;
4453 }
4454 
DisconnectAbility(sptr<IAbilityConnection> connect)4455 int AbilityManagerService::DisconnectAbility(sptr<IAbilityConnection> connect)
4456 {
4457     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4458     TAG_LOGI(AAFwkTag::SERVICE_EXT, "Disconnect ability begin.");
4459     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4460     int err = DisconnectLocalAbility(connect);
4461     if (err == ERR_OK) {
4462         return ERR_OK;
4463     }
4464     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4465     int remoteErr = DisconnectRemoteAbility(connect->AsObject());
4466     if (remoteErr == ERR_OK) {
4467         return ERR_OK;
4468     }
4469     if (remoteErr != INVALID_PARAMETERS_ERR &&
4470         remoteErr != CONNECTION_NOT_EXIST &&
4471         err == CONNECTION_NOT_EXIST) {
4472         err = remoteErr;
4473     }
4474     TAG_LOGE(AAFwkTag::SERVICE_EXT, "Disconnect ability error %{public}d", err);
4475     EventInfo eventInfo;
4476     eventInfo.errCode = err;
4477     EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4478     return err;
4479 }
4480 
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)4481 int32_t AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId,
4482     const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
4483     AppExecFwk::ExtensionAbilityType extensionType, const sptr<SessionInfo> &sessionInfo,
4484     bool isQueryExtensionOnly, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4485 {
4486     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4487     TAG_LOGD(AAFwkTag::SERVICE_EXT, "called");
4488     StartAbilityInfoWrap threadLocalInfo;
4489     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
4490     if (!CheckCrossUser(userId, extensionType)) {
4491         TAG_LOGE(AAFwkTag::SERVICE_EXT, "multi-user non-concurrent unsatisfied");
4492         return ERR_CROSS_USER;
4493     }
4494 
4495     AbilityRequest abilityRequest;
4496     ErrCode result = ERR_OK;
4497     TAG_LOGD(AAFwkTag::SERVICE_EXT, "start generate ability request, isQueryExtensionOnly: %{public}d, type: %{public}d",
4498         isQueryExtensionOnly, static_cast<int32_t>(extensionType));
4499     if (isQueryExtensionOnly ||
4500         AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4501         result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, userId);
4502     } else {
4503         result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId);
4504     }
4505     abilityRequest.sessionInfo = sessionInfo;
4506 
4507     Want requestWant = want;
4508     CHECK_POINTER_AND_RETURN_LOG(connect, ERR_INVALID_VALUE, "connect is nullptr");
4509     TAG_LOGD(AAFwkTag::SERVICE_EXT, "requestWant SetParam success");
4510 
4511     if (result != ERR_OK) {
4512         TAG_LOGE(AAFwkTag::SERVICE_EXT, "generate request error");
4513         return result;
4514     }
4515     result = CheckPermissionForUIService(extensionType, want, abilityRequest);
4516     if (result != ERR_OK) {
4517         return result;
4518     }
4519 
4520     auto abilityInfo = abilityRequest.abilityInfo;
4521     threadLocalInfo.SetStartAbilityInfo(abilityInfo);
4522     if (abilityInfo.isStageBasedModel) {
4523         bool isService = (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE);
4524         if (isService && extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
4525             TAG_LOGE(AAFwkTag::SERVICE_EXT, "Service extension type, please use ConnectAbility");
4526             return ERR_WRONG_INTERFACE_CALL;
4527         }
4528         // not allow app to connect other extension by using connectServiceExtensionAbility
4529         bool isVpn = abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::VPN;
4530         if (callerToken && extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && !isService && !isVpn) {
4531             TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability, type not service");
4532             return TARGET_ABILITY_NOT_SERVICE;
4533         }
4534     }
4535     int32_t validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : userId;
4536     TAG_LOGD(AAFwkTag::SERVICE_EXT, "validUserId : %{public}d, singleton is : %{public}d",
4537         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
4538 
4539     result = CheckStaticCfgPermission(abilityRequest, false, -1);
4540     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
4541         TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkStaticCfgPermission error, result=%{public}d", result);
4542         return ERR_STATIC_CFG_PERMISSION;
4543     }
4544 
4545     AppExecFwk::ExtensionAbilityType targetExtensionType = abilityInfo.extensionAbilityType;
4546     TAG_LOGD(AAFwkTag::SERVICE_EXT, "extension type %{public}d.", targetExtensionType);
4547     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4548         if (!AAFwk::UIExtensionUtils::IsUIExtension(targetExtensionType)
4549             && targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW) {
4550             TAG_LOGE(AAFwkTag::SERVICE_EXT, "UI extension, target ability not UI extension");
4551             return ERR_WRONG_INTERFACE_CALL;
4552         }
4553 
4554         // Cause window has used this api, don't check it when type is window.
4555         if (targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW &&
4556             !PermissionVerification::GetInstance()->VerifyCallingPermission(
4557                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY)) {
4558             TAG_LOGE(AAFwkTag::SERVICE_EXT, "permission %{public}s verification failed",
4559                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY);
4560             return ERR_PERMISSION_DENIED;
4561         }
4562     }
4563 
4564     auto type = abilityInfo.type;
4565     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4566         TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability failed, target ability not service");
4567         return TARGET_ABILITY_NOT_SERVICE;
4568     }
4569 
4570     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
4571         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
4572     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
4573         afterCheckExecuter_->DoProcess(afterCheckParam);
4574     if (result != ERR_OK) {
4575         TAG_LOGE(AAFwkTag::SERVICE_EXT, "afterCheckExecuter_ null or doProcess error");
4576         return result;
4577     }
4578 
4579     result = CheckCallServicePermission(abilityRequest);
4580     if (result != ERR_OK) {
4581         TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s checkCallServicePermission error", __func__);
4582         return result;
4583     }
4584 
4585     ReportAppConnectOtherExtensionEvent(abilityInfo, want);
4586 
4587     if (!ExtensionPermissionsUtil::CheckSAPermission(targetExtensionType)) {
4588         TAG_LOGE(AAFwkTag::SERVICE_EXT, "SA doesn't have target extension permission");
4589         return CHECK_PERMISSION_FAILED;
4590     }
4591 
4592     result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
4593     if (result != ERR_OK) {
4594         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectAbility: app data ability preloading failed, '%{public}s', %{public}d",
4595             abilityInfo.bundleName.c_str(),
4596             result);
4597         return result;
4598     }
4599 
4600     auto connectManager = GetConnectManagerByUserId(validUserId);
4601     if (connectManager == nullptr) {
4602         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", validUserId);
4603         return ERR_INVALID_VALUE;
4604     }
4605 
4606     SetAbilityRequestSessionInfo(abilityRequest, targetExtensionType);
4607     if (!ResSchedUtil::GetInstance().NeedReportByPidWhenConnect(abilityInfo)) {
4608         // these extension type is reported in connectManager instead of here
4609         ReportEventToRSS(abilityInfo, callerToken);
4610     }
4611     return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo);
4612 }
4613 
ConnectRemoteAbility(Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)4614 int AbilityManagerService::ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken,
4615     const sptr<IRemoteObject> &connect)
4616 {
4617     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin connectAbilityRemote", __func__);
4618     UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(want, callerToken);
4619     if (AddStartControlParam(want, callerToken) != ERR_OK) {
4620         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
4621         return ERR_INVALID_VALUE;
4622     }
4623     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, abilityName: %{public}s",
4624         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str());
4625     DistributedClient dmsClient;
4626     return dmsClient.ConnectRemoteAbility(want, connect);
4627 }
4628 
DisconnectLocalAbility(const sptr<IAbilityConnection> & connect)4629 int AbilityManagerService::DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)
4630 {
4631     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4632     auto currentConnectManager = GetCurrentConnectManager();
4633     CHECK_POINTER_AND_RETURN(currentConnectManager, ERR_NO_INIT);
4634     if (currentConnectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4635         return ERR_OK;
4636     }
4637     // If current connectManager does not exist connect, then try connectManagerU0
4638     auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
4639     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4640     if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4641         return ERR_OK;
4642     }
4643 
4644     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
4645     if (userId == U0_USER_ID) {
4646         auto connectManagers = GetConnectManagers();
4647         for (auto& item : connectManagers) {
4648             if (item.second && item.second->DisconnectAbilityLocked(connect) == ERR_OK) {
4649                 return ERR_OK;
4650             }
4651         }
4652     }
4653 
4654     // EnterpriseAdminExtensionAbility Scene
4655     connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT);
4656     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4657     return connectManager->DisconnectAbilityLocked(connect);
4658 }
4659 
DisconnectRemoteAbility(const sptr<IRemoteObject> & connect)4660 int AbilityManagerService::DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)
4661 {
4662     TAG_LOGD(AAFwkTag::SERVICE_EXT, "call");
4663     int32_t callerUid = IPCSkeleton::GetCallingUid();
4664     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4665     DistributedClient dmsClient;
4666     return dmsClient.DisconnectRemoteAbility(connect, callerUid, accessToken);
4667 }
4668 
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callBack,AAFwk::WantParams & wantParams)4669 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
4670     int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
4671 {
4672     CHECK_CALLER_IS_SYSTEM_APP;
4673     TAG_LOGI(AAFwkTag::ABILITYMGR, "continueMission missionId: %{public}d", missionId);
4674     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4675         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4676         return CHECK_PERMISSION_FAILED;
4677     }
4678 
4679     DistributedClient dmsClient;
4680     int32_t callingUid = IPCSkeleton::GetCallingUid();
4681     wantParams.SetParam(DMS_CALLING_UID, AAFwk::Integer::Box(callingUid));
4682     return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams);
4683 }
4684 
ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,const sptr<IRemoteObject> & callback)4685 int AbilityManagerService::ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,
4686     const sptr<IRemoteObject> &callback)
4687 {
4688     CHECK_CALLER_IS_SYSTEM_APP;
4689     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
4690     AAFWK::ContinueRadar::GetInstance().ClickIconContinue("ContinueMission");
4691     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4692         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4693         return CHECK_PERMISSION_FAILED;
4694     }
4695 
4696     DistributedClient dmsClient;
4697     int32_t callingUid = IPCSkeleton::GetCallingUid();
4698     continueMissionInfo.wantParams.SetParam(DMS_CALLING_UID, AAFwk::Integer::Box(callingUid));
4699     return dmsClient.ContinueMission(continueMissionInfo, callback);
4700 }
4701 
ContinueAbility(const std::string & deviceId,int32_t missionId,uint32_t versionCode)4702 int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)
4703 {
4704     TAG_LOGI(AAFwkTag::ABILITYMGR,
4705         "ContinueAbility missionId = %{public}d, version = %{public}u.", missionId, versionCode);
4706     if (!CheckCallerIsDmsProcess()) {
4707         TAG_LOGE(AAFwkTag::ABILITYMGR, "check processName failed");
4708         return ERR_INVALID_VALUE;
4709     }
4710 
4711     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4712     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4713         auto uiAbilityManager = GetCurrentUIAbilityManager();
4714         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4715         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4716     } else {
4717         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4718         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4719         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4720     }
4721     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4722 
4723     abilityRecord->ContinueAbility(deviceId, versionCode);
4724     return ERR_OK;
4725 }
4726 
StartContinuation(const Want & want,const sptr<IRemoteObject> & abilityToken,int32_t status)4727 int AbilityManagerService::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)
4728 {
4729     TAG_LOGI(AAFwkTag::ABILITYMGR, "start continuation");
4730     if (!CheckIfOperateRemote(want)) {
4731         TAG_LOGE(AAFwkTag::ABILITYMGR, "deviceId or bundleName or abilityName empty");
4732         return ERR_INVALID_VALUE;
4733     }
4734     CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4735 
4736     int32_t appUid = IPCSkeleton::GetCallingUid();
4737     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4738         TAG_LOGI(AAFwkTag::ABILITYMGR,
4739             "AbilityManagerService::try startContinuation");
4740     int32_t missionId = -1;
4741     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4742         missionId = GetMissionIdByAbilityTokenInner(abilityToken);
4743         if (!missionId) {
4744             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
4745             return ERR_INVALID_VALUE;
4746         }
4747     } else {
4748         missionId = GetMissionIdByAbilityToken(abilityToken);
4749     }
4750     if (missionId < 0) {
4751         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get missionId");
4752         return ERR_INVALID_VALUE;
4753     }
4754     AAFWK::ContinueRadar::GetInstance().SaveDataRemoteWant("StartContinuation");
4755     TAG_LOGD(AAFwkTag::ABILITYMGR,
4756         "bundleName: %{public}s, abilityName: %{public}s, missionId: %{public}d, status: %{public}d",
4757         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), missionId, status);
4758     DistributedClient dmsClient;
4759     auto result =  dmsClient.StartContinuation(want, missionId, appUid, status, accessToken);
4760     if (result != ERR_OK) {
4761         TAG_LOGE(AAFwkTag::ABILITYMGR, "startContinuation failed, result=%{public}d, notify caller", result);
4762         NotifyContinuationResult(missionId, result);
4763     }
4764     return result;
4765 }
4766 
NotifyCompleteContinuation(const std::string & deviceId,int32_t sessionId,bool isSuccess)4767 void AbilityManagerService::NotifyCompleteContinuation(const std::string &deviceId,
4768     int32_t sessionId, bool isSuccess)
4769 {
4770     TAG_LOGI(AAFwkTag::ABILITYMGR, "notifyCompleteContinuation");
4771     AAFWK::ContinueRadar::GetInstance().ClickIconRecvOver("NotifyCompleteContinuation");
4772     sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4773     if (samgrProxy == nullptr) {
4774         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get samgrProxy");
4775         return;
4776     }
4777     sptr<IRemoteObject> bmsProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
4778     if (bmsProxy == nullptr) {
4779         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bms from samgr");
4780         return;
4781     }
4782     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bmsProxy);
4783     if (bundleMgr == nullptr) {
4784         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bms");
4785         return;
4786     }
4787     int32_t callerUid = IPCSkeleton::GetCallingUid();
4788     std::string callerBundleName;
4789     // reset ipc identity
4790     auto identity = IPCSkeleton::ResetCallingIdentity();
4791     bool result = bundleMgr->GetBundleNameForUid(callerUid, callerBundleName);
4792     // set ipc identity to raw
4793     IPCSkeleton::SetCallingIdentity(identity);
4794     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName: %{public}s", callerBundleName.c_str());
4795     DistributedClient dmsClient;
4796     dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess, callerBundleName);
4797 }
4798 
NotifyContinuationResult(int32_t missionId,int32_t result)4799 int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result)
4800 {
4801     TAG_LOGI(AAFwkTag::ABILITYMGR, "notify continuation result : %{public}d", result);
4802 
4803     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4804     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4805         auto uiAbilityManager = GetCurrentUIAbilityManager();
4806         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4807         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4808     } else {
4809         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4810         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4811         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4812     }
4813     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4814 
4815     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
4816         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
4817         return ERR_INVALID_VALUE;
4818     }
4819     abilityRecord->NotifyContinuationResult(result);
4820     return ERR_OK;
4821 }
4822 
StartSyncRemoteMissions(const std::string & devId,bool fixConflict,int64_t tag)4823 int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
4824 {
4825     CHECK_CALLER_IS_SYSTEM_APP;
4826     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4827         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4828         return CHECK_PERMISSION_FAILED;
4829     }
4830     DistributedClient dmsClient;
4831     int32_t callingUid = IPCSkeleton::GetCallingUid();
4832     TAG_LOGD(AAFwkTag::ABILITYMGR, "fixConflict: %{public}d, tag: %{public}" PRId64, fixConflict, tag);
4833     return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag, callingUid);
4834 }
4835 
StopSyncRemoteMissions(const std::string & devId)4836 int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId)
4837 {
4838     CHECK_CALLER_IS_SYSTEM_APP;
4839     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4840         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4841         return CHECK_PERMISSION_FAILED;
4842     }
4843     DistributedClient dmsClient;
4844     int32_t callingUid = IPCSkeleton::GetCallingUid();
4845     return dmsClient.StopSyncRemoteMissions(devId, callingUid);
4846 }
4847 
RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4848 int AbilityManagerService::RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4849 {
4850     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4851         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
4852         return CHECK_PERMISSION_FAILED;
4853     }
4854     return DelayedSingleton<ConnectionStateManager>::GetInstance()->RegisterObserver(observer);
4855 }
4856 
UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4857 int AbilityManagerService::UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4858 {
4859     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4860         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
4861         return CHECK_PERMISSION_FAILED;
4862     }
4863     return DelayedSingleton<ConnectionStateManager>::GetInstance()->UnregisterObserver(observer);
4864 }
4865 
4866 #ifdef WITH_DLP
GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> & infos)4867 int AbilityManagerService::GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)
4868 {
4869     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4870         TAG_LOGE(AAFwkTag::ABILITYMGR, "can't get dlp connection infos if caller not sa");
4871         return CHECK_PERMISSION_FAILED;
4872     }
4873     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetDlpConnectionInfos(infos);
4874 
4875     return ERR_OK;
4876 }
4877 #endif // WITH_DLP
4878 
GetConnectionData(std::vector<AbilityRuntime::ConnectionData> & connectionData)4879 int AbilityManagerService::GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)
4880 {
4881     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4882         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller no sa no connection data");
4883         return CHECK_PERMISSION_FAILED;
4884     }
4885     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetConnectionData(connectionData);
4886 
4887     return ERR_OK;
4888 }
4889 
RegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4890 int AbilityManagerService::RegisterMissionListener(const std::string &deviceId,
4891     const sptr<IRemoteMissionListener> &listener)
4892 {
4893     CHECK_CALLER_IS_SYSTEM_APP;
4894     std::string localDeviceId;
4895     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4896         TAG_LOGE(AAFwkTag::ABILITYMGR, "registerMissionListener:check deviceId failed");
4897         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4898     }
4899     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4900     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4901         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4902         return CHECK_PERMISSION_FAILED;
4903     }
4904     DistributedClient dmsClient;
4905     int32_t callingUid = IPCSkeleton::GetCallingUid();
4906     return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject(), callingUid);
4907 }
4908 
RegisterOnListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4909 int AbilityManagerService::RegisterOnListener(const std::string &type,
4910     const sptr<IRemoteOnListener> &listener)
4911 {
4912     CHECK_CALLER_IS_SYSTEM_APP;
4913     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4914     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4915         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4916         return CHECK_PERMISSION_FAILED;
4917     }
4918     DistributedClient dmsClient;
4919     int32_t callingUid = IPCSkeleton::GetCallingUid();
4920     return dmsClient.RegisterOnListener(type, listener->AsObject(), callingUid);
4921 }
4922 
RegisterOffListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4923 int AbilityManagerService::RegisterOffListener(const std::string &type,
4924     const sptr<IRemoteOnListener> &listener)
4925 {
4926     CHECK_CALLER_IS_SYSTEM_APP;
4927     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4928     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4929         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4930         return CHECK_PERMISSION_FAILED;
4931     }
4932     DistributedClient dmsClient;
4933     int32_t callingUid = IPCSkeleton::GetCallingUid();
4934     return dmsClient.RegisterOffListener(type, listener->AsObject(), callingUid);
4935 }
4936 
UnRegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4937 int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId,
4938     const sptr<IRemoteMissionListener> &listener)
4939 {
4940     CHECK_CALLER_IS_SYSTEM_APP;
4941     std::string localDeviceId;
4942     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4943         TAG_LOGE(AAFwkTag::ABILITYMGR, "check deviceId failed");
4944         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4945     }
4946     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4947     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4948         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4949         return CHECK_PERMISSION_FAILED;
4950     }
4951     DistributedClient dmsClient;
4952     return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4953 }
4954 
GetWantSender(const WantSenderInfo & wantSenderInfo,const sptr<IRemoteObject> & callerToken,int32_t uid)4955 sptr<IWantSender> AbilityManagerService::GetWantSender(
4956     const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken,
4957     int32_t uid)
4958 {
4959     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4960     auto pendingWantManager = GetCurrentPendingWantManager();
4961     CHECK_POINTER_AND_RETURN(pendingWantManager, nullptr);
4962 
4963     auto bms = AbilityUtil::GetBundleManagerHelper();
4964     CHECK_POINTER_AND_RETURN(bms, nullptr);
4965 
4966     int32_t callerUid = IPCSkeleton::GetCallingUid();
4967     int32_t userId = wantSenderInfo.userId;
4968     int32_t bundleMgrResult = 0;
4969 
4970     if (userId < 0) {
4971         if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4972             GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4973             TAG_LOGE(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid failed uid=%{public}d", callerUid);
4974             return nullptr;
4975         }
4976     }
4977     TAG_LOGD(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid userId: %{public}d", userId);
4978     //sa caller and has uid,no need find from bms.
4979     bool isSpecifyUidBySa = (uid != -1) && (AAFwk::PermissionVerification::GetInstance()->IsSACall());
4980 
4981     int32_t appUid = -1;
4982     int32_t appIndex = 0;
4983     std::string bundleName = "";
4984     if (!wantSenderInfo.allWants.empty()) {
4985         bundleName = wantSenderInfo.allWants.back().want.GetElement().GetBundleName();
4986     }
4987     if (!bundleName.empty()) {
4988         if (!isSpecifyUidBySa) {
4989             AppExecFwk::BundleInfo bundleInfo;
4990             MultiAppUtils::GetRunningMultiAppIndex(bundleName, callerUid, appIndex);
4991             bundleMgrResult = IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName,
4992                 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
4993                 appIndex, bundleInfo, userId));
4994             if (bundleMgrResult == ERR_OK) {
4995                 appUid = bundleInfo.uid;
4996             }
4997         } else {
4998             appUid = uid;
4999         }
5000         TAG_LOGD(AAFwkTag::ABILITYMGR,
5001             "bundleName: %{public}s, uid: %{public}d, userId: %{public}d, appIndex: %{public}d", bundleName.c_str(),
5002             appUid, userId, appIndex);
5003     }
5004     if (!CheckSenderWantInfo(callerUid, wantSenderInfo)) {
5005         TAG_LOGE(AAFwkTag::ABILITYMGR, "check bundleName failed");
5006         return nullptr;
5007     }
5008 
5009     bool isSystemApp = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
5010 
5011     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, appIndex: %{public}d, isSystemApp: %{public}d",
5012         wantSenderInfo.bundleName.c_str(), appIndex, isSystemApp);
5013     return pendingWantManager->GetWantSender(callerUid, appUid, isSystemApp, wantSenderInfo, callerToken, appIndex);
5014 }
5015 
SendWantSender(sptr<IWantSender> target,const SenderInfo & senderInfo)5016 int AbilityManagerService::SendWantSender(sptr<IWantSender> target, const SenderInfo &senderInfo)
5017 {
5018     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5019     auto pendingWantManager = GetCurrentPendingWantManager();
5020     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
5021     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
5022     return pendingWantManager->SendWantSender(target, senderInfo);
5023 }
5024 
CancelWantSender(const sptr<IWantSender> & sender)5025 void AbilityManagerService::CancelWantSender(const sptr<IWantSender> &sender)
5026 {
5027     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5028     auto pendingWantManager = GetCurrentPendingWantManager();
5029     CHECK_POINTER(pendingWantManager);
5030     CHECK_POINTER(sender);
5031 
5032     sptr<IRemoteObject> obj = sender->AsObject();
5033     if (!obj || obj->IsProxyObject()) {
5034         TAG_LOGE(AAFwkTag::ABILITYMGR, "obj null or proxy obj");
5035         return;
5036     }
5037 
5038     auto bms = AbilityUtil::GetBundleManagerHelper();
5039     CHECK_POINTER(bms);
5040 
5041     int32_t callerUid = IPCSkeleton::GetCallingUid();
5042     sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
5043 
5044     int userId = -1;
5045     if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
5046         GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
5047         TAG_LOGE(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid failed uid=%{public}d", callerUid);
5048         return;
5049     }
5050     TAG_LOGD(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid userId: %{public}d", userId);
5051     bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
5052 
5053     pendingWantManager->CancelWantSender(isSystemAppCall, sender);
5054 }
5055 
CancelWantSenderByFlags(const sptr<IWantSender> & sender,uint32_t flags)5056 void AbilityManagerService::CancelWantSenderByFlags(const sptr<IWantSender> &sender, uint32_t flags)
5057 {
5058     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5059     auto pendingWantManager = GetCurrentPendingWantManager();
5060     CHECK_POINTER(pendingWantManager);
5061     CHECK_POINTER(sender);
5062 
5063     sptr<IRemoteObject> obj = sender->AsObject();
5064     if (!obj || obj->IsProxyObject()) {
5065         TAG_LOGE(AAFwkTag::ABILITYMGR, "obj null or proxy obj");
5066         return;
5067     }
5068 
5069     auto bms = AbilityUtil::GetBundleManagerHelper();
5070     CHECK_POINTER(bms);
5071 
5072     sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
5073     CHECK_POINTER(record);
5074 
5075     if (flags != 0 && record->GetKey() != nullptr &&
5076         (static_cast<uint32_t>(record->GetKey()->GetFlags()) & flags) == 0) {
5077         TAG_LOGI(AAFwkTag::ABILITYMGR, "flags=%{public}u not match wantAgent flags=%{public}d",
5078                 flags, record->GetKey()->GetFlags());
5079         return;
5080     }
5081 
5082     TAG_LOGI(AAFwkTag::ABILITYMGR, "code=%{public}d cancel by flags=%{public}u",
5083         record->GetKey() != nullptr ? record->GetKey()->GetCode() : -1, flags);
5084     bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
5085     pendingWantManager->CancelWantSender(isSystemAppCall, sender);
5086 }
5087 
GetPendingWantUid(const sptr<IWantSender> & target)5088 int AbilityManagerService::GetPendingWantUid(const sptr<IWantSender> &target)
5089 {
5090     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
5091     auto pendingWantManager = GetCurrentPendingWantManager();
5092     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5093     if (target == nullptr) {
5094         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5095         return -1;
5096     }
5097     return pendingWantManager->GetPendingWantUid(target);
5098 }
5099 
GetPendingWantUserId(const sptr<IWantSender> & target)5100 int AbilityManagerService::GetPendingWantUserId(const sptr<IWantSender> &target)
5101 {
5102     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
5103     auto pendingWantManager = GetCurrentPendingWantManager();
5104     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5105     if (target == nullptr) {
5106         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5107         return -1;
5108     }
5109     return pendingWantManager->GetPendingWantUserId(target);
5110 }
5111 
GetPendingWantBundleName(const sptr<IWantSender> & target)5112 std::string AbilityManagerService::GetPendingWantBundleName(const sptr<IWantSender> &target)
5113 {
5114     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
5115     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantBundleName");
5116     auto pendingWantManager = GetCurrentPendingWantManager();
5117     CHECK_POINTER_AND_RETURN(pendingWantManager, "");
5118     CHECK_POINTER_AND_RETURN(target, "");
5119     return pendingWantManager->GetPendingWantBundleName(target);
5120 }
5121 
GetPendingWantCode(const sptr<IWantSender> & target)5122 int AbilityManagerService::GetPendingWantCode(const sptr<IWantSender> &target)
5123 {
5124     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
5125     auto pendingWantManager = GetCurrentPendingWantManager();
5126     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5127     if (target == nullptr) {
5128         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5129         return -1;
5130     }
5131     return pendingWantManager->GetPendingWantCode(target);
5132 }
5133 
GetPendingWantType(const sptr<IWantSender> & target)5134 int AbilityManagerService::GetPendingWantType(const sptr<IWantSender> &target)
5135 {
5136     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
5137     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantType");
5138     auto pendingWantManager = GetCurrentPendingWantManager();
5139     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5140     if (target == nullptr) {
5141         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5142         return -1;
5143     }
5144     return pendingWantManager->GetPendingWantType(target);
5145 }
5146 
RegisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)5147 void AbilityManagerService::RegisterCancelListener(const sptr<IWantSender> &sender,
5148     const sptr<IWantReceiver> &receiver)
5149 {
5150     TAG_LOGI(AAFwkTag::ABILITYMGR, "register cancel listener");
5151     auto pendingWantManager = GetCurrentPendingWantManager();
5152     CHECK_POINTER(pendingWantManager);
5153     CHECK_POINTER(sender);
5154     CHECK_POINTER(receiver);
5155     pendingWantManager->RegisterCancelListener(sender, receiver);
5156 }
5157 
UnregisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)5158 void AbilityManagerService::UnregisterCancelListener(
5159     const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)
5160 {
5161     TAG_LOGI(AAFwkTag::ABILITYMGR, "unregister cancel listener");
5162     auto pendingWantManager = GetCurrentPendingWantManager();
5163     CHECK_POINTER(pendingWantManager);
5164     CHECK_POINTER(sender);
5165     CHECK_POINTER(receiver);
5166     pendingWantManager->UnregisterCancelListener(sender, receiver);
5167 }
5168 
GetPendingRequestWant(const sptr<IWantSender> & target,std::shared_ptr<Want> & want)5169 int AbilityManagerService::GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)
5170 {
5171     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5172     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get pending request want.");
5173     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingRequestWant");
5174     auto pendingWantManager = GetCurrentPendingWantManager();
5175     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
5176     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
5177     CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE);
5178     CHECK_CALLER_IS_SYSTEM_APP;
5179     return pendingWantManager->GetPendingRequestWant(target, want);
5180 }
5181 
LockMissionForCleanup(int32_t missionId)5182 int AbilityManagerService::LockMissionForCleanup(int32_t missionId)
5183 {
5184     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock for clean all, id=%{public}d", missionId);
5185     auto missionListManager = GetCurrentMissionListManager();
5186     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5187     CHECK_CALLER_IS_SYSTEM_APP;
5188 
5189     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5190         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5191         return CHECK_PERMISSION_FAILED;
5192     }
5193     return missionListManager->SetMissionLockedState(missionId, true);
5194 }
5195 
UnlockMissionForCleanup(int32_t missionId)5196 int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId)
5197 {
5198     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5199     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock for clean all, id=%{public}d", missionId);
5200     auto missionListManager = GetCurrentMissionListManager();
5201     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5202     CHECK_CALLER_IS_SYSTEM_APP;
5203 
5204     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5205         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5206         return CHECK_PERMISSION_FAILED;
5207     }
5208     return missionListManager->SetMissionLockedState(missionId, false);
5209 }
5210 
SetLockedState(int32_t sessionId,bool lockedState)5211 void AbilityManagerService::SetLockedState(int32_t sessionId, bool lockedState)
5212 {
5213     TAG_LOGI(AAFwkTag::ABILITYMGR, "request lock abilityRecord, sessionId :%{public}d", sessionId);
5214     if (!IsCallerSceneBoard()) {
5215         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
5216         return;
5217     }
5218     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5219     CHECK_POINTER(uiAbilityManager);
5220     auto abilityRecord = uiAbilityManager->GetAbilityRecordsById(sessionId);
5221     if (!abilityRecord) {
5222         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
5223         return;
5224     }
5225     abilityRecord->SetLockedState(lockedState);
5226 }
5227 
RegisterMissionListener(const sptr<IMissionListener> & listener)5228 int AbilityManagerService::RegisterMissionListener(const sptr<IMissionListener> &listener)
5229 {
5230     TAG_LOGI(AAFwkTag::ABILITYMGR, "request registerMissionListener");
5231     auto missionListManager = GetCurrentMissionListManager();
5232     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5233     CHECK_CALLER_IS_SYSTEM_APP;
5234 
5235     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5236         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5237         return CHECK_PERMISSION_FAILED;
5238     }
5239     return missionListManager->RegisterMissionListener(listener);
5240 }
5241 
UnRegisterMissionListener(const sptr<IMissionListener> & listener)5242 int AbilityManagerService::UnRegisterMissionListener(const sptr<IMissionListener> &listener)
5243 {
5244     TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
5245     auto missionListManager = GetCurrentMissionListManager();
5246     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5247     CHECK_CALLER_IS_SYSTEM_APP;
5248 
5249     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5250         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5251         return CHECK_PERMISSION_FAILED;
5252     }
5253     return missionListManager->UnRegisterMissionListener(listener);
5254 }
5255 
GetMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)5256 int AbilityManagerService::GetMissionInfos(const std::string& deviceId, int32_t numMax,
5257     std::vector<MissionInfo> &missionInfos)
5258 {
5259     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5260     TAG_LOGI(AAFwkTag::ABILITYMGR, "request getMissionInfos");
5261     auto missionListManager = GetCurrentMissionListManager();
5262     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5263     CHECK_CALLER_IS_SYSTEM_APP;
5264 
5265     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5266         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5267         return CHECK_PERMISSION_FAILED;
5268     }
5269 
5270     if (CheckIsRemote(deviceId)) {
5271         return GetRemoteMissionInfos(deviceId, numMax, missionInfos);
5272     }
5273 
5274     return missionListManager->GetMissionInfos(numMax, missionInfos);
5275 }
5276 
GetRemoteMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)5277 int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax,
5278     std::vector<MissionInfo> &missionInfos)
5279 {
5280     TAG_LOGI(AAFwkTag::ABILITYMGR, "getRemoteMissionInfos");
5281     DistributedClient dmsClient;
5282     int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos);
5283     if (result != ERR_OK) {
5284         TAG_LOGE(AAFwkTag::ABILITYMGR, "getRemoteMissionInfos failed, result=%{public}d", result);
5285         return result;
5286     }
5287     return ERR_OK;
5288 }
5289 
GetMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)5290 int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId,
5291     MissionInfo &missionInfo)
5292 {
5293     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5294     TAG_LOGI(AAFwkTag::ABILITYMGR, "request getMissionInfo, missionId:%{public}d", missionId);
5295     auto missionListManager = GetCurrentMissionListManager();
5296     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5297     CHECK_CALLER_IS_SYSTEM_APP;
5298 
5299     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5300         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5301         return CHECK_PERMISSION_FAILED;
5302     }
5303 
5304     if (CheckIsRemote(deviceId)) {
5305         return GetRemoteMissionInfo(deviceId, missionId, missionInfo);
5306     }
5307 
5308     return missionListManager->GetMissionInfo(missionId, missionInfo);
5309 }
5310 
GetRemoteMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)5311 int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId,
5312     MissionInfo &missionInfo)
5313 {
5314     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5315     TAG_LOGI(AAFwkTag::ABILITYMGR, "getMissionInfoFromDms");
5316     std::vector<MissionInfo> missionVector;
5317     int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector);
5318     if (result != ERR_OK) {
5319         return result;
5320     }
5321     for (auto iter = missionVector.begin(); iter != missionVector.end(); iter++) {
5322         if (iter->id == missionId) {
5323             missionInfo = *iter;
5324             return ERR_OK;
5325         }
5326     }
5327     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionId not found");
5328     return ERR_INVALID_VALUE;
5329 }
5330 
CleanMission(int32_t missionId)5331 int AbilityManagerService::CleanMission(int32_t missionId)
5332 {
5333     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5334     TAG_LOGI(AAFwkTag::ABILITYMGR, "request cleanMission, missionId:%{public}d", missionId);
5335     auto missionListManager = GetCurrentMissionListManager();
5336     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5337     CHECK_CALLER_IS_SYSTEM_APP;
5338 
5339     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5340         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5341         return CHECK_PERMISSION_FAILED;
5342     }
5343 
5344     return missionListManager->ClearMission(missionId);
5345 }
5346 
CleanAllMissions()5347 int AbilityManagerService::CleanAllMissions()
5348 {
5349     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5350     TAG_LOGI(AAFwkTag::ABILITYMGR, "request cleanAllMissions");
5351     auto missionListManager = GetCurrentMissionListManager();
5352     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5353     CHECK_CALLER_IS_SYSTEM_APP;
5354 
5355     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5356         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5357         return CHECK_PERMISSION_FAILED;
5358     }
5359 
5360     Want want;
5361     want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME);
5362     if (!IsAbilityControllerStart(want, AbilityConfig::LAUNCHER_BUNDLE_NAME)) {
5363         TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", want.GetBundle().c_str());
5364         return ERR_WOULD_BLOCK;
5365     }
5366 
5367     return missionListManager->ClearAllMissions();
5368 }
5369 
MoveMissionToFront(int32_t missionId)5370 int AbilityManagerService::MoveMissionToFront(int32_t missionId)
5371 {
5372     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5373     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5374     CHECK_CALLER_IS_SYSTEM_APP;
5375     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5376         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5377         return CHECK_PERMISSION_FAILED;
5378     }
5379 
5380     if (!IsAbilityControllerStartById(missionId)) {
5381         TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart false");
5382         return ERR_WOULD_BLOCK;
5383     }
5384 
5385     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5386         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5387         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5388         return uiAbilityManager->MoveMissionToFront(missionId);
5389     }
5390 
5391     auto missionListManager = GetCurrentMissionListManager();
5392     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5393     return missionListManager->MoveMissionToFront(missionId);
5394 }
5395 
MoveMissionToFront(int32_t missionId,const StartOptions & startOptions)5396 int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)
5397 {
5398     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5399     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5400     CHECK_CALLER_IS_SYSTEM_APP;
5401     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5402         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5403         return CHECK_PERMISSION_FAILED;
5404     }
5405 
5406     if (!IsAbilityControllerStartById(missionId)) {
5407         TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart false");
5408         return ERR_WOULD_BLOCK;
5409     }
5410 
5411     auto options = std::make_shared<StartOptions>(startOptions);
5412     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5413         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5414         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5415         return uiAbilityManager->MoveMissionToFront(missionId, options);
5416     }
5417 
5418     auto missionListManager = GetCurrentMissionListManager();
5419     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5420     return missionListManager->MoveMissionToFront(missionId, options);
5421 }
5422 
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)5423 int AbilityManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
5424 {
5425     CHECK_CALLER_IS_SYSTEM_APP;
5426     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5427         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5428         return CHECK_PERMISSION_FAILED;
5429     }
5430 #ifdef SUPPORT_SCREEN
5431     if (wmsHandler_) {
5432         auto ret = wmsHandler_->MoveMissionsToForeground(missionIds, topMissionId);
5433         if (ret) {
5434             TAG_LOGE(AAFwkTag::ABILITYMGR, "moveMissionsToForeground failed, missiondIds may invalid");
5435             return ERR_INVALID_VALUE;
5436         } else {
5437             return NO_ERROR;
5438         }
5439     }
5440 #endif // SUPPORT_SCREEN
5441     return ERR_NO_INIT;
5442 }
5443 
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)5444 int AbilityManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
5445     std::vector<int32_t>& result)
5446 {
5447     CHECK_CALLER_IS_SYSTEM_APP;
5448     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5449         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5450         return CHECK_PERMISSION_FAILED;
5451     }
5452 #ifdef SUPPORT_SCREEN
5453     if (wmsHandler_) {
5454         auto ret = wmsHandler_->MoveMissionsToBackground(missionIds, result);
5455         if (ret) {
5456             TAG_LOGE(AAFwkTag::ABILITYMGR, "moveMissionsToBackground failed, missiondIds may invalid");
5457             return ERR_INVALID_VALUE;
5458         } else {
5459             return NO_ERROR;
5460         }
5461     }
5462 #endif // SUPPORT_SCREEN
5463     return ERR_NO_INIT;
5464 }
5465 
GetMissionIdByToken(const sptr<IRemoteObject> & token)5466 int32_t AbilityManagerService::GetMissionIdByToken(const sptr<IRemoteObject> &token)
5467 {
5468     TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken.");
5469     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5470     if (!abilityRecord) {
5471         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
5472         return ERR_INVALID_VALUE;
5473     }
5474     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
5475         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
5476         return ERR_INVALID_VALUE;
5477     }
5478     return GetMissionIdByAbilityTokenInner(token);
5479 }
5480 
IsAbilityControllerStartById(int32_t missionId)5481 bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId)
5482 {
5483     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5484     auto missionListWrap = GetMissionListWrap();
5485     if (missionListWrap == nullptr) {
5486         TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null");
5487         return true;
5488     }
5489     InnerMissionInfo innerMissionInfo;
5490     int getMission = missionListWrap->GetInnerMissionInfoById(missionId, innerMissionInfo);
5491     if (getMission != ERR_OK) {
5492         TAG_LOGE(AAFwkTag::ABILITYMGR,
5493             "cannot find mission info:%{public}d", missionId);
5494         return true;
5495     }
5496     if (!IsAbilityControllerStart(innerMissionInfo.missionInfo.want, innerMissionInfo.missionInfo.want.GetBundle())) {
5497         TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s",
5498             innerMissionInfo.missionInfo.want.GetBundle().c_str());
5499         return false;
5500     }
5501     return true;
5502 }
5503 
GetConnectRecordListByCallback(sptr<IAbilityConnection> callback)5504 std::list<std::shared_ptr<ConnectionRecord>> AbilityManagerService::GetConnectRecordListByCallback(
5505     sptr<IAbilityConnection> callback)
5506 {
5507     auto connectManager = GetCurrentConnectManager();
5508     CHECK_POINTER_AND_RETURN(connectManager, std::list<std::shared_ptr<ConnectionRecord>>());
5509     return connectManager->GetConnectRecordListByCallback(callback);
5510 }
5511 
GenerateDataAbilityRequestByUri(const std::string & dataAbilityUri,AbilityRequest & abilityRequest,sptr<IRemoteObject> callerToken,int32_t userId)5512 bool AbilityManagerService::GenerateDataAbilityRequestByUri(const std::string& dataAbilityUri,
5513     AbilityRequest &abilityRequest, sptr<IRemoteObject> callerToken, int32_t userId)
5514 {
5515     auto bms = AbilityUtil::GetBundleManagerHelper();
5516     CHECK_POINTER_AND_RETURN(bms, false);
5517     TAG_LOGI(AAFwkTag::ABILITYMGR, "dataAbilityUri: %{public}s, userId: %{public}d", dataAbilityUri.c_str(), userId);
5518     bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo));
5519     if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) {
5520         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid ability info acquiring");
5521         return false;
5522     }
5523     abilityRequest.callerToken = callerToken;
5524     return true;
5525 }
5526 
AcquireDataAbility(const Uri & uri,bool tryBind,const sptr<IRemoteObject> & callerToken)5527 sptr<IAbilityScheduler> AbilityManagerService::AcquireDataAbility(
5528     const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
5529 {
5530     auto localUri(uri);
5531     if (localUri.GetScheme() != AbilityConfig::SCHEME_DATA_ABILITY) {
5532         TAG_LOGE(AAFwkTag::ABILITYMGR, "acquire data ability invalid uri scheme");
5533         return nullptr;
5534     }
5535     std::vector<std::string> pathSegments;
5536     localUri.GetPathSegments(pathSegments);
5537     if (pathSegments.empty()) {
5538         TAG_LOGE(AAFwkTag::ABILITYMGR, "acquire data ability invalid uri path");
5539         return nullptr;
5540     }
5541 
5542     auto userId = GetValidUserId(INVALID_USER_ID);
5543     AbilityRequest abilityRequest;
5544     if (!GenerateDataAbilityRequestByUri(localUri.ToString(), abilityRequest, callerToken, userId)) {
5545         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate data ability request failed");
5546         return nullptr;
5547     }
5548 
5549     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5550     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5551     if (!isSaCall && CheckCallDataAbilityPermission(abilityRequest, isShellCall, isSaCall) != ERR_OK) {
5552         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid ability request info acquiring");
5553         return nullptr;
5554     }
5555 
5556     TAG_LOGD(AAFwkTag::ABILITYMGR, "Query data ability info: %{public}s|%{public}s|%{public}s",
5557         abilityRequest.appInfo.name.c_str(), abilityRequest.appInfo.bundleName.c_str(),
5558         abilityRequest.abilityInfo.name.c_str());
5559 
5560     if (CheckStaticCfgPermission(abilityRequest, false, -1, true, isSaCall) !=
5561         AppExecFwk::Constants::PERMISSION_GRANTED) {
5562         TAG_LOGI(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission fail");
5563         return nullptr;
5564     }
5565 
5566     if (!VerificationAllToken(callerToken)) {
5567         TAG_LOGI(AAFwkTag::ABILITYMGR, "verificationAllToken fail");
5568         return nullptr;
5569     }
5570 
5571     if (abilityRequest.abilityInfo.applicationInfo.singleton) {
5572         userId = U0_USER_ID;
5573     }
5574 
5575     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5576     CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr);
5577     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
5578     bool isNotHap = isSaCall || isShellCall;
5579     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
5580     return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap);
5581 }
5582 
ReleaseDataAbility(sptr<IAbilityScheduler> dataAbilityScheduler,const sptr<IRemoteObject> & callerToken)5583 int AbilityManagerService::ReleaseDataAbility(
5584     sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
5585 {
5586     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
5587     if (!dataAbilityScheduler || !callerToken) {
5588         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilitySchedule or callerToken null");
5589         return ERR_INVALID_VALUE;
5590     }
5591 
5592     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler);
5593     if (!dataAbilityManager) {
5594         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityScheduler absent");
5595         return ERR_INVALID_VALUE;
5596     }
5597 
5598     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5599     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5600     bool isNotHap = isSaCall || isShellCall;
5601     return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isNotHap);
5602 }
5603 
AttachAbilityThread(const sptr<IAbilityScheduler> & scheduler,const sptr<IRemoteObject> & token)5604 int AbilityManagerService::AttachAbilityThread(
5605     const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
5606 {
5607     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5608     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called", __func__);
5609     CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE);
5610     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5611         return ERR_INVALID_VALUE;
5612     }
5613     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5614     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5615     if (!JudgeSelfCalled(abilityRecord)) {
5616         return CHECK_PERMISSION_FAILED;
5617     }
5618 
5619     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5620     auto abilityInfo = abilityRecord->GetAbilityInfo();
5621     auto type = abilityInfo.type;
5622     // force timeout ability for test
5623     if (IsNeedTimeoutForTest(abilityInfo.name, AbilityRecord::ConvertAbilityState(AbilityState::INITIAL))) {
5624         TAG_LOGW(AAFwkTag::ABILITYMGR,
5625             "force timeout ability, state:INITIAL, ability:%{public}s", abilityInfo.name.c_str());
5626         return ERR_OK;
5627     }
5628     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5629         auto connectManager = GetConnectManagerByUserId(userId);
5630         if (!connectManager) {
5631             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
5632             return ERR_INVALID_VALUE;
5633         }
5634         return connectManager->AttachAbilityThreadLocked(scheduler, token);
5635     } else if (type == AppExecFwk::AbilityType::DATA) {
5636         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5637         if (!dataAbilityManager) {
5638             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
5639             return ERR_INVALID_VALUE;
5640         }
5641         return dataAbilityManager->AttachAbilityThread(scheduler, token);
5642     } else {
5643         std::string entry = "AbilityManagerService::AttachAbilityThread; the end of load lifecycle.";
5644         FreezeUtil::GetInstance().AddLifecycleEvent(token, entry);
5645         int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5646         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5647             auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5648             CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5649             return uiAbilityManager->AttachAbilityThread(scheduler, token);
5650         }
5651         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5652         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
5653         return missionListManager->AttachAbilityThread(scheduler, token);
5654     }
5655 }
5656 
DumpSysInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5657 void AbilityManagerService::DumpSysInner(
5658     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5659 {
5660     std::vector<std::string> argList;
5661     SplitStr(args, " ", argList);
5662     if (argList.empty()) {
5663         return;
5664     }
5665 
5666     DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5667     DumpSysStateInner(args, info, isClient, isUserID, userId);
5668     DumpSysPendingInner(args, info, isClient, isUserID, userId);
5669     DumpSysProcess(args, info, isClient, isUserID, userId);
5670 }
5671 
DumpSysMissionListInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5672 void AbilityManagerService::DumpSysMissionListInner(
5673     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5674 {
5675     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5676         DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId);
5677         return;
5678     }
5679     std::shared_ptr<MissionListManagerInterface> targetManager;
5680     if (isUserID) {
5681         auto missionListManager = GetMissionListManagerByUserId(userId);
5682         if (missionListManager == nullptr) {
5683             info.push_back("error: No user found.");
5684             return;
5685         }
5686         targetManager = missionListManager;
5687     } else {
5688         targetManager = GetCurrentMissionListManager();
5689     }
5690 
5691     CHECK_POINTER(targetManager);
5692 
5693     std::vector<std::string> argList;
5694     SplitStr(args, " ", argList);
5695     if (argList.empty()) {
5696         return;
5697     }
5698 
5699     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5700         targetManager->DumpMissionList(info, isClient, argList[1]);
5701     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5702         targetManager->DumpMissionList(info, isClient);
5703     } else {
5704         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5705     }
5706 }
5707 
DumpSysMissionListInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5708 void AbilityManagerService::DumpSysMissionListInnerBySCB(
5709     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5710 {
5711     if (!isUserID) {
5712         userId = GetUserId();
5713     }
5714 
5715     std::vector<std::string> argList;
5716     SplitStr(args, " ", argList);
5717     if (argList.empty()) {
5718         return;
5719     }
5720 
5721     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5722     CHECK_POINTER(uiAbilityManager);
5723     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5724         uiAbilityManager->DumpMissionList(info, isClient, argList[1]);
5725     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5726         uiAbilityManager->DumpMissionList(info, isClient);
5727     } else {
5728         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5729     }
5730 }
5731 
DumpSysAbilityInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5732 void AbilityManagerService::DumpSysAbilityInner(
5733     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5734 {
5735     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5736         DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId);
5737         return;
5738     }
5739     std::shared_ptr<MissionListManagerInterface> targetManager;
5740     if (isUserID) {
5741         auto missionListManager = GetMissionListManagerByUserId(userId);
5742         if (missionListManager == nullptr) {
5743             info.push_back("error: No user found.");
5744             return;
5745         }
5746         targetManager = missionListManager;
5747     } else {
5748         targetManager = GetCurrentMissionListManager();
5749     }
5750 
5751     CHECK_POINTER(targetManager);
5752 
5753     std::vector<std::string> argList;
5754     SplitStr(args, " ", argList);
5755     if (argList.empty()) {
5756         return;
5757     }
5758     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5759         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList=%{public}s", argList[1].c_str());
5760         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5761         try {
5762             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5763             targetManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5764         } catch (...) {
5765             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5766             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5767         }
5768     } else {
5769         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5770     }
5771 }
5772 
DumpSysAbilityInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5773 void AbilityManagerService::DumpSysAbilityInnerBySCB(
5774     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5775 {
5776     if (!isUserID) {
5777         userId = GetUserId();
5778     }
5779 
5780     std::vector<std::string> argList;
5781     SplitStr(args, " ", argList);
5782     if (argList.empty()) {
5783         return;
5784     }
5785     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5786         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList=%{public}s", argList[1].c_str());
5787         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5788         try {
5789             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5790             auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5791             CHECK_POINTER(uiAbilityManager);
5792             uiAbilityManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5793         } catch (...) {
5794             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5795             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5796         }
5797     } else {
5798         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5799     }
5800 }
5801 
DumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5802 void AbilityManagerService::DumpSysStateInner(
5803     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5804 {
5805     TAG_LOGI(AAFwkTag::ABILITYMGR, "dumpSysStateInner begin:%{public}s", args.c_str());
5806     std::shared_ptr<AbilityConnectManager> targetManager;
5807 
5808     if (isUserID) {
5809         auto connectManager = GetConnectManagerByUserId(userId);
5810         if (connectManager == nullptr) {
5811             info.push_back("error: No user found.");
5812             return;
5813         }
5814         targetManager = connectManager;
5815     } else {
5816         targetManager = GetCurrentConnectManager();
5817     }
5818 
5819     CHECK_POINTER(targetManager);
5820 
5821     std::vector<std::string> argList;
5822     SplitStr(args, " ", argList);
5823     if (argList.empty()) {
5824         return;
5825     }
5826 
5827     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5828         targetManager->DumpState(info, isClient, argList[1]);
5829     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5830         targetManager->DumpState(info, isClient);
5831     } else {
5832         TAG_LOGI(AAFwkTag::ABILITYMGR, "uri=%{public}s", argList[1].c_str());
5833         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5834         targetManager->DumpStateByUri(info, isClient, argList[1], params);
5835     }
5836 }
5837 
DumpSysPendingInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5838 void AbilityManagerService::DumpSysPendingInner(
5839     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5840 {
5841     std::shared_ptr<PendingWantManager> targetManager;
5842     if (isUserID) {
5843         auto pendingWantManager = GetPendingWantManagerByUserId(userId);
5844         if (pendingWantManager == nullptr) {
5845             info.push_back("error: No user found.");
5846             return;
5847         }
5848         targetManager = pendingWantManager;
5849     } else {
5850         targetManager = GetCurrentPendingWantManager();
5851     }
5852 
5853     CHECK_POINTER(targetManager);
5854 
5855     std::vector<std::string> argList;
5856     SplitStr(args, " ", argList);
5857     if (argList.empty()) {
5858         return;
5859     }
5860 
5861     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5862         targetManager->DumpByRecordId(info, argList[1]);
5863     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5864         targetManager->Dump(info);
5865     } else {
5866         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5867     }
5868 }
5869 
DumpSysProcess(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5870 void AbilityManagerService::DumpSysProcess(
5871     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5872 {
5873     std::vector<std::string> argList;
5874     SplitStr(args, " ", argList);
5875     if (argList.empty()) {
5876         return;
5877     }
5878     std::vector<AppExecFwk::RunningProcessInfo> processInfos;
5879     int ret = 0;
5880     if (isUserID) {
5881         ret = GetProcessRunningInfosByUserId(processInfos, userId);
5882     } else {
5883         ret = GetProcessRunningInfos(processInfos);
5884     }
5885 
5886     if (ret != ERR_OK || processInfos.size() == 0) {
5887         return;
5888     }
5889 
5890     std::string dumpInfo = "  AppRunningRecords:";
5891     info.push_back(dumpInfo);
5892     auto processInfoID = 0;
5893     auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false);
5894     for (const auto& processInfo : processInfos) {
5895         if (hasProcessName && argList[1] != processInfo.processName_) {
5896             continue;
5897         }
5898 
5899         dumpInfo = "    AppRunningRecord ID #" + std::to_string(processInfoID);
5900         processInfoID++;
5901         info.push_back(dumpInfo);
5902         dumpInfo = "      process name [" + processInfo.processName_ + "]";
5903         info.push_back(dumpInfo);
5904         dumpInfo = "      pid #" + std::to_string(processInfo.pid_) +
5905             "  uid #" + std::to_string(processInfo.uid_);
5906         info.push_back(dumpInfo);
5907         auto appState = static_cast<AppState>(processInfo.state_);
5908         dumpInfo = "      state #" + DelayedSingleton<AppScheduler>::GetInstance()->ConvertAppState(appState);
5909         info.push_back(dumpInfo);
5910         DumpUIExtensionRootHostRunningInfos(processInfo.pid_, info);
5911         DumpUIExtensionProviderRunningInfos(processInfo.pid_, info);
5912     }
5913 }
5914 
DumpUIExtensionRootHostRunningInfos(pid_t pid,std::vector<std::string> & info)5915 void AbilityManagerService::DumpUIExtensionRootHostRunningInfos(pid_t pid, std::vector<std::string> &info)
5916 {
5917     auto appMgr = AppMgrUtil::GetAppMgr();
5918     if (appMgr == nullptr) {
5919         TAG_LOGW(AAFwkTag::ABILITYMGR, "get appMgr failed");
5920         return;
5921     }
5922 
5923     std::vector<pid_t> hostPids;
5924     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionRootHostPid(pid, hostPids));
5925     if (ret != ERR_OK) {
5926         TAG_LOGE(AAFwkTag::ABILITYMGR, "get root host process info faild");
5927         return;
5928     }
5929 
5930     if (hostPids.size() == 0) {
5931         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extenson root host of pid %{public}d.", pid);
5932         return;
5933     }
5934 
5935     std::string temp;
5936     for (size_t i = 0; i < hostPids.size(); i++) {
5937         temp = "      root caller #" + std::to_string(i);
5938         info.push_back(temp);
5939         temp = "        pid #" + std::to_string(hostPids[i]);
5940         info.push_back(temp);
5941     }
5942 }
5943 
DumpUIExtensionProviderRunningInfos(pid_t hostPid,std::vector<std::string> & info)5944 void AbilityManagerService::DumpUIExtensionProviderRunningInfos(pid_t hostPid, std::vector<std::string> &info)
5945 {
5946     auto appMgr = AppMgrUtil::GetAppMgr();
5947     if (appMgr == nullptr) {
5948         TAG_LOGW(AAFwkTag::ABILITYMGR, "get appMgr failed");
5949         return;
5950     }
5951 
5952     std::vector<pid_t> providerPids;
5953     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionProviderPid(hostPid, providerPids));
5954     if (ret != ERR_OK) {
5955         TAG_LOGE(AAFwkTag::ABILITYMGR, "get process info failed");
5956         return;
5957     }
5958 
5959     if (providerPids.size() == 0) {
5960         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extension provider of pid %{public}d.", hostPid);
5961         return;
5962     }
5963 
5964     std::string temp;
5965     for (size_t i = 0; i < providerPids.size(); i++) {
5966         temp = "      uiextension provider #" + std::to_string(i);
5967         info.push_back(temp);
5968         temp = "        pid #" + std::to_string(providerPids[i]);
5969         info.push_back(temp);
5970     }
5971 }
5972 
DataDumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5973 void AbilityManagerService::DataDumpSysStateInner(
5974     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5975 {
5976     std::shared_ptr<DataAbilityManager> targetManager;
5977     if (isUserID) {
5978         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5979         if (dataAbilityManager == nullptr) {
5980             info.push_back("error: No user found.");
5981             return;
5982         }
5983         targetManager = dataAbilityManager;
5984     } else {
5985         targetManager = GetCurrentDataAbilityManager();
5986     }
5987 
5988     CHECK_POINTER(targetManager);
5989 
5990     std::vector<std::string> argList;
5991     SplitStr(args, " ", argList);
5992     if (argList.empty()) {
5993         return;
5994     }
5995     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5996         targetManager->DumpSysState(info, isClient, argList[1]);
5997     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5998         targetManager->DumpSysState(info, isClient);
5999     } else {
6000         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6001     }
6002 }
6003 
DumpInner(const std::string & args,std::vector<std::string> & info)6004 void AbilityManagerService::DumpInner(const std::string &args, std::vector<std::string> &info)
6005 {
6006     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6007         auto uiAbilityManager = GetCurrentUIAbilityManager();
6008         CHECK_POINTER(uiAbilityManager);
6009         uiAbilityManager->Dump(info);
6010         return;
6011     }
6012 
6013     auto missionListManager = GetCurrentMissionListManager();
6014     if (missionListManager) {
6015         missionListManager->Dump(info);
6016     }
6017 }
6018 
DumpMissionListInner(const std::string & args,std::vector<std::string> & info)6019 void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector<std::string> &info)
6020 {
6021     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6022         auto uiAbilityManager = GetCurrentUIAbilityManager();
6023         CHECK_POINTER(uiAbilityManager);
6024         uiAbilityManager->DumpMissionList(info, false, " ");
6025         return;
6026     }
6027     auto missionListManager = GetCurrentMissionListManager();
6028     if (missionListManager) {
6029         missionListManager->DumpMissionList(info, false, "");
6030     }
6031 }
6032 
DumpMissionInfosInner(const std::string & args,std::vector<std::string> & info)6033 void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)
6034 {
6035     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6036         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
6037 #ifdef SUPPORT_GRAPHICS
6038         Rosen::WindowManager::GetInstance().DumpSessionAll(info);
6039 #endif // SUPPORT_GRAPHICS
6040         return;
6041     }
6042     auto missionListManager = GetCurrentMissionListManager();
6043     if (missionListManager) {
6044         missionListManager->DumpMissionInfos(info);
6045     }
6046 }
6047 
DumpMissionInner(const std::string & args,std::vector<std::string> & info)6048 void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector<std::string> &info)
6049 {
6050     std::vector<std::string> argList;
6051     SplitStr(args, " ", argList);
6052     if (argList.empty()) {
6053         return;
6054     }
6055     if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6056         info.push_back("error: invalid argument, please see 'ability dump -h'.");
6057         return;
6058     }
6059     int missionId = DEFAULT_INVAL_VALUE;
6060     (void)StrToInt(argList[1], missionId);
6061 
6062     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6063         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
6064 #ifdef SUPPORT_GRAPHICS
6065         Rosen::WindowManager::GetInstance().DumpSessionWithId(missionId, info);
6066 #endif // SUPPORT_GRAPHICS
6067         return;
6068     }
6069 
6070     auto missionListManager = GetCurrentMissionListManager();
6071     CHECK_POINTER_LOG(missionListManager, "Current mission manager not init.");
6072     missionListManager->DumpMission(missionId, info);
6073 }
6074 
DumpStateInner(const std::string & args,std::vector<std::string> & info)6075 void AbilityManagerService::DumpStateInner(const std::string &args, std::vector<std::string> &info)
6076 {
6077     auto connectManager = GetCurrentConnectManager();
6078     CHECK_POINTER_LOG(connectManager, "Current mission manager not init.");
6079     std::vector<std::string> argList;
6080     SplitStr(args, " ", argList);
6081     if (argList.empty()) {
6082         return;
6083     }
6084     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6085         connectManager->DumpState(info, false, argList[1]);
6086     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6087         connectManager->DumpState(info, false);
6088     } else {
6089         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
6090     }
6091 }
6092 
DataDumpStateInner(const std::string & args,std::vector<std::string> & info)6093 void AbilityManagerService::DataDumpStateInner(const std::string &args, std::vector<std::string> &info)
6094 {
6095     auto dataAbilityManager = GetCurrentDataAbilityManager();
6096     CHECK_POINTER(dataAbilityManager);
6097     std::vector<std::string> argList;
6098     SplitStr(args, " ", argList);
6099     if (argList.empty()) {
6100         return;
6101     }
6102     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6103         dataAbilityManager->DumpState(info, argList[1]);
6104     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6105         dataAbilityManager->DumpState(info);
6106     } else {
6107         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
6108     }
6109 }
6110 
DumpState(const std::string & args,std::vector<std::string> & info)6111 void AbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
6112 {
6113     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6114     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
6115     if (!isShellCall && !isHidumperServiceCall) {
6116         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
6117         return;
6118     }
6119     std::vector<std::string> argList;
6120     SplitStr(args, " ", argList);
6121     if (argList.empty()) {
6122         return;
6123     }
6124     auto key = DumpUtils::DumpMap(argList[0]);
6125     if (!key.first) {
6126         return;
6127     }
6128     switch (key.second) {
6129         case DumpUtils::KEY_DUMP_SERVICE:
6130             DumpStateInner(args, info);
6131             break;
6132         case DumpUtils::KEY_DUMP_DATA:
6133             DataDumpStateInner(args, info);
6134             break;
6135         case DumpUtils::KEY_DUMP_ALL:
6136             DumpInner(args, info);
6137             break;
6138         case DumpUtils::KEY_DUMP_MISSION:
6139             DumpMissionInner(args, info);
6140             break;
6141         case DumpUtils::KEY_DUMP_MISSION_LIST:
6142             DumpMissionListInner(args, info);
6143             break;
6144         case DumpUtils::KEY_DUMP_MISSION_INFOS:
6145             DumpMissionInfosInner(args, info);
6146             break;
6147         default:
6148             info.push_back("error: invalid argument, please see 'ability dump -h'.");
6149             break;
6150     }
6151 }
6152 
DumpSysState(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6153 void AbilityManagerService::DumpSysState(
6154     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
6155 {
6156     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
6157     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6158     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
6159     if (!isShellCall && !isHidumperServiceCall) {
6160         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
6161         return;
6162     }
6163     std::vector<std::string> argList;
6164     SplitStr(args, " ", argList);
6165     if (argList.empty()) {
6166         return;
6167     }
6168     auto key = DumpUtils::DumpsysMap(argList[0]);
6169     if (!key.first) {
6170         return;
6171     }
6172     switch (key.second) {
6173         case DumpUtils::KEY_DUMP_SYS_ALL:
6174             DumpSysInner(args, info, isClient, isUserID, userId);
6175             break;
6176         case DumpUtils::KEY_DUMP_SYS_SERVICE:
6177             DumpSysStateInner(args, info, isClient, isUserID, userId);
6178             break;
6179         case DumpUtils::KEY_DUMP_SYS_PENDING:
6180             DumpSysPendingInner(args, info, isClient, isUserID, userId);
6181             break;
6182         case DumpUtils::KEY_DUMP_SYS_PROCESS:
6183             DumpSysProcess(args, info, isClient, isUserID, userId);
6184             break;
6185         case DumpUtils::KEY_DUMP_SYS_DATA:
6186             DataDumpSysStateInner(args, info, isClient, isUserID, userId);
6187             break;
6188         case DumpUtils::KEY_DUMP_SYS_MISSION_LIST:
6189             DumpSysMissionListInner(args, info, isClient, isUserID, userId);
6190             break;
6191         case DumpUtils::KEY_DUMP_SYS_ABILITY:
6192             DumpSysAbilityInner(args, info, isClient, isUserID, userId);
6193             break;
6194         default:
6195             info.push_back("error: invalid argument, please see 'ability dump -h'.");
6196             break;
6197     }
6198 }
6199 
AbilityTransitionDone(const sptr<IRemoteObject> & token,int state,const PacMap & saveData)6200 int AbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
6201 {
6202     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6203     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
6204         return ERR_INVALID_VALUE;
6205     }
6206     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6207     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
6208     TAG_LOGI(AAFwkTag::ABILITYMGR, "AbilityTransitionDone, ability: %{public}s, state:%{public}d",
6209         abilityRecord->GetURI().c_str(), state);
6210     if (!JudgeSelfCalled(abilityRecord)) {
6211         return CHECK_PERMISSION_FAILED;
6212     }
6213 
6214     auto abilityInfo = abilityRecord->GetAbilityInfo();
6215     auto type = abilityInfo.type;
6216     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6217     // force timeout ability for test
6218     int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast<AbilityLifeCycleState>(state));
6219     bool isTerminate = abilityRecord->IsAbilityState(AbilityState::TERMINATING) && targetState == AbilityState::INITIAL;
6220     std::string tempState = isTerminate ? AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) :
6221         AbilityRecord::ConvertAbilityState(static_cast<AbilityState>(targetState));
6222     if (IsNeedTimeoutForTest(abilityInfo.name, tempState)) {
6223         TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability, state:%{public}s, ability:%{public}s",
6224             tempState.c_str(),
6225             abilityInfo.name.c_str());
6226         return ERR_OK;
6227     }
6228     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
6229         auto connectManager = GetConnectManagerByUserId(userId);
6230         if (!connectManager) {
6231             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6232             return ERR_INVALID_VALUE;
6233         }
6234         return connectManager->AbilityTransitionDone(token, state);
6235     }
6236     if (type == AppExecFwk::AbilityType::DATA) {
6237         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6238         if (!dataAbilityManager) {
6239             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
6240             return ERR_INVALID_VALUE;
6241         }
6242         return dataAbilityManager->AbilityTransitionDone(token, state);
6243     }
6244 
6245     if (targetState == AbilityState::BACKGROUND) {
6246         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of background lifecycle.";
6247         FreezeUtil::GetInstance().AddLifecycleEvent(token, entry);
6248     } else if (targetState != AbilityState::INITIAL) {
6249         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of foreground lifecycle."
6250             " the end of foreground lifecycle.";
6251         FreezeUtil::GetInstance().AddLifecycleEvent(token, entry);
6252     }
6253 
6254     int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
6255     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6256         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
6257         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
6258         return uiAbilityManager->AbilityTransactionDone(token, state, saveData);
6259     } else {
6260         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
6261         if (!missionListManager) {
6262             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", ownerMissionUserId);
6263             return ERR_INVALID_VALUE;
6264         }
6265         return missionListManager->AbilityTransactionDone(token, state, saveData);
6266     }
6267 }
6268 
AbilityWindowConfigTransitionDone(const sptr<IRemoteObject> & token,const WindowConfig & windowConfig)6269 int AbilityManagerService::AbilityWindowConfigTransitionDone(
6270     const sptr<IRemoteObject> &token, const WindowConfig &windowConfig)
6271 {
6272     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6273     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
6274         return ERR_INVALID_VALUE;
6275     }
6276     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6277     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record null.");
6278     if (!JudgeSelfCalled(abilityRecord)) {
6279         return CHECK_PERMISSION_FAILED;
6280     }
6281 
6282     TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", abilityRecord->GetURI().c_str());
6283     auto abilityInfo = abilityRecord->GetAbilityInfo();
6284     auto type = abilityInfo.extensionAbilityType;
6285     if (type != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
6286         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid type");
6287         return ERR_INVALID_VALUE;
6288     }
6289     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6290     auto connectManager = GetConnectManagerByUserId(userId);
6291     if(!connectManager) {
6292         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6293         return ERR_INVALID_VALUE;
6294     }
6295     return connectManager->AbilityWindowConfigTransactionDone(token, windowConfig);
6296 }
6297 
ScheduleConnectAbilityDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & remoteObject)6298 int AbilityManagerService::ScheduleConnectAbilityDone(
6299     const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
6300 {
6301     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6302     TAG_LOGD(AAFwkTag::SERVICE_EXT, "called");
6303     if (!VerificationAllToken(token)) {
6304         return ERR_INVALID_VALUE;
6305     }
6306 
6307     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6308     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6309     if (!JudgeSelfCalled(abilityRecord)) {
6310         return CHECK_PERMISSION_FAILED;
6311     }
6312 
6313     auto type = abilityRecord->GetAbilityInfo().type;
6314     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6315         TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability failed, target ability not service");
6316         return TARGET_ABILITY_NOT_SERVICE;
6317     }
6318     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6319     auto connectManager = GetConnectManagerByUserId(userId);
6320     if (!connectManager) {
6321         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", userId);
6322         return ERR_INVALID_VALUE;
6323     }
6324     return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject);
6325 }
6326 
ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> & token)6327 int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
6328 {
6329     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6330     TAG_LOGD(AAFwkTag::SERVICE_EXT, "call");
6331     if (!VerificationAllToken(token)) {
6332         return ERR_INVALID_VALUE;
6333     }
6334 
6335     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6336     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6337     if (!JudgeSelfCalled(abilityRecord)) {
6338         return CHECK_PERMISSION_FAILED;
6339     }
6340 
6341     auto type = abilityRecord->GetAbilityInfo().type;
6342     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6343         TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability failed, target ability not service");
6344         return TARGET_ABILITY_NOT_SERVICE;
6345     }
6346     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6347     auto connectManager = GetConnectManagerByUserId(userId);
6348     if (!connectManager) {
6349         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", userId);
6350         return ERR_INVALID_VALUE;
6351     }
6352     return connectManager->ScheduleDisconnectAbilityDoneLocked(token);
6353 }
6354 
ScheduleCommandAbilityDone(const sptr<IRemoteObject> & token)6355 int AbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
6356 {
6357     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6358     TAG_LOGD(AAFwkTag::SERVICE_EXT, "Schedule command ability done.");
6359     if (!VerificationAllToken(token)) {
6360         return ERR_INVALID_VALUE;
6361     }
6362 
6363     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6364     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6365     if (!JudgeSelfCalled(abilityRecord)) {
6366         return CHECK_PERMISSION_FAILED;
6367     }
6368     // force timeout ability for test
6369     if (IsNeedTimeoutForTest(abilityRecord->GetAbilityInfo().name, std::string("COMMAND"))) {
6370         TAG_LOGW(AAFwkTag::SERVICE_EXT, "force timeout ability, state:COMMAND, ability: %{public}s",
6371             abilityRecord->GetAbilityInfo().name.c_str());
6372         return ERR_OK;
6373     }
6374     auto type = abilityRecord->GetAbilityInfo().type;
6375     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6376         TAG_LOGE(AAFwkTag::SERVICE_EXT, "failed, target ability not service");
6377         return TARGET_ABILITY_NOT_SERVICE;
6378     }
6379     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6380     auto connectManager = GetConnectManagerByUserId(userId);
6381     if (!connectManager) {
6382         TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", userId);
6383         return ERR_INVALID_VALUE;
6384     }
6385     return connectManager->ScheduleCommandAbilityDoneLocked(token);
6386 }
6387 
ScheduleCommandAbilityWindowDone(const sptr<IRemoteObject> & token,const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd,AbilityCommand abilityCmd)6388 int AbilityManagerService::ScheduleCommandAbilityWindowDone(
6389     const sptr<IRemoteObject> &token,
6390     const sptr<SessionInfo> &sessionInfo,
6391     WindowCommand winCmd,
6392     AbilityCommand abilityCmd)
6393 {
6394     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6395     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter.");
6396     if (!VerificationAllToken(token)) {
6397         return ERR_INVALID_VALUE;
6398     }
6399 
6400     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6401     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6402     if (!JudgeSelfCalled(abilityRecord)) {
6403         return CHECK_PERMISSION_FAILED;
6404     }
6405 
6406     if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)
6407         && !UIExtensionUtils::IsWindowExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
6408         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not ui or window extension");
6409         return ERR_INVALID_VALUE;
6410     }
6411     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6412     auto connectManager = GetConnectManagerByUserId(userId);
6413     if (!connectManager) {
6414         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6415         return ERR_INVALID_VALUE;
6416     }
6417     return connectManager->ScheduleCommandAbilityWindowDone(token, sessionInfo, winCmd, abilityCmd);
6418 }
6419 
OnAbilityRequestDone(const sptr<IRemoteObject> & token,const int32_t state)6420 void AbilityManagerService::OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)
6421 {
6422     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6423     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6424     CHECK_POINTER(abilityRecord);
6425     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnAbilityRequestDone, bundleName: %{public}s, abilityName: %{public}s",
6426         abilityRecord->GetAbilityInfo().bundleName.c_str(), abilityRecord->GetAbilityInfo().name.c_str());
6427     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6428 
6429     auto type = abilityRecord->GetAbilityInfo().type;
6430     switch (type) {
6431         case AppExecFwk::AbilityType::DATA: {
6432             auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6433             if (!dataAbilityManager) {
6434                 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
6435                 return;
6436             }
6437             dataAbilityManager->OnAbilityRequestDone(token, state);
6438             break;
6439         }
6440         case AppExecFwk::AbilityType::SERVICE:
6441         case AppExecFwk::AbilityType::EXTENSION: {
6442             auto connectManager = GetConnectManagerByUserId(userId);
6443             if (!connectManager) {
6444                 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6445                 return;
6446             }
6447             connectManager->OnAbilityRequestDone(token, state);
6448             break;
6449         }
6450         default: {
6451             int32_t ownerUserId = abilityRecord->GetOwnerMissionUserId();
6452             if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6453                 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
6454                 CHECK_POINTER(uiAbilityManager);
6455                 uiAbilityManager->OnAbilityRequestDone(token, state);
6456             } else {
6457                 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
6458                 if (!missionListManager) {
6459                     TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", ownerUserId);
6460                     return;
6461                 }
6462                 missionListManager->OnAbilityRequestDone(token, state);
6463             }
6464             break;
6465         }
6466     }
6467 }
6468 
OnAppStateChanged(const AppInfo & info)6469 void AbilityManagerService::OnAppStateChanged(const AppInfo &info)
6470 {
6471     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6472     auto connectManager = GetCurrentConnectManager();
6473     CHECK_POINTER_LOG(connectManager, "Connect manager not init.");
6474     connectManager->OnAppStateChanged(info);
6475     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6476         auto uiAbilityManager = GetCurrentUIAbilityManager();
6477         CHECK_POINTER(uiAbilityManager);
6478         uiAbilityManager->OnAppStateChanged(info);
6479     } else {
6480         auto missionListManager = GetCurrentMissionListManager();
6481         CHECK_POINTER_LOG(missionListManager, "Current mission list manager not init.");
6482         missionListManager->OnAppStateChanged(info);
6483     }
6484     auto dataAbilityManager = GetCurrentDataAbilityManager();
6485     CHECK_POINTER(dataAbilityManager);
6486     dataAbilityManager->OnAppStateChanged(info);
6487 
6488     auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
6489     CHECK_POINTER(residentProcessMgr);
6490     residentProcessMgr->OnAppStateChanged(info);
6491 
6492     if (system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
6493         KeepAliveProcessManager::GetInstance().OnAppStateChanged(info);
6494     }
6495 }
6496 
GetEventHandler()6497 std::shared_ptr<AbilityEventHandler> AbilityManagerService::GetEventHandler()
6498 {
6499     return eventHandler_;
6500 }
6501 
6502 // multi user scene
GetUserId() const6503 int32_t AbilityManagerService::GetUserId() const
6504 {
6505     if (userController_) {
6506         auto userId = userController_->GetCurrentUserId();
6507         TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is %{public}d", userId);
6508         return userId;
6509     }
6510     return U0_USER_ID;
6511 }
6512 
StartHighestPriorityAbility(int32_t userId,bool isBoot,bool isAppRecovery)6513 int AbilityManagerService::StartHighestPriorityAbility(int32_t userId, bool isBoot, bool isAppRecovery)
6514 {
6515     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
6516     auto bms = AbilityUtil::GetBundleManagerHelper();
6517     CHECK_POINTER_AND_RETURN(bms, BMS_NOT_CONNECTED);
6518 
6519     /* Query the highest priority ability or extension ability, and start it. usually, it is OOBE or launcher */
6520     Want want;
6521     want.AddEntity(HIGHEST_PRIORITY_ABILITY_ENTITY);
6522     AppExecFwk::AbilityInfo abilityInfo;
6523     AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
6524     int attemptNums = 0;
6525     while (true) {
6526         bms->PreConnect();
6527         if (IN_PROCESS_CALL(bms->ImplicitQueryInfoByPriority(want,
6528             AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId,
6529             abilityInfo, extensionAbilityInfo))) {
6530             break;
6531         }
6532         TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting query highest priority ability info completed");
6533         ++attemptNums;
6534         if (!isBoot && attemptNums > SWITCH_ACCOUNT_TRY) {
6535             TAG_LOGE(AAFwkTag::ABILITYMGR, "query highest priority ability failed");
6536             return RESOLVE_ABILITY_ERR;
6537         }
6538         AbilityRequest abilityRequest;
6539         usleep(REPOLL_TIME_MICRO_SECONDS);
6540     }
6541 
6542     if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
6543         TAG_LOGE(AAFwkTag::ABILITYMGR, "query highest priority ability failed");
6544         return RESOLVE_ABILITY_ERR;
6545     }
6546 
6547     Want abilityWant; // donot use 'want' here, because the entity of 'want' is not empty
6548     if (!abilityInfo.name.empty()) {
6549         /* highest priority ability */
6550         TAG_LOGI(AAFwkTag::ABILITYMGR, "start highest priority ability bundleName:%{public}s, ability:%{public}s",
6551             abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
6552         abilityWant.SetElementName(abilityInfo.bundleName, abilityInfo.name);
6553     } else {
6554         /* highest priority extension ability */
6555         TAG_LOGI(AAFwkTag::ABILITYMGR,
6556             "start highest priority extension ability bundleName:%{public}s, ability:%{public}s",
6557             extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str());
6558         abilityWant.SetElementName(extensionAbilityInfo.bundleName, extensionAbilityInfo.name);
6559     }
6560 
6561 #ifdef SUPPORT_GRAPHICS
6562     abilityWant.SetParam(NEED_STARTINGWINDOW, false);
6563     // wait BOOT_ANIMATION_STARTED to start LAUNCHER
6564     WaitBootAnimationStart();
6565 #endif
6566     if (isAppRecovery) {
6567         abilityWant.SetParam("ohos.app.logout_recovery", true);
6568     }
6569     /* note: OOBE APP need disable itself, otherwise, it will be started when restart system everytime */
6570     return StartAbility(abilityWant, userId, DEFAULT_INVAL_VALUE);
6571 }
6572 
GenerateAbilityRequest(const Want & want,int requestCode,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)6573 int AbilityManagerService::GenerateAbilityRequest(const Want &want, int requestCode, AbilityRequest &request,
6574     const sptr<IRemoteObject> &callerToken, int32_t userId)
6575 {
6576     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6577     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6578     if (abilityRecord != nullptr) {
6579         request.callerTokenRecordId = abilityRecord->GetRecordId();
6580     }
6581     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6582         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6583         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6584         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6585     }
6586 
6587     int32_t appIndex = 0;
6588     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
6589     if (abilityRecord != nullptr &&
6590         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName() &&
6591         abilityRecord->GetAppIndex() == appIndex) {
6592         (const_cast<Want &>(want)).SetParam(DEBUG_APP, abilityRecord->IsDebugApp());
6593     }
6594 
6595     request.want = want;
6596     request.requestCode = requestCode;
6597     request.callerToken = callerToken;
6598     auto setting = AbilityStartSetting::GetEmptySetting();
6599     if (setting != nullptr) {
6600         setting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "false"); // default is false
6601         request.startSetting = std::make_shared<AbilityStartSetting>(*(setting.get()));
6602     }
6603 
6604     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6605     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6606         int32_t appIndex = 0;
6607         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6608             return ERR_APP_CLONE_INDEX_INVALID;
6609         }
6610         Want localWant = want;
6611         if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
6612             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
6613             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
6614             localWant.RemoveParam(PARAM_RESV_ANCO_IS_NEED_UPDATE_NAME);
6615             localWant.SetParam(Want::PARAM_RESV_CALLER_TOKEN, static_cast<int32_t>(IPCSkeleton::GetCallingTokenID()));
6616             localWant.SetParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid());
6617         }
6618         abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(localWant, userId, appIndex);
6619     }
6620     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6621     if (abilityInfo->status != ERR_OK) {
6622         return abilityInfo->status;
6623     }
6624     request.abilityInfo = abilityInfo->abilityInfo;
6625     request.extensionProcessMode = abilityInfo->extensionProcessMode;
6626     request.customProcess = abilityInfo->customProcess;
6627 
6628     if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
6629         request.collaboratorType = CollaboratorType::RESERVE_TYPE;
6630     } else if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::OTHERS_TYPE)) {
6631         request.collaboratorType = CollaboratorType::OTHERS_TYPE;
6632     }
6633 
6634     if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) {
6635         TAG_LOGI(AAFwkTag::ABILITYMGR, "stage mode, abilityInfo SERVICE type reset EXTENSION");
6636         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
6637     }
6638 
6639     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6640         TAG_LOGE(AAFwkTag::ABILITYMGR, "get app info failed");
6641         return RESOLVE_APP_ERR;
6642     }
6643     if (want.GetIntParam(AAFwk::SCREEN_MODE_KEY, ScreenMode::IDLE_SCREEN_MODE) == ScreenMode::JUMP_SCREEN_MODE &&
6644         (request.abilityInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE ||
6645         request.abilityInfo.launchMode != AppExecFwk::LaunchMode::SINGLETON)) {
6646         TAG_LOGE(AAFwkTag::ABILITYMGR, "interface of starting atomicService start only atomicService");
6647         return TARGET_ABILITY_NOT_SERVICE;
6648     }
6649     request.appInfo = request.abilityInfo.applicationInfo;
6650     request.uid = request.appInfo.uid;
6651     TAG_LOGD(AAFwkTag::ABILITYMGR,
6652         "GenerateAbilityRequest end, app name: %{public}s, moduleName name: %{public}s, uid: %{public}d.",
6653         request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid);
6654 
6655     request.want.SetModuleName(request.abilityInfo.moduleName);
6656 
6657     int32_t startRecent = AbilityPermissionUtil::GetInstance().CheckStartRecentAbility(want, request);
6658     if (startRecent != ERR_OK) {
6659         return startRecent;
6660     }
6661 
6662     if (ModalSystemDialogUtil::CheckDebugAppNotInDeveloperMode(request.abilityInfo.applicationInfo)) {
6663         // service and extension do not show dialog.
6664         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
6665             !(request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
6666                 request.abilityInfo.type == AppExecFwk::AbilityType::EXTENSION)) {
6667             ModalSystemDialogUtil::ShowDeveloperModeDialog(
6668                 request.abilityInfo.bundleName, request.abilityInfo.moduleName, request.abilityInfo.labelId, userId);
6669         }
6670         TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer mode");
6671         return ERR_NOT_DEVELOPER_MODE;
6672     }
6673 
6674     return ERR_OK;
6675 }
6676 
GenerateExtensionAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)6677 int AbilityManagerService::GenerateExtensionAbilityRequest(
6678     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
6679 {
6680     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6681     if (abilityRecord != nullptr) {
6682         request.callerTokenRecordId = abilityRecord->GetRecordId();
6683     }
6684     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6685         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6686         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6687         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6688     }
6689     request.want = want;
6690     request.callerToken = callerToken;
6691     request.startSetting = nullptr;
6692 
6693     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6694     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6695         int32_t appIndex = 0;
6696         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6697             return ERR_APP_CLONE_INDEX_INVALID;
6698         }
6699         abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, appIndex);
6700     }
6701     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6702     if (abilityInfo->status != ERR_OK) {
6703         return abilityInfo->status;
6704     }
6705     if (ModalSystemDialogUtil::CheckDebugAppNotInDeveloperMode(abilityInfo->abilityInfo.applicationInfo)) {
6706         TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer mode");
6707         return ERR_NOT_DEVELOPER_MODE;
6708     }
6709     auto result = InitialAbilityRequest(request, *abilityInfo);
6710     return result;
6711 }
6712 
InitialAbilityRequest(AbilityRequest & request,const StartAbilityInfo & abilityInfo) const6713 int32_t AbilityManagerService::InitialAbilityRequest(AbilityRequest &request,
6714     const StartAbilityInfo &abilityInfo) const
6715 {
6716     request.abilityInfo = abilityInfo.abilityInfo;
6717     request.extensionProcessMode = abilityInfo.extensionProcessMode;
6718     request.customProcess = abilityInfo.customProcess;
6719     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6720         TAG_LOGE(AAFwkTag::ABILITYMGR, "get app info failed");
6721         return RESOLVE_APP_ERR;
6722     }
6723     request.appInfo = request.abilityInfo.applicationInfo;
6724     request.uid = request.appInfo.uid;
6725     TAG_LOGD(AAFwkTag::ABILITYMGR,
6726         "GenerateExtensionAbilityRequest end, app name:%{public}s, bundle name:%{public}s, uid:%{public}d, moduleName:%{public}s",
6727         request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid, request.abilityInfo.moduleName.c_str());
6728 
6729     request.want.SetModuleName(request.abilityInfo.moduleName);
6730 
6731     return ERR_OK;
6732 }
6733 
StopServiceAbility(const Want & want,int32_t userId,const sptr<IRemoteObject> & token)6734 int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)
6735 {
6736     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6737     TAG_LOGD(AAFwkTag::ABILITYMGR, "call.");
6738 
6739     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6740     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6741     if (!isSaCall && !isShellCall) {
6742         auto abilityRecord = Token::GetAbilityRecordByToken(token);
6743         if (abilityRecord == nullptr) {
6744             TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord null");
6745             return ERR_INVALID_VALUE;
6746         }
6747     }
6748 
6749     int32_t validUserId = GetValidUserId(userId);
6750     if (!JudgeMultiUserConcurrency(validUserId)) {
6751         TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
6752         return ERR_CROSS_USER;
6753     }
6754 
6755     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
6756     AbilityRequest abilityRequest;
6757     auto result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId);
6758     if (result != ERR_OK) {
6759         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
6760         return result;
6761     }
6762 
6763     auto abilityInfo = abilityRequest.abilityInfo;
6764     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
6765     TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
6766         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
6767 
6768     auto type = abilityInfo.type;
6769     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6770         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not service type");
6771         return TARGET_ABILITY_NOT_SERVICE;
6772     }
6773 
6774     auto res = JudgeAbilityVisibleControl(abilityInfo);
6775     if (res != ERR_OK) {
6776         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability invisible");
6777         return res;
6778     }
6779 
6780     auto connectManager = GetConnectManagerByUserId(validUserId);
6781     if (connectManager == nullptr) {
6782         return ERR_INVALID_VALUE;
6783     }
6784 
6785     return connectManager->StopServiceAbility(abilityRequest);
6786 }
6787 
OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)6788 void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)
6789 {
6790     CHECK_POINTER(abilityRecord);
6791     TAG_LOGI(AAFwkTag::ABILITYMGR, "On ability died: %{public}s, %{public}d, %{public}" PRId64,
6792         abilityRecord->GetURI().c_str(), abilityRecord->GetRecordId(),
6793         abilityRecord->GetAbilityRecordId());
6794     if (abilityRecord->GetToken()) {
6795         FreezeUtil::GetInstance().DeleteLifecycleEvent(abilityRecord->GetToken()->AsObject());
6796     }
6797     FreezeUtil::GetInstance().DeleteAppLifecycleEvent(abilityRecord->GetPid());
6798     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6799         if (abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6800             auto uiAbilityManager = GetUIAbilityManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6801             CHECK_POINTER(uiAbilityManager);
6802             uiAbilityManager->OnAbilityDied(abilityRecord);
6803             return;
6804         }
6805     } else {
6806         auto manager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6807         if (manager && abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6808             ReleaseAbilityTokenMap(abilityRecord->GetToken());
6809             manager->OnAbilityDied(abilityRecord, GetUserId());
6810             return;
6811         }
6812     }
6813 
6814     auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
6815     if (connectManager) {
6816         connectManager->OnAbilityDied(abilityRecord, GetUserId());
6817         return;
6818     } else {
6819         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager not found");
6820     }
6821 
6822     auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken());
6823     if (dataAbilityManager) {
6824         dataAbilityManager->OnAbilityDied(abilityRecord);
6825     }
6826 }
6827 
OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)6828 void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
6829 {
6830     CHECK_POINTER(callRecord);
6831     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6832         auto uiAbilityManager = GetCurrentUIAbilityManager();
6833         CHECK_POINTER(uiAbilityManager);
6834         uiAbilityManager->OnCallConnectDied(callRecord);
6835         return;
6836     }
6837     auto missionListManager = GetCurrentMissionListManager();
6838     if (missionListManager) {
6839         missionListManager->OnCallConnectDied(callRecord);
6840     }
6841 }
6842 
ReleaseAbilityTokenMap(const sptr<IRemoteObject> & token)6843 void AbilityManagerService::ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)
6844 {
6845     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
6846     for (auto iter = callStubTokenMap_.begin(); iter != callStubTokenMap_.end(); iter++) {
6847         if (iter->second == token) {
6848             callStubTokenMap_.erase(iter);
6849             break;
6850         }
6851     }
6852 }
6853 
KillProcess(const std::string & bundleName,bool clearPageStack,int32_t appIndex)6854 int AbilityManagerService::KillProcess(const std::string &bundleName, bool clearPageStack, int32_t appIndex)
6855 {
6856     TAG_LOGI(AAFwkTag::ABILITYMGR, "Kill process, bundleName: %{public}s, clearPageStack: %{public}d",
6857         bundleName.c_str(), clearPageStack);
6858     auto bms = AbilityUtil::GetBundleManagerHelper();
6859     CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED);
6860     int32_t userId = GetUserId();
6861     AppExecFwk::BundleInfo bundleInfo;
6862     if (IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, appIndex,
6863         bundleInfo, userId)) != ERR_OK) {
6864         TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle info when kill process failed");
6865         return GET_BUNDLE_INFO_FAILED;
6866     }
6867 
6868     KeepAliveType type;
6869     if (KeepAliveUtils::IsKeepAliveBundle(bundleInfo, userId, type)
6870         && DelayedSingleton<AppScheduler>::GetInstance()->IsMemorySizeSufficent()) {
6871         TAG_LOGE(AAFwkTag::ABILITYMGR, "no kill alive process");
6872         return KILL_PROCESS_KEEP_ALIVE;
6873     }
6874 
6875     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName, clearPageStack, appIndex);
6876     if (ret != ERR_OK) {
6877         return KILL_PROCESS_FAILED;
6878     }
6879 
6880     return ERR_OK;
6881 }
6882 
UninstallApp(const std::string & bundleName,int32_t uid)6883 int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid)
6884 {
6885     return UninstallApp(bundleName, uid, 0);
6886 }
6887 
UninstallApp(const std::string & bundleName,int32_t uid,int32_t appIndex)6888 int32_t AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex)
6889 {
6890     TAG_LOGI(AAFwkTag::ABILITYMGR, "uninstall app, bundleName:%{public}s, uid=%{public}d, appIndex:%{public}d",
6891         bundleName.c_str(), uid, appIndex);
6892     return UninstallAppInner(bundleName, uid, appIndex, false, "");
6893 }
6894 
UpgradeApp(const std::string & bundleName,const int32_t uid,const std::string & exitMsg,int32_t appIndex)6895 int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg,
6896     int32_t appIndex)
6897 {
6898     TAG_LOGI(AAFwkTag::ABILITYMGR,
6899         "upgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg:%{public}s, appIndex:%{public}d",
6900         bundleName.c_str(), uid, exitMsg.c_str(), appIndex);
6901     return UninstallAppInner(bundleName, uid, appIndex, true, exitMsg);
6902 }
6903 
UninstallAppInner(const std::string & bundleName,const int32_t uid,int32_t appIndex,const bool isUpgrade,const std::string & exitMsg)6904 int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex,
6905     const bool isUpgrade, const std::string &exitMsg)
6906 {
6907     pid_t callingPid = IPCSkeleton::GetCallingPid();
6908     pid_t pid = getprocpid();
6909     if (callingPid != pid) {
6910         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: not bundleMgr", __func__);
6911         return CHECK_PERMISSION_FAILED;
6912     }
6913 
6914     auto userId = uid / BASE_USER_RANGE;
6915     if (isUpgrade) {
6916         CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
6917         AAFwk::ExitReason exitReason = { REASON_UPGRADE, exitMsg };
6918         appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
6919     } else {
6920         IN_PROCESS_CALL_WITHOUT_RET(
6921             KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(bundleName, userId, false, true, false));
6922     }
6923     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppExecFwk::AppMgrClient>::
6924         GetInstance()->SetKeepAliveEnableState(bundleName, false, uid));
6925     auto connectManager = GetConnectManagerByUserId(userId);
6926     if (connectManager) {
6927         connectManager->UninstallApp(bundleName, uid);
6928     }
6929 
6930     CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT);
6931     subManagersHelper_->UninstallApp(bundleName, uid);
6932     std::string killReason = isUpgrade ? "UpgradeApp" : "UninstallApp";
6933     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplicationByUid(bundleName, uid, killReason);
6934     if (ret != ERR_OK) {
6935         return UNINSTALL_APP_FAILED;
6936     }
6937     if (!isUpgrade) {
6938         DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->DeleteAppExitReason(bundleName, uid,
6939             appIndex);
6940     }
6941     return ERR_OK;
6942 }
6943 
PreLoadAppDataAbilities(const std::string & bundleName,const int32_t userId)6944 int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)
6945 {
6946     if (bundleName.empty()) {
6947         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name preloading");
6948         return ERR_INVALID_VALUE;
6949     }
6950 
6951     if (taskHandler_ == nullptr) {
6952         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler null");
6953         return ERR_INVALID_STATE;
6954     }
6955 
6956     taskHandler_->SubmitTask([weak = weak_from_this(), bundleName, userId]() {
6957         auto pthis = weak.lock();
6958         if (pthis == nullptr) {
6959             TAG_LOGE(AAFwkTag::ABILITYMGR, "pthis null");
6960             return;
6961         }
6962         pthis->PreLoadAppDataAbilitiesTask(bundleName, userId);
6963         });
6964 
6965     return ERR_OK;
6966 }
6967 
PreLoadAppDataAbilitiesTask(const std::string & bundleName,const int32_t userId)6968 void AbilityManagerService::PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId)
6969 {
6970     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6971     auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6972     if (dataAbilityManager == nullptr) {
6973         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid data ability manager preloading");
6974         return;
6975     }
6976 
6977     auto bms = AbilityUtil::GetBundleManagerHelper();
6978     CHECK_POINTER(bms);
6979 
6980     AppExecFwk::BundleInfo bundleInfo;
6981     bool ret = IN_PROCESS_CALL(
6982         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
6983     if (!ret) {
6984         TAG_LOGE(AAFwkTag::ABILITYMGR,
6985             "get bundleInfo preloading failed, userId:%{public}d", userId);
6986         return;
6987     }
6988 
6989     auto begin = system_clock::now();
6990     AbilityRequest dataAbilityRequest;
6991     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(dataAbilityRequest.want, nullptr);
6992     dataAbilityRequest.appInfo = bundleInfo.applicationInfo;
6993     for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
6994         if (it->type != AppExecFwk::AbilityType::DATA) {
6995             continue;
6996         }
6997         if ((system_clock::now() - begin) >= DATA_ABILITY_START_TIMEOUT) {
6998             TAG_LOGE(AAFwkTag::ABILITYMGR, "app data ability preloading '%{public}s' timeout", bundleName.c_str());
6999             return;
7000         }
7001         dataAbilityRequest.abilityInfo = *it;
7002         dataAbilityRequest.uid = bundleInfo.uid;
7003         TAG_LOGD(AAFwkTag::ABILITYMGR, "App data ability preloading: '%{public}s.%{public}s'...",
7004             it->bundleName.c_str(), it->name.c_str());
7005 
7006         auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false);
7007         if (dataAbility == nullptr) {
7008             TAG_LOGE(AAFwkTag::ABILITYMGR,
7009                 "preload data ability failed  '%{public}s.%{public}s'", it->bundleName.c_str(), it->name.c_str());
7010             return;
7011         }
7012     }
7013 }
7014 
IsSystemUiApp(const AppExecFwk::AbilityInfo & info) const7015 bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const
7016 {
7017     if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) {
7018         return false;
7019     }
7020     return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR ||
7021         info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR ||
7022         info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME);
7023 }
7024 
IsSystemUI(const std::string & bundleName) const7025 bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const
7026 {
7027     return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME;
7028 }
7029 
HandleLoadTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)7030 void AbilityManagerService::HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
7031 {
7032     TAG_LOGD(AAFwkTag::ABILITYMGR, "load timeout %{public}" PRId64, abilityRecordId);
7033     if (isExtension) {
7034         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
7035         if (connectManager != nullptr) {
7036             connectManager->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
7037         }
7038         return;
7039     }
7040 
7041     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7042         auto uiAbilityManagers = GetUIAbilityManagers();
7043         for (auto& item : uiAbilityManagers) {
7044             if (item.second) {
7045                 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
7046             }
7047         }
7048         return;
7049     }
7050     auto missionListManagers = GetMissionListManagers();
7051     for (auto& item : missionListManagers) {
7052         if (item.second) {
7053             item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
7054         }
7055     }
7056 }
7057 
HandleActiveTimeOut(int64_t abilityRecordId)7058 void AbilityManagerService::HandleActiveTimeOut(int64_t abilityRecordId)
7059 {
7060     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle active timeout.");
7061     auto missionListManagers = GetMissionListManagers();
7062     for (auto& item : missionListManagers) {
7063         if (item.second) {
7064             item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecordId);
7065         }
7066     }
7067 }
7068 
HandleInactiveTimeOut(int64_t abilityRecordId)7069 void AbilityManagerService::HandleInactiveTimeOut(int64_t abilityRecordId)
7070 {
7071     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle inactive timeout.");
7072     auto missionListManagers = GetMissionListManagers();
7073     for (auto& item : missionListManagers) {
7074         if (item.second) {
7075             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
7076         }
7077     }
7078     auto connectManagers = GetConnectManagers();
7079     for (auto& item : connectManagers) {
7080         if (item.second) {
7081             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
7082         }
7083     }
7084 }
7085 
HandleForegroundTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)7086 void AbilityManagerService::HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
7087 {
7088     TAG_LOGD(AAFwkTag::ABILITYMGR, "foreground timeout %{public}" PRId64, abilityRecordId);
7089     if (isExtension) {
7090         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
7091         if (connectManager != nullptr) {
7092             connectManager->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
7093         }
7094         return;
7095     }
7096 
7097     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7098         auto uiAbilityManagers = GetUIAbilityManagers();
7099         for (auto& item : uiAbilityManagers) {
7100             if (item.second) {
7101                 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
7102             }
7103         }
7104         return;
7105     }
7106     auto missionListManagers = GetMissionListManagers();
7107     for (auto& item : missionListManagers) {
7108         if (item.second) {
7109             item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
7110         }
7111     }
7112 }
7113 
HandleShareDataTimeOut(int64_t uniqueId)7114 void AbilityManagerService::HandleShareDataTimeOut(int64_t uniqueId)
7115 {
7116     WantParams wantParam;
7117     int32_t ret = GetShareDataPairAndReturnData(nullptr, ERR_TIMED_OUT, uniqueId, wantParam);
7118     if (ret) {
7119         TAG_LOGE(AAFwkTag::ABILITYMGR, "acqurieShareData failed");
7120     }
7121 }
7122 
GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)7123 int32_t AbilityManagerService::GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,
7124     const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
7125 {
7126     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d, wantParam size:%{public}d",
7127         resultCode, uniqueId, wantParam.Size());
7128     {
7129         std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
7130         auto it = iAcquireShareDataMap_.find(uniqueId);
7131         if (it != iAcquireShareDataMap_.end()) {
7132             auto shareDataPair = it->second;
7133             if (abilityRecord && shareDataPair.first != abilityRecord->GetAbilityRecordId()) {
7134                 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is not the abilityRecord from request");
7135                 return ERR_INVALID_VALUE;
7136             }
7137             auto callback = shareDataPair.second;
7138             if (!callback) {
7139                 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback object null");
7140                 return ERR_INVALID_VALUE;
7141             }
7142             auto ret = callback->AcquireShareDataDone(resultCode, wantParam);
7143             iAcquireShareDataMap_.erase(it);
7144             return ret;
7145         }
7146     }
7147     TAG_LOGE(AAFwkTag::ABILITYMGR, "iAcquireShareData null");
7148     return ERR_INVALID_VALUE;
7149 }
7150 
VerificationToken(const sptr<IRemoteObject> & token)7151 bool AbilityManagerService::VerificationToken(const sptr<IRemoteObject> &token)
7152 {
7153     TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token");
7154     auto dataAbilityManager = GetCurrentDataAbilityManager();
7155     CHECK_POINTER_RETURN_BOOL(dataAbilityManager);
7156     auto connectManager = GetCurrentConnectManager();
7157     CHECK_POINTER_RETURN_BOOL(connectManager);
7158     auto missionListManager = GetCurrentMissionListManager();
7159     CHECK_POINTER_RETURN_BOOL(missionListManager);
7160 
7161     if (missionListManager->GetAbilityRecordByToken(token)) {
7162         return true;
7163     }
7164     if (missionListManager->GetAbilityFromTerminateList(token)) {
7165         return true;
7166     }
7167 
7168     if (dataAbilityManager->GetAbilityRecordByToken(token)) {
7169         TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token4");
7170         return true;
7171     }
7172 
7173     if (connectManager->GetExtensionByTokenFromServiceMap(token)) {
7174         TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
7175         return true;
7176     }
7177 
7178     if (AbilityCacheManager::GetInstance().FindRecordByToken(token)) {
7179         TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
7180         return true;
7181     }
7182 
7183     if (connectManager->GetExtensionByTokenFromTerminatingMap(token)) {
7184         TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
7185         return true;
7186     }
7187 
7188     TAG_LOGE(AAFwkTag::ABILITYMGR, "verify token failed");
7189     return false;
7190 }
7191 
VerificationAllToken(const sptr<IRemoteObject> & token)7192 bool AbilityManagerService::VerificationAllToken(const sptr<IRemoteObject> &token)
7193 {
7194     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7195     CHECK_POINTER_AND_RETURN(subManagersHelper_, false);
7196     return subManagersHelper_->VerificationAllToken(token);
7197 }
7198 
GetCurrentDataAbilityManager()7199 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetCurrentDataAbilityManager()
7200 {
7201     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7202     return subManagersHelper_->GetCurrentDataAbilityManager();
7203 }
7204 
GetDataAbilityManager(const sptr<IAbilityScheduler> & scheduler)7205 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManager(
7206     const sptr<IAbilityScheduler> &scheduler)
7207 {
7208     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7209     return subManagersHelper_->GetDataAbilityManager(scheduler);
7210 }
7211 
GetDataAbilityManagerByUserId(int32_t userId)7212 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId)
7213 {
7214     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7215     return subManagersHelper_->GetDataAbilityManagerByUserId(userId);
7216 }
7217 
GetDataAbilityManagerByToken(const sptr<IRemoteObject> & token)7218 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByToken(
7219     const sptr<IRemoteObject> &token)
7220 {
7221     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7222     return subManagersHelper_->GetDataAbilityManagerByToken(token);
7223 }
7224 
GetConnectManagers()7225 std::unordered_map<int, std::shared_ptr<AbilityConnectManager>> AbilityManagerService::GetConnectManagers()
7226 {
7227     if (subManagersHelper_ == nullptr) {
7228         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
7229         return std::unordered_map<int, std::shared_ptr<AbilityConnectManager>>();
7230     }
7231     return subManagersHelper_->GetConnectManagers();
7232 }
7233 
GetCurrentConnectManager()7234 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetCurrentConnectManager()
7235 {
7236     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7237     return subManagersHelper_->GetCurrentConnectManager();
7238 }
7239 
GetConnectManagerByUserId(int32_t userId)7240 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByUserId(int32_t userId)
7241 {
7242     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7243     return subManagersHelper_->GetConnectManagerByUserId(userId);
7244 }
7245 
GetConnectManagerByToken(const sptr<IRemoteObject> & token)7246 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByToken(
7247     const sptr<IRemoteObject> &token)
7248 {
7249     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7250     return subManagersHelper_->GetConnectManagerByToken(token);
7251 }
7252 
GetConnectManagerByAbilityRecordId(const int64_t & abilityRecordId)7253 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByAbilityRecordId(
7254     const int64_t &abilityRecordId)
7255 {
7256     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7257     return subManagersHelper_->GetConnectManagerByAbilityRecordId(abilityRecordId);
7258 }
7259 
GetCurrentPendingWantManager()7260 std::shared_ptr<PendingWantManager> AbilityManagerService::GetCurrentPendingWantManager()
7261 {
7262     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7263     return subManagersHelper_->GetCurrentPendingWantManager();
7264 }
7265 
GetPendingWantManagerByUserId(int32_t userId)7266 std::shared_ptr<PendingWantManager> AbilityManagerService::GetPendingWantManagerByUserId(int32_t userId)
7267 {
7268     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7269     return subManagersHelper_->GetPendingWantManagerByUserId(userId);
7270 }
7271 
GetMissionListManagers()7272 std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>> AbilityManagerService::GetMissionListManagers()
7273 {
7274     if (subManagersHelper_ == nullptr) {
7275         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
7276         return std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>>();
7277     }
7278     return subManagersHelper_->GetMissionListManagers();
7279 }
7280 
GetCurrentMissionListManager()7281 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetCurrentMissionListManager()
7282 {
7283     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7284     return subManagersHelper_->GetCurrentMissionListManager();
7285 }
7286 
GetMissionListManagerByUserId(int32_t userId)7287 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetMissionListManagerByUserId(int32_t userId)
7288 {
7289     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7290     return subManagersHelper_->GetMissionListManagerByUserId(userId);
7291 }
7292 
GetMissionListWrap()7293 std::shared_ptr<MissionListWrap> AbilityManagerService::GetMissionListWrap()
7294 {
7295     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7296     return subManagersHelper_->GetMissionListWrap();
7297 }
7298 
GetUIAbilityManagers()7299 std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>> AbilityManagerService::GetUIAbilityManagers()
7300 {
7301     if (subManagersHelper_ == nullptr) {
7302         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
7303         return std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>>();
7304     }
7305     return subManagersHelper_->GetUIAbilityManagers();
7306 }
7307 
GetCurrentUIAbilityManager()7308 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetCurrentUIAbilityManager()
7309 {
7310     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7311     return subManagersHelper_->GetCurrentUIAbilityManager();
7312 }
7313 
GetUIAbilityManagerByUserId(int32_t userId) const7314 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUserId(int32_t userId) const
7315 {
7316     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7317     return subManagersHelper_->GetUIAbilityManagerByUserId(userId);
7318 }
7319 
GetUIAbilityManagerByUid(int32_t uid)7320 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUid(int32_t uid)
7321 {
7322     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
7323     return subManagersHelper_->GetUIAbilityManagerByUid(uid);
7324 }
7325 
StartResidentApps(int32_t userId)7326 void AbilityManagerService::StartResidentApps(int32_t userId)
7327 {
7328     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps %{public}d", userId);
7329     ConnectServices();
7330     auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
7331     CHECK_POINTER(residentProcessManager);
7332     std::vector<AppExecFwk::BundleInfo> bundleInfos;
7333     if (!residentProcessManager->GetResidentBundleInfosForUser(bundleInfos, userId)) {
7334         TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident bundleinfos failed");
7335         return;
7336     }
7337     residentProcessManager->Init();
7338     TAG_LOGI(AAFwkTag::ABILITYMGR, "startResidentApps getBundleInfos size:%{public}zu", bundleInfos.size());
7339 
7340     residentProcessManager->StartResidentProcessWithMainElement(bundleInfos, userId);
7341     if (!bundleInfos.empty()) {
7342 #ifdef SUPPORT_GRAPHICS
7343         if (userId == U0_USER_ID) {
7344             WaitBootAnimationStart();
7345         }
7346 #endif
7347         residentProcessManager->StartResidentProcess(bundleInfos);
7348     }
7349 }
7350 
StartKeepAliveApps(int32_t userId)7351 void AbilityManagerService::StartKeepAliveApps(int32_t userId)
7352 {
7353     if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
7354         return;
7355     }
7356     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps %{public}d", userId);
7357     ConnectServices();
7358     std::vector<AppExecFwk::BundleInfo> bundleInfos;
7359     if (!KeepAliveProcessManager::GetInstance().GetKeepAliveBundleInfosForUser(
7360         bundleInfos, userId)) {
7361         TAG_LOGE(AAFwkTag::ABILITYMGR, "get keep-alive bundle info failed");
7362         return;
7363     }
7364     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps getBundleInfos size:%{public}zu", bundleInfos.size());
7365 
7366     KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfos, userId);
7367 }
7368 
StartAutoStartupApps()7369 void AbilityManagerService::StartAutoStartupApps()
7370 {
7371     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7372     if (abilityAutoStartupService_ == nullptr) {
7373         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
7374         return;
7375     }
7376     std::vector<AutoStartupInfo> infoList;
7377     int32_t result = abilityAutoStartupService_->QueryAllAutoStartupApplicationsWithoutPermission(infoList,
7378         GetUserId());
7379     if (result != ERR_OK) {
7380         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed query data");
7381         return;
7382     }
7383 
7384     if (taskHandler_ == nullptr) {
7385         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler null");
7386         return;
7387     }
7388     std::queue<AutoStartupInfo> infoQueue;
7389     for (auto &info : infoList) {
7390         info.retryCount = START_AUTO_START_APP_RETRY_MAX_TIMES;
7391         infoQueue.push(info);
7392     }
7393     StartAutoStartupApps(infoQueue);
7394 }
7395 
StartAutoStartupApps(std::queue<AutoStartupInfo> infoQueue)7396 void AbilityManagerService::StartAutoStartupApps(std::queue<AutoStartupInfo> infoQueue)
7397 {
7398     if (infoQueue.empty()) {
7399         return;
7400     }
7401     if (taskHandler_ == nullptr) {
7402         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler null");
7403         return;
7404     }
7405     auto info = infoQueue.front();
7406     infoQueue.pop();
7407     AppExecFwk::ElementName element;
7408     element.SetBundleName(info.bundleName);
7409     element.SetAbilityName(info.abilityName);
7410     element.SetModuleName(info.moduleName);
7411     Want want;
7412     want.SetElement(element);
7413     want.SetParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, true);
7414     if (info.appCloneIndex >= 0 && info.appCloneIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
7415         want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, info.appCloneIndex);
7416     }
7417     if (StartAbility(want) != ERR_OK && info.retryCount > 0) {
7418         info.retryCount--;
7419         infoQueue.push(info);
7420     }
7421     auto nextStartAutoStartupAppsTask = [aams = weak_from_this(), infoQueue]() {
7422         auto obj = aams.lock();
7423         if (obj == nullptr) {
7424             TAG_LOGE(AAFwkTag::ABILITYMGR, "start auto startup app error, obj null");
7425             return;
7426         }
7427         obj->StartAutoStartupApps(infoQueue);
7428     };
7429     taskHandler_->SubmitTask(nextStartAutoStartupAppsTask, "StartAutoStartupApps", START_AUTO_START_APP_DELAY_TIME);
7430 }
7431 
SubscribeScreenUnlockedEvent()7432 void AbilityManagerService::SubscribeScreenUnlockedEvent()
7433 {
7434     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7435     // add listen screen unlocked.
7436     EventFwk::MatchingSkills matchingSkills;
7437     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
7438     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
7439     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
7440     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
7441     screenSubscriber_ = std::make_shared<AbilityRuntime::AbilityManagerEventSubscriber>(subscribeInfo,
7442         GetScreenUnlockCallback(), GetUserScreenUnlockCallback());
7443     bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber_);
7444     if (!subResult) {
7445         RetrySubscribeScreenUnlockedEvent(RETRY_COUNT);
7446     }
7447 }
7448 
GetScreenUnlockCallback()7449 std::function<void()> AbilityManagerService::GetScreenUnlockCallback()
7450 {
7451     auto screenUnlockCallback = [abilityManager = weak_from_this()]() {
7452         TAG_LOGI(AAFwkTag::ABILITYMGR, "on screen unlocked");
7453         auto abilityMgr = abilityManager.lock();
7454         if (abilityMgr == nullptr) {
7455             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
7456             return;
7457         }
7458         auto taskHandler = abilityMgr->GetTaskHandler();
7459         if (taskHandler == nullptr) {
7460             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid taskHandler pointer");
7461             return;
7462         }
7463         auto screenUnlockTask = [abilityManager]() {
7464             auto abilityMgr = abilityManager.lock();
7465             if (abilityMgr == nullptr) {
7466                 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
7467                 return;
7468             }
7469             abilityMgr->RemoveScreenUnlockInterceptor();
7470             abilityMgr->UnSubscribeScreenUnlockedEvent();
7471             DelayedSingleton<ResidentProcessManager>::GetInstance()->StartFailedResidentAbilities();
7472         };
7473         taskHandler->SubmitTask(screenUnlockTask, "ScreenUnlockTask");
7474         auto delayStartAutoStartupAppTask = [abilityManager]() {
7475             auto abilityMgr = abilityManager.lock();
7476             if (abilityMgr == nullptr) {
7477                 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
7478                 return;
7479             }
7480             abilityMgr->StartAutoStartupApps();
7481         };
7482         taskHandler->SubmitTask(delayStartAutoStartupAppTask, "DelayStartAutoStartupApps",
7483             START_AUTO_START_APP_DELAY_TIME);
7484     };
7485     return screenUnlockCallback;
7486 }
7487 
GetUserScreenUnlockCallback()7488 std::function<void()> AbilityManagerService::GetUserScreenUnlockCallback()
7489 {
7490     auto userScreenUnlockCallback = [abilityManager = weak_from_this()]() {
7491         TAG_LOGD(AAFwkTag::ABILITYMGR, "On user screen unlocked.");
7492         auto abilityMgr = abilityManager.lock();
7493         if (abilityMgr == nullptr) {
7494             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
7495             return;
7496         }
7497         abilityMgr->RemoveScreenUnlockInterceptor();
7498     };
7499     return userScreenUnlockCallback;
7500 }
7501 
UnSubscribeScreenUnlockedEvent()7502 void AbilityManagerService::UnSubscribeScreenUnlockedEvent()
7503 {
7504     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7505     bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_);
7506     TAG_LOGD(AAFwkTag::ABILITYMGR, "Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult);
7507 }
7508 
RetrySubscribeScreenUnlockedEvent(int32_t retryCount)7509 void AbilityManagerService::RetrySubscribeScreenUnlockedEvent(int32_t retryCount)
7510 {
7511     TAG_LOGD(AAFwkTag::ABILITYMGR, "RetryCount: %{public}d.", retryCount);
7512     auto retrySubscribeScreenUnlockedEventTask = [aams = weak_from_this(), screenSubscriber = screenSubscriber_,
7513                                                      retryCount]() {
7514         bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber);
7515         auto obj = aams.lock();
7516         if (obj == nullptr) {
7517             TAG_LOGE(AAFwkTag::ABILITYMGR, "retry subscribe screen unlocked event, obj null");
7518             return;
7519         }
7520         if (!subResult && retryCount > 0) {
7521             obj->RetrySubscribeScreenUnlockedEvent(retryCount - 1);
7522         }
7523     };
7524     constexpr int delaytime = 200;
7525     CHECK_POINTER(taskHandler_);
7526     taskHandler_->SubmitTask(retrySubscribeScreenUnlockedEventTask, "RetrySubscribeScreenUnlockedEvent", delaytime);
7527 }
7528 
RemoveScreenUnlockInterceptor()7529 void AbilityManagerService::RemoveScreenUnlockInterceptor()
7530 {
7531     if (interceptorExecuter_ != nullptr) {
7532         interceptorExecuter_->RemoveInterceptor("ScreenUnlock");
7533     }
7534 }
7535 
RemoveUnauthorizedLaunchReasonMessage(const Want & want,AbilityRequest & abilityRequest,const sptr<IRemoteObject> & callerToken)7536 void AbilityManagerService::RemoveUnauthorizedLaunchReasonMessage(const Want &want, AbilityRequest &abilityRequest,
7537     const sptr<IRemoteObject> &callerToken)
7538 {
7539     std::string value = want.GetStringParam(Want::PARM_LAUNCH_REASON_MESSAGE);
7540     if (value.empty()) {
7541         return;
7542     }
7543 
7544     if (callerToken == nullptr) {
7545         TAG_LOGD(AAFwkTag::ABILITYMGR, "callertoken is nullptr, remove launch reason message.");
7546         (const_cast<Want &>(want)).RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
7547         abilityRequest.want.RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
7548     } else {
7549         auto targetRecord = Token::GetAbilityRecordByToken(callerToken);
7550         if (targetRecord == nullptr) {
7551             TAG_LOGD(AAFwkTag::ABILITYMGR, "targetRecord is nullptr.");
7552             return;
7553         }
7554         auto tokenId = targetRecord->GetAbilityInfo().applicationInfo.accessTokenId;
7555         if (!PermissionVerification::GetInstance()->VerifyPermissionByTokenId(tokenId,
7556             PermissionConstants::PERMISSION_SET_LAUNCH_REASON_MESSAGE) ||
7557             (!PermissionVerification::GetInstance()->IsSystemAppCall() &&
7558             !PermissionVerification::GetInstance()->IsSACall())) {
7559             TAG_LOGD(AAFwkTag::ABILITYMGR, "verifyPermission failed, remove launch reason message.");
7560             (const_cast<Want &>(want)).RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
7561             abilityRequest.want.RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
7562         }
7563     }
7564 }
7565 
ConnectServices()7566 void AbilityManagerService::ConnectServices()
7567 {
7568     TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting appMgr service run completed");
7569     while (!DelayedSingleton<AppScheduler>::GetInstance()->Init(shared_from_this())) {
7570         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed init appScheduler");
7571         usleep(REPOLL_TIME_MICRO_SECONDS);
7572     }
7573 
7574     TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting bundleMgr service run completed");
7575     while (AbilityUtil::GetBundleManagerHelper() == nullptr) {
7576         TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle manager helper failed");
7577         usleep(REPOLL_TIME_MICRO_SECONDS);
7578     }
7579     AbilityUtil::GetBundleManagerHelper()->ConnectTillSuccess();
7580     TAG_LOGI(AAFwkTag::ABILITYMGR, "bms success");
7581 }
7582 
GetWantSenderInfo(const sptr<IWantSender> & target,std::shared_ptr<WantSenderInfo> & info)7583 int AbilityManagerService::GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)
7584 {
7585     TAG_LOGI(AAFwkTag::ABILITYMGR, "get pending request info");
7586     auto pendingWantManager = GetCurrentPendingWantManager();
7587     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
7588     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
7589     CHECK_POINTER_AND_RETURN(info, ERR_INVALID_VALUE);
7590     return pendingWantManager->GetWantSenderInfo(target, info);
7591 }
7592 
GetAppMemorySize()7593 int AbilityManagerService::GetAppMemorySize()
7594 {
7595     TAG_LOGI(AAFwkTag::ABILITYMGR, "service getAppMemorySize start");
7596     const char *key = "const.product.arkheaplimit";
7597     const char *def = "512m";
7598     char *valueGet = nullptr;
7599     unsigned int len = 128;
7600     int ret = GetParameter(key, def, valueGet, len);
7601     int resultInt = 0;
7602     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7603         if (valueGet == nullptr) {
7604             TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, valueGet null", __func__);
7605             return APP_MEMORY_SIZE;
7606         }
7607         int len = strlen(valueGet);
7608         for (int i = 0; i < len; i++) {
7609             if (valueGet[i] >= '0' && valueGet[i] <= '9') {
7610                 resultInt *= SIZE_10;
7611                 resultInt += valueGet[i] - '0';
7612             }
7613         }
7614         if (resultInt == 0) {
7615             return APP_MEMORY_SIZE;
7616         }
7617         return resultInt;
7618     }
7619     return APP_MEMORY_SIZE;
7620 }
7621 
IsRamConstrainedDevice()7622 bool AbilityManagerService::IsRamConstrainedDevice()
7623 {
7624     TAG_LOGI(AAFwkTag::ABILITYMGR, "service IsRamConstrainedDevice start");
7625     const char *key = "const.product.islowram";
7626     const char *def = "0";
7627     char *valueGet = nullptr;
7628     unsigned int len = 128;
7629     int ret = GetParameter(key, def, valueGet, len);
7630     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7631         int value = atoi(valueGet);
7632         if (value) {
7633             return true;
7634         }
7635         return false;
7636     }
7637     return false;
7638 }
7639 
GetMissionIdByAbilityToken(const sptr<IRemoteObject> & token)7640 int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)
7641 {
7642     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7643     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7644     if (!abilityRecord) {
7645         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
7646         return -1;
7647     }
7648     if (!JudgeSelfCalled(abilityRecord)) {
7649         return -1;
7650     }
7651     return GetMissionIdByAbilityTokenInner(token);
7652 }
7653 
GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> & token)7654 int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)
7655 {
7656     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7657     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7658     if (!abilityRecord) {
7659         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
7660         return -1;
7661     }
7662     auto userId = abilityRecord->GetOwnerMissionUserId();
7663     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7664         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7665         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7666         return uiAbilityManager->GetSessionIdByAbilityToken(token);
7667     }
7668     auto missionListManager = GetMissionListManagerByUserId(userId);
7669     if (!missionListManager) {
7670         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null mission userId=%{public}d", userId);
7671         return -1;
7672     }
7673     return missionListManager->GetMissionIdByAbilityToken(token);
7674 }
7675 
GetAbilityTokenByMissionId(int32_t missionId)7676 sptr<IRemoteObject> AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId)
7677 {
7678     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7679     auto missionListManager = GetCurrentMissionListManager();
7680     if (!missionListManager) {
7681         return nullptr;
7682     }
7683     return missionListManager->GetAbilityTokenByMissionId(missionId);
7684 }
7685 
StartRemoteAbilityByCall(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)7686 int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken,
7687     const sptr<IRemoteObject> &connect)
7688 {
7689     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin startRemoteAbilityByCall", __func__);
7690     Want remoteWant = want;
7691     UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(remoteWant, callerToken);
7692     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
7693         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
7694         return ERR_INVALID_VALUE;
7695     }
7696     int32_t missionId = -1;
7697     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7698         missionId = GetMissionIdByAbilityTokenInner(callerToken);
7699         if (!missionId) {
7700             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
7701             return ERR_INVALID_VALUE;
7702         }
7703     } else {
7704         missionId = GetMissionIdByAbilityToken(callerToken);
7705 }
7706     if (missionId < 0) {
7707         return ERR_INVALID_VALUE;
7708     }
7709     remoteWant.SetParam(DMS_MISSION_ID, missionId);
7710     DistributedClient dmsClient;
7711     return dmsClient.StartRemoteAbilityByCall(remoteWant, connect);
7712 }
7713 
ReleaseRemoteAbility(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element)7714 int AbilityManagerService::ReleaseRemoteAbility(const sptr<IRemoteObject> &connect,
7715     const AppExecFwk::ElementName &element)
7716 {
7717     DistributedClient dmsClient;
7718     return dmsClient.ReleaseRemoteAbility(connect, element);
7719 }
7720 
StartAbilityByCall(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId)7721 int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect,
7722     const sptr<IRemoteObject> &callerToken, int32_t accountId)
7723 {
7724     std::string errMsg;
7725     return StartAbilityByCallWithErrMsg(want, connect, callerToken, accountId, errMsg);
7726 }
7727 
StartAbilityByCallWithErrMsg(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId,std::string & errMsg)7728 int AbilityManagerService::StartAbilityByCallWithErrMsg(const Want &want, const sptr<IAbilityConnection> &connect,
7729     const sptr<IRemoteObject> &callerToken, int32_t accountId, std::string &errMsg)
7730 {
7731     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
7732     int paramCheckResult = AbilityStartByCallHelper::CheckParam(connect, errMsg);
7733     if (paramCheckResult != ERR_OK) {
7734         return paramCheckResult;
7735     }
7736 
7737     if (IsCrossUserCall(accountId)) {
7738         CHECK_CALLER_IS_SYSTEM_APP;
7739     }
7740 
7741     if (VerifyAccountPermission(accountId) == CHECK_PERMISSION_FAILED) {
7742         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
7743         errMsg = "verify account permission failed";
7744         return CHECK_PERMISSION_FAILED;
7745     }
7746 
7747     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7748     if (abilityRecord && !JudgeSelfCalled(abilityRecord)) {
7749         errMsg = "verify account permission failed";
7750         return CHECK_PERMISSION_FAILED;
7751     }
7752 
7753     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
7754     int32_t appIndex = 0;
7755     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
7756         errMsg = "app index is error";
7757         return ERR_APP_CLONE_INDEX_INVALID;
7758     }
7759     auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
7760         GetUserId(), appIndex, callerToken);
7761     if (checkRet != ERR_OK) {
7762         return checkRet;
7763     }
7764 
7765 #ifdef SUPPORT_SCREEN
7766     DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
7767 #endif
7768 
7769     StartAbilityInfoWrap threadLocalInfo(want, GetUserId(), appIndex, callerToken);
7770     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
7771     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), true, nullptr,
7772         shouldBlockFunc);
7773     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
7774         interceptorExecuter_->DoProcess(interceptorParam);
7775     if (result != ERR_OK) {
7776         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
7777         return result;
7778     }
7779 
7780     if (CheckIfOperateRemote(want)) {
7781         TAG_LOGI(AAFwkTag::ABILITYMGR, "start remote ability by call");
7782         return StartRemoteAbilityByCall(want, callerToken, connect->AsObject());
7783     }
7784 
7785     if (accountId == U0_USER_ID) {
7786         accountId = DEFAULT_INVAL_VALUE;
7787     }
7788     int32_t oriValidUserId = GetValidUserId(accountId);
7789     if (!JudgeMultiUserConcurrency(oriValidUserId)) {
7790         TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
7791         return ERR_CROSS_USER;
7792     }
7793 
7794     AbilityRequest abilityRequest;
7795     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
7796     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
7797     abilityRequest.callerToken = callerToken;
7798     abilityRequest.startSetting = nullptr;
7799     abilityRequest.want = want;
7800     abilityRequest.connect = connect;
7801     result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
7802     if (result != ERR_OK) {
7803         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request error");
7804         return result;
7805     }
7806 
7807     if (!abilityRequest.abilityInfo.isStageBasedModel) {
7808         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not stage base model");
7809         return RESOLVE_CALL_ABILITY_VERSION_ERR;
7810     }
7811 
7812     result = CheckStartByCallPermission(abilityRequest);
7813     if (result != ERR_OK) {
7814         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStartByCallPermission fail, result:%{public}d", result);
7815         return result;
7816     }
7817 
7818     TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityInfo.applicationInfo.singleton is %{public}s",
7819         abilityRequest.abilityInfo.applicationInfo.singleton ? "true" : "false");
7820     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
7821     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
7822         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityRequest.abilityInfo), false, appIndex);
7823     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
7824         afterCheckExecuter_->DoProcess(afterCheckParam);
7825     if (result != ERR_OK) {
7826         errMsg = "afterCheckParam is nullptr";
7827         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
7828         return result;
7829     }
7830 
7831     RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerToken);
7832     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7833         ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7834         abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
7835         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
7836         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7837         return uiAbilityManager->ResolveLocked(abilityRequest);
7838     }
7839 
7840     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
7841     if (missionListMgr == nullptr) {
7842         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null designated user id=%{public}d", oriValidUserId);
7843         errMsg = "userId is not invalid";
7844         return ERR_INVALID_VALUE;
7845     }
7846     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7847 
7848     return missionListMgr->ResolveLocked(abilityRequest);
7849 }
7850 
StartAbilityJust(AbilityRequest & abilityRequest,int32_t validUserId)7851 int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)
7852 {
7853     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7854     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
7855     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
7856     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7857         ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7858         auto uiAbilityManager = GetUIAbilityManagerByUserId(validUserId);
7859         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7860         return uiAbilityManager->ResolveLocked(abilityRequest);
7861     }
7862 
7863     auto missionListMgr = GetMissionListManagerByUserId(validUserId);
7864     if (missionListMgr == nullptr) {
7865         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null designated userId=%{public}d", validUserId);
7866         return ERR_INVALID_VALUE;
7867     }
7868     ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7869 
7870     return missionListMgr->ResolveLocked(abilityRequest);
7871 }
7872 
ReleaseCall(const sptr<IAbilityConnection> & connect,const AppExecFwk::ElementName & element)7873 int AbilityManagerService::ReleaseCall(
7874     const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
7875 {
7876     TAG_LOGD(AAFwkTag::ABILITYMGR, "Release called ability.");
7877 
7878     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7879     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7880 
7881     std::string elementName = element.GetURI();
7882     TAG_LOGD(AAFwkTag::ABILITYMGR, "try to release called ability, name: %{public}s.", elementName.c_str());
7883 
7884     if (CheckIsRemote(element.GetDeviceID())) {
7885         TAG_LOGI(AAFwkTag::ABILITYMGR, "release remote ability");
7886         return ReleaseRemoteAbility(connect->AsObject(), element);
7887     }
7888 
7889     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7890         auto uiAbilityManager = GetCurrentUIAbilityManager();
7891         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7892         return uiAbilityManager->ReleaseCallLocked(connect, element);
7893     }
7894     auto missionListManager = GetCurrentMissionListManager();
7895     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
7896     return missionListManager->ReleaseCallLocked(connect, element);
7897 }
7898 
JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo & abilityInfo)7899 int AbilityManagerService::JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)
7900 {
7901     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
7902     if (abilityInfo.visible) {
7903         return ERR_OK;
7904     }
7905     auto callerTokenId = IPCSkeleton::GetCallingTokenID();
7906     if (callerTokenId == abilityInfo.applicationInfo.accessTokenId ||
7907         callerTokenId == static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID())) {  // foundation call is allowed
7908         return ERR_OK;
7909     }
7910     if (AccessTokenKit::VerifyAccessToken(callerTokenId,
7911         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == AppExecFwk::Constants::PERMISSION_GRANTED) {
7912         return ERR_OK;
7913     }
7914     TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken:%{private}u, targetToken:%{private}u, caller without permission",
7915         callerTokenId, abilityInfo.applicationInfo.accessTokenId);
7916     return ABILITY_VISIBLE_FALSE_DENY_REQUEST;
7917 }
7918 
StartUser(int userId,sptr<IUserCallback> callback,bool isAppRecovery)7919 int AbilityManagerService::StartUser(int userId, sptr<IUserCallback> callback, bool isAppRecovery)
7920 {
7921     TAG_LOGI(AAFwkTag::ABILITYMGR, "startUser in service:%{public}d", userId);
7922     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7923         TAG_LOGE(AAFwkTag::ABILITYMGR, "startUser permission verification failed, not account process");
7924         if (callback != nullptr) {
7925             callback->OnStartUserDone(userId, CHECK_PERMISSION_FAILED);
7926         }
7927         return CHECK_PERMISSION_FAILED;
7928     }
7929 
7930     if (ShouldBlockAllAppStart()) {
7931         TAG_LOGI(AAFwkTag::ABILITYMGR, "low-mem mode");
7932         auto connectManager = GetConnectManagerByUserId(userId);
7933         if (connectManager == nullptr || connectManager->GetSceneBoardTokenId() == 0) {
7934             TAG_LOGE(AAFwkTag::ABILITYMGR, "low-mem mode, disallow cold start");
7935             callback->OnStartUserDone(userId, ERR_ALL_APP_START_BLOCKED);
7936             return ERR_ALL_APP_START_BLOCKED;
7937         }
7938     }
7939 
7940     if (userController_) {
7941         return userController_->StartUser(userId, callback, isAppRecovery);
7942     }
7943     return 0;
7944 }
7945 
StopUser(int userId,const sptr<IUserCallback> & callback)7946 int AbilityManagerService::StopUser(int userId, const sptr<IUserCallback> &callback)
7947 {
7948     TAG_LOGI(AAFwkTag::ABILITYMGR, "stopUser in service:%{public}d", userId);
7949     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7950         TAG_LOGE(AAFwkTag::ABILITYMGR, "stopUser permission verification failed, not account process");
7951         if (callback != nullptr) {
7952             callback->OnStopUserDone(userId, CHECK_PERMISSION_FAILED);
7953         }
7954         return CHECK_PERMISSION_FAILED;
7955     }
7956 
7957     auto ret = -1;
7958     if (userController_) {
7959         ret = userController_->StopUser(userId);
7960         TAG_LOGD(AAFwkTag::ABILITYMGR, "ret = %{public}d", ret);
7961     }
7962     if (callback) {
7963         callback->OnStopUserDone(userId, ret);
7964     }
7965     if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
7966         return 0;
7967     }
7968     std::vector<AppExecFwk::BundleInfo> bundleInfos;
7969     if (!KeepAliveProcessManager::GetInstance().GetKeepAliveBundleInfosForUser(bundleInfos, userId)) {
7970         TAG_LOGE(AAFwkTag::ABILITYMGR, "get keep-alive bundle info failed");
7971         return 0;
7972     }
7973     for (const auto &bundleInfo : bundleInfos) {
7974         IN_PROCESS_CALL_WITHOUT_RET(KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(
7975             bundleInfo.name, userId, false, true, false));
7976     }
7977     return 0;
7978 }
7979 
LogoutUser(int32_t userId,sptr<IUserCallback> callback)7980 int AbilityManagerService::LogoutUser(int32_t userId, sptr<IUserCallback> callback)
7981 {
7982     TAG_LOGI(AAFwkTag::ABILITYMGR, "LogoutUser in service:%{public}d", userId);
7983     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7984         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed, not account process");
7985         if (callback != nullptr) {
7986             callback->OnLogoutUserDone(userId, CHECK_PERMISSION_FAILED);
7987         }
7988         return CHECK_PERMISSION_FAILED;
7989     }
7990 
7991     // Lister screen unlock for auto startup apps.
7992     if (system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) {
7993         InitInterceptorForScreenUnlock();
7994         SubscribeScreenUnlockedEvent();
7995     }
7996 
7997     if (userController_) {
7998         auto ret = userController_->LogoutUser(userId, callback);
7999         TAG_LOGD(AAFwkTag::ABILITYMGR, "logout user return = %{public}d", ret);
8000         return ret;
8001     }
8002     return ERR_OK;
8003 }
8004 
OnAcceptWantResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)8005 void AbilityManagerService::OnAcceptWantResponse(
8006     const AAFwk::Want &want, const std::string &flag, int32_t requestId)
8007 {
8008     TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
8009     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8010         auto uiAbilityManager = GetCurrentUIAbilityManager();
8011         CHECK_POINTER(uiAbilityManager);
8012         uiAbilityManager->OnAcceptWantResponse(want, flag, requestId);
8013         return;
8014     }
8015     auto missionListManager = GetCurrentMissionListManager();
8016     if (!missionListManager) {
8017         return;
8018     }
8019     missionListManager->OnAcceptWantResponse(want, flag);
8020 }
8021 
OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want & want,int32_t requestId)8022 void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
8023 {
8024     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", want.GetElement().GetURI().c_str());
8025     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8026         auto uiAbilityManager = GetCurrentUIAbilityManager();
8027         CHECK_POINTER(uiAbilityManager);
8028         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
8029         return;
8030     }
8031     auto missionListManager = GetCurrentMissionListManager();
8032     if (!missionListManager) {
8033         return;
8034     }
8035     missionListManager->OnStartSpecifiedAbilityTimeoutResponse(want);
8036 }
8037 
OnStartSpecifiedProcessResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)8038 void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag,
8039     int32_t requestId)
8040 {
8041     TAG_LOGD(AAFwkTag::ABILITYMGR, "flag = %{public}s", flag.c_str());
8042     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8043         auto uiAbilityManager = GetCurrentUIAbilityManager();
8044         CHECK_POINTER(uiAbilityManager);
8045         uiAbilityManager->OnStartSpecifiedProcessResponse(want, flag, requestId);
8046         return;
8047     }
8048 }
8049 
OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want & want,int32_t requestId)8050 void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
8051 {
8052     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", want.GetElement().GetURI().c_str());
8053     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8054         auto uiAbilityManager = GetCurrentUIAbilityManager();
8055         CHECK_POINTER(uiAbilityManager);
8056         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
8057         return;
8058     }
8059 }
8060 
OnStartSpecifiedFailed(int32_t requestId)8061 void AbilityManagerService::OnStartSpecifiedFailed(int32_t requestId)
8062 {
8063     TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
8064     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8065         auto uiAbilityManager = GetCurrentUIAbilityManager();
8066         CHECK_POINTER(uiAbilityManager);
8067         uiAbilityManager->OnStartSpecifiedFailed(requestId);
8068         return;
8069     }
8070 }
8071 
GetAbilityRunningInfos(std::vector<AbilityRunningInfo> & info)8072 int AbilityManagerService::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
8073 {
8074     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8075     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get running ability infos.");
8076     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
8077     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8078         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
8079         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
8080         uiAbilityManager->GetAbilityRunningInfos(info, isPerm);
8081     } else {
8082         auto missionListManager = GetCurrentMissionListManager();
8083         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
8084         missionListManager->GetAbilityRunningInfos(info, isPerm);
8085     }
8086 
8087     UpdateFocusState(info);
8088 
8089     return ERR_OK;
8090 }
8091 
UpdateFocusState(std::vector<AbilityRunningInfo> & info)8092 void AbilityManagerService::UpdateFocusState(std::vector<AbilityRunningInfo> &info)
8093 {
8094     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8095     if (info.empty()) {
8096         return;
8097     }
8098 
8099 #ifdef SUPPORT_GRAPHICS
8100     sptr<IRemoteObject> token;
8101     int ret = IN_PROCESS_CALL(GetTopAbility(token));
8102     if (ret != ERR_OK || token == nullptr) {
8103         return;
8104     }
8105 
8106     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8107     if (abilityRecord == nullptr) {
8108         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
8109         return;
8110     }
8111 
8112     for (auto &item : info) {
8113         if (item.uid == abilityRecord->GetUid() && item.pid == abilityRecord->GetPid() &&
8114             item.ability == abilityRecord->GetElementName()) {
8115             item.abilityState = static_cast<int>(AbilityState::ACTIVE);
8116             break;
8117         }
8118     }
8119 #endif
8120 }
8121 
GetExtensionRunningInfos(int upperLimit,std::vector<ExtensionRunningInfo> & info)8122 int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)
8123 {
8124     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8125     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension infos, upperLimit : %{public}d", upperLimit);
8126     CHECK_CALLER_IS_SYSTEM_APP;
8127     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
8128     auto connectManager = GetCurrentConnectManager();
8129     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
8130     connectManager->GetExtensionRunningInfos(upperLimit, info, GetUserId(), isPerm);
8131     return ERR_OK;
8132 }
8133 
GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> & info)8134 int AbilityManagerService::GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)
8135 {
8136     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfos(info);
8137 }
8138 
GetAllIntentExemptionInfo(std::vector<AppExecFwk::IntentExemptionInfo> & info)8139 int32_t AbilityManagerService::GetAllIntentExemptionInfo(std::vector<AppExecFwk::IntentExemptionInfo> &info)
8140 {
8141     const auto exemptionData =
8142         DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetAllIntentExemptionInfo();
8143     for (auto& data : exemptionData) {
8144         AppExecFwk::IntentExemptionInfo tmpInfo;
8145         tmpInfo.uid_ = data.first;
8146         tmpInfo.duration_ = INTENT_EXEMPTION_DURATION;
8147         info.push_back(tmpInfo);
8148     }
8149     return ERR_OK;
8150 }
8151 
GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> & info,int32_t userId)8152 int AbilityManagerService::GetProcessRunningInfosByUserId(
8153     std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)
8154 {
8155     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfosByUserId(info, userId);
8156 }
8157 
ClearUserData(int32_t userId)8158 void AbilityManagerService::ClearUserData(int32_t userId)
8159 {
8160     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8161     CHECK_POINTER(subManagersHelper_);
8162     subManagersHelper_->ClearSubManagers(userId);
8163 }
8164 
RegisterSnapshotHandler(const sptr<ISnapshotHandler> & handler)8165 int AbilityManagerService::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
8166 {
8167     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8168     if (!isSaCall) {
8169         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s:permission verification failed", __func__);
8170         return 0;
8171     }
8172 
8173     auto missionListManager = GetCurrentMissionListManager();
8174     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
8175     missionListManager->RegisterSnapshotHandler(handler);
8176     TAG_LOGI(AAFwkTag::ABILITYMGR, "snapshot: abilityManagerService register snapshot handler success");
8177     return ERR_OK;
8178 }
8179 
GetMissionSnapshot(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot,bool isLowResolution)8180 int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId,
8181     MissionSnapshot& missionSnapshot, bool isLowResolution)
8182 {
8183     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8184     CHECK_CALLER_IS_SYSTEM_APP;
8185     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
8186         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
8187         return CHECK_PERMISSION_FAILED;
8188     }
8189 
8190     if (CheckIsRemote(deviceId)) {
8191         TAG_LOGI(AAFwkTag::ABILITYMGR, "get remote mission snapshot");
8192         return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot);
8193     }
8194     TAG_LOGI(AAFwkTag::ABILITYMGR, "get local mission snapshot");
8195     auto missionListManager = GetCurrentMissionListManager();
8196     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
8197     auto token = GetAbilityTokenByMissionId(missionId);
8198     bool result = missionListManager->GetMissionSnapshot(missionId, token, missionSnapshot, isLowResolution);
8199     if (!result) {
8200         return INNER_ERR;
8201     }
8202     return ERR_OK;
8203 }
8204 #ifdef SUPPORT_SCREEN
UpdateMissionSnapShot(const sptr<IRemoteObject> & token,const std::shared_ptr<Media::PixelMap> & pixelMap)8205 void AbilityManagerService::UpdateMissionSnapShot(const sptr<IRemoteObject> &token,
8206     const std::shared_ptr<Media::PixelMap> &pixelMap)
8207 {
8208     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)) {
8209         return;
8210     }
8211     auto missionListManager = GetCurrentMissionListManager();
8212     if (missionListManager) {
8213         missionListManager->UpdateSnapShot(token, pixelMap);
8214     }
8215 }
8216 #endif // SUPPORT_SCREEN
EnableRecoverAbility(const sptr<IRemoteObject> & token)8217 void AbilityManagerService::EnableRecoverAbility(const sptr<IRemoteObject>& token)
8218 {
8219     TAG_LOGD(AAFwkTag::ABILITYMGR, "Enable recovery ability.");
8220     if (token == nullptr) {
8221         return;
8222     }
8223     auto record = Token::GetAbilityRecordByToken(token);
8224     if (record == nullptr) {
8225         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::failed find abilityRecord by token", __func__);
8226         return;
8227     }
8228     if (record->IsClearMissionFlag()) {
8229         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::not allow EnableRecoverAbility before clearMission",
8230             __func__);
8231         return;
8232     }
8233 
8234     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8235     auto tokenID = record->GetApplicationInfo().accessTokenId;
8236     if (callingTokenId != tokenID) {
8237         TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery scheduleRecoverAbility not self, not enabled");
8238         return;
8239     }
8240     {
8241         std::lock_guard<ffrt::mutex> guard(globalLock_);
8242         auto it = appRecoveryHistory_.find(record->GetUid());
8243         if (it == appRecoveryHistory_.end()) {
8244             appRecoveryHistory_.emplace(record->GetUid(), 0);
8245         }
8246     }
8247     auto userId = record->GetOwnerMissionUserId();
8248     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8249         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
8250         CHECK_POINTER(uiAbilityManager);
8251         const auto& abilityInfo = record->GetAbilityInfo();
8252         std::string abilityName = abilityInfo.name;
8253         auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
8254         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
8255             abilityName += std::to_string(sessionId);
8256         }
8257         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->AddAbilityRecoverInfo(
8258             abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName, sessionId);
8259     } else {
8260         auto missionListMgr = GetMissionListManagerByUserId(userId);
8261         if (missionListMgr == nullptr) {
8262             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null");
8263             return;
8264         }
8265         missionListMgr->EnableRecoverAbility(record->GetMissionId());
8266     }
8267 }
8268 
ScheduleClearRecoveryPageStack()8269 void AbilityManagerService::ScheduleClearRecoveryPageStack()
8270 {
8271     int32_t callerUid = IPCSkeleton::GetCallingUid();
8272     std::string bundleName;
8273     auto bms = AbilityUtil::GetBundleManagerHelper();
8274     CHECK_POINTER_IS_NULLPTR(bms);
8275 
8276     if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
8277         TAG_LOGE(AAFwkTag::ABILITYMGR, "scheduleClearRecoveryPageStack get bundleName failed");
8278         return;
8279     }
8280 
8281     auto tokenId = IPCSkeleton::GetCallingTokenID();
8282 
8283     TAG_LOGI(AAFwkTag::ABILITYMGR,
8284         "ScheduleClearRecoveryPageStack bundleName = %{public}s, callerUid = %{public}d, tokenId = %{public}d",
8285         bundleName.c_str(), callerUid, tokenId);
8286     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
8287         DeleteAppExitReason(bundleName, tokenId);
8288     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
8289         DeleteAllRecoverInfoByTokenId(tokenId);
8290 }
8291 
ReportAppRecoverResult(const int32_t appId,const AppExecFwk::ApplicationInfo & appInfo,const std::string & abilityName,const std::string & result)8292 void AbilityManagerService::ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo,
8293     const std::string& abilityName, const std::string& result)
8294 {
8295     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
8296         "APP_UID", appId,
8297         "VERSION_CODE", std::to_string(appInfo.versionCode),
8298         "VERSION_NAME", appInfo.versionName,
8299         "BUNDLE_NAME", appInfo.bundleName,
8300         "ABILITY_NAME", abilityName,
8301         "RECOVERY_RESULT", result);
8302 }
8303 
SubmitSaveRecoveryInfo(const sptr<IRemoteObject> & token)8304 void AbilityManagerService::SubmitSaveRecoveryInfo(const sptr<IRemoteObject>& token)
8305 {
8306     if (token == nullptr) {
8307         TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo token null");
8308         return;
8309     }
8310     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8311     if (abilityRecord == nullptr) {
8312         TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo abilityRecord null");
8313         return;
8314     }
8315     auto abilityInfo = abilityRecord->GetAbilityInfo();
8316     auto userId = abilityRecord->GetOwnerMissionUserId();
8317     auto tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
8318     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8319     if (callingTokenId != tokenId) {
8320         TAG_LOGE(AAFwkTag::ABILITYMGR, "SubmitSaveRecoveryInfo not self, not enabled");
8321         return;
8322     }
8323     std::string abilityName = abilityInfo.name;
8324     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8325         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
8326         CHECK_POINTER(uiAbilityManager);
8327         auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
8328         if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
8329             abilityName += std::to_string(sessionId);
8330         }
8331     } else {
8332         auto missionListMgr = GetMissionListManagerByUserId(userId);
8333         if (missionListMgr == nullptr) {
8334             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null");
8335             return;
8336         }
8337         abilityName += std::to_string(abilityRecord->GetMissionId());
8338     }
8339     TAG_LOGI(AAFwkTag::ABILITYMGR,
8340         "submitInfo bundleName = %{public}s, moduleName = %{public}s, abilityName = %{public}s, tokenId = %{public}d",
8341         abilityInfo.bundleName.c_str(),  abilityInfo.moduleName.c_str(), abilityName.c_str(), tokenId);
8342     RecoveryInfo recoveryInfo;
8343     recoveryInfo.bundleName = abilityInfo.bundleName;
8344     recoveryInfo.moduleName = abilityInfo.moduleName;
8345     recoveryInfo.abilityName = abilityName;
8346     recoveryInfo.time = time(nullptr);
8347     OHOS::AAFwk::RecoveryInfoTimer::GetInstance().SubmitSaveRecoveryInfo(recoveryInfo);
8348 }
8349 
AppRecoverKill(pid_t pid,int32_t reason)8350 void AbilityManagerService::AppRecoverKill(pid_t pid, int32_t reason)
8351 {
8352     AppExecFwk::AppFaultDataBySA faultDataSA;
8353     faultDataSA.errorObject.name = "appRecovery";
8354     switch (reason) {
8355         case AppExecFwk::StateReason::CPP_CRASH:
8356             faultDataSA.faultType = AppExecFwk::FaultDataType::CPP_CRASH;
8357             break;
8358         case AppExecFwk::StateReason::JS_ERROR:
8359             faultDataSA.faultType = AppExecFwk::FaultDataType::JS_ERROR;
8360             break;
8361         case AppExecFwk::StateReason::LIFECYCLE:
8362         case AppExecFwk::StateReason::APP_FREEZE:
8363             faultDataSA.faultType = AppExecFwk::FaultDataType::APP_FREEZE;
8364             break;
8365         default:
8366             faultDataSA.faultType = AppExecFwk::FaultDataType::UNKNOWN;
8367     }
8368     faultDataSA.pid = pid;
8369     IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFaultBySA(faultDataSA));
8370 }
8371 
ScheduleRecoverAbility(const sptr<IRemoteObject> & token,int32_t reason,const Want * want)8372 void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)
8373 {
8374     if (token == nullptr) {
8375         return;
8376     }
8377     auto record = Token::GetAbilityRecordByToken(token);
8378     if (record == nullptr) {
8379         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::failed find abilityRecord by token", __func__);
8380         return;
8381     }
8382     if (!record->IsForeground() && !record->GetAbilityForegroundingFlag()) {
8383         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::recoveryAbility failed"
8384             "due background", __func__);
8385         return;
8386     }
8387 
8388     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8389     auto tokenID = record->GetApplicationInfo().accessTokenId;
8390     if (callingTokenId != tokenID) {
8391         TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery scheduleRecoverAbility no self, no enabled");
8392         return;
8393     }
8394 
8395     AAFwk::Want curWant;
8396     {
8397         std::lock_guard<ffrt::mutex> guard(globalLock_);
8398         auto type = record->GetAbilityInfo().type;
8399         if (type != AppExecFwk::AbilityType::PAGE) {
8400             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::only recover for page ability", __func__);
8401             return;
8402         }
8403 
8404         constexpr int64_t MIN_RECOVERY_TIME = 60;
8405         int64_t now = time(nullptr);
8406         auto it = appRecoveryHistory_.find(record->GetUid());
8407         auto appInfo = record->GetApplicationInfo();
8408         auto abilityInfo = record->GetAbilityInfo();
8409 
8410         if ((it != appRecoveryHistory_.end()) &&
8411             (it->second + MIN_RECOVERY_TIME > now)) {
8412             TAG_LOGE(AAFwkTag::ABILITYMGR,
8413                 "%{public}s appRecovery recover more once in one minute, kill app(%{public}d)",
8414                 __func__, record->GetPid());
8415             ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_WITHIN_ONE_MINUTE");
8416             AppRecoverKill(record->GetPid(), reason);
8417             return;
8418         }
8419 
8420         if (want != nullptr) {
8421             TAG_LOGD(AAFwkTag::ABILITYMGR, "BundleName:%{public}s targetBundleName:%{public}s.",
8422                 appInfo.bundleName.c_str(), want->GetElement().GetBundleName().c_str());
8423             if (want->GetElement().GetBundleName().empty() ||
8424                 (appInfo.bundleName.compare(want->GetElement().GetBundleName()) != 0)) {
8425                 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery bundleName not match, not recovery ability");
8426                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_BUNDLE_NAME_NOT_MATCH");
8427                 return;
8428             }
8429             if (want->GetElement().GetAbilityName().empty()) {
8430                 TAG_LOGD(AAFwkTag::ABILITYMGR, "AppRecovery recovery target ability is empty");
8431                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_TARGET_ABILITY_EMPTY");
8432                 return;
8433             }
8434             auto bms = AbilityUtil::GetBundleManagerHelper();
8435             CHECK_POINTER_IS_NULLPTR(bms);
8436             AppExecFwk::BundleInfo bundleInfo;
8437             auto bundleName = want->GetElement().GetBundleName();
8438             int32_t userId = GetUserId();
8439             bool ret = IN_PROCESS_CALL(
8440                 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo,
8441                 userId));
8442             if (!ret) {
8443                 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery get bundleInfo fail, not recovery");
8444                 return;
8445             }
8446             bool isRestartPage = false;
8447             auto abilityName = want->GetElement().GetAbilityName();
8448             for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
8449                 if ((abilityName.compare(it->name) == 0) && it->type == AppExecFwk::AbilityType::PAGE) {
8450                     isRestartPage = true;
8451                     break;
8452                 }
8453             }
8454             if (!isRestartPage) {
8455                 TAG_LOGI(AAFwkTag::ABILITYMGR, "appRecovery target ability type not PAGE");
8456                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityName, "FAIL_TARGET_ABILITY_NOT_PAGE");
8457                 return;
8458             }
8459         }
8460 
8461         appRecoveryHistory_[record->GetUid()] = now;
8462         curWant = (want == nullptr) ? record->GetWant() : *want;
8463         curWant.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
8464 
8465         ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "SUCCESS");
8466     }
8467     RestartApp(curWant, true);
8468 }
8469 
GetRemoteMissionSnapshotInfo(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot)8470 int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId,
8471     MissionSnapshot& missionSnapshot)
8472 {
8473     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8474     TAG_LOGI(AAFwkTag::ABILITYMGR, "getRemoteMissionSnapshotInfo");
8475     std::unique_ptr<MissionSnapshot> missionSnapshotPtr = std::make_unique<MissionSnapshot>();
8476     DistributedClient dmsClient;
8477     int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr);
8478     if (result != ERR_OK) {
8479         TAG_LOGE(AAFwkTag::ABILITYMGR, "getRemoteMissionSnapshotInfo failed, result=%{public}d", result);
8480         return result;
8481     }
8482     missionSnapshot = *missionSnapshotPtr;
8483     return ERR_OK;
8484 }
8485 
StartSwitchUserDialog()8486 void AbilityManagerService::StartSwitchUserDialog()
8487 {
8488     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog extension ability come");
8489     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8490         TAG_LOGE(AAFwkTag::ABILITYMGR, "scene board enabled, dialog not show");
8491         return;
8492     }
8493 
8494     if (userController_ == nullptr) {
8495         TAG_LOGE(AAFwkTag::ABILITYMGR, "user Controller instance null");
8496         return;
8497     }
8498 #ifdef SUPPORT_GRAPHICS
8499     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
8500     if (sysDialog == nullptr) {
8501         TAG_LOGE(AAFwkTag::ABILITYMGR, "system dialog scheduler instance null");
8502         return;
8503     }
8504 
8505     Want dialogWant = sysDialog->GetSwitchUserDialogWant();
8506     StartSwitchUserDialogInner(dialogWant, userController_->GetFreezingNewUserId());
8507 #endif // SUPPORT_GRAPHICS
8508 }
8509 
8510 
StartSwitchUserDialogInner(const Want & want,int32_t lastUserId)8511 void AbilityManagerService::StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)
8512 {
8513     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog inner come");
8514     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
8515     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
8516     AbilityRequest abilityRequest;
8517     auto result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
8518     if (result != ERR_OK) {
8519         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
8520         eventInfo.errCode = result;
8521         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8522         return;
8523     }
8524 
8525     auto abilityInfo = abilityRequest.abilityInfo;
8526     auto startUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
8527     result = CheckOptExtensionAbility(want, abilityRequest, startUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
8528     if (result != ERR_OK) {
8529         TAG_LOGE(AAFwkTag::ABILITYMGR, "check extensionAbility type error");
8530         eventInfo.errCode = result;
8531         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8532         return;
8533     }
8534 
8535     auto connectManager = GetConnectManagerByUserId(startUserId);
8536     if (connectManager == nullptr) {
8537         CHECK_POINTER(subManagersHelper_);
8538         subManagersHelper_->InitConnectManager(startUserId, false);
8539         connectManager = GetConnectManagerByUserId(startUserId);
8540         if (connectManager == nullptr) {
8541             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", startUserId);
8542             eventInfo.errCode = ERR_INVALID_VALUE;
8543             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8544             return;
8545         }
8546     }
8547 
8548     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
8549     if (eventInfo.errCode != ERR_OK) {
8550         TAG_LOGE(AAFwkTag::ABILITYMGR, "eventInfo errCode:%{public}d", eventInfo.errCode);
8551         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8552     }
8553 }
8554 
StartFreezingScreen()8555 void AbilityManagerService::StartFreezingScreen()
8556 {
8557     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8558 #ifdef SUPPORT_GRAPHICS
8559     StartSwitchUserDialog();
8560     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8561     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Freeze(displayIds));
8562 #endif
8563 }
8564 
StopFreezingScreen()8565 void AbilityManagerService::StopFreezingScreen()
8566 {
8567     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8568 #ifdef SUPPORT_GRAPHICS
8569     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8570     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Unfreeze(displayIds));
8571     StopSwitchUserDialog();
8572 #endif
8573 }
8574 
UserStarted(int32_t userId)8575 void AbilityManagerService::UserStarted(int32_t userId)
8576 {
8577     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8578     CHECK_POINTER(subManagersHelper_);
8579     subManagersHelper_->InitSubManagers(userId, false);
8580 }
8581 
SwitchToUser(int32_t oldUserId,int32_t userId,sptr<IUserCallback> callback,bool isAppRecovery)8582 int AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId, sptr<IUserCallback> callback,
8583     bool isAppRecovery)
8584 {
8585     TAG_LOGI(AAFwkTag::ABILITYMGR,
8586         "%{public}s, oldUserId:%{public}d, newUserId:%{public}d, isAppRecovery:%{public}d", __func__,
8587         oldUserId, userId, isAppRecovery);
8588     SwitchManagers(userId);
8589     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8590         PauseOldUser(oldUserId);
8591         ConnectServices();
8592         StartUserApps();
8593     }
8594     bool isBoot = oldUserId == U0_USER_ID ? true : false;
8595     auto ret = StartHighestPriorityAbility(userId, isBoot, isAppRecovery);
8596     if (ret != ERR_OK) {
8597         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartHighestPriorityAbility failed: %{public}d", ret);
8598     }
8599     if (callback) {
8600         callback->OnStartUserDone(userId, ret);
8601     }
8602     if (taskHandler_) {
8603         taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() {
8604             TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps userId:%{public}d", userId);
8605             abilityMs->StartResidentApps(userId);
8606         });
8607     }
8608     StartKeepAliveAppsInner(userId);
8609     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
8610         AmsConfigurationParameter::GetInstance().MultiUserType() != 0) {
8611         TAG_LOGI(AAFwkTag::ABILITYMGR, "no need terminate old scb");
8612         return ret;
8613     }
8614     PauseOldConnectManager(oldUserId);
8615     return ret;
8616 }
8617 
StartKeepAliveAppsInner(int32_t userId)8618 void AbilityManagerService::StartKeepAliveAppsInner(int32_t userId)
8619 {
8620     if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
8621         TAG_LOGE(AAFwkTag::ABILITYMGR, "not supported");
8622         return;
8623     }
8624     if (taskHandler_ == nullptr) {
8625         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler nullptr");
8626         return;
8627     }
8628     taskHandler_->SubmitTask([abilityMs = shared_from_this(),
8629         connectManager = GetConnectManagerByUserId(userId), userId]() {
8630         if (connectManager == nullptr) {
8631             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr");
8632             return;
8633         }
8634         if (connectManager->GetSceneBoardTokenId() == 0) {
8635             TAG_LOGI(AAFwkTag::ABILITYMGR, "SCB not ready, do not start keep-alive apps");
8636             return;
8637         }
8638         TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps userId:%{public}d", userId);
8639         abilityMs->StartKeepAliveApps(userId);
8640     });
8641 }
8642 
SwitchManagers(int32_t userId,bool switchUser)8643 void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser)
8644 {
8645     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId);
8646     CHECK_POINTER(subManagersHelper_);
8647     subManagersHelper_->InitSubManagers(userId, switchUser);
8648     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----end", __func__, userId);
8649 }
8650 
PauseOldUser(int32_t userId)8651 void AbilityManagerService::PauseOldUser(int32_t userId)
8652 {
8653     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId);
8654     PauseOldMissionListManager(userId);
8655     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----end", __func__, userId);
8656 }
8657 
PauseOldMissionListManager(int32_t userId)8658 void AbilityManagerService::PauseOldMissionListManager(int32_t userId)
8659 {
8660     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId);
8661     auto manager = GetMissionListManagerByUserId(userId);
8662     CHECK_POINTER(manager);
8663     manager->PauseManager();
8664     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId);
8665 }
8666 
PauseOldConnectManager(int32_t userId)8667 void AbilityManagerService::PauseOldConnectManager(int32_t userId)
8668 {
8669     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----begin", __func__, userId);
8670     if (userId == U0_USER_ID) {
8671         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, u0 not stop, id:%{public}d-----null", __func__, userId);
8672         return;
8673     }
8674 
8675     auto manager = GetConnectManagerByUserId(userId);
8676     CHECK_POINTER(manager);
8677     manager->PauseExtensions();
8678     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----end", __func__, userId);
8679 }
8680 
StartUserApps()8681 void AbilityManagerService::StartUserApps()
8682 {
8683     auto missionListManager = GetCurrentMissionListManager();
8684     if (missionListManager && missionListManager->IsStarted()) {
8685         TAG_LOGI(AAFwkTag::ABILITYMGR, "missionListManager ResumeManager");
8686         missionListManager->ResumeManager();
8687     }
8688 }
8689 
GetValidUserId(const int32_t userId)8690 int32_t AbilityManagerService::GetValidUserId(const int32_t userId)
8691 {
8692     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId = %{public}d.", userId);
8693     int32_t validUserId = userId;
8694 
8695     if (DEFAULT_INVAL_VALUE == userId) {
8696         validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
8697         TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId = %{public}d, CallingUid = %{public}d.", validUserId,
8698             IPCSkeleton::GetCallingUid());
8699         if (validUserId == U0_USER_ID) {
8700             validUserId = GetUserId();
8701         }
8702     }
8703     return validUserId;
8704 }
8705 
SetAbilityController(const sptr<IAbilityController> & abilityController,bool imAStabilityTest)8706 int AbilityManagerService::SetAbilityController(const sptr<IAbilityController> &abilityController,
8707     bool imAStabilityTest)
8708 {
8709     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest);
8710     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyControllerPerm();
8711     if (!isPerm) {
8712         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
8713         return CHECK_PERMISSION_FAILED;
8714     }
8715 
8716     std::lock_guard<ffrt::mutex> guard(globalLock_);
8717     abilityController_ = abilityController;
8718     controllerIsAStabilityTest_ = imAStabilityTest;
8719     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, end", __func__);
8720     return ERR_OK;
8721 }
8722 
IsRunningInStabilityTest()8723 bool AbilityManagerService::IsRunningInStabilityTest()
8724 {
8725     std::lock_guard<ffrt::mutex> guard(globalLock_);
8726     bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_;
8727     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret);
8728     return ret;
8729 }
8730 
IsAbilityControllerStart(const Want & want,const std::string & bundleName)8731 bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName)
8732 {
8733     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8734     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8735     if (abilityController_ == nullptr) {
8736         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8737         return true;
8738     }
8739 
8740     if (controllerIsAStabilityTest_) {
8741         bool isStart = abilityController_->AllowAbilityStart(want, bundleName);
8742         if (!isStart) {
8743             TAG_LOGI(AAFwkTag::ABILITYMGR,
8744                 "controller starting can't start ability:%{public}s", bundleName.c_str());
8745             return false;
8746         }
8747     }
8748     return true;
8749 }
8750 
IsAbilityControllerForeground(const std::string & bundleName)8751 bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName)
8752 {
8753     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8754     if (abilityController_ == nullptr) {
8755         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8756         return true;
8757     }
8758 
8759     if (controllerIsAStabilityTest_) {
8760         bool isResume = abilityController_->AllowAbilityBackground(bundleName);
8761         if (!isResume) {
8762             TAG_LOGI(AAFwkTag::ABILITYMGR,
8763                 "controller resuming can't terminate ability:%{public}s", bundleName.c_str());
8764             return false;
8765         }
8766     }
8767     return true;
8768 }
8769 
StartUserTest(const Want & want,const sptr<IRemoteObject> & observer)8770 int AbilityManagerService::StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)
8771 {
8772     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8773     if (observer == nullptr) {
8774         TAG_LOGE(AAFwkTag::ABILITYMGR, "observer null");
8775         return ERR_INVALID_VALUE;
8776     }
8777 
8778     std::string bundleName = want.GetStringParam("-b");
8779     if (bundleName.empty()) {
8780         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name");
8781         return ERR_INVALID_VALUE;
8782     }
8783 
8784     auto checkResult = AbilityUtil::CheckInstanceKey(want);
8785     if (checkResult != ERR_OK) {
8786         return checkResult;
8787     }
8788     int32_t appIndex = 0;
8789     if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex) || appIndex != 0) {
8790         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support app clone");
8791         return ERR_NOT_SUPPORT_APP_CLONE;
8792     }
8793 
8794     auto bms = AbilityUtil::GetBundleManagerHelper();
8795     CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL);
8796     AppExecFwk::BundleInfo bundleInfo;
8797     if (!IN_PROCESS_CALL(
8798         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID))) {
8799         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundleInfo by U0_USER_ID %{public}d", U0_USER_ID);
8800         int32_t userId = GetUserId();
8801         TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId);
8802         if (!IN_PROCESS_CALL(
8803             bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
8804             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundleInfo by userId %{public}d", userId);
8805             return GET_BUNDLE_INFO_FAILED;
8806         }
8807     }
8808 
8809     bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
8810     if (isDebugApp && bundleInfo.applicationInfo.appProvisionType != AppExecFwk::Constants::APP_PROVISION_TYPE_DEBUG) {
8811         TAG_LOGE(AAFwkTag::ABILITYMGR, "release app not support debug");
8812         return ERR_NOT_IN_APP_PROVISION_MODE;
8813     }
8814 
8815     return DelayedSingleton<AppScheduler>::GetInstance()->StartUserTest(want, observer, bundleInfo, GetUserId());
8816 }
8817 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName)8818 int AbilityManagerService::FinishUserTest(
8819     const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
8820 {
8821     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8822     if (bundleName.empty()) {
8823         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name");
8824         return ERR_INVALID_VALUE;
8825     }
8826 
8827     return DelayedSingleton<AppScheduler>::GetInstance()->FinishUserTest(msg, resultCode, bundleName);
8828 }
8829 
GetTopAbility(sptr<IRemoteObject> & token)8830 int AbilityManagerService::GetTopAbility(sptr<IRemoteObject> &token)
8831 {
8832     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8833     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8834     if (!isSaCall) {
8835         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
8836         return CHECK_PERMISSION_FAILED;
8837     }
8838 #ifdef SUPPORT_SCREEN
8839     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8840         Rosen::FocusChangeInfo focusChangeInfo;
8841         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
8842         token = focusChangeInfo.abilityToken_;
8843     } else {
8844         if (!wmsHandler_) {
8845             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
8846             return ERR_INVALID_VALUE;
8847         }
8848         wmsHandler_->GetFocusWindow(token);
8849     }
8850 
8851     if (!token) {
8852         TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
8853         return ERR_INVALID_VALUE;
8854     }
8855 #endif
8856     return ERR_OK;
8857 }
8858 
DelegatorDoAbilityForeground(const sptr<IRemoteObject> & token)8859 int AbilityManagerService::DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)
8860 {
8861     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8862     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8863     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8864     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8865     int32_t callerPid = IPCSkeleton::GetCallingPid();
8866     int32_t appPid = abilityRecord->GetPid();
8867     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8868     if (callerPid != appPid) {
8869         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not application itself");
8870         return ERR_INVALID_VALUE;
8871     }
8872     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8873         auto sessionId = GetMissionIdByAbilityTokenInner(token);
8874         if (!sessionId) {
8875             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid session id");
8876             return ERR_INVALID_VALUE;
8877         }
8878         auto want = abilityRecord->GetWant();
8879         if (!IsAbilityControllerStart(want, want.GetBundle())) {
8880             TAG_LOGE(AAFwkTag::ABILITYMGR,
8881                 "sceneBoard IsAbilityControllerStart failed:%{public}s", want.GetBundle().c_str());
8882             return ERR_WOULD_BLOCK;
8883         }
8884         return ERR_OK;
8885     }
8886     auto missionId = GetMissionIdByAbilityToken(token);
8887     if (missionId < 0) {
8888         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid mission id");
8889         return ERR_INVALID_VALUE;
8890     }
8891     return DelegatorMoveMissionToFront(missionId);
8892 }
8893 
DelegatorDoAbilityBackground(const sptr<IRemoteObject> & token)8894 int AbilityManagerService::DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)
8895 {
8896     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8897     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8898     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8899     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8900     int32_t appPid = abilityRecord->GetPid();
8901     int32_t callerPid = IPCSkeleton::GetCallingPid();
8902     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8903     if (callerPid != appPid) {
8904         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not application itself");
8905         return ERR_INVALID_VALUE;
8906     }
8907     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8908         return ERR_OK;
8909     }
8910     return MinimizeAbility(token, true);
8911 }
8912 
DoAbilityForeground(const sptr<IRemoteObject> & token,uint32_t flag)8913 int AbilityManagerService::DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)
8914 {
8915     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityForeground, sceneFlag:%{public}u", flag);
8916     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8917     if (!VerificationToken(token) && !VerificationAllToken(token)) {
8918         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s token error", __func__);
8919         return ERR_INVALID_VALUE;
8920     }
8921 
8922     std::lock_guard<ffrt::mutex> guard(globalLock_);
8923     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8924     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8925     if (!JudgeSelfCalled(abilityRecord)) {
8926         return CHECK_PERMISSION_FAILED;
8927     }
8928 
8929     auto type = abilityRecord->GetAbilityInfo().type;
8930     if (type != AppExecFwk::AbilityType::PAGE) {
8931         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except page ability");
8932         return ERR_WRONG_INTERFACE_CALL;
8933     }
8934 
8935     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
8936         TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerForeground false");
8937         return ERR_WOULD_BLOCK;
8938     }
8939 
8940     auto missionListManager = GetCurrentMissionListManager();
8941     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8942     return missionListManager->DoAbilityForeground(abilityRecord, flag);
8943 }
8944 
DoAbilityBackground(const sptr<IRemoteObject> & token,uint32_t flag)8945 int AbilityManagerService::DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)
8946 {
8947     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityBackground, sceneFlag:%{public}u", flag);
8948     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8949 
8950     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8951     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8952 
8953     abilityRecord->lifeCycleStateInfo_.sceneFlag = flag;
8954     int ret = MinimizeAbility(token);
8955     abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL;
8956     return ret;
8957 }
8958 
DelegatorMoveMissionToFront(int32_t missionId)8959 int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId)
8960 {
8961     TAG_LOGI(AAFwkTag::ABILITYMGR, "enter missionId:%{public}d", missionId);
8962     auto missionListManager = GetCurrentMissionListManager();
8963     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8964 
8965     if (!IsAbilityControllerStartById(missionId)) {
8966         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
8967         return ERR_WOULD_BLOCK;
8968     }
8969 
8970     return missionListManager->MoveMissionToFront(missionId);
8971 }
8972 
JudgeMultiUserConcurrency(const int32_t userId)8973 bool AbilityManagerService::JudgeMultiUserConcurrency(const int32_t userId)
8974 {
8975     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8976     if (userId == U0_USER_ID) {
8977         TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, userId is 0.", __func__);
8978         return true;
8979     }
8980 
8981     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, current userId : %{public}d", userId, GetUserId());
8982 
8983     // Only non-concurrent mode is supported
8984     bool concurrencyMode = CONCURRENCY_MODE_FALSE;
8985     if (!concurrencyMode) {
8986         return (userId == GetUserId());
8987     }
8988 
8989     return true;
8990 }
8991 
8992 #ifdef ABILITY_COMMAND_FOR_TEST
ForceTimeoutForTest(const std::string & abilityName,const std::string & state)8993 int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, const std::string &state)
8994 {
8995     if (abilityName.empty()) {
8996         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityName empty");
8997         return INVALID_DATA;
8998     }
8999     std::lock_guard guard(timeoutMapLock_);
9000     if (abilityName == "clean") {
9001         timeoutMap_.clear();
9002         return ERR_OK;
9003     }
9004     if (state != AbilityRecord::ConvertAbilityState(AbilityState::INITIAL) &&
9005         state != AbilityRecord::ConvertAbilityState(AbilityState::INACTIVE) &&
9006         state != AbilityRecord::ConvertAbilityState(AbilityState::FOREGROUND) &&
9007         state != AbilityRecord::ConvertAbilityState(AbilityState::BACKGROUND) &&
9008         state != AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) &&
9009         state != std::string("COMMAND")) {
9010         TAG_LOGE(AAFwkTag::ABILITYMGR, "lifecycle state invalid");
9011         return INVALID_DATA;
9012     }
9013     timeoutMap_.insert(std::make_pair(state, abilityName));
9014     return ERR_OK;
9015 }
9016 #endif
9017 
CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo & abilityInfo,uint32_t tokenId)9018 int AbilityManagerService::CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo,
9019     uint32_t tokenId)
9020 {
9021     if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId,
9022         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) {
9023         return AppExecFwk::Constants::PERMISSION_GRANTED;
9024     }
9025 
9026     for (const auto &permission : abilityInfo.permissions) {
9027         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
9028             AppExecFwk::Constants::PERMISSION_GRANTED) {
9029             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission:%{public}s",
9030                 permission.c_str());
9031             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9032         }
9033     }
9034 
9035     return AppExecFwk::Constants::PERMISSION_GRANTED;
9036 }
9037 
CheckOneSkillPermission(const AppExecFwk::Skill & skill,uint32_t tokenId)9038 bool AbilityManagerService::CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId)
9039 {
9040     for (auto permission : skill.permissions) {
9041         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
9042             AppExecFwk::Constants::PERMISSION_GRANTED) {
9043             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission:%{public}s",
9044                 permission.c_str());
9045             return false;
9046         }
9047     }
9048 
9049     return true;
9050 }
9051 
CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest & abilityRequest,uint32_t tokenId)9052 int AbilityManagerService::CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest,
9053     uint32_t tokenId)
9054 {
9055     auto abilityInfo = abilityRequest.abilityInfo;
9056     auto resultAbilityPermission = CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
9057     if (resultAbilityPermission != AppExecFwk::Constants::PERMISSION_GRANTED) {
9058         return resultAbilityPermission;
9059     }
9060 
9061     if (abilityInfo.skills.empty()) {
9062         return AppExecFwk::Constants::PERMISSION_GRANTED;
9063     }
9064     int32_t result = AppExecFwk::Constants::PERMISSION_GRANTED;
9065     for (auto skill : abilityInfo.skills) {
9066         if (skill.Match(abilityRequest.want)) {
9067             if (CheckOneSkillPermission(skill, tokenId)) {
9068                 return AppExecFwk::Constants::PERMISSION_GRANTED;
9069             } else {
9070                 result = AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9071             }
9072         }
9073     }
9074     return result;
9075 }
9076 
CheckStaticCfgPermission(const AppExecFwk::AbilityRequest & abilityRequest,bool isStartAsCaller,uint32_t callerTokenId,bool isData,bool isSaCall,bool isImplicit)9077 int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest,
9078     bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit)
9079 {
9080     auto abilityInfo = abilityRequest.abilityInfo;
9081     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9082     if (AppUtils::GetInstance().IsSupportAncoApp() &&
9083         StartAbilityUtils::IsCallFromAncoShellOrBroker(abilityRequest.callerToken)) {
9084         TAG_LOGD(AAFwkTag::ABILITYMGR,
9085             "Check static permission, name is %{public}s.", abilityInfo.name.c_str());
9086         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9087         if (collaborator == nullptr) {
9088             TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator null");
9089             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9090         }
9091         int result = collaborator->CheckStaticCfgPermission(abilityRequest.want, isImplicit);
9092         if (result != ERR_OK) {
9093             TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker");
9094             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9095         }
9096     }
9097     if (!isData) {
9098         isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9099     }
9100     if (isSaCall) {
9101         // do not need check static config permission when start ability by SA
9102         return AppExecFwk::Constants::PERMISSION_GRANTED;
9103     }
9104 
9105     uint32_t tokenId;
9106     if (isStartAsCaller) {
9107         tokenId = callerTokenId;
9108     } else {
9109         tokenId = IPCSkeleton::GetCallingTokenID();
9110     }
9111 
9112     if (abilityInfo.applicationInfo.accessTokenId == tokenId) {
9113         return AppExecFwk::Constants::PERMISSION_GRANTED;
9114     }
9115 
9116     if (abilityRequest.want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME) ==
9117         AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
9118         abilityRequest.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
9119         return AppExecFwk::Constants::PERMISSION_GRANTED;
9120     }
9121 
9122     if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
9123         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) ||
9124         (abilityInfo.type == AppExecFwk::AbilityType::DATA)) {
9125         // just need check the read permission and write permission of extension ability or data ability
9126         if (!abilityInfo.readPermission.empty()) {
9127             int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission, false);
9128             if (checkReadPermission == ERR_OK) {
9129                 return AppExecFwk::Constants::PERMISSION_GRANTED;
9130             }
9131             TAG_LOGW(AAFwkTag::ABILITYMGR,
9132                 "verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str());
9133         }
9134         if (!abilityInfo.writePermission.empty()) {
9135             int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission, false);
9136             if (checkWritePermission == ERR_OK) {
9137                 return AppExecFwk::Constants::PERMISSION_GRANTED;
9138             }
9139             TAG_LOGW(AAFwkTag::ABILITYMGR,
9140                 "verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str());
9141         }
9142 
9143         if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) {
9144             // 'readPermission' and 'writePermission' take precedence over 'permission'
9145             // when 'readPermission' or 'writePermission' is not empty, no need check 'permission'
9146             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9147         }
9148     }
9149 
9150     if (!isImplicit) {
9151         return CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
9152     }
9153     return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId);
9154 }
9155 
CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,const Want & want,const AbilityRequest & abilityRequest)9156 int AbilityManagerService::CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,
9157     const Want &want, const AbilityRequest &abilityRequest)
9158 {
9159     AppExecFwk::ExtensionAbilityType targetExtType = abilityRequest.abilityInfo.extensionAbilityType;
9160     if (targetExtType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9161         return ERR_OK;
9162     }
9163     if (!want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
9164         TAG_LOGE(AAFwkTag::ABILITYMGR, "need UISERVICEHOSTPROXY_KEY connect UI_SERVICE");
9165         return ERR_WRONG_INTERFACE_CALL;
9166     }
9167     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9168         TAG_LOGE(AAFwkTag::ABILITYMGR, "interface not support connect UI_SERVICE");
9169         return ERR_WRONG_INTERFACE_CALL;
9170     }
9171     if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
9172         TAG_LOGE(AAFwkTag::ABILITYMGR, "ABILITYMS_ENABLE_UISERVICE false");
9173         return ERR_CAPABILITY_NOT_SUPPORT;
9174     }
9175 
9176     return ERR_OK;
9177 }
9178 
IsNeedTimeoutForTest(const std::string & abilityName,const std::string & state) const9179 bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const
9180 {
9181     std::lock_guard guard(timeoutMapLock_);
9182     for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) {
9183         if (iter->first == state && iter->second == abilityName) {
9184             return true;
9185         }
9186     }
9187     return false;
9188 }
9189 
GetValidDataAbilityUri(const std::string & abilityInfoUri,std::string & adjustUri)9190 bool AbilityManagerService::GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)
9191 {
9192     // note: do not use abilityInfo.uri directly, need check uri first.
9193     size_t firstSeparator = abilityInfoUri.find_first_of('/');
9194     size_t lastSeparator = abilityInfoUri.find_last_of('/');
9195     if (lastSeparator - firstSeparator != 1) {
9196         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability info uri error, uri: %{public}s", abilityInfoUri.c_str());
9197         return false;
9198     }
9199 
9200     adjustUri = abilityInfoUri;
9201     adjustUri.insert(lastSeparator, "/");
9202     return true;
9203 }
9204 
GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> & abilityInfos,const std::string & mainAbility,std::string & uri)9205 bool AbilityManagerService::GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos,
9206     const std::string &mainAbility, std::string &uri)
9207 {
9208     if (abilityInfos.empty() || mainAbility.empty()) {
9209         TAG_LOGE(AAFwkTag::ABILITYMGR,
9210             "abilityInfos or mainAbility empty mainAbility:%{public}s", mainAbility.c_str());
9211         return false;
9212     }
9213 
9214     std::string dataAbilityUri;
9215     for (auto abilityInfo : abilityInfos) {
9216         if (abilityInfo.type == AppExecFwk::AbilityType::DATA &&
9217             abilityInfo.name == mainAbility) {
9218             dataAbilityUri = abilityInfo.uri;
9219             TAG_LOGI(AAFwkTag::ABILITYMGR, "get data ability uri:%{public}s", dataAbilityUri.c_str());
9220             break;
9221         }
9222     }
9223 
9224     return GetValidDataAbilityUri(dataAbilityUri, uri);
9225 }
9226 
GetAbilityRunningInfo(std::vector<AbilityRunningInfo> & info,std::shared_ptr<AbilityRecord> & abilityRecord)9227 void AbilityManagerService::GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info,
9228     std::shared_ptr<AbilityRecord> &abilityRecord)
9229 {
9230     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9231     AbilityRunningInfo runningInfo;
9232     AppExecFwk::RunningProcessInfo processInfo;
9233     CHECK_POINTER(abilityRecord);
9234     runningInfo.ability = abilityRecord->GetElementName();
9235     runningInfo.startTime = abilityRecord->GetStartTime();
9236     runningInfo.abilityState = static_cast<int>(abilityRecord->GetAbilityState());
9237 
9238     DelayedSingleton<AppScheduler>::GetInstance()->
9239         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
9240     runningInfo.pid = processInfo.pid_;
9241     runningInfo.uid = processInfo.uid_;
9242     runningInfo.processName = processInfo.processName_;
9243     runningInfo.appCloneIndex = processInfo.appCloneIndex;
9244     info.emplace_back(runningInfo);
9245 }
9246 
VerifyAccountPermission(int32_t userId)9247 int AbilityManagerService::VerifyAccountPermission(int32_t userId)
9248 {
9249     if ((userId < 0) || (userController_ && (userController_->GetCurrentUserId() == userId))) {
9250         return ERR_OK;
9251     }
9252     return AAFwk::PermissionVerification::GetInstance()->VerifyAccountPermission();
9253 }
9254 
FreeInstallAbilityFromRemote(const Want & want,const sptr<IRemoteObject> & callback,int32_t userId,int requestCode)9255 int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
9256     int32_t userId, int requestCode)
9257 {
9258     auto callingUid = IPCSkeleton::GetCallingUid();
9259     if (callingUid != DMS_UID) {
9260         TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support DMS");
9261         return CHECK_PERMISSION_FAILED;
9262     }
9263     int32_t validUserId = GetValidUserId(userId);
9264     if (freeInstallManager_ == nullptr) {
9265         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
9266         return ERR_INVALID_VALUE;
9267     }
9268     return freeInstallManager_->FreeInstallAbilityFromRemote(want, callback, validUserId, requestCode);
9269 }
9270 
GetTopAbility(bool isNeedLocalDeviceId)9271 AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId)
9272 {
9273     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9274     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
9275     AppExecFwk::ElementName elementName = {};
9276     if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
9277         auto callerPid = IPCSkeleton::GetCallingPid();
9278         AppExecFwk::RunningProcessInfo processInfo;
9279         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
9280         if (!processInfo.isTestProcess) {
9281             TAG_LOGE(AAFwkTag::ABILITYMGR, "can't use system-api or not test process");
9282             return elementName;
9283         }
9284     }
9285 #ifdef SUPPORT_GRAPHICS
9286     sptr<IRemoteObject> token;
9287     int ret = IN_PROCESS_CALL(GetTopAbility(token));
9288     if (ret) {
9289         return elementName;
9290     }
9291     if (!token) {
9292         TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
9293         return elementName;
9294     }
9295     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9296     if (abilityRecord == nullptr) {
9297         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
9298         return elementName;
9299     }
9300     elementName = abilityRecord->GetElementName();
9301     bool isDeviceEmpty = elementName.GetDeviceID().empty();
9302     std::string localDeviceId;
9303     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
9304         elementName.SetDeviceID(localDeviceId);
9305     }
9306 #endif
9307     return elementName;
9308 }
9309 
GetElementNameByToken(sptr<IRemoteObject> token,bool isNeedLocalDeviceId)9310 AppExecFwk::ElementName AbilityManagerService::GetElementNameByToken(sptr<IRemoteObject> token,
9311     bool isNeedLocalDeviceId)
9312 {
9313     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9314     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
9315     AppExecFwk::ElementName elementName = {};
9316 #ifdef SUPPORT_GRAPHICS
9317     if (!token) {
9318         TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
9319         return elementName;
9320     }
9321     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9322     if (abilityRecord == nullptr) {
9323         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
9324         return elementName;
9325     }
9326     elementName = abilityRecord->GetElementName();
9327     bool isDeviceEmpty = elementName.GetDeviceID().empty();
9328     std::string localDeviceId;
9329     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
9330         elementName.SetDeviceID(localDeviceId);
9331     }
9332 #endif
9333     return elementName;
9334 }
9335 
Dump(int fd,const std::vector<std::u16string> & args)9336 int AbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
9337 {
9338     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump begin fd: %{public}d", fd);
9339     std::string result;
9340     auto errCode = Dump(args, result);
9341     int ret = dprintf(fd, "%s\n", result.c_str());
9342     if (ret < 0) {
9343         TAG_LOGE(AAFwkTag::ABILITYMGR, "dprintf error");
9344         return ERR_AAFWK_HIDUMP_ERROR;
9345     }
9346     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump end");
9347     return errCode;
9348 }
9349 
Dump(const std::vector<std::u16string> & args,std::string & result)9350 int AbilityManagerService::Dump(const std::vector<std::u16string>& args, std::string& result)
9351 {
9352     ErrCode errCode = ERR_OK;
9353     auto size = args.size();
9354     if (size == 0) {
9355         ShowHelp(result);
9356         return errCode;
9357     }
9358 
9359     std::vector<std::string> argsStr;
9360     for (auto arg : args) {
9361         argsStr.emplace_back(Str16ToStr8(arg));
9362     }
9363 
9364     if (argsStr[0] == "-h") {
9365         ShowHelp(result);
9366     } else {
9367         errCode = ProcessMultiParam(argsStr, result);
9368         if (errCode == ERR_AAFWK_HIDUMP_INVALID_ARGS) {
9369             ShowIllegalInfomation(result);
9370         }
9371     }
9372     return errCode;
9373 }
9374 
ProcessMultiParam(std::vector<std::string> & argsStr,std::string & result)9375 ErrCode AbilityManagerService::ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)
9376 {
9377     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
9378     bool isClient = false;
9379     bool isUser = false;
9380     int userID = DEFAULT_INVAL_VALUE;
9381     std::vector<std::string>::iterator it;
9382     for (it = argsStr.begin(); it != argsStr.end();) {
9383         if (*it == ARGS_CLIENT) {
9384             isClient = true;
9385             it = argsStr.erase(it);
9386             continue;
9387         }
9388         if (*it == ARGS_USER_ID) {
9389             it = argsStr.erase(it);
9390             if (it == argsStr.end()) {
9391                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
9392                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
9393             }
9394             (void)StrToInt(*it, userID);
9395             if (userID < 0) {
9396                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
9397                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
9398             }
9399             isUser = true;
9400             it = argsStr.erase(it);
9401             continue;
9402         }
9403         it++;
9404     }
9405     std::string cmd;
9406     for (unsigned int i = 0; i < argsStr.size(); i++) {
9407         cmd.append(argsStr[i]);
9408         if (i != argsStr.size() - 1) {
9409             cmd.append(" ");
9410         }
9411     }
9412     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, isClient:%{public}d, userID:%{public}d, cmd:%{public}s",
9413         __func__, isClient, userID, cmd.c_str());
9414 
9415     std::vector<std::string> dumpResults;
9416     DumpSysState(cmd, dumpResults, isClient, isUser, userID);
9417     for (auto it : dumpResults) {
9418         result += it + "\n";
9419     }
9420     return ERR_OK;
9421 }
9422 
ShowHelp(std::string & result)9423 void AbilityManagerService::ShowHelp(std::string& result)
9424 {
9425     result.append("Usage:\n")
9426         .append("-h                          ")
9427         .append("help text for the tool\n")
9428         .append("-a [-c | -u {UserId}]       ")
9429         .append("dump all ability infomation in the system or all ability infomation of client/UserId\n")
9430         .append("-l                          ")
9431         .append("dump all mission list information in the system\n")
9432         .append("-i {AbilityRecordId}        ")
9433         .append("dump an ability infomation by ability record id\n")
9434         .append("-e                          ")
9435         .append("dump all extension infomation in the system(FA: ServiceAbilityRecords, Stage: ExtensionRecords)\n")
9436         .append("-p [PendingWantRecordId]    ")
9437         .append("dump all pendingwant record infomation in the system\n")
9438         .append("-r                          ")
9439         .append("dump all process in the system\n")
9440         .append("-d                          ")
9441         .append("dump all data ability infomation in the system");
9442 }
9443 
ShowIllegalInfomation(std::string & result)9444 void AbilityManagerService::ShowIllegalInfomation(std::string& result)
9445 {
9446     result.append(ILLEGAL_INFOMATION);
9447 }
9448 
DumpAbilityInfoDone(std::vector<std::string> & infos,const sptr<IRemoteObject> & callerToken)9449 int AbilityManagerService::DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)
9450 {
9451     TAG_LOGD(AAFwkTag::ABILITYMGR, "dumpAbilityInfoDone begin");
9452     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
9453     if (abilityRecord == nullptr) {
9454         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
9455         return ERR_INVALID_VALUE;
9456     }
9457     if (!JudgeSelfCalled(abilityRecord)) {
9458         return CHECK_PERMISSION_FAILED;
9459     }
9460     abilityRecord->DumpAbilityInfoDone(infos);
9461     return ERR_OK;
9462 }
9463 
SetMissionContinueState(const sptr<IRemoteObject> & token,const AAFwk::ContinueState & state)9464 int AbilityManagerService::SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)
9465 {
9466     TAG_LOGD(AAFwkTag::ABILITYMGR, "SetMissionContinueState begin. State: %{public}d", state);
9467 
9468     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
9469 
9470     int32_t missionId = GetMissionIdByAbilityToken(token);
9471     if (missionId == -1) {
9472         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed state:%{public}d", state);
9473         return ERR_INVALID_VALUE;
9474     }
9475 
9476     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9477     if (!abilityRecord) {
9478         TAG_LOGE(AAFwkTag::ABILITYMGR,
9479             "no such ability record missionId:%{public}d, state:%{public}d",
9480             missionId, state);
9481         return -1;
9482     }
9483 
9484     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9485     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9486     if (callingTokenId != tokenID) {
9487         TAG_LOGE(AAFwkTag::ABILITYMGR,
9488             "setMissionContinueState not self, not enabled. missionId:%{public}d, state:%{public}d",
9489             missionId, state);
9490         return -1;
9491     }
9492 
9493     auto userId = abilityRecord->GetOwnerMissionUserId();
9494     auto missionListManager = GetMissionListManagerByUserId(userId);
9495     if (!missionListManager) {
9496         TAG_LOGE(AAFwkTag::ABILITYMGR, "find missionListManager failed missionId:%{public}d, state:%{public}d",
9497             missionId, state);
9498         return -1;
9499     }
9500 
9501     auto setResult = missionListManager->SetMissionContinueState(token, missionId, state);
9502     if (setResult != ERR_OK) {
9503         TAG_LOGE(AAFwkTag::ABILITYMGR,
9504             "missionListManager set failed, result:%{public}d, missionId:%{public}d, state:%{public}d",
9505             setResult, missionId, state);
9506         return setResult;
9507     }
9508 
9509     DistributedClient dmsClient;
9510     int32_t callingUid = IPCSkeleton::GetCallingUid();
9511     auto result =  dmsClient.SetMissionContinueState(missionId, state, callingUid);
9512     if (result != ERR_OK) {
9513         TAG_LOGE(AAFwkTag::ABILITYMGR,
9514             "Notify DMS client failed, result: %{public}d. Mission id: %{public}d, state: %{public}d",
9515             result, missionId, state);
9516     }
9517 
9518     TAG_LOGD(AAFwkTag::ABILITYMGR,
9519         "SetMissionContinueState end. Mission id: %{public}d, state: %{public}d", missionId, state);
9520     return ERR_OK;
9521 }
9522 
9523 #ifdef SUPPORT_SCREEN
SetMissionLabel(const sptr<IRemoteObject> & token,const std::string & label)9524 int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
9525 {
9526     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9527     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9528     if (!abilityRecord) {
9529         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
9530         return -1;
9531     }
9532 
9533     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9534     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9535     if (callingTokenId != tokenID) {
9536         TAG_LOGE(AAFwkTag::ABILITYMGR, "setMissionLabel not self, not enabled");
9537         return -1;
9538     }
9539 
9540     auto userId = abilityRecord->GetOwnerMissionUserId();
9541     auto missionListManager = GetMissionListManagerByUserId(userId);
9542     if (!missionListManager) {
9543         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager find failed when set mission label");
9544         return -1;
9545     }
9546 
9547     return missionListManager->SetMissionLabel(token, label);
9548 }
9549 
SetMissionIcon(const sptr<IRemoteObject> & token,const std::shared_ptr<OHOS::Media::PixelMap> & icon)9550 int AbilityManagerService::SetMissionIcon(const sptr<IRemoteObject> &token,
9551     const std::shared_ptr<OHOS::Media::PixelMap> &icon)
9552 {
9553     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9554     CHECK_CALLER_IS_SYSTEM_APP;
9555     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9556     if (!abilityRecord) {
9557         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
9558         return -1;
9559     }
9560 
9561     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9562     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9563     if (callingTokenId != tokenID) {
9564         TAG_LOGE(AAFwkTag::ABILITYMGR, "not self, not enable set mission icon");
9565         return -1;
9566     }
9567 
9568     auto userId = abilityRecord->GetOwnerMissionUserId();
9569     auto missionListManager = GetMissionListManagerByUserId(userId);
9570     if (!missionListManager) {
9571         TAG_LOGE(AAFwkTag::ABILITYMGR, "find missionListManager failed");
9572         return -1;
9573     }
9574 
9575     return missionListManager->SetMissionIcon(token, icon);
9576 }
9577 
RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> & handler,bool animationEnabled)9578 int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler,
9579     bool animationEnabled)
9580 {
9581     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9582     if (!isSaCall) {
9583         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
9584         return CHECK_PERMISSION_FAILED;
9585     }
9586     wmsHandler_ = handler;
9587     isAnimationEnabled_ = animationEnabled;
9588     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s: WMS handler registered successfully.", __func__);
9589     return ERR_OK;
9590 }
9591 
GetWMSHandler() const9592 sptr<IWindowManagerServiceHandler> AbilityManagerService::GetWMSHandler() const
9593 {
9594     return wmsHandler_;
9595 }
9596 
CompleteFirstFrameDrawing(const sptr<IRemoteObject> & abilityToken)9597 void AbilityManagerService::CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)
9598 {
9599     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9600     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
9601         TAG_LOGE(AAFwkTag::ABILITYMGR, "not foundation call");
9602         return;
9603     }
9604     auto abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
9605     CHECK_POINTER(abilityRecord);
9606 
9607     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
9608     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
9609     CHECK_POINTER(missionListManager);
9610     missionListManager->CompleteFirstFrameDrawing(abilityToken);
9611 }
9612 
CompleteFirstFrameDrawing(int32_t sessionId)9613 void AbilityManagerService::CompleteFirstFrameDrawing(int32_t sessionId)
9614 {
9615     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9616     if (!IsCallerSceneBoard()) {
9617         TAG_LOGE(AAFwkTag::ABILITYMGR, "not sceneboard called, not allowed");
9618         return;
9619     }
9620     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
9621     CHECK_POINTER(uiAbilityManager);
9622     uiAbilityManager->CompleteFirstFrameDrawing(sessionId);
9623 }
9624 
ShowPickerDialog(const Want & want,int32_t userId,const sptr<IRemoteObject> & callerToken)9625 int32_t AbilityManagerService::ShowPickerDialog(
9626     const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)
9627 {
9628     AAFwk::Want newWant = want;
9629     std::string sharePickerBundleName =
9630         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME);
9631     std::string sharePickerAbilityName =
9632         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_ABILITY_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME);
9633     newWant.SetElementName(sharePickerBundleName, sharePickerAbilityName);
9634     newWant.SetParam(TOKEN_KEY, callerToken);
9635     // note: clear actions
9636     newWant.SetAction("");
9637     return IN_PROCESS_CALL(StartAbility(newWant, DEFAULT_INVAL_VALUE, userId));
9638 }
9639 
CheckWindowMode(int32_t windowMode,const std::vector<AppExecFwk::SupportWindowMode> & windowModes) const9640 bool AbilityManagerService::CheckWindowMode(int32_t windowMode,
9641     const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const
9642 {
9643     TAG_LOGI(AAFwkTag::ABILITYMGR, "window mode:%{public}d", windowMode);
9644     if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED) {
9645         return true;
9646     }
9647 
9648     auto bmsWindowMode = WindowOptionsUtils::WindowModeMap(windowMode);
9649     if (bmsWindowMode.first) {
9650         for (const auto& mode : windowModes) {
9651             if (mode == bmsWindowMode.second) {
9652                 return true;
9653             }
9654         }
9655     }
9656     return false;
9657 }
9658 
PrepareTerminateAbility(const sptr<IRemoteObject> & token,sptr<IPrepareTerminateCallback> & callback)9659 int AbilityManagerService::PrepareTerminateAbility(const sptr<IRemoteObject> &token,
9660     sptr<IPrepareTerminateCallback> &callback)
9661 {
9662     TAG_LOGD(AAFwkTag::ABILITYMGR, "call PrepareTerminateAbility");
9663     if (callback == nullptr) {
9664         TAG_LOGE(AAFwkTag::ABILITYMGR, "callback null");
9665         return ERR_INVALID_VALUE;
9666     }
9667 
9668     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9669     auto err = AbilityPermissionUtil::GetInstance().CheckPrepareTerminateEnable(abilityRecord);
9670     if (err != ERR_OK) {
9671         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckPrepareTerminateEnable failed: %{public}d", err);
9672         callback->DoPrepareTerminate();
9673         return err;
9674     }
9675 
9676     if (!JudgeSelfCalled(abilityRecord)) {
9677         TAG_LOGE(AAFwkTag::ABILITYMGR, "not self call");
9678         callback->DoPrepareTerminate();
9679         return CHECK_PERMISSION_FAILED;
9680     }
9681 
9682     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
9683     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
9684     bool res = uiAbilityManager->PrepareTerminateAbility(abilityRecord, false);
9685     if (!res) {
9686         callback->DoPrepareTerminate();
9687         return ERR_OK;
9688     }
9689     std::lock_guard<std::mutex> guard(prepareTermiationCallbackMutex_);
9690     auto abilityRecordId = std::to_string(abilityRecord->GetAbilityRecordId());
9691     if (prepareTermiationCallbacks_.find(abilityRecordId) != prepareTermiationCallbacks_.end()) {
9692         TAG_LOGI(AAFwkTag::ABILITYMGR, "abilityRecordId=%{public}s already exists", abilityRecordId.c_str());
9693         return ERR_OK;
9694     }
9695     prepareTermiationCallbacks_[abilityRecordId] = callback;
9696 
9697     auto timeoutTask = [callback]() {
9698         if (callback != nullptr) {
9699             callback->DoPrepareTerminate();
9700         }
9701     };
9702     if (taskHandler_) {
9703         taskHandler_->SubmitTask(timeoutTask, "PrepareTermiante_" + abilityRecordId,
9704             GlobalConstant::PREPARE_TERMINATE_TIMEOUT_TIME);
9705     }
9706     return ERR_OK;
9707 }
9708 
PrepareTerminateAbilityDone(const sptr<IRemoteObject> & token,bool isTerminate)9709 void AbilityManagerService::PrepareTerminateAbilityDone(const sptr<IRemoteObject> &token, bool isTerminate)
9710 {
9711     TAG_LOGD(AAFwkTag::ABILITYMGR, "call PrepareTerminateAbilityDone, isTerminate=%{public}d", isTerminate);
9712     if (token == nullptr) {
9713         TAG_LOGE(AAFwkTag::ABILITYMGR, "null token");
9714         return;
9715     }
9716     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
9717     CHECK_POINTER(uiAbilityManager);
9718     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9719     CHECK_POINTER(abilityRecord);
9720     if (!JudgeSelfCalled(abilityRecord)) {
9721         TAG_LOGE(AAFwkTag::ABILITYMGR, "not self caller");
9722         return;
9723     }
9724     auto abilityRecordId = std::to_string(abilityRecord->GetAbilityRecordId());
9725     std::lock_guard<std::mutex> guard(prepareTermiationCallbackMutex_);
9726     auto iter = prepareTermiationCallbacks_.find(abilityRecordId);
9727     if (iter == prepareTermiationCallbacks_.end()) {
9728         TAG_LOGI(AAFwkTag::ABILITYMGR, "scb call, abilityRecordId=%{public}s not found", abilityRecordId.c_str());
9729         uiAbilityManager->PrepareTerminateAbilityDone(abilityRecord, isTerminate);
9730         return;
9731     }
9732     if (iter->second != nullptr && !isTerminate) {
9733         TAG_LOGI(AAFwkTag::ABILITYMGR, "abilityRecordId=%{public}s, calling callback", abilityRecordId.c_str());
9734         iter->second->DoPrepareTerminate();
9735     }
9736     prepareTermiationCallbacks_.erase(iter);
9737     if (taskHandler_) {
9738         taskHandler_->CancelTask("PrepareTermiante_" + abilityRecordId);
9739     }
9740 }
9741 
KillProcessWithPrepareTerminateDone(const std::string & moduleName,int32_t prepareTermination,bool isExist)9742 void AbilityManagerService::KillProcessWithPrepareTerminateDone(const std::string &moduleName,
9743     int32_t prepareTermination, bool isExist)
9744 {
9745     TAG_LOGI(AAFwkTag::ABILITYMGR, "call KillProcessWithPrepareTerminateDone, moduleName=%{public}s, "
9746         "prepareTermination=%{public}d, isExist=%{public}d", moduleName.c_str(), prepareTermination, isExist);
9747     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
9748     CHECK_POINTER(uiAbilityManager);
9749     uiAbilityManager->TryPrepareTerminateByPidsDone(moduleName, prepareTermination, isExist);
9750 }
9751 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9752 void AbilityManagerService::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9753 {
9754     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle focused event");
9755     auto missionListManager = GetCurrentMissionListManager();
9756     CHECK_POINTER(missionListManager);
9757     CHECK_POINTER(focusChangeInfo);
9758     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9759     missionListManager->NotifyMissionFocused(missionId);
9760 }
9761 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9762 void AbilityManagerService::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9763 {
9764     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle unfocused event");
9765     auto missionListManager = GetCurrentMissionListManager();
9766     CHECK_POINTER(missionListManager);
9767     CHECK_POINTER(focusChangeInfo);
9768     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9769     missionListManager->NotifyMissionUnfocused(missionId);
9770 }
9771 
InitFocusListener()9772 void AbilityManagerService::InitFocusListener()
9773 {
9774     TAG_LOGI(AAFwkTag::ABILITYMGR, "init ability focus listener");
9775     if (focusListener_) {
9776         return;
9777     }
9778 
9779     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
9780     auto registerTask = [innerService = shared_from_this()]() {
9781         if (innerService) {
9782             TAG_LOGI(AAFwkTag::ABILITYMGR, "registerFocusListener task");
9783             innerService->RegisterFocusListener();
9784         }
9785     };
9786     if (taskHandler_) {
9787         taskHandler_->SubmitTaskJust(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
9788     }
9789 }
9790 
RegisterFocusListener()9791 void AbilityManagerService::RegisterFocusListener()
9792 {
9793     TAG_LOGI(AAFwkTag::ABILITYMGR, "register focus listener");
9794     if (!focusListener_) {
9795         TAG_LOGE(AAFwkTag::ABILITYMGR, "no listener obj");
9796         return;
9797     }
9798     Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
9799     TAG_LOGI(AAFwkTag::ABILITYMGR, "register focus listener success");
9800 }
9801 
RegisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer,const std::string & targetBundleName)9802 int AbilityManagerService::RegisterAbilityFirstFrameStateObserver(
9803     const sptr<IAbilityFirstFrameStateObserver> &observer, const std::string &targetBundleName)
9804 {
9805     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9806         RegisterAbilityFirstFrameStateObserver(observer, targetBundleName);
9807 }
9808 
UnregisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer)9809 int AbilityManagerService::UnregisterAbilityFirstFrameStateObserver(
9810     const sptr<IAbilityFirstFrameStateObserver> &observer)
9811 {
9812     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9813         UnregisterAbilityFirstFrameStateObserver(observer);
9814 }
9815 
GetAnimationFlag()9816 bool AbilityManagerService::GetAnimationFlag()
9817 {
9818     return isAnimationEnabled_;
9819 }
9820 
9821 #endif
9822 
CheckCallServicePermission(const AbilityRequest & abilityRequest)9823 int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest)
9824 {
9825     if (abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()) ==
9826         AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
9827         abilityRequest.want.GetElement().GetBundleName() == AppUtils::GetInstance().GetBrokerDelegateBundleName()) {
9828         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9829         if (collaborator != nullptr) {
9830             TAG_LOGI(AAFwkTag::ABILITYMGR, "Collaborator CheckCallAbilityPermission");
9831             return collaborator->CheckCallAbilityPermission(abilityRequest.want);
9832         }
9833     }
9834     if (abilityRequest.abilityInfo.isStageBasedModel) {
9835         auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9836         TAG_LOGD(AAFwkTag::ABILITYMGR, "extensionType is %{public}d.", static_cast<int>(extensionType));
9837         if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE ||
9838             extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
9839             extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9840             return CheckCallServiceExtensionPermission(abilityRequest);
9841         } else {
9842             return CheckCallOtherExtensionPermission(abilityRequest);
9843         }
9844     } else {
9845         return CheckCallServiceAbilityPermission(abilityRequest);
9846     }
9847 }
9848 
CheckCallDataAbilityPermission(AbilityRequest & abilityRequest,bool isShell,bool isSACall)9849 int AbilityManagerService::CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)
9850 {
9851     abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo;
9852     abilityRequest.uid = abilityRequest.appInfo.uid;
9853     if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) {
9854         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app info acquiring");
9855         return ERR_INVALID_VALUE;
9856     }
9857     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) {
9858         TAG_LOGE(AAFwkTag::ABILITYMGR, "BMS query result not data ability");
9859         return ERR_WRONG_INTERFACE_CALL;
9860     }
9861 
9862     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest,
9863         true, isShell, isSACall);
9864     if (isShell) {
9865         verificationInfo.isBackgroundCall = true;
9866     }
9867     if (!isShell && IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall, true) != ERR_OK) {
9868         return ERR_INVALID_VALUE;
9869     }
9870     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallDataAbilityPermission(verificationInfo,
9871         isShell);
9872     if (result != ERR_OK) {
9873         TAG_LOGE(AAFwkTag::ABILITYMGR, "without start DataAbility permission");
9874         return result;
9875     }
9876 
9877     return ERR_OK;
9878 }
9879 
CreateVerificationInfo(const AbilityRequest & abilityRequest,bool isData,bool isShell,bool isSA)9880 AAFwk::PermissionVerification::VerificationInfo AbilityManagerService::CreateVerificationInfo(
9881     const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)
9882 {
9883     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9884     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9885     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9886     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9887     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call ServiceAbility or DataAbility, target bundleName: %{public}s.",
9888         abilityRequest.appInfo.bundleName.c_str());
9889     if (whiteListassociatedWakeUpFlag_ &&
9890         abilityRequest.appInfo.bundleName == BUNDLE_NAME_SETTINGSDATA) {
9891         TAG_LOGD(AAFwkTag::ABILITYMGR,
9892             "Call ServiceAbility or DataAbility, target bundle in white-list, allow associatedWakeUp.");
9893         verificationInfo.associatedWakeUp = true;
9894     } else {
9895         verificationInfo.associatedWakeUp = abilityRequest.appInfo.associatedWakeUp;
9896     }
9897     if (!isData) {
9898         isSA = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9899         isShell = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
9900     }
9901     if (isSA || isShell) {
9902         return verificationInfo;
9903     }
9904     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9905     if (callerAbility) {
9906         verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9907     }
9908 
9909     return verificationInfo;
9910 }
9911 
CheckCallServiceExtensionPermission(const AbilityRequest & abilityRequest)9912 int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)
9913 {
9914     TAG_LOGD(AAFwkTag::ABILITYMGR, "begin");
9915 
9916     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9917     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9918     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9919     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9920     verificationInfo.isBackgroundCall = false;
9921     if (isParamStartAbilityEnable_) {
9922         bool stopContinuousTaskFlag = ShouldPreventStartAbility(abilityRequest);
9923         if (stopContinuousTaskFlag) {
9924             TAG_LOGE(AAFwkTag::ABILITYMGR, "no have permission to start ServiceExtension");
9925             return CHECK_PERMISSION_FAILED;
9926         }
9927     }
9928 
9929     if (abilityRequest.abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9930         TAG_LOGE(AAFwkTag::ABILITYMGR, "background startup UI_SERVICE");
9931         verificationInfo.isBackgroundCall = true;
9932         std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9933         if (callerAbility) {
9934             verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9935         }
9936         if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9937             TAG_LOGE(AAFwkTag::ABILITYMGR, "not background startup UI_SERVICE");
9938             return ERR_INVALID_VALUE;
9939         }
9940     }
9941 
9942     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo);
9943     if (result != ERR_OK) {
9944         TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceExtension or sataShareExtension permission");
9945     }
9946     return result;
9947 }
9948 
9949 #ifdef SUPPORT_AUTO_FILL
CheckCallAutoFillExtensionPermission(const AbilityRequest & abilityRequest)9950 int AbilityManagerService::CheckCallAutoFillExtensionPermission(const AbilityRequest &abilityRequest)
9951 {
9952     if (!abilityRequest.appInfo.isSystemApp) {
9953         TAG_LOGE(AAFwkTag::ABILITYMGR, "application requesting call isn't system application");
9954         return CHECK_PERMISSION_FAILED;
9955     }
9956     std::string jsonDataStr = abilityRequest.want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY);
9957     AbilityBase::ViewData viewData;
9958     viewData.FromJsonString(jsonDataStr.c_str());
9959     std::string callerName;
9960     int32_t uid = 0;
9961     auto callerPid = IPCSkeleton::GetCallingPid();
9962     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
9963     if (viewData.bundleName != callerName) {
9964         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not %{public}s called, no allowed", viewData.bundleName.c_str());
9965         return ERR_WRONG_INTERFACE_CALL;
9966     }
9967     return ERR_OK;
9968 }
9969 #endif // SUPPORT_AUTO_FILL
9970 
CheckCallOtherExtensionPermission(const AbilityRequest & abilityRequest)9971 int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)
9972 {
9973     if (IPCSkeleton::GetCallingUid() != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
9974         AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9975         return ERR_OK;
9976     }
9977     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9978     TAG_LOGD(AAFwkTag::ABILITYMGR, "OtherExtension type: %{public}d.", static_cast<int32_t>(extensionType));
9979     if (system::GetBoolParameter(DEVELOPER_MODE_STATE, false) &&
9980         PermissionVerification::GetInstance()->VerifyShellStartExtensionType(static_cast<int32_t>(extensionType))) {
9981         TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckCallOtherExtensionPermission, allow aa start with debug mode.");
9982         return ERR_OK;
9983     }
9984     if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) {
9985         CHECK_CALLER_IS_SYSTEM_APP;
9986         return ERR_OK;
9987     }
9988     if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) {
9989         return ERR_OK;
9990     }
9991 #ifdef SUPPORT_AUTO_FILL
9992     if (extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD ||
9993         extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART) {
9994         return CheckCallAutoFillExtensionPermission(abilityRequest);
9995     }
9996 #endif // SUPPORT_AUTO_FILL
9997     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
9998         return CheckUIExtensionPermission(abilityRequest);
9999     }
10000     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
10001         return ERR_OK;
10002     }
10003     if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION) {
10004         return CheckFileAccessExtensionPermission(abilityRequest);
10005     }
10006     if (extensionType == AppExecFwk::ExtensionAbilityType::CALLER_INFO_QUERY) {
10007         return CheckCallerInfoQueryExtensionPermission(abilityRequest);
10008     }
10009     TAG_LOGE(AAFwkTag::ABILITYMGR, "not SA, can't start other extension");
10010     return CHECK_PERMISSION_FAILED;
10011 }
10012 
CheckCallerInfoQueryExtensionPermission(const AbilityRequest & abilityRequest)10013 int AbilityManagerService::CheckCallerInfoQueryExtensionPermission(const AbilityRequest &abilityRequest)
10014 {
10015     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
10016         PermissionConstants::PERMISSION_GET_TELEPHONY_STATE);
10017     if (!ret) {
10018         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny for callerInfoQueryExtension");
10019         return CHECK_PERMISSION_FAILED;
10020     }
10021     TAG_LOGI(AAFwkTag::ABILITYMGR, "check permission success");
10022     return ERR_OK;
10023 }
10024 
CheckFileAccessExtensionPermission(const AbilityRequest & abilityRequest)10025 int AbilityManagerService::CheckFileAccessExtensionPermission(const AbilityRequest &abilityRequest)
10026 {
10027     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
10028         PermissionConstants::PERMISSION_FILE_ACCESS_MANAGER);
10029     if (!ret) {
10030         return CHECK_PERMISSION_FAILED;
10031     }
10032     TAG_LOGD(AAFwkTag::ABILITYMGR, "Temporary, FILEACCESS_EXTENSION use serviceExtension start-up rule.");
10033     return CheckCallServiceExtensionPermission(abilityRequest);
10034 }
10035 
CheckUIExtensionPermission(const AbilityRequest & abilityRequest)10036 int AbilityManagerService::CheckUIExtensionPermission(const AbilityRequest &abilityRequest)
10037 {
10038     if (abilityRequest.want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
10039         // If started by embedded atomic service, allow it.
10040         return ERR_OK;
10041     }
10042 
10043     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
10044     if (AAFwk::UIExtensionUtils::IsSystemUIExtension(extensionType)) {
10045         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10046         if (callerRecord == nullptr) {
10047             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid caller");
10048             return NO_FOUND_ABILITY_BY_CALLER;
10049         }
10050 
10051         if (!abilityRequest.appInfo.isSystemApp) {
10052             TAG_LOGE(AAFwkTag::ABILITYMGR, "bundle %{public}s want start or caller bundle %{public}s "
10053                 "isn't system app, type %{public}d not allowed", abilityRequest.appInfo.bundleName.c_str(),
10054                 callerRecord->GetApplicationInfo().bundleName.c_str(), extensionType);
10055             return CHECK_PERMISSION_FAILED;
10056         }
10057     }
10058 
10059     if (AAFwk::UIExtensionUtils::IsSystemCallerNeeded(extensionType)) {
10060         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10061         if (callerRecord == nullptr) {
10062             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid caller");
10063             return NO_FOUND_ABILITY_BY_CALLER;
10064         }
10065 
10066         if (!callerRecord->GetApplicationInfo().isSystemApp
10067             && !AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10068             TAG_LOGE(AAFwkTag::ABILITYMGR,
10069                      "bundle %{public}s want start but caller bundle %{public}s "
10070                      "isn't system app, type %{public}d not allowed",
10071                      abilityRequest.appInfo.bundleName.c_str(), callerRecord->GetApplicationInfo().bundleName.c_str(),
10072                      extensionType);
10073             return CHECK_PERMISSION_FAILED;
10074         }
10075     }
10076 
10077     if (!CheckUIExtensionCallerIsForeground(abilityRequest)) {
10078         return CHECK_PERMISSION_FAILED;
10079     }
10080 
10081     if (!CheckUIExtensionCallerPidByHostWindowId(abilityRequest)) {
10082         return ERR_INVALID_CALLER;
10083     }
10084 
10085     return ERR_OK;
10086 }
10087 
CheckUIExtensionCallerIsForeground(const AbilityRequest & abilityRequest)10088 bool AbilityManagerService::CheckUIExtensionCallerIsForeground(const AbilityRequest &abilityRequest)
10089 {
10090     if (!CheckUIExtensionCallerIsUIAbility(abilityRequest)) {
10091         // Check only if the caller is uiability, if caller is not a uiability, don't check.
10092         return true;
10093     }
10094 
10095     bool isBackgroundCall = true;
10096     auto ret = IsCallFromBackground(abilityRequest, isBackgroundCall);
10097     if (ret != ERR_OK) {
10098         TAG_LOGE(AAFwkTag::UI_EXT, "start uea when background");
10099         return false;
10100     }
10101 
10102     if (!isBackgroundCall) {
10103         return true;
10104     }
10105 
10106     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10107     if (callerAbility != nullptr) {
10108         if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
10109             auto tokenId = callerAbility->GetApplicationInfo().accessTokenId;
10110             bool isFocused = false;
10111             if (CheckUIExtensionIsFocused(tokenId, isFocused) == ERR_OK && isFocused) {
10112                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Root caller is foreground");
10113                 return true;
10114             }
10115         }
10116 
10117         if (callerAbility->IsSceneBoard()) {
10118             return true;
10119         }
10120     }
10121 
10122     if (PermissionVerification::GetInstance()->VerifyCallingPermission(
10123         PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
10124         return true;
10125     }
10126 
10127     TAG_LOGE(AAFwkTag::ABILITYMGR, "caller app not foreground, can't start %{public}s",
10128         abilityRequest.want.GetElement().GetURI().c_str());
10129     return false;
10130 }
10131 
CheckUIExtensionCallerIsUIAbility(const AbilityRequest & abilityRequest)10132 bool AbilityManagerService::CheckUIExtensionCallerIsUIAbility(const AbilityRequest &abilityRequest)
10133 {
10134     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10135     if (callerAbility == nullptr) {
10136         TAG_LOGE(AAFwkTag::UI_EXT, "caller ability invalid");
10137         return false;
10138     }
10139 
10140     if (callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
10141         return true;
10142     }
10143 
10144     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
10145         callerAbility = GetUIExtensionRootCaller(abilityRequest.callerToken, abilityRequest.userId);
10146         if (callerAbility != nullptr && callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
10147             return true;
10148         }
10149     }
10150 
10151     return false;
10152 }
10153 
CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest & abilityRequest)10154 bool AbilityManagerService::CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest &abilityRequest)
10155 {
10156 #ifdef SUPPORT_SCREEN
10157     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10158         return true;
10159     }
10160 
10161     auto sessionInfo = abilityRequest.sessionInfo;
10162     CHECK_POINTER_AND_RETURN(sessionInfo, false);
10163     auto hostWindowId = sessionInfo->hostWindowId;
10164     auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
10165     CHECK_POINTER_AND_RETURN(sceneSessionManager, false);
10166     pid_t hostPid = 0;
10167     // If host window id is scb, it will return with error.
10168     auto tokenId = abilityRequest.appInfo.accessTokenId;
10169     auto element = abilityRequest.want.GetElement();
10170     auto extType = abilityRequest.abilityInfo.extensionAbilityType;
10171     {
10172         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "Rosen::SceneSessionManager::CheckUIExtensionCreation");
10173         auto ret = sceneSessionManager->CheckUIExtensionCreation(hostWindowId, tokenId, element, extType, hostPid);
10174         if (ret == Rosen::WMError::WM_ERROR_INVALID_PERMISSION) {
10175             // If check permission failed, means target ability can't show on lock screen.
10176             TAG_LOGE(AAFwkTag::UI_EXT, "Check fail, tokenId: %{public}d, element: %{public}s, ret: %{public}d",
10177                 tokenId, element.GetURI().c_str(), ret);
10178             return false;
10179         }
10180     }
10181 
10182     TAG_LOGD(AAFwkTag::UI_EXT, "get pid %{public}d by windowId %{public}d", hostPid, hostWindowId);
10183     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10184     CHECK_POINTER_AND_RETURN(callerAbility, false);
10185     if (callerAbility->IsSceneBoard()) {
10186         return true;
10187     }
10188     if (hostPid != 0 && callerAbility->GetPid() == hostPid) {
10189         return true;
10190     }
10191 
10192     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
10193         TAG_LOGD(AAFwkTag::UI_EXT, "caller is nested uiextability");
10194         auto connectManager = GetCurrentConnectManager();
10195         CHECK_POINTER_AND_RETURN(connectManager, false);
10196         bool matched = false;
10197         std::list<sptr<IRemoteObject>> callerList;
10198         connectManager->GetUIExtensionCallerTokenList(callerAbility, callerList);
10199         for (auto &item : callerList) {
10200             auto ability = AAFwk::Token::GetAbilityRecordByToken(item);
10201             if (ability == nullptr) {
10202                 TAG_LOGW(AAFwkTag::UI_EXT, "wrong ability");
10203                 continue;
10204             }
10205 
10206             if ((hostPid != 0 && ability->GetPid() == hostPid) || ability->IsSceneBoard()) {
10207                 matched = true;
10208                 return true;
10209             }
10210         }
10211         if (!matched) {
10212             TAG_LOGE(AAFwkTag::UI_EXT, "Check nested uiextability failed");
10213         }
10214     }
10215 
10216     TAG_LOGE(AAFwkTag::UI_EXT, "check pid %{public}d fail, got %{public}d actual %{public}d",
10217         hostWindowId, hostPid, callerAbility->GetPid());
10218     return false;
10219 #else
10220     return true;
10221 #endif // SUPPORT_SCREEN
10222 }
10223 
CheckCallServiceAbilityPermission(const AbilityRequest & abilityRequest)10224 int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)
10225 {
10226     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
10227     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest);
10228     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
10229         return ERR_INVALID_VALUE;
10230     }
10231 
10232     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceAbilityPermission(verificationInfo);
10233     if (result != ERR_OK) {
10234         TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceAbility permission");
10235     }
10236     return result;
10237 }
10238 
CheckCallAbilityPermission(const AbilityRequest & abilityRequest,uint32_t specifyTokenId,bool isCallByShortcut)10239 int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId,
10240     bool isCallByShortcut)
10241 {
10242     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10243     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
10244 
10245     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
10246     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
10247     verificationInfo.visible = abilityRequest.abilityInfo.visible;
10248     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
10249     verificationInfo.specifyTokenId = specifyTokenId;
10250     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
10251         return ERR_INVALID_VALUE;
10252     }
10253 
10254     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission(
10255         verificationInfo, isCallByShortcut);
10256     if (result != ERR_OK) {
10257         TAG_LOGE(AAFwkTag::ABILITYMGR, "without start pageAbility(FA) or ability(Stage) permission");
10258     }
10259     return result;
10260 }
10261 
CheckStartByCallPermission(const AbilityRequest & abilityRequest)10262 int AbilityManagerService::CheckStartByCallPermission(const AbilityRequest &abilityRequest)
10263 {
10264     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
10265     // check whether the target ability is page type and not specified mode.
10266     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::PAGE ||
10267         abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
10268         TAG_LOGE(AAFwkTag::ABILITYMGR, "called ability not common ability");
10269         return RESOLVE_CALL_ABILITY_TYPE_ERR;
10270     }
10271 
10272     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
10273     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
10274     verificationInfo.visible = abilityRequest.abilityInfo.visible;
10275     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
10276     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
10277         return ERR_INVALID_VALUE;
10278     }
10279 
10280     if (AAFwk::PermissionVerification::GetInstance()->CheckStartByCallPermission(verificationInfo) != ERR_OK) {
10281         TAG_LOGE(AAFwkTag::ABILITYMGR, "without startAbilityByCall permission");
10282         return RESOLVE_CALL_NO_PERMISSIONS;
10283     }
10284     TAG_LOGD(AAFwkTag::ABILITYMGR, "caller has permission to resolve the call proxy of common ability");
10285     return ERR_OK;
10286 }
10287 
IsCallFromBackground(const AbilityRequest & abilityRequest,bool & isBackgroundCall,bool isData)10288 int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall,
10289     bool isData)
10290 {
10291     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10292     if (!isData && AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10293         isBackgroundCall = true;
10294         return ERR_OK;
10295     }
10296 
10297     if (!isData && (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
10298         AbilityUtil::IsStartFreeInstall(abilityRequest.want))) {
10299         isBackgroundCall = false;
10300         return ERR_OK;
10301     }
10302 
10303     AppExecFwk::RunningProcessInfo processInfo;
10304     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10305     if (callerAbility && callerAbility->GetAbilityInfo().bundleName == BUNDLE_NAME_DIALOG) {
10306         callerAbility = callerAbility->GetCallerRecord();
10307     }
10308     if (callerAbility) {
10309         if (callerAbility->IsForeground() || callerAbility->GetAbilityForegroundingFlag()) {
10310             isBackgroundCall = false;
10311             return ERR_OK;
10312         }
10313         // CallerAbility is not foreground, so check process state
10314         DelayedSingleton<AppScheduler>::GetInstance()->
10315             GetRunningProcessInfoByToken(callerAbility->GetToken(), processInfo);
10316         if (IsDelegatorCall(processInfo, abilityRequest)) {
10317             TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
10318             isBackgroundCall = false;
10319             return ERR_OK;
10320         }
10321 #ifdef SUPPORT_SCREEN
10322         if (AppUtils::GetInstance().IsStartOptionsWithAnimation() &&
10323             callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
10324             AbilityPermissionUtil::GetInstance().CheckStartCallHasFloatingWindow(
10325             abilityRequest.callerToken) == ERR_OK) {
10326             isBackgroundCall = false;
10327             return ERR_OK;
10328         }
10329 #endif // SUPPORT_SCREEN
10330         auto abilityState = callerAbility->GetAbilityState();
10331         if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING ||
10332             // If uiability or uiextensionability ability state is foreground when terminate,
10333             // it will move to background firstly. So if startAbility in onBackground() lifecycle,
10334             // the actual ability state may be had changed to terminating from background or backgrounding.
10335             abilityState == AbilityState::TERMINATING) {
10336             return ERR_OK;
10337         }
10338     } else if (AbilityPermissionUtil::GetInstance().IsStartSelfUIAbility()) {
10339         TAG_LOGI(AAFwkTag::ABILITYMGR, "call from capi, already checked background call");
10340         isBackgroundCall = false;
10341         return ERR_OK;
10342     } else {
10343         auto callerPid = IPCSkeleton::GetCallingPid();
10344         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
10345         if (processInfo.processName_.empty()) {
10346             TAG_LOGD(AAFwkTag::ABILITYMGR, "Can not find caller application by callerPid: %{private}d.", callerPid);
10347             if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
10348                 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
10349                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller has PERMISSION_START_ABILITIES_FROM_BACKGROUND, PASS.");
10350                 isBackgroundCall = false;
10351                 return ERR_OK;
10352             }
10353             TAG_LOGE(AAFwkTag::ABILITYMGR, "without PERMISSION_START_ABILITIES_FROM_BACKGROUND, REJECT");
10354             return ERR_INVALID_VALUE;
10355         }
10356     }
10357     return SetBackgroundCall(processInfo, abilityRequest, isBackgroundCall);
10358 }
10359 
SetBackgroundCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest,bool & isBackgroundCall) const10360 int32_t AbilityManagerService::SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo,
10361     const AbilityRequest &abilityRequest, bool &isBackgroundCall) const
10362 {
10363     if (IsDelegatorCall(processInfo, abilityRequest)) {
10364         TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
10365         isBackgroundCall = false;
10366         return ERR_OK;
10367     }
10368 
10369     if (backgroundJudgeFlag_) {
10370         isBackgroundCall = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND &&
10371             !processInfo.isFocused && !processInfo.isAbilityForegrounding;
10372     } else {
10373         isBackgroundCall = !processInfo.isFocused;
10374         if (!processInfo.isFocused && processInfo.state_ == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) {
10375             // Allow background startup within 1 second after application startup if state is FOREGROUND
10376             int64_t aliveTime = AbilityUtil::SystemTimeMillis() - processInfo.startTimeMillis_;
10377             isBackgroundCall = aliveTime > APP_ALIVE_TIME_MS;
10378             TAG_LOGD(AAFwkTag::ABILITYMGR, "Process %{public}s is alive %{public}s ms.",
10379                 processInfo.processName_.c_str(), std::to_string(aliveTime).c_str());
10380         }
10381     }
10382     TAG_LOGD(AAFwkTag::ABILITYMGR,
10383         "backgroundJudgeFlag: %{public}d, isBackgroundCall: %{public}d, callerAppState: %{public}d.",
10384         static_cast<int32_t>(backgroundJudgeFlag_),
10385         static_cast<int32_t>(isBackgroundCall),
10386         static_cast<int32_t>(processInfo.state_));
10387 
10388     return ERR_OK;
10389 }
10390 
IsTargetPermission(const Want & want) const10391 bool AbilityManagerService::IsTargetPermission(const Want &want) const
10392 {
10393     std::string bundleName = PERMISSIONMGR_BUNDLE_NAME;
10394     std::string abilityName = PERMISSIONMGR_ABILITY_NAME;
10395     Security::AccessToken::PermissionGrantInfo info;
10396     Security::AccessToken::AccessTokenKit::GetPermissionManagerInfo(info);
10397     if (!info.grantBundleName.empty() && !info.grantServiceAbilityName.empty()) {
10398         bundleName = info.grantBundleName;
10399         abilityName = info.grantServiceAbilityName;
10400     }
10401     if (want.GetElement().GetBundleName() == bundleName &&
10402         want.GetElement().GetAbilityName() == abilityName) {
10403         return true;
10404     }
10405 
10406     return false;
10407 }
10408 
IsDelegatorCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest) const10409 inline bool AbilityManagerService::IsDelegatorCall(
10410     const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest) const
10411 {
10412     /*  To make sure the AbilityDelegator is not counterfeited
10413      *   1. The caller-process must be test-process
10414      *   2. The callerToken must be nullptr
10415      */
10416     if (processInfo.isTestProcess &&
10417         !abilityRequest.callerToken && abilityRequest.want.GetBoolParam(IS_DELEGATOR_CALL, false)) {
10418         return true;
10419     }
10420     return false;
10421 }
10422 
CheckNewRuleSwitchState(const std::string & param)10423 bool AbilityManagerService::CheckNewRuleSwitchState(const std::string &param)
10424 {
10425     char value[NEW_RULE_VALUE_SIZE] = "false";
10426     int retSysParam = GetParameter(param.c_str(), "false", value, NEW_RULE_VALUE_SIZE);
10427     TAG_LOGI(AAFwkTag::ABILITYMGR, "checkNewRuleSwitchState, %{public}s value: %{public}s", param.c_str(), value);
10428     if (retSysParam > 0 && !std::strcmp(value, "true")) {
10429         return true;
10430     }
10431     return false;
10432 }
10433 
GetStartUpNewRuleFlag() const10434 bool AbilityManagerService::GetStartUpNewRuleFlag() const
10435 {
10436     return startUpNewRule_;
10437 }
10438 
CallRequestDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callStub)10439 void AbilityManagerService::CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)
10440 {
10441     {
10442         std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
10443         callStubTokenMap_[callStub] = token;
10444     }
10445     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10446     CHECK_POINTER(abilityRecord);
10447     if (!JudgeSelfCalled(abilityRecord)) {
10448         return;
10449     }
10450 
10451     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10452         auto uiAbilityManager = GetCurrentUIAbilityManager();
10453         CHECK_POINTER(uiAbilityManager);
10454         uiAbilityManager->CallRequestDone(abilityRecord, callStub);
10455         return;
10456     }
10457 
10458     auto missionListManager = GetCurrentMissionListManager();
10459     CHECK_POINTER(missionListManager);
10460     missionListManager->CallRequestDone(abilityRecord, callStub);
10461 }
10462 
GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> & callStub,sptr<IRemoteObject> & token)10463 void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)
10464 {
10465     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
10466     auto it = callStubTokenMap_.find(callStub);
10467     if (it == callStubTokenMap_.end()) {
10468         token = nullptr;
10469         return;
10470     }
10471     token = callStubTokenMap_[callStub];
10472 }
10473 
AddStartControlParam(Want & want,const sptr<IRemoteObject> & callerToken)10474 int AbilityManagerService::AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)
10475 {
10476     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10477     if (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
10478         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10479         return ERR_OK;
10480     }
10481     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
10482     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
10483     int32_t apiVersion = abilityRecord->GetApplicationInfo().apiTargetVersion;
10484     want.SetParam(DMS_API_VERSION, apiVersion);
10485     bool isCallerBackground = true;
10486     AppExecFwk::RunningProcessInfo processInfo;
10487     DelayedSingleton<AppScheduler>::GetInstance()->
10488         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
10489     if (backgroundJudgeFlag_) {
10490         isCallerBackground = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND;
10491     } else {
10492         isCallerBackground = !processInfo.isFocused;
10493     }
10494     want.SetParam(DMS_IS_CALLER_BACKGROUND, isCallerBackground);
10495     return ERR_OK;
10496 }
10497 
10498 #ifdef WITH_DLP
CheckDlpForExtension(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,EventInfo & eventInfo,const EventName & eventName)10499 int AbilityManagerService::CheckDlpForExtension(
10500     const Want &want, const sptr<IRemoteObject> &callerToken,
10501     int32_t userId, EventInfo &eventInfo, const EventName &eventName)
10502 {
10503     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10504     // check if form frs
10505     auto callingUid = IPCSkeleton::GetCallingUid();
10506     std::string bundleName = want.GetBundle();
10507     if (callingUid == FOUNDATION_UID && FRS_BUNDLE_NAME == bundleName) {
10508         return ERR_OK;
10509     }
10510 
10511     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
10512         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
10513         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
10514         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
10515         eventInfo.errCode = CHECK_PERMISSION_FAILED;
10516         EventReport::SendExtensionEvent(eventName, HiSysEventType::FAULT, eventInfo);
10517         return CHECK_PERMISSION_FAILED;
10518     }
10519     return ERR_OK;
10520 }
10521 #endif // WITH_DLP
10522 
JudgeSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)10523 bool AbilityManagerService::JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
10524 {
10525     if (IPCSkeleton::GetCallingPid() == getprocpid()) {
10526         return true;
10527     }
10528 
10529     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10530     CHECK_POINTER_RETURN_BOOL(abilityRecord);
10531     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10532     if (callingTokenId != tokenID) {
10533         TAG_LOGE(AAFwkTag::ABILITYMGR, "no self, no enabled, callingTokenId:%{public}u, tokenId:%{public}u", callingTokenId, tokenID);
10534         return false;
10535     }
10536 
10537     return true;
10538 }
10539 
IsAppSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)10540 bool AbilityManagerService::IsAppSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
10541 {
10542     CHECK_POINTER_RETURN_BOOL(abilityRecord);
10543     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10544     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10545     if (callingTokenId != tokenID) {
10546         TAG_LOGE(AAFwkTag::ABILITYMGR, "not app self called");
10547         return false;
10548     }
10549     return true;
10550 }
10551 
GetFocusAbility()10552 std::shared_ptr<AbilityRecord> AbilityManagerService::GetFocusAbility()
10553 {
10554 #ifdef SUPPORT_SCREEN
10555     sptr<IRemoteObject> token;
10556     if (!wmsHandler_) {
10557         TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
10558         return nullptr;
10559     }
10560 
10561     wmsHandler_->GetFocusWindow(token);
10562     if (!token) {
10563         TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
10564         return nullptr;
10565     }
10566 
10567     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10568     if (!abilityRecord) {
10569         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
10570     }
10571     return abilityRecord;
10572 #endif
10573 
10574     return nullptr;
10575 }
10576 
CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId,bool & isFocused)10577 int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)
10578 {
10579     sptr<IRemoteObject> token;
10580     auto ret = GetTopAbility(token);
10581     if (ret != ERR_OK) {
10582         TAG_LOGE(AAFwkTag::ABILITYMGR, "getTopAbility failed");
10583         return ret;
10584     }
10585 
10586     auto topAbility = Token::GetAbilityRecordByToken(token);
10587     if (topAbility != nullptr) {
10588         TAG_LOGD(AAFwkTag::ABILITYMGR, "top ability: %{public}s, pid: %{public}d, tokenId: %{public}d",
10589             topAbility->GetWant().GetElement().GetURI().c_str(), topAbility->GetPid(),
10590             topAbility->GetApplicationInfo().accessTokenId);
10591     }
10592 
10593     bool focused = false;
10594     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10595     auto connectManager = GetConnectManagerByUserId(userId);
10596     if (connectManager) {
10597         focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
10598             || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
10599     } else {
10600         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:%{public}d", userId);
10601     }
10602     if (!focused && userId != U0_USER_ID) {
10603         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check connectManager in user0");
10604         connectManager = GetConnectManagerByUserId(U0_USER_ID);
10605         if (connectManager) {
10606             focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
10607                 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
10608         } else {
10609             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId: 0");
10610         }
10611     }
10612     isFocused = focused;
10613     TAG_LOGD(AAFwkTag::ABILITYMGR, "isFocused: %{public}d", isFocused);
10614     return ERR_OK;
10615 }
10616 
AddFreeInstallObserver(const sptr<IRemoteObject> & callerToken,const sptr<AbilityRuntime::IFreeInstallObserver> & observer)10617 int AbilityManagerService::AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken,
10618     const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
10619 {
10620     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10621     if (freeInstallManager_ == nullptr) {
10622         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
10623         return ERR_INVALID_VALUE;
10624     }
10625     return freeInstallManager_->AddFreeInstallObserver(callerToken, observer);
10626 }
10627 
IsValidMissionIds(const std::vector<int32_t> & missionIds,std::vector<MissionValidResult> & results)10628 int32_t AbilityManagerService::IsValidMissionIds(
10629     const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)
10630 {
10631     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
10632     auto missionlistMgr = GetMissionListManagerByUserId(userId);
10633     if (missionlistMgr == nullptr) {
10634         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionlistMgr null");
10635         return ERR_INVALID_VALUE;
10636     }
10637 
10638     return missionlistMgr->IsValidMissionIds(missionIds, results);
10639 }
10640 
VerifyPermission(const std::string & permission,int pid,int uid)10641 int AbilityManagerService::VerifyPermission(const std::string &permission, int pid, int uid)
10642 {
10643     TAG_LOGI(AAFwkTag::ABILITYMGR, "permission=%{public}s, pid=%{public}d, uid=%{public}d",
10644         permission.c_str(),
10645         pid,
10646         uid);
10647     if (permission.empty()) {
10648         TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission permission invalid");
10649         return CHECK_PERMISSION_FAILED;
10650     }
10651 
10652     auto bms = AbilityUtil::GetBundleManagerHelper();
10653     CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
10654 
10655     std::string bundleName;
10656     if (IN_PROCESS_CALL(bms->GetNameForUid(uid, bundleName)) != ERR_OK) {
10657         TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission get bundle name failed");
10658         return CHECK_PERMISSION_FAILED;
10659     }
10660 
10661     int account = -1;
10662     DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, account);
10663     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, account: %{private}d", bundleName.c_str(), account);
10664     AppExecFwk::ApplicationInfo appInfo;
10665     if (!IN_PROCESS_CALL(bms->GetApplicationInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
10666         account, appInfo))) {
10667         TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission get application info failed");
10668         return CHECK_PERMISSION_FAILED;
10669     }
10670 
10671     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false);
10672     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
10673         TAG_LOGE(AAFwkTag::ABILITYMGR, "PERMISSION_DENIED");
10674         return CHECK_PERMISSION_FAILED;
10675     }
10676 
10677     return ERR_OK;
10678 }
10679 
AcquireShareData(const int32_t & missionId,const sptr<IAcquireShareDataCallback> & shareData)10680 int32_t AbilityManagerService::AcquireShareData(
10681     const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)
10682 {
10683     TAG_LOGD(AAFwkTag::ABILITYMGR, "missionId is %{public}d.", missionId);
10684     CHECK_CALLER_IS_SYSTEM_APP;
10685     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
10686     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10687         auto uiAbilityManager = GetCurrentUIAbilityManager();
10688         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10689         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
10690     } else {
10691         auto missionListManager = GetCurrentMissionListManager();
10692         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
10693         abilityRecord = missionListManager->GetAbilityRecordByMissionId(missionId);
10694     }
10695     if (!abilityRecord) {
10696         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
10697         return ERR_INVALID_VALUE;
10698     }
10699     std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
10700     uniqueId_ = (uniqueId_ == INT_MAX) ? 0 : (uniqueId_ + 1);
10701     std::pair<int64_t, const sptr<IAcquireShareDataCallback>> shareDataPair =
10702         std::make_pair(abilityRecord->GetAbilityRecordId(), shareData);
10703     iAcquireShareDataMap_.emplace(uniqueId_, shareDataPair);
10704     abilityRecord->ShareData(uniqueId_);
10705     return ERR_OK;
10706 }
10707 
ShareDataDone(const sptr<IRemoteObject> & token,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)10708 int32_t AbilityManagerService::ShareDataDone(
10709     const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
10710 {
10711     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d", resultCode, uniqueId);
10712     if (!VerificationAllToken(token)) {
10713         return ERR_INVALID_VALUE;
10714     }
10715     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10716     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record is nullptr.");
10717     if (!JudgeSelfCalled(abilityRecord)) {
10718         return CHECK_PERMISSION_FAILED;
10719     }
10720     CHECK_POINTER_AND_RETURN_LOG(eventHandler_, ERR_INVALID_VALUE, "fail to get abilityEventHandler.");
10721     eventHandler_->RemoveEvent(SHAREDATA_TIMEOUT_MSG, uniqueId);
10722     return GetShareDataPairAndReturnData(abilityRecord, resultCode, uniqueId, wantParam);
10723 }
10724 
NotifySaveAsResult(const Want & want,int resultCode,int requestCode)10725 int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCode, int requestCode)
10726 {
10727     TAG_LOGD(AAFwkTag::ABILITYMGR, "requestCode is %{public}d.", requestCode);
10728     CHECK_CALLER_IS_SYSTEM_APP;
10729 #ifdef WITH_DLP
10730     //caller check
10731     if (!DlpUtils::CheckCallerIsDlpManager(AbilityUtil::GetBundleManagerHelper())) {
10732         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller check failed");
10733         return CHECK_PERMISSION_FAILED;
10734     }
10735 #endif // WITH_DLP
10736     auto checkResult = AbilityUtil::CheckInstanceKey(want);
10737     if (checkResult != ERR_OK) {
10738         return checkResult;
10739     }
10740     for (const auto &item : startAbilityChain_) {
10741         if (item.second && item.second->GetHandlerName() == StartAbilitySandboxSavefile::handlerName_) {
10742             auto savefileHandler = (StartAbilitySandboxSavefile*)(item.second.get());
10743             CHECK_POINTER_AND_RETURN(savefileHandler, ERR_INVALID_VALUE);
10744             savefileHandler->HandleResult(want, resultCode, requestCode);
10745             break;
10746         }
10747     }
10748     return ERR_OK;
10749 }
10750 
SetRootSceneSession(const sptr<IRemoteObject> & rootSceneSession)10751 void AbilityManagerService::SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)
10752 {
10753     if (!IsCallerSceneBoard()) {
10754         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10755         return;
10756     }
10757     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10758     CHECK_POINTER(uiAbilityManager);
10759     uiAbilityManager->SetRootSceneSession(rootSceneSession);
10760 }
10761 
CallUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isColdStart)10762 void AbilityManagerService::CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isColdStart)
10763 {
10764     if (!IsCallerSceneBoard()) {
10765         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10766         return;
10767     }
10768     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10769     CHECK_POINTER(uiAbilityManager);
10770     uiAbilityManager->CallUIAbilityBySCB(sessionInfo, isColdStart);
10771 }
10772 
SetSessionManagerService(const sptr<IRemoteObject> & sessionManagerService)10773 int32_t AbilityManagerService::SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)
10774 {
10775     if (!IsCallerSceneBoard()) {
10776         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10777         return ERR_WRONG_INTERFACE_CALL;
10778     }
10779 
10780     TAG_LOGI(AAFwkTag::ABILITYMGR, "call setSessionManagerService of WMS");
10781     bool ret = Rosen::MockSessionManagerService::GetInstance().SetSessionManagerService(sessionManagerService);
10782     if (ret) {
10783         TAG_LOGD(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10784         return ERR_OK;
10785     }
10786     TAG_LOGE(AAFwkTag::ABILITYMGR, "SMS setSessionManagerService return false");
10787     return SET_SMS_FAILED;
10788 }
10789 
StartSpecifiedAbilityBySCB(const Want & want)10790 void AbilityManagerService::StartSpecifiedAbilityBySCB(const Want &want)
10791 {
10792     if (!IsCallerSceneBoard()) {
10793         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10794         return;
10795     }
10796     int32_t appIndex = 0;
10797     if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex)) {
10798         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app clone index");
10799     }
10800     (void)AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
10801         GetUserId(), appIndex, nullptr);
10802     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10803     CHECK_POINTER(uiAbilityManager);
10804     uiAbilityManager->StartSpecifiedAbilityBySCB(want);
10805 }
10806 
RegisterIAbilityManagerCollaborator(int32_t type,const sptr<IAbilityManagerCollaborator> & impl)10807 int32_t AbilityManagerService::RegisterIAbilityManagerCollaborator(
10808     int32_t type, const sptr<IAbilityManagerCollaborator> &impl)
10809 {
10810     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10811     auto callingUid = IPCSkeleton::GetCallingUid();
10812     if (!isSaCall || (callingUid != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
10813         callingUid != AppUtils::GetInstance().GetCollaboratorBrokerReserveUID())) {
10814         TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
10815         return CHECK_PERMISSION_FAILED;
10816     }
10817     if (!CheckCollaboratorType(type)) {
10818         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator register failed, invalid type");
10819         return ERR_INVALID_VALUE;
10820     }
10821     {
10822         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10823         collaboratorMap_[type] = impl;
10824     }
10825     return ERR_OK;
10826 }
10827 
UnregisterIAbilityManagerCollaborator(int32_t type)10828 int32_t AbilityManagerService::UnregisterIAbilityManagerCollaborator(int32_t type)
10829 {
10830     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10831     auto callingUid = IPCSkeleton::GetCallingUid();
10832     if (!isSaCall || (callingUid != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
10833         callingUid != AppUtils::GetInstance().GetCollaboratorBrokerReserveUID())) {
10834         TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
10835         return CHECK_PERMISSION_FAILED;
10836     }
10837     if (!CheckCollaboratorType(type)) {
10838         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator unregister failed, invalid type");
10839         return ERR_INVALID_VALUE;
10840     }
10841     {
10842         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10843         collaboratorMap_.erase(type);
10844     }
10845     return ERR_OK;
10846 }
10847 
GetCollaborator(int32_t type)10848 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetCollaborator(int32_t type)
10849 {
10850     if (!CheckCollaboratorType(type)) {
10851         return nullptr;
10852     }
10853     {
10854         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10855         auto it = collaboratorMap_.find(type);
10856         if (it != collaboratorMap_.end()) {
10857             return it->second;
10858         }
10859     }
10860     return nullptr;
10861 }
10862 
CheckCollaboratorType(int32_t type)10863 bool AbilityManagerService::CheckCollaboratorType(int32_t type)
10864 {
10865     if (type != CollaboratorType::RESERVE_TYPE && type != CollaboratorType::OTHERS_TYPE) {
10866         return false;
10867     }
10868     return true;
10869 }
10870 
GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> & sessionInfo,std::shared_ptr<AbilityConnectManager> & connectManager,std::shared_ptr<AbilityRecord> & targetAbility,bool needCheck)10871 void AbilityManagerService::GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo,
10872     std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility,
10873     bool needCheck)
10874 {
10875     targetAbility = nullptr;
10876     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10877     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId=%{public}d", userId);
10878     connectManager = GetConnectManagerByUserId(userId);
10879     if (connectManager) {
10880         targetAbility = connectManager->GetUIExtensionBySessionInfo(sessionInfo);
10881         if (needCheck && targetAbility == nullptr) {
10882             targetAbility = connectManager->GetUIExtensionBySessionFromServiceMap(sessionInfo);
10883         }
10884     } else {
10885         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:%{public}d", userId);
10886     }
10887     if (targetAbility == nullptr && userId != U0_USER_ID) {
10888         TAG_LOGD(AAFwkTag::ABILITYMGR, "try to find UIExtension in user0");
10889         connectManager = GetConnectManagerByUserId(U0_USER_ID);
10890         if (connectManager) {
10891             targetAbility = connectManager->GetUIExtensionBySessionInfo(sessionInfo);
10892             if (needCheck && targetAbility == nullptr) {
10893                 targetAbility = connectManager->GetUIExtensionBySessionFromServiceMap(sessionInfo);
10894             }
10895         } else {
10896             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:0");
10897         }
10898     }
10899 }
10900 
RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)10901 int32_t AbilityManagerService::RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)
10902 {
10903     if (!IsCallerSceneBoard()) {
10904         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10905         return ERR_WRONG_INTERFACE_CALL;
10906     }
10907     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10908     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10909     return uiAbilityManager->RegisterStatusBarDelegate(delegate);
10910 }
10911 
KillProcessWithPrepareTerminate(const std::vector<int32_t> & pids)10912 int32_t AbilityManagerService::KillProcessWithPrepareTerminate(const std::vector<int32_t>& pids)
10913 {
10914     if (!IsCallerSceneBoard()) {
10915         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10916         return ERR_WRONG_INTERFACE_CALL;
10917     }
10918     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10919     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10920     return uiAbilityManager->TryPrepareTerminateByPids(pids);
10921 }
10922 
ProcessLowMemoryKill(int32_t pid,const ExitReason & reason)10923 bool AbilityManagerService::ProcessLowMemoryKill(int32_t pid, const ExitReason &reason)
10924 {
10925     if (reason.reason != Reason::REASON_RESOURCE_CONTROL || reason.exitMsg != GlobalConstant::LOW_MEMORY_KILL) {
10926         return false;
10927     }
10928     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10929     if (uiAbilityManager == nullptr) {
10930         TAG_LOGW(AAFwkTag::ABILITYMGR, "null uiAbilityManager");
10931         return false;
10932     }
10933     if (uiAbilityManager->IsBundleStarting(pid)) {
10934         return true;
10935     }
10936     // set ability record kill reason
10937     uiAbilityManager->RecordPidKilling(pid, GlobalConstant::LOW_MEMORY_KILL);
10938     return false;
10939 }
10940 
KillProcessWithReason(int32_t pid,const ExitReason & reason)10941 int32_t AbilityManagerService::KillProcessWithReason(int32_t pid, const ExitReason &reason)
10942 {
10943     bool supportShell = AmsConfigurationParameter::GetInstance().IsSupportAAKillWithReason();
10944     auto isShellCall = PermissionVerification::GetInstance()->IsShellCall();
10945     auto isCallingPerm = PermissionVerification::GetInstance()->VerifyCallingPermission(
10946         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
10947     if (!isCallingPerm && !(supportShell && isShellCall)) {
10948         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
10949         return ERR_PERMISSION_DENIED;
10950     }
10951 
10952     if (ProcessLowMemoryKill(pid, reason)) {
10953         // if app is already starting, return
10954         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}d is starting", pid);
10955         return ERR_OK;
10956     }
10957 
10958     TAG_LOGI(AAFwkTag::ABILITYMGR, "pid:%{public}d, reason:%{public}d, subReason:%{public}d, killMsg:%{public}s",
10959         pid, reason.reason, reason.subReason, reason.exitMsg.c_str());
10960     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
10961     auto ret = appExitReasonHelper_->RecordProcessExitReason(pid, reason, true);
10962     if (ret != ERR_OK && ret != ERR_GET_ACTIVE_ABILITY_LIST_EMPTY) {
10963         TAG_LOGE(AAFwkTag::ABILITYMGR, "RecordAppExitReason failed, ret:%{public}d", ret);
10964         return ret;
10965     }
10966     std::vector<int32_t> pidToBeKilled = { pid };
10967     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppScheduler>::GetInstance()->KillProcessesByPids(pidToBeKilled,
10968         reason.exitMsg));
10969     return ERR_OK;
10970 }
10971 
RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10972 int32_t AbilityManagerService::RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10973 {
10974     if (abilityAutoStartupService_ == nullptr) {
10975         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10976         return ERR_NO_INIT;
10977     }
10978     return abilityAutoStartupService_->RegisterAutoStartupSystemCallback(callback);
10979 }
10980 
UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10981 int32_t AbilityManagerService::UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10982 {
10983     if (abilityAutoStartupService_ == nullptr) {
10984         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10985         return ERR_NO_INIT;
10986     }
10987     return abilityAutoStartupService_->UnregisterAutoStartupSystemCallback(callback);
10988 }
10989 
SetApplicationAutoStartup(const AutoStartupInfo & info)10990 int32_t AbilityManagerService::SetApplicationAutoStartup(const AutoStartupInfo &info)
10991 {
10992     if (abilityAutoStartupService_ == nullptr) {
10993         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10994         return ERR_NO_INIT;
10995     }
10996     return abilityAutoStartupService_->SetApplicationAutoStartup(info);
10997 }
10998 
CancelApplicationAutoStartup(const AutoStartupInfo & info)10999 int32_t AbilityManagerService::CancelApplicationAutoStartup(const AutoStartupInfo &info)
11000 {
11001     if (abilityAutoStartupService_ == nullptr) {
11002         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
11003         return ERR_NO_INIT;
11004     }
11005     return abilityAutoStartupService_->CancelApplicationAutoStartup(info);
11006 }
11007 
QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> & infoList)11008 int32_t AbilityManagerService::QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)
11009 {
11010     if (abilityAutoStartupService_ == nullptr) {
11011         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
11012         return ERR_NO_INIT;
11013     }
11014     return abilityAutoStartupService_->QueryAllAutoStartupApplications(infoList, GetUserId());
11015 }
11016 
PrepareTerminateAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isTerminate)11017 int AbilityManagerService::PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)
11018 {
11019     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11020     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
11021     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
11022         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
11023         return ERR_INVALID_VALUE;
11024     }
11025 
11026     if (!IsCallerSceneBoard()) {
11027         TAG_LOGE(AAFwkTag::ABILITYMGR, "not sceneboard called, not allowed");
11028         return ERR_WRONG_INTERFACE_CALL;
11029     }
11030 
11031     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11032     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11033     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
11034     isTerminate = uiAbilityManager->PrepareTerminateAbility(abilityRecord, true);
11035 
11036     return ERR_OK;
11037 }
11038 
RegisterSessionHandler(const sptr<IRemoteObject> & object)11039 int AbilityManagerService::RegisterSessionHandler(const sptr<IRemoteObject> &object)
11040 {
11041     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
11042     if (!IsCallerSceneBoard()) {
11043         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11044         return ERR_WRONG_INTERFACE_CALL;
11045     }
11046     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11047     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11048     sptr<ISessionHandler> handler = iface_cast<ISessionHandler>(object);
11049     uiAbilityManager->SetSessionHandler(handler);
11050     return ERR_OK;
11051 }
11052 
CheckProcessOptions(const Want & want,const StartOptions & startOptions,int32_t userId)11053 int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const StartOptions &startOptions, int32_t userId)
11054 {
11055     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11056     if (startOptions.processOptions == nullptr ||
11057         (!ProcessOptions::IsValidProcessMode(startOptions.processOptions->processMode) &&
11058         !startOptions.processOptions->isRestartKeepAlive)) {
11059         return ERR_OK;
11060     }
11061 
11062     TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability with process options");
11063     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
11064     CHECK_TRUE_RETURN_RET(!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable,
11065         ERR_CAPABILITY_NOT_SUPPORT, "not support process options");
11066 
11067     auto element = want.GetElement();
11068     CHECK_TRUE_RETURN_RET(element.GetAbilityName().empty() || want.GetAction().compare(ACTION_CHOOSE) == 0,
11069         ERR_NOT_ALLOW_IMPLICIT_START, "not allow implicit start");
11070 
11071     if (PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)
11072         && startOptions.processOptions->isRestartKeepAlive) {
11073         TAG_LOGI(AAFwkTag::ABILITYMGR, "restart keep-alive app.");
11074         return ERR_OK;
11075     }
11076 
11077     int32_t appIndex = 0;
11078     appIndex = !AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex) ? 0 : appIndex;
11079     CHECK_TRUE_RETURN_RET(!CheckCallingTokenId(element.GetBundleName(), userId, appIndex),
11080         ERR_NOT_SELF_APPLICATION, "not self application");
11081 
11082     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11083     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11084 
11085     auto callerPid = IPCSkeleton::GetCallingPid();
11086     AppExecFwk::RunningProcessInfo processInfo;
11087     DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
11088     CHECK_TRUE_RETURN_RET((ProcessOptions::IsAttachToStatusBarMode(startOptions.processOptions->processMode) &&
11089         !uiAbilityManager->IsCallerInStatusBar(processInfo.instanceKey)), ERR_START_OPTIONS_CHECK_FAILED,
11090         "not in status bar");
11091 
11092     auto abilityRecords = uiAbilityManager->GetAbilityRecordsByName(element);
11093     CHECK_TRUE_RETURN_RET(!abilityRecords.empty() && abilityRecords[0] &&
11094         abilityRecords[0]->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::STANDARD &&
11095         abilityRecords[0]->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::SPECIFIED,
11096         ERR_ABILITY_ALREADY_RUNNING, "if not STANDARD or SPECIFIED mode, repeated starts not allowed");
11097 
11098     return ERR_OK;
11099 }
11100 
CheckStartSelfUIAbilityStartOptions(const Want & want,const StartOptions & startOptions)11101 int32_t AbilityManagerService::CheckStartSelfUIAbilityStartOptions(const Want &want, const StartOptions &startOptions)
11102 {
11103     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11104     if (startOptions.processOptions == nullptr) {
11105         return ERR_OK;
11106     }
11107 
11108     TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability with process options");
11109     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
11110     CHECK_TRUE_RETURN_RET(!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable,
11111         ERR_CAPABILITY_NOT_SUPPORT, "not support process options");
11112 
11113     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11114     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11115 
11116     auto callerPid = IPCSkeleton::GetCallingPid();
11117     AppExecFwk::RunningProcessInfo processInfo;
11118     DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByChildProcessPid(callerPid, processInfo);
11119     CHECK_TRUE_RETURN_RET(!uiAbilityManager->IsCallerInStatusBar(processInfo.instanceKey), ERR_START_OPTIONS_CHECK_FAILED,
11120         "not in status bar");
11121 
11122     return ERR_OK;
11123 }
11124 
RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)11125 int32_t AbilityManagerService::RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
11126 {
11127     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11128     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
11129         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
11130         return CHECK_PERMISSION_FAILED;
11131     }
11132     return DelayedSingleton<AppScheduler>::GetInstance()->RegisterAppDebugListener(listener);
11133 }
11134 
UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)11135 int32_t AbilityManagerService::UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
11136 {
11137     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11138     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
11139         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
11140         return CHECK_PERMISSION_FAILED;
11141     }
11142     return DelayedSingleton<AppScheduler>::GetInstance()->UnregisterAppDebugListener(listener);
11143 }
11144 
ConnectInitAbilityDebugDeal()11145 std::shared_ptr<AbilityDebugDeal> AbilityManagerService::ConnectInitAbilityDebugDeal()
11146 {
11147     if (abilityDebugDeal_ != nullptr) {
11148         return abilityDebugDeal_;
11149     }
11150 
11151     std::unique_lock<ffrt::mutex> lock(abilityDebugDealLock_);
11152     if (abilityDebugDeal_ != nullptr) {
11153         return abilityDebugDeal_;
11154     }
11155 
11156     TAG_LOGD(AAFwkTag::ABILITYMGR, "Creat ability debug deal object.");
11157     abilityDebugDeal_ = std::make_shared<AbilityDebugDeal>();
11158     if (abilityDebugDeal_ == nullptr) {
11159         TAG_LOGE(AAFwkTag::ABILITYMGR, "creat ability debug deal object failed");
11160         return nullptr;
11161     }
11162 
11163     abilityDebugDeal_->RegisterAbilityDebugResponse();
11164     return abilityDebugDeal_;
11165 }
11166 
AttachAppDebug(const std::string & bundleName,bool isDebugFromLocal)11167 int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName, bool isDebugFromLocal)
11168 {
11169     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11170     if (isDebugFromLocal && !AAFwk::PermissionVerification::GetInstance()-> VerifyStartLocalDebug()) {
11171         TAG_LOGE(AAFwkTag::ABILITYMGR, "local debugging, permission denied");
11172         return CHECK_PERMISSION_FAILED;
11173     } else if (!isDebugFromLocal && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
11174         TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
11175         return ERR_NOT_DEVELOPER_MODE;
11176     }
11177 
11178     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
11179         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
11180         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
11181         return CHECK_PERMISSION_FAILED;
11182     }
11183 
11184     int32_t err = ERR_OK;
11185     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
11186     if ((err = StartAbilityUtils::CheckAppProvisionMode(bundleName, userId)) != ERR_OK) {
11187         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckAppProvisionMode returns errcode=%{public}d", err);
11188         return err;
11189     }
11190 
11191     ConnectInitAbilityDebugDeal();
11192     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->AttachAppDebug(bundleName, isDebugFromLocal));
11193 }
11194 
DetachAppDebug(const std::string & bundleName,bool isDebugFromLocal)11195 int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName, bool isDebugFromLocal)
11196 {
11197     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11198     if (isDebugFromLocal && !AAFwk::PermissionVerification::GetInstance()-> VerifyStartLocalDebug()) {
11199         TAG_LOGE(AAFwkTag::ABILITYMGR, "local debugging, permission denied");
11200         return CHECK_PERMISSION_FAILED;
11201     } else if (!isDebugFromLocal && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
11202         TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
11203         return ERR_NOT_DEVELOPER_MODE;
11204     }
11205 
11206     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
11207         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
11208         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
11209         return CHECK_PERMISSION_FAILED;
11210     }
11211 
11212     int32_t err = ERR_OK;
11213     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
11214     if ((err = StartAbilityUtils::CheckAppProvisionMode(bundleName, userId)) != ERR_OK) {
11215         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckAppProvisionMode returns errcode=%{public}d", err);
11216         return err;
11217     }
11218 
11219     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->DetachAppDebug(bundleName));
11220 }
11221 
InsightIntentGetcallerBundleName()11222 std::string AbilityManagerService::InsightIntentGetcallerBundleName()
11223 {
11224     TAG_LOGD(AAFwkTag::ABILITYMGR, "InsightIntentGetcallerBundleName called");
11225     int32_t callerUid = IPCSkeleton::GetCallingUid();
11226     auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
11227     std::string callerBundlename;
11228     if (bundleMgr != nullptr) {
11229        IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, callerBundlename));
11230     }
11231     return callerBundlename;
11232 }
11233 
ExecuteIntent(uint64_t key,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)11234 int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken,
11235     const InsightIntentExecuteParam &param)
11236 {
11237     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11238     auto callerBundlename = InsightIntentGetcallerBundleName();
11239     if (callerBundlename.empty()) {
11240         TAG_LOGD(AAFwkTag::ABILITYMGR, "callerBundlename is null");
11241     }
11242 
11243     auto paramPtr = std::make_shared<InsightIntentExecuteParam>(param);
11244     int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateParam(key, callerToken,
11245         paramPtr, callerBundlename);
11246     if (ret != ERR_OK) {
11247         return ret;
11248     }
11249 
11250     Want want;
11251     ret = InsightIntentExecuteManager::GenerateWant(paramPtr, want);
11252     if (ret != ERR_OK) {
11253         return ret;
11254     }
11255 
11256     switch (param.executeMode_) {
11257         case AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND:
11258             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_FOREGROUND.");
11259             ret = StartAbilityWithInsightIntent(want);
11260             break;
11261         case AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND: {
11262             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_BACKGROUND.");
11263             ret = StartAbilityByCallWithInsightIntent(want, callerToken, param);
11264             break;
11265         }
11266         case AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY:
11267             TAG_LOGW(AAFwkTag::ABILITYMGR, "executeMode UI_EXTENSION_ABILITY not supported");
11268             ret = ERR_INVALID_OPERATION;
11269             break;
11270         case AppExecFwk::ExecuteMode::SERVICE_EXTENSION_ABILITY:
11271             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode SERVICE_EXTENSION_ABILITY.");
11272             ret = StartExtensionAbilityWithInsightIntent(want, AppExecFwk::ExtensionAbilityType::SERVICE);
11273             break;
11274         default:
11275             TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid executeMode");
11276             ret = ERR_INVALID_OPERATION;
11277             break;
11278     }
11279     if (ret == START_ABILITY_WAITING) {
11280         TAG_LOGD(AAFwkTag::ABILITYMGR, "Top ability is foregrounding. The intent will be queued for execution");
11281         ret = ERR_OK;
11282     }
11283     if (ret != ERR_OK) {
11284         DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->RemoveExecuteIntent(paramPtr->insightIntentId_);
11285     }
11286 
11287     TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteIntent done, ret: %{public}d.", ret);
11288     return ret;
11289 }
11290 
IsAbilityStarted(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord,const int32_t oriValidUserId)11291 bool AbilityManagerService::IsAbilityStarted(AbilityRequest &abilityRequest,
11292     std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)
11293 {
11294     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11295         TAG_LOGI(AAFwkTag::ABILITYMGR, "scene board enable");
11296         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
11297         CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
11298         return uiAbilityManager->IsAbilityStarted(abilityRequest, targetRecord);
11299     }
11300 
11301     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
11302     if (missionListMgr == nullptr) {
11303         return false;
11304     }
11305     return missionListMgr->IsAbilityStarted(abilityRequest, targetRecord);
11306 }
11307 
OnExecuteIntent(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord)11308 int32_t AbilityManagerService::OnExecuteIntent(AbilityRequest &abilityRequest,
11309     std::shared_ptr<AbilityRecord> &targetRecord)
11310 {
11311     TAG_LOGI(AAFwkTag::ABILITYMGR, "onExecuteIntent");
11312     if (targetRecord == nullptr || targetRecord->GetScheduler() == nullptr) {
11313         TAG_LOGE(AAFwkTag::ABILITYMGR, "null scheduler");
11314         return ERR_INVALID_VALUE;
11315     }
11316     targetRecord->GetScheduler()->OnExecuteIntent(abilityRequest.want);
11317 
11318     return ERR_OK;
11319 }
11320 
StartAbilityWithInsightIntent(const Want & want,int32_t userId,int requestCode)11321 int32_t AbilityManagerService::StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)
11322 {
11323     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11324     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
11325     if (startWithAccount || IsCrossUserCall(userId)) {
11326         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
11327         CHECK_CALLER_IS_SYSTEM_APP;
11328     }
11329     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
11330     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
11331     EventInfo eventInfo = BuildEventInfo(want, userId);
11332     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
11333     int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
11334     if (ret != ERR_OK) {
11335         eventInfo.errCode = ret;
11336         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
11337     }
11338     return ret;
11339 }
11340 
StartExtensionAbilityWithInsightIntent(const Want & want,AppExecFwk::ExtensionAbilityType extensionType)11341 int32_t AbilityManagerService::StartExtensionAbilityWithInsightIntent(const Want &want,
11342     AppExecFwk::ExtensionAbilityType extensionType)
11343 {
11344     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11345     return StartExtensionAbilityInner(want, nullptr, DEFAULT_INVAL_VALUE, extensionType, true);
11346 }
11347 
StartAbilityByCallWithInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)11348 int32_t AbilityManagerService::StartAbilityByCallWithInsightIntent(const Want &want,
11349     const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam &param)
11350 {
11351     TAG_LOGI(AAFwkTag::ABILITYMGR, "call startAbilityByCallWithInsightIntent");
11352     sptr<IAbilityConnection> connect = sptr<AbilityBackgroundConnection>::MakeSptr();
11353     if (connect == nullptr) {
11354         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid connect");
11355         return ERR_INVALID_VALUE;
11356     }
11357 
11358     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
11359     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
11360     AbilityRequest abilityRequest;
11361     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
11362     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
11363     abilityRequest.callerToken = callerToken;
11364     abilityRequest.startSetting = nullptr;
11365     abilityRequest.want = want;
11366     abilityRequest.connect = connect;
11367     int32_t result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
11368     if (result != ERR_OK) {
11369         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request error");
11370         return result;
11371     }
11372     std::shared_ptr<AbilityRecord> targetRecord;
11373     int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
11374     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
11375     if (IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId)) {
11376         TAG_LOGI(AAFwkTag::ABILITYMGR, "ability has already started");
11377         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
11378         result = OnExecuteIntent(abilityRequest, targetRecord);
11379     }  else {
11380         result = StartAbilityByCall(want, connect, callerToken);
11381     }
11382     ResSchedUtil::GetInstance().ReportAbilityIntentExemptionInfoToRSS(abilityRequest.uid, 0);
11383     DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->SetIntentExemptionInfo(
11384         abilityRequest.uid);
11385     TAG_LOGI(AAFwkTag::ABILITYMGR, "startAbilityByCallWithInsightIntent %{public}d uid:%{public}d",
11386         result, abilityRequest.uid);
11387     return result;
11388 }
11389 
IsAbilityControllerStart(const Want & want)11390 bool AbilityManagerService::IsAbilityControllerStart(const Want &want)
11391 {
11392     auto callingUid = IPCSkeleton::GetCallingUid();
11393     bool isBrokerCall = (callingUid == AppUtils::GetInstance().GetCollaboratorBrokerUID() ||
11394         callingUid == AppUtils::GetInstance().GetCollaboratorBrokerReserveUID());
11395     if (isBrokerCall) {
11396         return IsAbilityControllerStart(want, want.GetBundle());
11397     }
11398     TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
11399     return true;
11400 }
11401 
ExecuteInsightIntentDone(const sptr<IRemoteObject> & token,uint64_t intentId,const InsightIntentExecuteResult & result)11402 int32_t AbilityManagerService::ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId,
11403     const InsightIntentExecuteResult &result)
11404 {
11405     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11406     auto abilityRecord = Token::GetAbilityRecordByToken(token);
11407     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
11408     if (!JudgeSelfCalled(abilityRecord)) {
11409         return CHECK_PERMISSION_FAILED;
11410     }
11411 
11412     // check send by same bundleName.
11413     std::string bundleNameStored = "";
11414     auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetBundleName(intentId, bundleNameStored);
11415     if (ret != ERR_OK) {
11416         TAG_LOGE(AAFwkTag::ABILITYMGR, "matched bundleName failed, intentId:%{public}" PRIu64"", intentId);
11417         return ERR_INVALID_VALUE;
11418     }
11419 
11420     std::string bundleName = abilityRecord->GetAbilityInfo().bundleName;
11421     if (bundleNameStored != bundleName) {
11422         TAG_LOGE(AAFwkTag::ABILITYMGR,
11423             "bundleName %{public}s and %{public}s mismatch", bundleName.c_str(), bundleNameStored.c_str());
11424         return ERR_INVALID_VALUE;
11425     }
11426 
11427     std::string callerBundleName;
11428     DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetCallerBundleName(intentId, callerBundleName);
11429     uint32_t initiatorTokenId = abilityRecord->GetApplicationInfo().accessTokenId;
11430 #ifdef SUPPORT_UPMS
11431     if (!callerBundleName.empty()) {
11432         abilityRecord->GrantUriPermission(result.uris, result.flags, callerBundleName, initiatorTokenId);
11433     }
11434 #endif // SUPPORT_UPMS
11435 
11436     return DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
11437         intentId, result.innerErr, result);
11438 }
11439 
SetApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)11440 int32_t AbilityManagerService::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
11441 {
11442     if (abilityAutoStartupService_ == nullptr) {
11443         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
11444         return ERR_NO_INIT;
11445     }
11446     return abilityAutoStartupService_->SetApplicationAutoStartupByEDM(info, flag);
11447 }
11448 
CancelApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)11449 int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
11450 {
11451     if (abilityAutoStartupService_ == nullptr) {
11452         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
11453         return ERR_NO_INIT;
11454     }
11455     return abilityAutoStartupService_->CancelApplicationAutoStartupByEDM(info, flag);
11456 }
11457 
GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> & list)11458 int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)
11459 {
11460     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11461     CHECK_CALLER_IS_SYSTEM_APP;
11462     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
11463     if (!isPerm) {
11464         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
11465         return CHECK_PERMISSION_FAILED;
11466     }
11467 
11468     std::vector<AbilityRunningInfo> abilityRunningInfos;
11469     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11470         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11471         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11472         uiAbilityManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
11473     } else {
11474         auto missionListManager = GetCurrentMissionListManager();
11475         CHECK_POINTER_AND_RETURN(missionListManager, ERR_NULL_OBJECT);
11476         missionListManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
11477     }
11478 
11479     for (auto &info : abilityRunningInfos) {
11480         if (info.abilityState != AbilityState::FOREGROUND) {
11481             continue;
11482         }
11483 
11484         AppExecFwk::AbilityStateData abilityData;
11485         abilityData.bundleName = info.ability.GetBundleName();
11486         abilityData.moduleName = info.ability.GetModuleName();
11487         abilityData.abilityName = info.ability.GetAbilityName();
11488         abilityData.abilityState = info.abilityState;
11489         abilityData.pid = info.pid;
11490         abilityData.uid = info.uid;
11491         abilityData.abilityType = static_cast<int32_t>(AppExecFwk::AbilityType::PAGE);
11492         abilityData.appCloneIndex = info.appCloneIndex;
11493         AppExecFwk::ApplicationInfo appInfo;
11494         if (!StartAbilityUtils::GetApplicationInfo(abilityData.bundleName, GetUserId(), appInfo)) {
11495             TAG_LOGE(AAFwkTag::ABILITYMGR, "can't get applicationInfo through bundleName");
11496         } else if (appInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
11497             abilityData.isAtomicService = true;
11498         }
11499         list.push_back(abilityData);
11500     }
11501     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get foreground ui abilities end, list.size = %{public}zu.", list.size());
11502     return ERR_OK;
11503 }
11504 
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)11505 void AbilityManagerService::NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)
11506 {
11507     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
11508     if (collaborator == nullptr) {
11509         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator getCollaborator null");
11510         return;
11511     }
11512     collaborator->UpdateConfiguration(config, userId);
11513 }
11514 
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)11515 void AbilityManagerService::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
11516 {
11517     if (userController_ == nullptr) {
11518         TAG_LOGE(AAFwkTag::ABILITYMGR, "userController_ null");
11519         return;
11520     }
11521     auto currentUser = userController_->GetCurrentUserId();
11522     std::vector<AppExecFwk::BundleInfo> bundleInfosForU0;
11523     std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
11524     for (const auto &item: bundleInfos) {
11525         auto user = item.uid / BASE_USER_RANGE;
11526         if (user == U0_USER_ID) {
11527             bundleInfosForU0.push_back(item);
11528         } else if (user == currentUser) {
11529             bundleInfosForCurrentUser.push_back(item);
11530         }
11531     }
11532 
11533     auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
11534     CHECK_POINTER(residentProcessMgr);
11535 
11536     residentProcessMgr->StartResidentProcessWithMainElement(
11537         bundleInfosForU0, U0_USER_ID);
11538     if (!bundleInfosForU0.empty()) {
11539         residentProcessMgr->StartResidentProcess(bundleInfosForU0);
11540     }
11541 
11542     residentProcessMgr->StartResidentProcessWithMainElement(
11543         bundleInfosForCurrentUser, currentUser);
11544     if (!bundleInfosForCurrentUser.empty()) {
11545         residentProcessMgr->StartResidentProcess(bundleInfosForCurrentUser);
11546     }
11547 }
11548 
NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)11549 void AbilityManagerService::NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
11550 {
11551     if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
11552         return;
11553     }
11554 
11555     auto userId = GetUserId();
11556     std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
11557     for (const auto &item: bundleInfos) {
11558         if (item.uid / BASE_USER_RANGE == userId) {
11559             bundleInfosForCurrentUser.push_back(item);
11560         }
11561     }
11562 
11563     if (bundleInfosForCurrentUser.size() == 0) {
11564         TAG_LOGI(AAFwkTag::ABILITYMGR, "no app to restart");
11565         return;
11566     }
11567 
11568     KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfosForCurrentUser, userId);
11569 }
11570 
NotifyAppPreCache(int32_t pid,int32_t userId)11571 void AbilityManagerService::NotifyAppPreCache(int32_t pid, int32_t userId)
11572 {
11573     ForceTerminateServiceExtensionByPid(pid, userId);
11574 }
11575 
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> & abilityTokens)11576 void AbilityManagerService::OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens)
11577 {
11578     std::shared_ptr<AbilityRecord> abilityRecord;
11579     for (auto &token : abilityTokens) {
11580         abilityRecord = Token::GetAbilityRecordByToken(token);
11581         if (abilityRecord == nullptr) {
11582             continue;
11583         }
11584         TAG_LOGI(AAFwkTag::ABILITYMGR, "app onRemoteDied, ability:%{public}s, app:%{public}s",
11585             abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
11586         abilityRecord->OnProcessDied();
11587     }
11588 }
11589 
OnStartProcessFailed(sptr<IRemoteObject> token)11590 void AbilityManagerService::OnStartProcessFailed(sptr<IRemoteObject> token)
11591 {
11592     auto abilityRecord = Token::GetAbilityRecordByToken(token);
11593     CHECK_POINTER_LOG(abilityRecord, "Null record.");
11594     TAG_LOGW(AAFwkTag::ABILITYMGR, "NotifStartProcessFailed, ability:%{public}s, bundle:%{public}s",
11595         abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
11596 
11597     if (abilityRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::EXTENSION) {
11598         auto connectManager = GetConnectManagerByToken(token);
11599         CHECK_POINTER(connectManager);
11600         connectManager->OnLoadAbilityFailed(abilityRecord);
11601         return;
11602     }
11603 }
11604 
OnCacheExitInfo(uint32_t accessTokenId,const AAFwk::LastExitDetailInfo & exitInfo,const std::string & bundleName,const std::vector<std::string> & abilityNames,const std::vector<std::string> & uiExtensionNames)11605 void AbilityManagerService::OnCacheExitInfo(uint32_t accessTokenId, const AAFwk::LastExitDetailInfo &exitInfo,
11606     const std::string &bundleName, const std::vector<std::string> &abilityNames,
11607     const std::vector<std::string> &uiExtensionNames)
11608 {
11609     ExitCacheInfo cacheInfo = {};
11610     cacheInfo.exitInfo = exitInfo;
11611     cacheInfo.bundleName = bundleName;
11612     cacheInfo.abilityNames = abilityNames;
11613     cacheInfo.uiExtensionNames = uiExtensionNames;
11614     if (!ExitInfoDataManager::GetInstance().AddExitInfo(accessTokenId, cacheInfo)) {
11615         TAG_LOGE(AAFwkTag::ABILITYMGR, "AddExitInfo failed");
11616         return;
11617     }
11618     auto delayClearReason = [ accessTokenId ]() {
11619         if (!ExitInfoDataManager::GetInstance().DeleteExitInfo(accessTokenId)) {
11620             TAG_LOGE(AAFwkTag::ABILITYMGR, "DeleteExitInfo failed");
11621             return;
11622         }
11623     };
11624     delayClearReasonHandler_->SubmitTaskJust(delayClearReason, "delayClearReason", CLEAR_REASON_DELAY_TIME);
11625 }
11626 
OpenFile(const Uri & uri,uint32_t flag)11627 int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag)
11628 {
11629     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
11630 #ifdef SUPPORT_UPMS
11631     if (!IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission(
11632         uri, flag, accessTokenId))) {
11633         TAG_LOGE(AAFwkTag::ABILITYMGR, "premission check failed");
11634         return -1;
11635     }
11636 #endif // SUPPORT_UPMS
11637     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
11638     if (collaborator == nullptr) {
11639         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator getCollaborator null");
11640         return ERR_COLLABORATOR_NOT_REGISTER;
11641     }
11642     return collaborator->OpenFile(uri, flag);
11643 }
11644 #ifdef SUPPORT_SCREEN
GetDialogSessionInfo(const std::string & dialogSessionId,sptr<DialogSessionInfo> & dialogSessionInfo)11645 int AbilityManagerService::GetDialogSessionInfo(const std::string &dialogSessionId,
11646     sptr<DialogSessionInfo> &dialogSessionInfo)
11647 {
11648     CHECK_CALLER_IS_SYSTEM_APP;
11649     dialogSessionInfo = DialogSessionManager::GetInstance().GetDialogSessionInfo(dialogSessionId);
11650     if (dialogSessionInfo) {
11651         TAG_LOGD(AAFwkTag::ABILITYMGR, "success");
11652         return ERR_OK;
11653     }
11654     TAG_LOGD(AAFwkTag::ABILITYMGR, "fail");
11655     return INNER_ERR;
11656 }
11657 
SendDialogResult(const Want & want,const std::string & dialogSessionId,bool isAllowed)11658 int AbilityManagerService::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed)
11659 {
11660     CHECK_CALLER_IS_SYSTEM_APP;
11661     return DialogSessionManager::GetInstance().SendDialogResult(want, dialogSessionId, isAllowed);
11662 }
11663 
CreateCloneSelectorDialog(AbilityRequest & request,int32_t userId,const std::string & replaceWantString)11664 int AbilityManagerService::CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId,
11665     const std::string &replaceWantString)
11666 {
11667     CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
11668     return implicitStartProcessor_->ImplicitStartAbility(request, userId, 0, replaceWantString, true);
11669 }
11670 #endif // SUPPORT_SCREEN
RemoveSelectorIdentity(int32_t tokenId)11671 void AbilityManagerService::RemoveSelectorIdentity(int32_t tokenId)
11672 {
11673     CHECK_POINTER(implicitStartProcessor_);
11674     implicitStartProcessor_->RemoveIdentity(tokenId);
11675 }
11676 
SetTargetCloneIndexInSameBundle(const Want & want,sptr<IRemoteObject> callerToken)11677 void AbilityManagerService::SetTargetCloneIndexInSameBundle(const Want &want, sptr<IRemoteObject> callerToken)
11678 {
11679     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
11680     CHECK_POINTER(callerRecord);
11681     if (callerRecord->GetAbilityInfo().bundleName != want.GetElement().GetBundleName()) {
11682         TAG_LOGD(AAFwkTag::ABILITYMGR, "not the same bundle");
11683         return;
11684     }
11685     if (want.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY)) {
11686         TAG_LOGD(AAFwkTag::ABILITYMGR, "want with app clone index.");
11687         return;
11688     }
11689     int32_t appIndex = callerRecord->GetApplicationInfo().appIndex;
11690     if (appIndex >= 0 && appIndex < AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
11691         (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
11692     }
11693 }
11694 
RemoveLauncherDeathRecipient(int32_t userId)11695 void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId)
11696 {
11697     auto connectManager = GetConnectManagerByUserId(userId);
11698     if (connectManager == nullptr) {
11699         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
11700         return;
11701     }
11702     connectManager->RemoveLauncherDeathRecipient();
11703 }
11704 
GenerateEmbeddableUIAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)11705 int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest(
11706     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
11707 {
11708     int32_t screenMode = want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
11709     int32_t result = ERR_OK;
11710     if (IsEmbeddableStart(screenMode)) {
11711         result = GenerateAbilityRequest(want, -1, request, callerToken, userId);
11712         request.abilityInfo.isModuleJson = true;
11713         request.abilityInfo.isStageBasedModel = true;
11714         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
11715         request.abilityInfo.extensionAbilityType = AppExecFwk::ExtensionAbilityType::UI;
11716         struct timespec time = {0, 0};
11717         clock_gettime(CLOCK_MONOTONIC, &time);
11718         int64_t times = static_cast<int64_t>(time.tv_sec);
11719         request.abilityInfo.process = request.abilityInfo.bundleName + PROCESS_SUFFIX + std::to_string(times);
11720     } else {
11721         result = GenerateExtensionAbilityRequest(want, request, callerToken, userId);
11722     }
11723     return result;
11724 }
11725 
CheckDebugAssertPermission()11726 int32_t AbilityManagerService::CheckDebugAssertPermission()
11727 {
11728     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11729     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11730     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
11731         TAG_LOGE(AAFwkTag::ABILITYMGR, "assert fault product dialog not enabled");
11732         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11733     }
11734     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
11735         TAG_LOGE(AAFwkTag::ABILITYMGR, "developer mode false");
11736         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11737     }
11738 
11739     auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
11740     CHECK_POINTER_AND_RETURN(bundleMgr, ERR_INVALID_VALUE);
11741     int32_t flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
11742     AppExecFwk::BundleInfo bundleInfo;
11743     auto ret = bundleMgr->GetBundleInfoForSelf(flags, bundleInfo);
11744     if (ret != ERR_OK) {
11745         TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle info failed");
11746         return ret;
11747     }
11748     if (!bundleInfo.applicationInfo.debug) {
11749         TAG_LOGE(AAFwkTag::ABILITYMGR, "non-debug version app");
11750         return ERR_INVALID_VALUE;
11751     }
11752     return ERR_OK;
11753 }
11754 
CloseAssertDialog(const std::string & assertSessionId)11755 void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId)
11756 {
11757     TAG_LOGD(AAFwkTag::ABILITYMGR, "Close assert fault dialog begin.");
11758     auto validUserId = GetUserId();
11759     auto connectManager = GetConnectManagerByUserId(validUserId);
11760     if (connectManager == nullptr) {
11761         TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId: %{public}d", validUserId);
11762         return;
11763     }
11764 
11765     connectManager->CloseAssertDialog(assertSessionId);
11766 }
11767 
SetResidentProcessEnabled(const std::string & bundleName,bool enable)11768 int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable)
11769 {
11770     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11771     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) {
11772         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
11773         return ERR_NOT_SYSTEM_APP;
11774     }
11775 
11776     auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
11777     CHECK_POINTER_AND_RETURN(residentProcessManager, INNER_ERR);
11778 
11779     std::string callerName;
11780     int32_t uid = 0;
11781     auto callerPid = IPCSkeleton::GetCallingPid();
11782     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
11783     if (callerName.empty()) {
11784         TAG_LOGE(AAFwkTag::ABILITYMGR, "obtain caller name failed");
11785         return INNER_ERR;
11786     }
11787 
11788     return residentProcessManager->SetResidentProcessEnabled(bundleName, callerName, enable);
11789 }
11790 
RequestAssertFaultDialog(const sptr<IRemoteObject> & callback,const AAFwk::WantParams & wantParams)11791 int32_t AbilityManagerService::RequestAssertFaultDialog(
11792     const sptr<IRemoteObject> &callback, const AAFwk::WantParams &wantParams)
11793 {
11794     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog begin.");
11795     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11796     auto checkRet = CheckDebugAssertPermission();
11797     if (checkRet != ERR_OK) {
11798         TAG_LOGE(AAFwkTag::ABILITYMGR, "check debug assert permission error");
11799         return checkRet;
11800     }
11801     sptr<IRemoteObject> remoteCallback = callback;
11802     if (remoteCallback == nullptr) {
11803         TAG_LOGE(AAFwkTag::ABILITYMGR, "params remote callback null");
11804         return ERR_INVALID_VALUE;
11805     }
11806     auto debugDeal = ConnectInitAbilityDebugDeal();
11807     Want want;
11808 #ifdef SUPPORT_SCREEN
11809     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
11810     if (sysDialog == nullptr || debugDeal == nullptr) {
11811         TAG_LOGE(AAFwkTag::ABILITYMGR, "sysDialog or debugDeal null");
11812         return ERR_INVALID_VALUE;
11813     }
11814     if (!sysDialog->GetAssertFaultDialogWant(want)) {
11815         TAG_LOGE(AAFwkTag::ABILITYMGR, "get assert fault dialog want failed");
11816         return ERR_INVALID_VALUE;
11817     }
11818 #endif // SUPPORT_SCREEN
11819     uint64_t assertFaultSessionId = reinterpret_cast<uint64_t>(remoteCallback.GetRefPtr());
11820     want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, std::to_string(assertFaultSessionId));
11821     want.SetParam(ASSERT_FAULT_DETAIL, wantParams.GetStringParam(ASSERT_FAULT_DETAIL));
11822     auto &connection = AbilityRuntime::ModalSystemAssertUIExtension::GetInstance();
11823     want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
11824     if (!IN_PROCESS_CALL(connection.CreateModalUIExtension(want))) {
11825         TAG_LOGE(AAFwkTag::ABILITYMGR, "create modal ui extension failed");
11826         return ERR_INVALID_VALUE;
11827     }
11828     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11829     if (callbackDeathMgr == nullptr) {
11830         TAG_LOGE(AAFwkTag::ABILITYMGR, "get callback death manager instance null");
11831         return ERR_INVALID_VALUE;
11832     }
11833     auto callbackTask = [weak = weak_from_this()] (const std::string &assertSessionId) {
11834         auto abilityMgr = weak.lock();
11835         if (abilityMgr == nullptr) {
11836             TAG_LOGE(AAFwkTag::ABILITYMGR, "ability manager instance null");
11837             return;
11838         }
11839         abilityMgr->CloseAssertDialog(assertSessionId);
11840     };
11841     callbackDeathMgr->AddAssertFaultCallback(remoteCallback, callbackTask);
11842     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog end.");
11843     return ERR_OK;
11844 }
11845 
NotifyDebugAssertResult(uint64_t assertFaultSessionId,AAFwk::UserStatus userStatus)11846 int32_t AbilityManagerService::NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus)
11847 {
11848     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11849     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
11850         TAG_LOGE(AAFwkTag::ABILITYMGR, "assert fault dialog product not enabled");
11851         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11852     }
11853 
11854     CHECK_CALLER_IS_SYSTEM_APP;
11855     auto permissionSA = PermissionVerification::GetInstance();
11856     if (permissionSA == nullptr) {
11857         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification instance null");
11858         return ERR_INVALID_VALUE;
11859     }
11860     if (!permissionSA->VerifyCallingPermission(PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT)) {
11861         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
11862             PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT);
11863         return ERR_PERMISSION_DENIED;
11864     }
11865 
11866     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11867     if (callbackDeathMgr == nullptr) {
11868         TAG_LOGE(AAFwkTag::ABILITYMGR, "get callback death manager instance null");
11869         return ERR_INVALID_VALUE;
11870     }
11871     callbackDeathMgr->CallAssertFaultCallback(assertFaultSessionId, userStatus);
11872     return ERR_OK;
11873 }
11874 
UpdateSessionInfoBySCB(std::list<SessionInfo> & sessionInfos,int32_t userId,std::vector<int32_t> & sessionIds)11875 int32_t AbilityManagerService::UpdateSessionInfoBySCB(std::list<SessionInfo> &sessionInfos, int32_t userId,
11876     std::vector<int32_t> &sessionIds)
11877 {
11878     if (!IsCallerSceneBoard()) {
11879         TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11880         return ERR_WRONG_INTERFACE_CALL;
11881     }
11882     TAG_LOGI(AAFwkTag::ABILITYMGR, "sceneboard being restored");
11883     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11884     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11885     return uiAbilityManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds);
11886 }
11887 
CheckSenderWantInfo(int32_t callerUid,const WantSenderInfo & wantSenderInfo)11888 bool AbilityManagerService::CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)
11889 {
11890     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
11891         auto bms = AbilityUtil::GetBundleManagerHelper();
11892         CHECK_POINTER_AND_RETURN(bms, false);
11893 
11894         std::string bundleName;
11895         if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
11896             TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle name failed");
11897             return false;
11898         }
11899         if (wantSenderInfo.bundleName != bundleName) {
11900             TAG_LOGE(AAFwkTag::ABILITYMGR, "wantSender bundleName check failed");
11901             return false;
11902         }
11903     }
11904     return true;
11905 }
11906 
CheckCallerIsDmsProcess()11907 bool AbilityManagerService::CheckCallerIsDmsProcess()
11908 {
11909     Security::AccessToken::NativeTokenInfo nativeTokenInfo;
11910     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
11911     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
11912     int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
11913     if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
11914         result != ERR_OK || nativeTokenInfo.processName != DMS_PROCESS_NAME) {
11915         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not dms");
11916         return false;
11917     }
11918     return true;
11919 }
11920 
WaitBootAnimationStart()11921 void AbilityManagerService::WaitBootAnimationStart()
11922 {
11923     char value[BOOTEVENT_BOOT_ANIMATION_READY_SIZE] = "";
11924     int32_t ret = GetParameter(BOOTEVENT_BOOT_ANIMATION_READY, "", value,
11925         BOOTEVENT_BOOT_ANIMATION_READY_SIZE);
11926     if (ret > 0 && !std::strcmp(value, "false")) {
11927         // Get new param success and new param is not ready, wait the new param.
11928         WaitParameter(BOOTEVENT_BOOT_ANIMATION_READY, "true",
11929             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11930     } else if (ret <= 0 || !std::strcmp(value, "")) {
11931         // Get new param failed or new param is not set, wait the old param.
11932         WaitParameter(BOOTEVENT_BOOT_ANIMATION_STARTED, "true",
11933             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11934     }
11935     // other, the animation is ready, not wait.
11936 }
11937 
GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,UIExtensionHostInfo & hostInfo,int32_t userId)11938 int32_t AbilityManagerService::GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,
11939     UIExtensionHostInfo &hostInfo, int32_t userId)
11940 {
11941     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11942     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11943     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11944 
11945     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11946         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
11947         return ERR_PERMISSION_DENIED;
11948     }
11949 
11950     auto callerRecord = GetUIExtensionRootCaller(token, userId);
11951     if (callerRecord == nullptr) {
11952         TAG_LOGE(AAFwkTag::UI_EXT, "get root host info failed");
11953         return ERR_INVALID_VALUE;
11954     }
11955 
11956     hostInfo.elementName_ = callerRecord->GetElementName();
11957     TAG_LOGD(AAFwkTag::UI_EXT, "uri: %{public}s.", hostInfo.elementName_.GetURI().c_str());
11958     return ERR_OK;
11959 }
11960 
GetUIExtensionRootCaller(const sptr<IRemoteObject> token,int32_t userId)11961 std::shared_ptr<AbilityRecord> AbilityManagerService::GetUIExtensionRootCaller(const sptr<IRemoteObject> token,
11962     int32_t userId)
11963 {
11964     auto validUserId = GetValidUserId(userId);
11965     auto connectManager = GetConnectManagerByUserId(validUserId);
11966     if (connectManager == nullptr) {
11967         TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId:%{public}d", validUserId);
11968         return nullptr;
11969     }
11970 
11971     auto callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11972     if (callerRecord == nullptr && validUserId != U0_USER_ID) {
11973         connectManager = GetConnectManagerByUserId(U0_USER_ID);
11974         if (connectManager == nullptr) {
11975             TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId: %{public}d", U0_USER_ID);
11976             return nullptr;
11977         }
11978         callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11979     }
11980 
11981     return callerRecord;
11982 }
11983 
GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,UIExtensionSessionInfo & uiExtensionSessionInfo,int32_t userId)11984 int32_t AbilityManagerService::GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,
11985     UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId)
11986 {
11987     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11988     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11989     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11990 
11991     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11992         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
11993         return ERR_PERMISSION_DENIED;
11994     }
11995 
11996     auto validUserId = GetValidUserId(userId);
11997     auto connectManager = GetConnectManagerByUserId(validUserId);
11998     if (connectManager == nullptr) {
11999         TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId:%{public}d", validUserId);
12000         return ERR_INVALID_VALUE;
12001     }
12002 
12003     auto ret = connectManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo);
12004     if (ret != ERR_OK) {
12005         TAG_LOGE(AAFwkTag::ABILITYMGR, "get ui extension session info failed");
12006         return ret;
12007     }
12008 
12009     return ERR_OK;
12010 }
12011 
RestartApp(const AAFwk::Want & want,bool isAppRecovery)12012 int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want, bool isAppRecovery)
12013 {
12014     TAG_LOGI(AAFwkTag::ABILITYMGR, "RestartApp, isAppRecovery: %{public}d", isAppRecovery);
12015     auto callerPid = IPCSkeleton::GetCallingPid();
12016     AppExecFwk::RunningProcessInfo processInfo;
12017     DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
12018     int32_t callerUid = IPCSkeleton::GetCallingUid();
12019     int32_t userId = callerUid / BASE_USER_RANGE;
12020     auto result = CheckRestartAppWant(want, processInfo.appCloneIndex, userId);
12021     if (result != ERR_OK) {
12022         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkRestartAppWant error");
12023         return result;
12024     }
12025     if (!processInfo.isFocused && !processInfo.isAbilityForegrounding) {
12026         TAG_LOGE(AAFwkTag::ABILITYMGR, "restartApp, is not foreground");
12027         return AAFwk::NOT_TOP_ABILITY;
12028     }
12029 
12030     RestartAppKeyType key(processInfo.instanceKey, callerUid);
12031     int64_t now = time(nullptr);
12032     if (!isAppRecovery && RestartAppManager::GetInstance().IsRestartAppFrequent(key, now)) {
12033         return AAFwk::ERR_RESTART_APP_FREQUENT;
12034     }
12035 
12036     result = SignRestartAppFlag(userId, callerUid, processInfo.instanceKey, processInfo.appMode, isAppRecovery);
12037     if (result != ERR_OK) {
12038         TAG_LOGE(AAFwkTag::ABILITYMGR, "signRestartAppFlag error");
12039         return result;
12040     }
12041 
12042     (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, processInfo.appCloneIndex);
12043     (const_cast<Want &>(want)).SetParam(AAFwk::Want::APP_INSTANCE_KEY, processInfo.instanceKey);
12044     (const_cast<Want &>(want)).RemoveParam(Want::CREATE_APP_INSTANCE_KEY);
12045     result = StartAbilityWrap(want, nullptr, DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, 0, true);
12046     if (result != ERR_OK) {
12047         TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility error");
12048         return result;
12049     }
12050     if (!isAppRecovery) {
12051         RestartAppManager::GetInstance().AddRestartAppHistory(key, now);
12052     }
12053     return result;
12054 }
12055 
CheckRestartAppWant(const AAFwk::Want & want,int32_t appIndex,int32_t userId)12056 int32_t AbilityManagerService::CheckRestartAppWant(const AAFwk::Want &want, int32_t appIndex, int32_t userId)
12057 {
12058     std::string bundleName = want.GetElement().GetBundleName();
12059     if (!CheckCallingTokenId(bundleName, userId, appIndex)) {
12060         TAG_LOGE(AAFwkTag::ABILITYMGR, "no itself called, no allowed");
12061         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
12062     }
12063 
12064     auto bms = AbilityUtil::GetBundleManagerHelper();
12065     CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
12066     auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
12067 
12068     TAG_LOGD(AAFwkTag::ABILITYMGR,
12069         "bundleName: %{public}s, abilityName: %{public}s, appIndex: %{public}d, userId: %{public}d",
12070         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), appIndex, userId);
12071     AppExecFwk::AbilityInfo abilityInfo;
12072     auto queryResult = IN_PROCESS_CALL(
12073         bms->QueryCloneAbilityInfo(want.GetElement(), abilityInfoFlag, appIndex, abilityInfo, userId));
12074     if (queryResult != ERR_OK || abilityInfo.name.empty() || abilityInfo.bundleName.empty() ||
12075         abilityInfo.type != AbilityType::PAGE) {
12076         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability invalid or not UIAbility");
12077         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
12078     }
12079     return ERR_OK;
12080 }
12081 
SignRestartAppFlag(int32_t userId,int32_t uid,const std::string & instanceKey,AppExecFwk::MultiAppModeType type,bool isAppRecovery)12082 int32_t AbilityManagerService::SignRestartAppFlag(int32_t userId, int32_t uid, const std::string &instanceKey,
12083     AppExecFwk::MultiAppModeType type, bool isAppRecovery)
12084 {
12085     auto appMgr = AppMgrUtil::GetAppMgr();
12086     if (appMgr == nullptr) {
12087         TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
12088         return ERR_INVALID_VALUE;
12089     }
12090     auto ret = IN_PROCESS_CALL(appMgr->SignRestartAppFlag(uid, instanceKey));
12091     if (ret != ERR_OK) {
12092         TAG_LOGE(AAFwkTag::ABILITYMGR, "appMgr signRestartAppFlag error");
12093         return ret;
12094     }
12095 
12096     auto connectManager = GetConnectManagerByUserId(userId);
12097     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
12098     connectManager->SignRestartAppFlag(uid, instanceKey);
12099     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
12100         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
12101         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12102         uiAbilityManager->SignRestartAppFlag(uid, instanceKey, isAppRecovery);
12103     } else {
12104         auto missionListManager = GetMissionListManagerByUserId(userId);
12105         if (missionListManager == nullptr) {
12106             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId:%{public}d", userId);
12107             return ERR_INVALID_VALUE;
12108         }
12109         missionListManager->SignRestartAppFlag(uid, instanceKey);
12110     }
12111 
12112     if (type == AppExecFwk::MultiAppModeType::MULTI_INSTANCE) {
12113         return appMgr->KillAppSelfWithInstanceKey(instanceKey, false, "RestartInstance");
12114     } else {
12115         return DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->KillApplicationSelf(false, "RestartApp");
12116     }
12117 }
12118 
IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken,const std::string & appId)12119 bool AbilityManagerService::IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken, const std::string &appId)
12120 {
12121     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12122     if (!AppUtils::GetInstance().IsLaunchEmbededUIAbility()) {
12123         TAG_LOGE(AAFwkTag::ABILITYMGR, "device type not allowd");
12124         return false;
12125     }
12126     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
12127     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
12128     if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
12129         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not hap");
12130         return false;
12131     }
12132     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12133     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12134     auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
12135     if (callerAbility == nullptr) {
12136         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
12137         return false;
12138     }
12139     if (callerAbility->GetApplicationInfo().accessTokenId != accessTokenId) {
12140         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken don't belong caller");
12141         return false;
12142     }
12143     if (!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag()) {
12144         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not foreground");
12145         return false;
12146     }
12147     CHECK_POINTER_AND_RETURN(freeInstallManager_, false);
12148     std::string bundleName = ATOMIC_SERVICE_PREFIX + appId;
12149     Want want;
12150     want.SetBundle(bundleName);
12151     want.SetParam("send_to_erms_embedded", 1);
12152     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(want, callerToken);
12153     int32_t ret = freeInstallManager_->StartFreeInstall(want, GetUserId(), 0, callerToken);
12154     if (ret != ERR_OK) {
12155         TAG_LOGE(AAFwkTag::ABILITYMGR, "target not allowed free install");
12156         return false;
12157     }
12158     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
12159     auto erms = std::make_shared<EcologicalRuleInterceptor>();
12160     return erms->DoProcess(want, GetUserId());
12161 }
12162 
AddQueryERMSObserver(sptr<IRemoteObject> callerToken,sptr<AbilityRuntime::IQueryERMSObserver> observer)12163 int32_t AbilityManagerService::AddQueryERMSObserver(sptr<IRemoteObject> callerToken,
12164     sptr<AbilityRuntime::IQueryERMSObserver> observer)
12165 {
12166     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12167     if (callerToken == nullptr || !JudgeSelfCalled(Token::GetAbilityRecordByToken(callerToken))) {
12168         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
12169         return ERR_PERMISSION_DENIED;
12170     }
12171     return QueryERMSManager::GetInstance().AddQueryERMSObserver(callerToken, observer);
12172 }
12173 
QueryAtomicServiceStartupRule(sptr<IRemoteObject> callerToken,const std::string & appId,const std::string & startTime,AtomicServiceStartupRule & rule)12174 int32_t AbilityManagerService::QueryAtomicServiceStartupRule(sptr<IRemoteObject> callerToken,
12175     const std::string &appId, const std::string &startTime, AtomicServiceStartupRule &rule)
12176 {
12177     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12178     CHECK_TRUE_RETURN_RET(!AppUtils::GetInstance().IsLaunchEmbededUIAbility(),
12179         ERR_CAPABILITY_NOT_SUPPORT, "device type not allowd");
12180     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
12181     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
12182     CHECK_TRUE_RETURN_RET(type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP, INNER_ERR, "caller not hap");
12183     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12184     CHECK_POINTER_AND_RETURN(uiAbilityManager, INNER_ERR);
12185     auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
12186     CHECK_POINTER_AND_RETURN(callerAbility, INNER_ERR);
12187     CHECK_TRUE_RETURN_RET(callerAbility->GetApplicationInfo().accessTokenId != accessTokenId,
12188         INNER_ERR, "callerToken don't belong caller");
12189     CHECK_TRUE_RETURN_RET(!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag(),
12190         INNER_ERR, "caller not foreground");
12191 
12192     Want want;
12193     want.SetBundle(ATOMIC_SERVICE_PREFIX + appId);
12194     want.SetParam("send_to_erms_embedded", 1);
12195     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(want, callerToken);
12196     auto userId = GetUserId();
12197     int32_t ret = freeInstallManager_->StartFreeInstall(want, userId, 0, callerToken);
12198     if (ret != ERR_OK) {
12199         TAG_LOGE(AAFwkTag::ABILITYMGR, "free install failed:%{public}d", ret);
12200         rule.isOpenAllowed = false;
12201         rule.isEmbeddedAllowed = false;
12202         return ERR_OK;
12203     }
12204 
12205     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
12206     auto erms = std::make_shared<EcologicalRuleInterceptor>();
12207     sptr<Want> replaceWant = nullptr;
12208     ret = erms->QueryAtomicServiceStartupRule(want, callerToken, GetUserId(), rule, replaceWant);
12209     if (ret == ERR_OK) {
12210         TAG_LOGI(AAFwkTag::ABILITYMGR, "QueryAtomicServiceStartupRule succeeded");
12211         return ERR_OK;
12212     }
12213     if (ret != ERR_ECOLOGICAL_CONTROL_STATUS) {
12214         TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryAtomicServiceStartupRule failed:%{public}d", ret);
12215         if (ret == ERR_CAPABILITY_NOT_SUPPORT) {
12216             TAG_LOGE(AAFwkTag::ABILITYMGR, "not supported");
12217             return ret;
12218         }
12219         return INNER_ERR;
12220     }
12221     AbilityRequest abilityRequest;
12222     ret = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, userId);
12223     CHECK_TRUE_RETURN_RET(ret != ERR_OK, INNER_ERR, "GenerateAbilityRequest failed");
12224 
12225     abilityRequest.isQueryERMS = true;
12226     abilityRequest.appId = appId;
12227     abilityRequest.startTime = startTime;
12228     abilityRequest.isEmbeddedAllowed = rule.isEmbeddedAllowed;
12229     ret = DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, userId, *replaceWant);
12230     TAG_LOGI(AAFwkTag::ABILITYMGR, "HandleErmsResult: ret=%{public}d", ret);
12231     CHECK_TRUE_RETURN_RET(ret != ERR_OK, INNER_ERR, "HandleErmsResult failed");
12232     return ERR_ECOLOGICAL_CONTROL_STATUS;
12233 }
12234 
CheckProcessIsBackground(int32_t pid,AbilityState currentState)12235 bool AbilityManagerService::CheckProcessIsBackground(int32_t pid, AbilityState currentState)
12236 {
12237     TAG_LOGI(AAFwkTag::ABILITYMGR, "pid:%{public}d, currentState:%{public}d", pid, currentState);
12238     std::lock_guard<ffrt::mutex> myLockGuard(windowVisibleListLock_);
12239     if (currentState == AAFwk::AbilityState::BACKGROUND &&
12240         windowVisibleList_.find(pid) != windowVisibleList_.end()) {
12241         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process window is occluded");
12242         return false;
12243     }
12244 
12245     if (currentState != AAFwk::AbilityState::BACKGROUND) {
12246         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is not on background Pass");
12247         return false;
12248     }
12249     return true;
12250 }
12251 
InitWindowVisibilityChangedListener()12252 void AbilityManagerService::InitWindowVisibilityChangedListener()
12253 {
12254     if (windowVisibilityChangedListener_ != nullptr) {
12255         TAG_LOGW(AAFwkTag::ABILITYMGR, "visibility already initiate");
12256         return;
12257     }
12258 
12259     windowVisibilityChangedListener_ =
12260         new (std::nothrow) WindowVisibilityChangedListener(weak_from_this(), taskHandler_);
12261     if (windowVisibilityChangedListener_ == nullptr) {
12262         TAG_LOGE(AAFwkTag::ABILITYMGR, "window visibility changed listener null");
12263         return;
12264     }
12265 
12266     Rosen::WindowManager::GetInstance().RegisterVisibilityChangedListener(windowVisibilityChangedListener_);
12267 }
12268 
FreeWindowVisibilityChangedListener()12269 void AbilityManagerService::FreeWindowVisibilityChangedListener()
12270 {
12271     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12272     if (windowVisibilityChangedListener_ == nullptr) {
12273         TAG_LOGW(AAFwkTag::ABILITYMGR, "visibility listener already free");
12274         return;
12275     }
12276     Rosen::WindowManager::GetInstance().UnregisterVisibilityChangedListener(windowVisibilityChangedListener_);
12277     windowVisibilityChangedListener_ = nullptr;
12278 }
12279 
HandleWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)12280 void AbilityManagerService::HandleWindowVisibilityChanged(
12281     const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
12282 {
12283     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12284     if (windowVisibilityInfos.empty()) {
12285         TAG_LOGW(AAFwkTag::ABILITYMGR, "window visibility info empty");
12286         return;
12287     }
12288     std::lock_guard<ffrt::mutex> myLockGuard(windowVisibleListLock_);
12289     for (const auto &info : windowVisibilityInfos) {
12290         if (info == nullptr) {
12291             TAG_LOGE(AAFwkTag::ABILITYMGR, "null info");
12292             continue;
12293         }
12294         int uid = 0;
12295         std::string bundleName;
12296         if (info->windowType_ == Rosen::WindowType::WINDOW_TYPE_DESKTOP &&
12297             info->visibilityState_ == Rosen::WINDOW_VISIBILITY_STATE_NO_OCCLUSION) {
12298             TAG_LOGD(AAFwkTag::ABILITYMGR, "desktop is visible clear windowVisibleList_");
12299             windowVisibleList_.clear();
12300             continue;
12301         }
12302         DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(info->pid_, bundleName, uid);
12303         if (info->visibilityState_ == Rosen::WINDOW_VISIBILITY_STATE_NO_OCCLUSION &&
12304             bundleName != SCENEBOARD_BUNDLE_NAME) {
12305             windowVisibleList_.insert(info->pid_);
12306         }
12307     }
12308 }
12309 
ShouldPreventStartAbility(const AbilityRequest & abilityRequest)12310 bool AbilityManagerService::ShouldPreventStartAbility(const AbilityRequest &abilityRequest)
12311 {
12312     std::shared_ptr<AbilityRecord> abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
12313     if (abilityRecord == nullptr) {
12314         TAG_LOGD(AAFwkTag::ABILITYMGR, "No matched token pass");
12315         return false;
12316     }
12317     auto abilityInfo = abilityRequest.abilityInfo;
12318     auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
12319     PrintStartAbilityInfo(callerAbilityInfo, abilityInfo);
12320     if (abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD < API12) {
12321         TAG_LOGD(AAFwkTag::ABILITYMGR, "API version %{public}d pass",
12322             abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD);
12323         return false;
12324     }
12325     bool continuousFlag = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
12326     if(!IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->
12327         IsProcessContainsOnlyUIAbility(abilityRecord->GetPid()))) {
12328         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has other extension except UIAbility, pass");
12329         return false;
12330     }
12331     if (abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::DATASHARE &&
12332         abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
12333         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process did not call service or datashare extension Pass");
12334         return false;
12335     }
12336     if (abilityInfo.applicationInfo.uid == IPCSkeleton::GetCallingUid()) {
12337         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in same bundle Pass");
12338         return false;
12339     }
12340     if (callerAbilityInfo.type != AppExecFwk::AbilityType::PAGE) {
12341         TAG_LOGD(AAFwkTag::ABILITYMGR, "Is not UI Ability Pass");
12342         return false;
12343     }
12344     if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckIntentIsExemption(
12345         abilityRecord->GetUid())) {
12346         TAG_LOGD(AAFwkTag::ABILITYMGR, "Is Exemption Pass");
12347         return false;
12348     }
12349     if (!CheckProcessIsBackground(abilityRecord->GetPid(), abilityRecord->GetAbilityState())) {
12350         return false;
12351     }
12352     if (continuousFlag) {
12353         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has continuous task Pass");
12354         return false;
12355     }
12356     if (IsInWhiteList(callerAbilityInfo.bundleName, abilityInfo.bundleName, abilityInfo.name)) {
12357         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in white list Pass");
12358         return false;
12359     }
12360     TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceExtension %{public}s permission",
12361         abilityRecord->GetURI().c_str());
12362     ReportPreventStartAbilityResult(callerAbilityInfo, abilityInfo);
12363     return true;
12364 }
12365 
PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo,AppExecFwk::AbilityInfo calledInfo)12366 void AbilityManagerService::PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo, AppExecFwk::AbilityInfo calledInfo)
12367 {
12368     TAG_LOGD(AAFwkTag::ABILITYMGR, "calledAbilityInfo toString: "
12369         "calledUid is: %{public}d, "
12370         "name is: %{public}s, "
12371         "bundleName is: %{public}s, "
12372         "type is: %{public}d, "
12373         "extensionAbilityType is: %{public}d, "
12374         "moduleName is: %{public}s, "
12375         "applicationName is: %{public}s",
12376         calledInfo.applicationInfo.uid,
12377         calledInfo.name.c_str(),
12378         calledInfo.bundleName.c_str(),
12379         static_cast<int32_t>(calledInfo.type),
12380         static_cast<int32_t>(calledInfo.extensionAbilityType),
12381         calledInfo.moduleName.c_str(),
12382         calledInfo.applicationName.c_str());
12383 
12384 
12385     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerAbilityInfo toString: "
12386         "callerUid is: %{public}d, "
12387         "callerPid is: %{public}d, "
12388         "name is: %{public}s, "
12389         "bundleName is: %{public}s, "
12390         "type is: %{public}d, "
12391         "extensionAbilityType is: %{public}d, "
12392         "moduleName is: %{public}s, "
12393         "applicationName is: %{public}s",
12394         IPCSkeleton::GetCallingUid(),
12395         IPCSkeleton::GetCallingPid(),
12396         callerInfo.name.c_str(),
12397         callerInfo.bundleName.c_str(),
12398         static_cast<int32_t>(callerInfo.type),
12399         static_cast<int32_t>(callerInfo.extensionAbilityType),
12400         callerInfo.moduleName.c_str(),
12401         callerInfo.applicationName.c_str());
12402 }
12403 
ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo & callerAbilityInfo,const AppExecFwk::AbilityInfo & abilityInfo)12404 void AbilityManagerService::ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo,
12405     const AppExecFwk::AbilityInfo &abilityInfo)
12406 {
12407     int32_t callerUid = IPCSkeleton::GetCallingUid();
12408     int32_t callerPid = IPCSkeleton::GetCallingPid();
12409     int32_t extensionAbilityType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
12410     TAG_LOGD(AAFwkTag::ABILITYMGR,
12411         "Prevent start ability debug log CALLER_BUNDLE_NAME %{public}s CALLEE_BUNDLE_NAME"
12412         "%{public}s ABILITY_NAME %{public}s",
12413         callerAbilityInfo.bundleName.c_str(), abilityInfo.name.c_str(), abilityInfo.name.c_str());
12414     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "PREVENT_START_ABILITY", HiSysEvent::EventType::BEHAVIOR,
12415         "CALLER_UID", callerUid,
12416         "CALLER_PID", callerPid,
12417         "CALLER_PROCESS_NAME", callerAbilityInfo.process,
12418         "CALLER_BUNDLE_NAME", callerAbilityInfo.bundleName,
12419         "CALLEE_BUNDLE_NAME", abilityInfo.bundleName,
12420         "CALLEE_PROCESS_NAME", abilityInfo.process,
12421         "EXTENSION_ABILITY_TYPE", extensionAbilityType,
12422         "ABILITY_NAME", abilityInfo.name);
12423 }
12424 
IsInWhiteList(const std::string & callerBundleName,const std::string & calleeBundleName,const std::string & calleeAbilityName)12425 bool AbilityManagerService::IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName,
12426     const std::string &calleeAbilityName)
12427 {
12428     std::lock_guard<std::mutex> locker(whiteListMutex_);
12429     std::map<std::string, std::list<std::string>>::iterator iter = whiteListMap_.find(callerBundleName);
12430     std::string uri = calleeBundleName + "/" + calleeAbilityName;
12431     if (iter != whiteListMap_.end()) {
12432         if (std::find(std::begin(iter->second), std::end(iter->second), uri) != std::end(iter->second)) {
12433             return true;
12434         }
12435     }
12436     std::list<std::string>::iterator it = std::find(exportWhiteList_.begin(), exportWhiteList_.end(), uri);
12437     if (it != exportWhiteList_.end()) {
12438         return true;
12439     }
12440     return false;
12441 }
12442 
ParseJsonFromBoot(const std::string & relativePath)12443 bool AbilityManagerService::ParseJsonFromBoot(const std::string &relativePath)
12444 {
12445     nlohmann::json jsonObj;
12446     std::string absolutePath = GetConfigFileAbsolutePath(relativePath);
12447     if (ParseJsonValueFromFile(jsonObj, absolutePath) != ERR_OK) {
12448         return false;
12449     }
12450     std::lock_guard<std::mutex> locker(whiteListMutex_);
12451     nlohmann::json whiteListJsonList = jsonObj[WHITE_LIST];
12452     for (const auto& [key, value] : whiteListJsonList.items()) {
12453         if (!value.is_array()) {
12454             continue;
12455         }
12456         whiteListMap_.emplace(key, std::list<std::string>());
12457         for (const auto& it : value) {
12458             if (it.is_string()) {
12459                 whiteListMap_[key].push_back(it);
12460             }
12461         }
12462     }
12463     if (!jsonObj.contains("exposed_white_list")) {
12464         return false;
12465     }
12466     nlohmann::json exportWhiteJsonList = jsonObj["exposed_white_list"];
12467     for (const auto& it : exportWhiteJsonList) {
12468         if (it.is_string()) {
12469             exportWhiteList_.push_back(it);
12470         }
12471     }
12472     return true;
12473 }
12474 
GetConfigFileAbsolutePath(const std::string & relativePath)12475 std::string AbilityManagerService::GetConfigFileAbsolutePath(const std::string &relativePath)
12476 {
12477     if (relativePath.empty()) {
12478         TAG_LOGE(AAFwkTag::ABILITYMGR, "relativePath empty");
12479         return "";
12480     }
12481     char buf[PATH_MAX];
12482     char *tmpPath = GetOneCfgFile(relativePath.c_str(), buf, PATH_MAX);
12483     char absolutePath[PATH_MAX] = {0};
12484     if (!tmpPath || strlen(tmpPath) > PATH_MAX || !realpath(tmpPath, absolutePath)) {
12485         TAG_LOGE(AAFwkTag::ABILITYMGR, "get file fail");
12486         return "";
12487     }
12488     return std::string(absolutePath);
12489 }
12490 
ParseJsonValueFromFile(nlohmann::json & value,const std::string & filePath)12491 int32_t AbilityManagerService::ParseJsonValueFromFile(nlohmann::json &value, const std::string &filePath)
12492 {
12493     std::ifstream fin;
12494     std::string realPath;
12495     if (!ConvertFullPath(filePath, realPath)) {
12496         TAG_LOGE(AAFwkTag::ABILITYMGR, "get real path failed");
12497         return ERR_INVALID_VALUE;
12498     }
12499     fin.open(realPath, std::ios::in);
12500     if (!fin.is_open()) {
12501         TAG_LOGE(AAFwkTag::ABILITYMGR, "can't open file %{private}s", realPath.c_str());
12502         return ERR_INVALID_VALUE;
12503     }
12504     char buffer[MAX_BUFFER];
12505     std::ostringstream os;
12506     while (fin.getline(buffer, MAX_BUFFER)) {
12507         os << buffer;
12508     }
12509     const std::string data = os.str();
12510     value = nlohmann::json::parse(data, nullptr, false);
12511     if (value.is_discarded()) {
12512         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed due data discarded");
12513         return ERR_INVALID_VALUE;
12514     }
12515     return ERR_OK;
12516 }
12517 
ConvertFullPath(const std::string & partialPath,std::string & fullPath)12518 bool AbilityManagerService::ConvertFullPath(const std::string& partialPath, std::string& fullPath)
12519 {
12520     if (partialPath.empty() || partialPath.length() >= PATH_MAX) {
12521         return false;
12522     }
12523     char tmpPath[PATH_MAX] = {0};
12524     if (realpath(partialPath.c_str(), tmpPath) == nullptr) {
12525         return false;
12526     }
12527     fullPath = tmpPath;
12528     return true;
12529 }
12530 
StartShortcut(const Want & want,const StartOptions & startOptions)12531 int32_t AbilityManagerService::StartShortcut(const Want &want, const StartOptions &startOptions)
12532 {
12533     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12534     if (!PermissionVerification::GetInstance()->IsSystemAppCall()) {
12535         TAG_LOGE(AAFwkTag::ABILITYMGR, "non-system app calling system api");
12536         return ERR_NOT_SYSTEM_APP;
12537     }
12538     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
12539         PermissionConstants::PERMISSION_START_SHORTCUT)) {
12540         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
12541             PermissionConstants::PERMISSION_START_SHORTCUT);
12542         return ERR_PERMISSION_DENIED;
12543     }
12544     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
12545     return StartUIAbilityForOptionWrap(want, startOptions, nullptr, false, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE,
12546         0, false, true);
12547 }
12548 
GetAbilityStateByPersistentId(int32_t persistentId,bool & state)12549 int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentId, bool &state)
12550 {
12551     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12552     if (!CheckCallerIsDmsProcess()) {
12553         TAG_LOGE(AAFwkTag::ABILITYMGR, "getAbilityStateByPersistentId, caller not dms");
12554         return ERR_PERMISSION_DENIED;
12555     }
12556 
12557     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
12558         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12559         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12560         return uiAbilityManager->GetAbilityStateByPersistentId(persistentId, state);
12561     }
12562     TAG_LOGE(AAFwkTag::ABILITYMGR, "getAbilityStateByPersistentId, mission without persistent id");
12563     return INNER_ERR;
12564 }
12565 
TransferAbilityResultForExtension(const sptr<IRemoteObject> & callerToken,int32_t resultCode,const Want & want)12566 int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptr<IRemoteObject> &callerToken,
12567     int32_t resultCode, const Want &want)
12568 {
12569     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12570     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
12571     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
12572     if (!JudgeSelfCalled(abilityRecord)) {
12573         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller mismatch");
12574         return ERR_INVALID_VALUE;
12575     }
12576     auto type = abilityRecord->GetAbilityInfo().type;
12577     if (type != AppExecFwk::AbilityType::EXTENSION) {
12578         TAG_LOGE(AAFwkTag::ABILITYMGR, "type not uiextension");
12579         return ERR_INVALID_VALUE;
12580     }
12581     // save result to caller AbilityRecord.
12582     (const_cast<Want &>(want)).RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
12583     abilityRecord->SaveResultToCallers(resultCode, &want);
12584     abilityRecord->SendResultToCallers();
12585     return ERR_OK;
12586 }
12587 
NotifyFrozenProcessByRSS(const std::vector<int32_t> & pidList,int32_t uid)12588 void AbilityManagerService::NotifyFrozenProcessByRSS(const std::vector<int32_t> &pidList, int32_t uid)
12589 {
12590     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(RSS_PROCESS_NAME)) {
12591         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not RSS");
12592         return;
12593     }
12594     auto userId = uid / BASE_USER_RANGE;
12595     auto connectManager = GetConnectManagerByUserId(userId);
12596     CHECK_POINTER_LOG(connectManager, "can't find user connect manager");
12597     connectManager->HandleProcessFrozen(pidList, uid);
12598 }
12599 
HandleRestartResidentProcessDependedOnWeb()12600 void AbilityManagerService::HandleRestartResidentProcessDependedOnWeb()
12601 {
12602     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
12603     auto appMgr = AppMgrUtil::GetAppMgr();
12604     CHECK_POINTER_LOG(appMgr, "get appMgr fail");
12605     appMgr->RestartResidentProcessDependedOnWeb();
12606 }
12607 
PreStartMission(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & startTime)12608 int32_t AbilityManagerService::PreStartMission(const std::string& bundleName, const std::string& moduleName,
12609     const std::string& abilityName, const std::string& startTime)
12610 {
12611     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12612     CHECK_CALLER_IS_SYSTEM_APP;
12613 
12614     if (!PermissionVerification::GetInstance()->VerifyPreStartAtomicServicePermission()) {
12615         TAG_LOGE(AAFwkTag::ABILITYMGR, "calling user not ag");
12616         return ERR_PERMISSION_DENIED;
12617     }
12618 
12619     if (!freeInstallManager_) {
12620         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
12621         return ERR_INVALID_VALUE;
12622     }
12623 
12624     FreeInstallInfo taskInfo;
12625     if (!freeInstallManager_->GetFreeInstallTaskInfo(bundleName, abilityName, startTime, taskInfo)) {
12626         TAG_LOGE(AAFwkTag::ABILITYMGR,
12627             "failed find free install task info:bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
12628             bundleName.c_str(), abilityName.c_str(), startTime.c_str());
12629         return ERR_FREE_INSTALL_TASK_NOT_EXIST;
12630     }
12631 
12632     if (taskInfo.isFreeInstallFinished) {
12633         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install finished");
12634         if (!taskInfo.isInstalled) {
12635             TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
12636                 taskInfo.resultCode);
12637         } else {
12638             TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeded");
12639         }
12640         // if free install is already finished then either the window is opened (on success)
12641         // or the user is informed of the error (on failure).
12642         return taskInfo.resultCode;
12643     }
12644 
12645     return PreStartInner(taskInfo);
12646 }
12647 
PreStartInner(const FreeInstallInfo & taskInfo)12648 int32_t AbilityManagerService::PreStartInner(const FreeInstallInfo& taskInfo)
12649 {
12650     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12651 
12652     const Want& want = taskInfo.want;
12653     sptr<IRemoteObject> callerToken = taskInfo.callerToken;
12654 
12655     EventInfo eventInfo = BuildEventInfo(want, taskInfo.userId);
12656     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12657 
12658     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
12659         eventInfo.errCode = ERR_INVALID_VALUE;
12660         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
12661         return ERR_INVALID_CALLER;
12662     }
12663 
12664     int32_t oriValidUserId = GetValidUserId(taskInfo.userId);
12665 
12666     int32_t appIndex = 0;
12667     StartAbilityInfoWrap threadLocalInfo(want, oriValidUserId,
12668         StartAbilityUtils::GetAppIndex(want, callerToken, appIndex), callerToken);
12669 
12670     AbilityRequest abilityRequest = {
12671         .want = want,
12672         .requestCode = taskInfo.requestCode,
12673         .callerToken = callerToken,
12674         .startSetting = nullptr
12675     };
12676 
12677     TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
12678     UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
12679 
12680     // sceneboard
12681     abilityRequest.userId = oriValidUserId;
12682     abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
12683     std::string sessionId = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
12684         std::chrono::system_clock::now().time_since_epoch()).count());
12685     abilityRequest.want.SetParam(KEY_SESSION_ID, sessionId);
12686     auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
12687     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12688     sptr<SessionInfo> sessionInfo = nullptr;
12689     auto errCode = uiAbilityManager->NotifySCBToPreStartUIAbility(abilityRequest, sessionInfo);
12690     if (errCode != ERR_OK) {
12691         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed notify sceneboard pre-start uiability");
12692         return errCode;
12693     }
12694     CHECK_POINTER_AND_RETURN(freeInstallManager_, ERR_INVALID_VALUE);
12695     freeInstallManager_->SetFreeInstallTaskSessionId(taskInfo.want.GetElement().GetBundleName(),
12696         taskInfo.want.GetElement().GetAbilityName(),
12697         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), sessionId);
12698 
12699     freeInstallManager_->SetPreStartMissionCallStatus(taskInfo.want.GetElement().GetBundleName(),
12700         taskInfo.want.GetElement().GetAbilityName(),
12701         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME),
12702         true);
12703     return ERR_OK;
12704 }
12705 
StartUIAbilityByPreInstall(const FreeInstallInfo & taskInfo)12706 int32_t AbilityManagerService::StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo)
12707 {
12708     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12709     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12710     if (!taskInfo.isFreeInstallFinished || !taskInfo.isInstalled) {
12711         TAG_LOGE(AAFwkTag::ABILITYMGR, "free install not finished or failed");
12712         return ERR_INVALID_VALUE;
12713     }
12714     if (!taskInfo.isStartUIAbilityBySCBCalled) {
12715         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install finished, startUIAbilityBySCB not called");
12716         return ERR_OK;
12717     }
12718 
12719     const auto& want = taskInfo.want;
12720     auto sessionId = want.GetStringParam(KEY_SESSION_ID);
12721     if (sessionId.empty()) {
12722         TAG_LOGE(AAFwkTag::ABILITYMGR, "session id empty");
12723         return ERR_INVALID_VALUE;
12724     }
12725     auto bundleName = want.GetElement().GetBundleName();
12726     auto abilityName = want.GetElement().GetAbilityName();
12727     auto startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME);
12728     TAG_LOGI(AAFwkTag::ABILITYMGR, "call"
12729         "sessionId=%{public}s,bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
12730         sessionId.c_str(), bundleName.c_str(), abilityName.c_str(), startTime.c_str());
12731     sptr<SessionInfo> sessionInfo = nullptr;
12732     {
12733         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12734         auto it = preStartSessionMap_.find(sessionId);
12735         if (it == preStartSessionMap_.end()) {
12736             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed find session info with sessionId=%{public}s",
12737                 sessionId.c_str());
12738             return ERR_INVALID_VALUE;
12739         }
12740         sessionInfo = it->second;
12741         CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
12742         (sessionInfo->want).SetElement(want.GetElement());
12743     }
12744 
12745     if (sessionInfo->isMinimizedDuringFreeInstall) {
12746         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability is already minimized");
12747         return ATOMIC_SERVICE_MINIMIZED;
12748     }
12749 
12750     bool isColdStart = true;
12751     int errCode = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, 0, isColdStart);
12752     if (errCode != ERR_OK) {
12753         TAG_LOGE(AAFwkTag::ABILITYMGR, "startUIAbilityByPreInstallInner failed,errCode=%{public}d", errCode);
12754         return errCode;
12755     }
12756     RemovePreStartSession(sessionId);
12757     return errCode;
12758 }
12759 
12760 // StartUIAbilityByPreInstallInner is called when free install task is already finished
StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo,uint32_t specifyTokenId,uint32_t sceneFlag,bool & isColdStart)12761 int AbilityManagerService::StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo, uint32_t specifyTokenId,
12762     uint32_t sceneFlag, bool &isColdStart)
12763 {
12764     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12765     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
12766     auto callerToken = sessionInfo->callerToken;
12767     const auto& want = sessionInfo->want;
12768     const auto userId = sessionInfo->userId;
12769     const auto requestCode = sessionInfo->requestCode;
12770     bool isStartAsCaller = false;
12771 
12772     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
12773         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
12774             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
12775         if (!isSpecificSA) {
12776             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
12777             return ERR_INVALID_CALLER;
12778         }
12779         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: caller specific system ability", __func__);
12780     }
12781 
12782     int32_t oriValidUserId = GetValidUserId(userId);
12783     int32_t validUserId = oriValidUserId;
12784 
12785     int32_t appIndex = 0;
12786     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
12787         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s GetAppIndex failed", __func__);
12788         return ERR_APP_CLONE_INDEX_INVALID;
12789     }
12790     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
12791     auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
12792     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
12793         true, nullptr, shouldBlockFunc);
12794     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
12795         interceptorExecuter_->DoProcess(interceptorParam);
12796     if (result != ERR_OK) {
12797         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
12798         return result;
12799     }
12800 
12801     AbilityRequest abilityRequest;
12802     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
12803     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
12804     std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
12805 
12806     if (result != ERR_OK) {
12807         TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
12808         return result;
12809     }
12810 
12811     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
12812         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
12813     } else if (!isStartAsCaller) {
12814         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
12815         UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
12816     } else if (callerBundleName == BUNDLE_NAME_DIALOG) {
12817 #ifdef SUPPORT_SCREEN
12818         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
12819         implicitStartProcessor_->ResetCallingIdentityAsCaller(
12820             abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), true);
12821 #endif // SUPPORT_SCREEN
12822     }
12823 
12824     auto abilityInfo = abilityRequest.abilityInfo;
12825     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
12826     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
12827         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
12828 
12829     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
12830         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false);
12831     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
12832         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
12833         return ERR_STATIC_CFG_PERMISSION;
12834     }
12835 
12836     result = CheckCallPermission(want, abilityInfo, abilityRequest, false,
12837         false, specifyTokenId, callerBundleName);
12838     if (result != ERR_OK) {
12839         TAG_LOGE(AAFwkTag::ABILITYMGR, "checkCallPermission error, result:%{public}d", result);
12840         return result;
12841     }
12842 
12843     Want newWant = abilityRequest.want;
12844     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
12845         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
12846     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
12847         afterCheckExecuter_->DoProcess(afterCheckParam);
12848     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
12849     newWant.RemoveParam("queryWantFromErms");
12850     if (result != ERR_OK && isReplaceWantExist == false) {
12851         TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
12852         return result;
12853     }
12854 #ifdef SUPPORT_SCREEN
12855     if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
12856         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
12857     }
12858     if (result == ERR_OK &&
12859         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
12860         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
12861         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
12862     }
12863 #endif // SUPPORT_SCREEN
12864 
12865     if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
12866         abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
12867         TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability by connectManager, type:%{public}d",
12868             static_cast<int32_t>(abilityInfo.type));
12869         return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
12870     }
12871 
12872     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
12873         TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", abilityInfo.bundleName.c_str());
12874         return ERR_WOULD_BLOCK;
12875     }
12876 
12877     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
12878     if (specifyTokenId > 0) {
12879         TAG_LOGD(AAFwkTag::ABILITYMGR, "set specifyTokenId, the specifyTokenId is %{public}d", specifyTokenId);
12880         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
12881         abilityRequest.specifyTokenId = specifyTokenId;
12882     }
12883     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
12884 
12885     auto uiAbilityManager = GetCurrentUIAbilityManager();
12886     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12887 
12888     return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
12889 }
12890 
NotifySCBToHandleAtomicServiceException(const std::string & sessionId,int32_t errCode,const std::string & reason)12891 void AbilityManagerService::NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode,
12892     const std::string& reason)
12893 {
12894     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12895     sptr<SessionInfo> sessionInfo = nullptr;
12896     {
12897         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12898         auto it = preStartSessionMap_.find(sessionId);
12899         if (it == preStartSessionMap_.end()) {
12900             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed find session info with sessionId=%{public}s",
12901                 sessionId.c_str());
12902             return;
12903         }
12904         sessionInfo = it->second;
12905         preStartSessionMap_.erase(it);
12906     }
12907     if (sessionInfo == nullptr) {
12908         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
12909         return;
12910     }
12911     auto uiAbilityManager = GetCurrentUIAbilityManager();
12912     CHECK_POINTER(uiAbilityManager);
12913     return uiAbilityManager->NotifySCBToHandleAtomicServiceException(sessionInfo, errCode, reason);
12914 }
12915 
RemovePreStartSession(const std::string & sessionId)12916 void AbilityManagerService::RemovePreStartSession(const std::string& sessionId)
12917 {
12918     std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
12919     preStartSessionMap_.erase(sessionId);
12920 }
12921 
OpenLink(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int requestCode)12922 ErrCode AbilityManagerService::OpenLink(const Want& want, sptr<IRemoteObject> callerToken,
12923     int32_t userId, int requestCode)
12924 {
12925     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12926     AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
12927     std::string callerBundleName;
12928     Want convertedWant = want;
12929     if (!WantUtils::IsAtomicServiceUrl(want) ||
12930         WantUtils::GetCallerBundleName(callerBundleName) != ERR_OK) {
12931         TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
12932         int retCode = StartAbility(want, callerToken, userId, requestCode);
12933         CHECK_RET_RETURN_RET(retCode, "startAbility failed");
12934         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12935     }
12936 
12937     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName=%{public}s", callerBundleName.c_str());
12938     convertedWant.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
12939     if (WantUtils::ConvertToExplicitWant(convertedWant) != ERR_OK ||
12940         freeInstallManager_ == nullptr) {
12941         TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
12942         int retCode = StartAbility(want, callerToken, userId, requestCode);
12943         CHECK_RET_RETURN_RET(retCode, "startAbility failed");
12944         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12945     }
12946 
12947     convertedWant.AddFlags(Want::FLAG_INSTALL_ON_DEMAND);
12948     TAG_LOGD(AAFwkTag::ABILITYMGR, "convertedWant=%{private}s", convertedWant.ToString().c_str());
12949     auto param = std::make_shared<FreeInstallParams>();
12950     param->isAsync = true;
12951     param->isOpenAtomicServiceShortUrl = true;
12952     param->originalWant = std::make_shared<Want>(want);
12953     ErrCode retCode = freeInstallManager_->StartFreeInstall(convertedWant, GetValidUserId(userId),
12954         requestCode, callerToken, param);
12955     if (retCode != ERR_OK) {
12956         TAG_LOGW(AAFwkTag::ABILITYMGR, "startFreeInstall returns errCode=%{public}d", retCode);
12957         if (retCode == NOT_TOP_ABILITY) {
12958             TAG_LOGE(AAFwkTag::ABILITYMGR, "start from background not allowed");
12959             return retCode;
12960         }
12961         TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
12962         retCode = StartAbility(want, callerToken, userId, requestCode);
12963         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12964         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12965     }
12966     return ERR_OK;
12967 }
12968 
CleanUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool isUserRequestedExit,uint32_t sceneFlag)12969 int32_t AbilityManagerService::CleanUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool isUserRequestedExit,
12970     uint32_t sceneFlag)
12971 {
12972     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12973     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
12974         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo invalid");
12975         return ERR_INVALID_VALUE;
12976     }
12977 
12978     if (!IsCallerSceneBoard()) {
12979         TAG_LOGE(AAFwkTag::ABILITYMGR, "only support sceneboard call");
12980         return ERR_WRONG_INTERFACE_CALL;
12981     }
12982 
12983     SetMinimizedDuringFreeInstall(sessionInfo);
12984 
12985     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12986     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12987     TAG_LOGI(AAFwkTag::ABILITYMGR, "user request clean session: %{public}d", sessionInfo->persistentId);
12988     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
12989     if(!abilityRecord){
12990         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
12991             DeleteAbilityRecoverInfoBySessionId(sessionInfo->persistentId);
12992     }
12993     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
12994     abilityRecord->SetSceneFlag(sceneFlag);
12995     if (isUserRequestedExit) {
12996         CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
12997         AAFwk::ExitReason exitReason = { REASON_USER_REQUEST, "User Request" };
12998         appExitReasonHelper_->RecordUIAbilityExitReason(abilityRecord->GetPid(), abilityRecord->GetAbilityInfo().name,
12999             exitReason);
13000     }
13001     int32_t errCode = uiAbilityManager->CleanUIAbility(abilityRecord);
13002     ReportCleanSession(sessionInfo, abilityRecord, errCode);
13003     return errCode;
13004 }
13005 
ForceTerminateServiceExtensionByPid(int32_t pid,int32_t userId)13006 void AbilityManagerService::ForceTerminateServiceExtensionByPid(int32_t pid, int32_t userId)
13007 {
13008     std::vector<sptr<IRemoteObject>> tokens;
13009     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppScheduler>::GetInstance()->GetAbilityRecordsByProcessID(
13010         pid, tokens));
13011     auto connectManager = GetConnectManagerByUserId(userId);
13012     if (connectManager) {
13013         for (const auto& token : tokens) {
13014             auto abilityRecord = Token::GetAbilityRecordByToken(token);
13015             if (abilityRecord &&
13016                 abilityRecord->GetAbilityInfo().extensionAbilityType ==
13017                 AppExecFwk::ExtensionAbilityType::SERVICE) {
13018                 TAG_LOGI(AAFwkTag::ABILITYMGR, "app ForceTerminateServiceExtensionByPid, pid is %{public}d", pid);
13019                 connectManager->TerminateAbility(token);
13020             }
13021         }
13022     }
13023 }
13024 
ReportCleanSession(const sptr<SessionInfo> & sessionInfo,const std::shared_ptr<AbilityRecord> & abilityRecord,int32_t errCode)13025 void AbilityManagerService::ReportCleanSession(const sptr<SessionInfo> &sessionInfo,
13026     const std::shared_ptr<AbilityRecord> &abilityRecord, int32_t errCode)
13027 {
13028     if (!sessionInfo || !abilityRecord) {
13029         return;
13030     }
13031 
13032     const auto &abilityInfo = abilityRecord->GetAbilityInfo();
13033     std::string abilityName = abilityInfo.name;
13034     if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
13035         abilityName += std::to_string(sessionInfo->persistentId);
13036     }
13037     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
13038         DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
13039 
13040     EventInfo eventInfo;
13041     eventInfo.errCode = errCode;
13042     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
13043     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
13044     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
13045     if (eventInfo.errCode != ERR_OK) {
13046         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
13047     }
13048 }
13049 
SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want,uint32_t specifyTokenId)13050 void AbilityManagerService::SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo& abilityInfo,
13051     const Want& want, uint32_t specifyTokenId)
13052 {
13053     if (abilityInfo.type != AppExecFwk::AbilityType::EXTENSION ||
13054         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
13055         return;
13056     }
13057     EventInfo eventInfo;
13058     eventInfo.bundleName = abilityInfo.bundleName;
13059     eventInfo.moduleName = abilityInfo.moduleName;
13060     eventInfo.abilityName = abilityInfo.name;
13061     eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
13062     if (specifyTokenId > 0) {
13063         // come from want agent or form
13064         Security::AccessToken::HapTokenInfo hapInfo;
13065         if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(specifyTokenId, hapInfo) == ERR_OK) {
13066             eventInfo.callerBundleName = hapInfo.bundleName;
13067         }
13068     } else {
13069         eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
13070         if (eventInfo.callerBundleName.empty()) {
13071             eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
13072         }
13073     }
13074     TAG_LOGI(AAFwkTag::ABILITYMGR,
13075         "SendStartAbilityOtherExtensionEvent, bundleName:%{public}s, extensionAbilityType:%{public}d",
13076         eventInfo.bundleName.c_str(), eventInfo.extensionType);
13077     EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
13078 }
13079 
SetAbilityRequestSessionInfo(AbilityRequest & abilityRequest,AppExecFwk::ExtensionAbilityType extensionType)13080 void AbilityManagerService::SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest,
13081     AppExecFwk::ExtensionAbilityType extensionType)
13082 {
13083     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
13084     if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
13085         return;
13086     }
13087 
13088     abilityRequest.want.RemoveParam(WANT_PARAMS_HOST_WINDOW_ID_KEY);
13089     auto callerAbilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
13090     CHECK_POINTER_LOG(callerAbilityRecord, "callerAbilityRecord is nullptr");
13091     sptr<SessionInfo> callerSessionInfo = callerAbilityRecord->GetSessionInfo();
13092     CHECK_POINTER_LOG(callerSessionInfo, "callerSessionInfo is nullptr");
13093 
13094     if (callerAbilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
13095         TAG_LOGI(AAFwkTag::ABILITYMGR, "UIAbility Caller");
13096         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, callerSessionInfo->persistentId);
13097     } else if (AAFwk::UIExtensionUtils::IsUIExtension(callerAbilityRecord->GetAbilityInfo().extensionAbilityType)) {
13098         int32_t mainWindowId = -1;
13099         auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().
13100             GetSceneSessionManagerLiteProxy();
13101         CHECK_POINTER_LOG(sceneSessionManager, "sceneSessionManager is nullptr");
13102         auto err = sceneSessionManager->GetRootMainWindowId(static_cast<int32_t>(callerSessionInfo->hostWindowId),mainWindowId);
13103         TAG_LOGI(AAFwkTag::ABILITYMGR, "callerSessionInfo->hostWindowId = %{public}d, mainWindowId = %{public}d, err = %{public}d",
13104             callerSessionInfo->hostWindowId, mainWindowId, err);
13105         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, mainWindowId);
13106     } else {
13107         abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, 0);
13108     }
13109 }
13110 
TerminateMission(int32_t missionId)13111 int32_t AbilityManagerService::TerminateMission(int32_t missionId)
13112 {
13113     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13114     TAG_LOGI(AAFwkTag::ABILITYMGR, "terminateMission call");
13115     auto missionListManager = GetCurrentMissionListManager();
13116     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
13117     CHECK_CALLER_IS_SYSTEM_APP;
13118 
13119     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
13120         PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
13121         TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
13122         return CHECK_PERMISSION_FAILED;
13123     }
13124 
13125     return missionListManager->ClearMission(missionId);
13126 }
13127 
BlockAllAppStart(bool flag)13128 int32_t AbilityManagerService::BlockAllAppStart(bool flag)
13129 {
13130     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13131     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
13132 
13133     if (!AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
13134         TAG_LOGE(AAFwkTag::ABILITYMGR, "not supported device");
13135         return ERR_PERMISSION_DENIED;
13136     }
13137 
13138     if (!PermissionVerification::GetInstance()->VerifyBlockAllAppStartPermission()) {
13139         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
13140         return ERR_PERMISSION_DENIED;
13141     }
13142 
13143     std::unique_lock<ffrt::mutex> lock(shouldBlockAllAppStartMutex_);
13144     shouldBlockAllAppStart_ = flag;
13145     return ERR_OK;
13146 }
13147 
ShouldBlockAllAppStart()13148 bool AbilityManagerService::ShouldBlockAllAppStart()
13149 {
13150     if (!AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
13151         return false;
13152     }
13153 
13154     std::unique_lock<ffrt::mutex> lock(shouldBlockAllAppStartMutex_);
13155     return shouldBlockAllAppStart_;
13156 }
13157 
UpdateAssociateConfigList(const std::map<std::string,std::list<std::string>> & configs,const std::list<std::string> & exportConfigs,int32_t flag)13158 int32_t AbilityManagerService::UpdateAssociateConfigList(const std::map<std::string, std::list<std::string>>& configs,
13159     const std::list<std::string>& exportConfigs, int32_t flag)
13160 {
13161     if (IPCSkeleton::GetCallingUid() != RESOURCE_SCHEDULE_UID) {
13162         TAG_LOGE(AAFwkTag::ABILITYMGR, "Update associate config, current process not rss process");
13163         return CHECK_PERMISSION_FAILED;
13164     }
13165     std::lock_guard<std::mutex> locker(whiteListMutex_);
13166     if (flag == UPDATE_CONFIG_FLAG_COVER) {
13167         whiteListMap_ = configs;
13168         exportWhiteList_ = exportConfigs;
13169     } else if (flag == UPDATE_CONFIG_FLAG_APPEND) {
13170         for (const auto& config : configs) {
13171             for (const auto& item : config.second) {
13172                 whiteListMap_[config.first].push_back(item);
13173             }
13174         }
13175         for (const auto& config : exportConfigs) {
13176             exportWhiteList_.push_back(config);
13177         }
13178     }
13179     return ERR_OK;
13180 }
13181 
EnableListForSCBRecovery(int32_t userId) const13182 void AbilityManagerService::EnableListForSCBRecovery(int32_t userId) const
13183 {
13184     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
13185     CHECK_POINTER_LOG(uiAbilityManager, "UIAbilityMgr not exist.");
13186     uiAbilityManager->EnableListForSCBRecovery();
13187 }
13188 
UpdateKeepAliveEnableState(const std::string & bundleName,const std::string & moduleName,const std::string & mainElement,bool updateEnable,int32_t userId)13189 int32_t AbilityManagerService::UpdateKeepAliveEnableState(const std::string &bundleName,
13190     const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId)
13191 {
13192     auto connectManager = GetConnectManagerByUserId(userId);
13193     CHECK_POINTER_AND_RETURN(connectManager, ERR_NULL_OBJECT);
13194     int32_t ret = connectManager->UpdateKeepAliveEnableState(bundleName, moduleName, mainElement, updateEnable);
13195     if (ret != ERR_OK) {
13196         TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateKeepAliveEnableState failed, err:%{public}d", ret);
13197     }
13198     return ret;
13199 }
13200 
IsInStatusBar(uint32_t accessTokenId,int32_t uid,bool isMultiInstance)13201 bool AbilityManagerService::IsInStatusBar(uint32_t accessTokenId, int32_t uid, bool isMultiInstance)
13202 {
13203     auto uiAbilityManager = GetUIAbilityManagerByUid(uid);
13204     CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
13205 
13206     return uiAbilityManager->IsInStatusBar(accessTokenId, isMultiInstance);
13207 }
13208 
IsSupportStatusBar(int32_t uid)13209 bool AbilityManagerService::IsSupportStatusBar(int32_t uid)
13210 {
13211     auto uiAbilityManager = GetUIAbilityManagerByUid(uid);
13212     CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
13213 
13214     return uiAbilityManager->IsSupportStatusBar();
13215 }
13216 
SetApplicationKeepAlive(const std::string & bundleName,int32_t userId,bool flag)13217 int32_t AbilityManagerService::SetApplicationKeepAlive(const std::string &bundleName, int32_t userId, bool flag)
13218 {
13219     return KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(
13220         bundleName, userId, flag, false, false);
13221 }
13222 
QueryKeepAliveApplications(int32_t appType,int32_t userId,std::vector<KeepAliveInfo> & list)13223 int32_t AbilityManagerService::QueryKeepAliveApplications(int32_t appType, int32_t userId,
13224     std::vector<KeepAliveInfo> &list)
13225 {
13226     return KeepAliveProcessManager::GetInstance().QueryKeepAliveApplications(
13227         appType, userId, list, false);
13228 }
13229 
SetApplicationKeepAliveByEDM(const std::string & bundleName,int32_t userId,bool flag)13230 int32_t AbilityManagerService::SetApplicationKeepAliveByEDM(const std::string &bundleName, int32_t userId, bool flag)
13231 {
13232     return KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(
13233         bundleName, userId, flag, true, false);
13234 }
13235 
QueryKeepAliveApplicationsByEDM(int32_t appType,int32_t userId,std::vector<KeepAliveInfo> & list)13236 int32_t AbilityManagerService::QueryKeepAliveApplicationsByEDM(int32_t appType, int32_t userId,
13237     std::vector<KeepAliveInfo> &list)
13238 {
13239     return KeepAliveProcessManager::GetInstance().QueryKeepAliveApplications(
13240         appType, userId, list, true);
13241 }
13242 
StartSelfUIAbilityInner(StartSelfUIAbilityParam param)13243 int AbilityManagerService::StartSelfUIAbilityInner(StartSelfUIAbilityParam param)
13244 {
13245     CHECK_TRUE_RETURN_RET(!AppUtils::GetInstance().IsStartOptionsWithAnimation(),
13246         ERR_CAPABILITY_NOT_SUPPORT, "not supported");
13247 
13248     auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
13249     CHECK_POINTER_AND_RETURN(bundleMgrHelper, INNER_ERR);
13250 
13251     AppExecFwk::AbilityInfo abilityInfo;
13252     CHECK_TRUE_RETURN_RET(!IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(param.want,
13253         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, GetUserId(), abilityInfo)),
13254         ERR_NOT_ALLOW_IMPLICIT_START, "bundle or ability not exist");
13255 
13256     CHECK_TRUE_RETURN_RET(abilityInfo.type != AppExecFwk::AbilityType::PAGE,
13257         RESOLVE_CALL_ABILITY_TYPE_ERR, "not UIAbility");
13258 
13259     auto callingPid = IPCSkeleton::GetCallingPid();
13260     AppExecFwk::RunningProcessInfo processInfo;
13261     DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByChildProcessPid(callingPid, processInfo);
13262     CHECK_TRUE_RETURN_RET(processInfo.bundleNames.empty(), INNER_ERR, "failed to get by child process pid");
13263 
13264     auto iter = std::find_if(processInfo.bundleNames.begin(), processInfo.bundleNames.end(),
13265         [targetBundleName = param.want.GetBundle()](const std::string &bundleName) {
13266             return bundleName == targetBundleName;
13267         });
13268     CHECK_TRUE_RETURN_RET(iter == processInfo.bundleNames.end(), ERR_START_OTHER_APP_FAILED, "cannot start other app");
13269 
13270     param.want.RemoveParam(Want::PARAM_APP_CLONE_INDEX_KEY);
13271     if (processInfo.appMode == AppExecFwk::MultiAppModeType::APP_CLONE) {
13272         TAG_LOGI(AAFwkTag::ABILITYMGR, "set appIndex: %{public}d", processInfo.appCloneIndex);
13273         param.want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, processInfo.appCloneIndex);
13274     }
13275 
13276     if (processInfo.appMode == AppExecFwk::MultiAppModeType::MULTI_INSTANCE &&
13277         !param.want.HasParameter(Want::APP_INSTANCE_KEY) &&
13278         !param.want.GetBoolParam(Want::CREATE_APP_INSTANCE_KEY, false)) {
13279         TAG_LOGI(AAFwkTag::ABILITYMGR, "set instanceKey: %{public}s", processInfo.instanceKey.c_str());
13280         param.want.SetParam(Want::APP_INSTANCE_KEY, processInfo.instanceKey);
13281     }
13282 
13283     auto tokenId = abilityInfo.applicationInfo.accessTokenId;
13284     StartSelfUIAbilityRecordGuard startSelfUIAbilityRecordGuard(callingPid, tokenId);
13285     CHECK_TRUE_RETURN_RET(!PermissionVerification::GetInstance()->VerifyStartSelfUIAbility(tokenId),
13286         CHECK_PERMISSION_FAILED, "permission denied");
13287 
13288     CHECK_TRUE_RETURN_RET(processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND,
13289         NOT_TOP_ABILITY, "caller not foreground");
13290 
13291     if (!param.hasStartOptions) {
13292         return StartAbility(param.want);
13293     }
13294     return StartAbility(param.want, param.options, nullptr);
13295 }
13296 
StartSelfUIAbility(const Want & want)13297 int AbilityManagerService::StartSelfUIAbility(const Want &want)
13298 {
13299     TAG_LOGI(AAFwkTag::ABILITYMGR, "call StartSelfUIAbility");
13300 
13301     StartSelfUIAbilityParam param;
13302     param.want = want;
13303     return StartSelfUIAbilityInner(param);
13304 }
13305 
StartSelfUIAbilityWithStartOptions(const Want & want,const StartOptions & options)13306 int AbilityManagerService::StartSelfUIAbilityWithStartOptions(const Want &want, const StartOptions &options)
13307 {
13308     TAG_LOGI(AAFwkTag::ABILITYMGR, "call StartSelfUIAbility with startOptions");
13309 
13310     if(options.processOptions != nullptr) {
13311        options.processOptions->isStartFromNDK = true;
13312     }
13313 
13314     StartSelfUIAbilityParam param = { want, options, true };
13315     return StartSelfUIAbilityInner(param);
13316 }
13317 
CheckCrossUser(const int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)13318 bool AbilityManagerService::CheckCrossUser(const int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
13319 {
13320     if (AAFwk::UIExtensionUtils::IsEnterpriseAdmin(extensionType) || JudgeMultiUserConcurrency(userId)) {
13321         return true;
13322     }
13323     if (AppUtils::GetInstance().IsConnectSupportCrossUser() && (extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE
13324         || extensionType == AppExecFwk::ExtensionAbilityType::SERVICE)) {
13325         return true;
13326     }
13327     return false;
13328 }
13329 
KillProcessForPermissionUpdate(uint32_t accessTokenId)13330 int32_t AbilityManagerService::KillProcessForPermissionUpdate(uint32_t accessTokenId)
13331 {
13332     int32_t callingUid = IPCSkeleton::GetCallingUid();
13333     TAG_LOGI(AAFwkTag::ABILITYMGR,
13334         "Call KillProcessForPermissionUpdate. callingUid: %{public}d", callingUid);
13335     auto isCallingPerm = PermissionVerification::GetInstance()->VerifyCallingPermission(
13336         PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
13337     if (!isCallingPerm) {
13338         TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to kill processes.");
13339         return ERR_PERMISSION_DENIED;
13340     }
13341 
13342     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
13343         auto uiAbilityManager = GetUIAbilityManagerByUid(callingUid);
13344         CHECK_POINTER_AND_RETURN_LOG(uiAbilityManager, ERR_NULL_OBJECT, "uiAbilityLifecycleManager nullptr");
13345         uiAbilityManager->SetKillForPermissionUpdateFlag(accessTokenId);
13346     }
13347 
13348     int32_t ret =
13349         DelayedSingleton<AppScheduler>::GetInstance()->KillProcessesByAccessTokenId(accessTokenId);
13350     if (ret != ERR_OK) {
13351         TAG_LOGE(AAFwkTag::ABILITYMGR, "KillProcessesByAccessTokenId error");
13352         return ret;
13353     }
13354 
13355     return ERR_OK;
13356 }
13357 
RegisterHiddenStartObserver(const sptr<IHiddenStartObserver> & observer)13358 int32_t AbilityManagerService::RegisterHiddenStartObserver(const sptr<IHiddenStartObserver> &observer)
13359 {
13360     if (!AAFwk::PermissionVerification::GetInstance()->VerifyStartUIAbilityToHiddenPermission()) {
13361         TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterHiddenStartObserver permission verification failed");
13362         return ERR_PERMISSION_DENIED;
13363     }
13364     return HiddenStartObserverManager::GetInstance().RegisterObserver(observer);
13365 }
13366 
UnregisterHiddenStartObserver(const sptr<IHiddenStartObserver> & observer)13367 int32_t AbilityManagerService::UnregisterHiddenStartObserver(const sptr<IHiddenStartObserver> &observer)
13368 {
13369     if (!AAFwk::PermissionVerification::GetInstance()->VerifyStartUIAbilityToHiddenPermission()) {
13370         TAG_LOGE(AAFwkTag::ABILITYMGR, "UnregisterHiddenStartObserver permission verification failed");
13371         return ERR_PERMISSION_DENIED;
13372     }
13373     return HiddenStartObserverManager::GetInstance().UnregisterObserver(observer);
13374 }
13375 
QueryPreLoadUIExtensionRecord(const AppExecFwk::ElementName & element,const std::string & moduleName,const std::string & hostBundleName,int32_t & recordNum,int32_t userId)13376 int32_t AbilityManagerService::QueryPreLoadUIExtensionRecord(const AppExecFwk::ElementName &element,
13377                                                              const std::string &moduleName,
13378                                                              const std::string &hostBundleName,
13379                                                              int32_t &recordNum,
13380                                                              int32_t userId)
13381 {
13382   // check preload ui extension permission.
13383   CHECK_CALLER_IS_SYSTEM_APP;
13384   if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
13385           PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
13386       TAG_LOGE(AAFwkTag::UI_EXT, "permission %{public}s verification failed",
13387                PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
13388       return ERR_PERMISSION_DENIED;
13389   }
13390   int32_t validUserId = GetValidUserId(userId);
13391   auto connectManager = GetConnectManagerByUserId(validUserId);
13392   if (!connectManager) {
13393       TAG_LOGE(AAFwkTag::UI_EXT, "connectManager null. userId=%{public}d", userId);
13394       return ERR_INVALID_VALUE;
13395   }
13396   return connectManager->QueryPreLoadUIExtensionRecordInner(
13397       element, moduleName, hostBundleName, recordNum);
13398 }
13399 }  // namespace AAFwk
13400 }  // namespace OHOS
13401