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_business_error.h"
22 #include "ability_connect_manager.h"
23 #include "ability_errors_util.h"
24 #include "ability_manager_radar.h"
25 #include "ability_start_by_call_helper.h"
26 #include "ability_start_with_wait_observer_utils.h"
27 #include "ability_start_with_wait_observer_manager.h"
28 #include "accesstoken_kit.h"
29 #include "ability_manager_xcollie.h"
30 #include "app_utils.h"
31 #include "app_exit_reason_data_manager.h"
32 #include "application_util.h"
33 #include "app_mgr_constants.h"
34 #include "app_mgr_util.h"
35 #include "recovery_info_timer.h"
36 #include "assert_fault_callback_death_mgr.h"
37 #include "concurrent_task_client.h"
38 #include "connection_state_manager.h"
39 #include "c/executor_task.h"
40 #include "display_manager.h"
41 #include "display_util.h"
42 #include "distributed_client.h"
43 #include "ipc_skeleton.h"
44 #ifdef WITH_DLP
45 #include "dlp_utils.h"
46 #endif // WITH_DLP
47 #include "exit_info_data_manager.h"
48 #include "ffrt.h"
49 #include "ffrt_inner.h"
50 #include "freeze_util.h"
51 #include "global_constant.h"
52 #include "hitrace_meter.h"
53 #include "insight_intent_execute_manager.h"
54 #include "insight_intent_db_cache.h"
55 #include "insight_intent_utils.h"
56 #include "interceptor/ability_jump_interceptor.h"
57 #include "interceptor/block_all_app_start_interceptor.h"
58 #include "interceptor/control_interceptor.h"
59 #include "interceptor/crowd_test_interceptor.h"
60 #include "interceptor/disposed_rule_interceptor.h"
61 #include "interceptor/ecological_rule_interceptor.h"
62 #include "interceptor/extension_control_interceptor.h"
63 #include "interceptor/screen_unlock_interceptor.h"
64 #include "interceptor/start_other_app_interceptor.h"
65 #include "interceptor/kiosk_interceptor.h"
66 #include "int_wrapper.h"
67 #include "ipc_skeleton.h"
68 #include "iservice_registry.h"
69 #include "keep_alive_process_manager.h"
70 #include "keep_alive_utils.h"
71 #include "main_element_utils.h"
72 #ifdef MEMMGR_OVERRIDE_ENABLE
73 #include "mem_mgr_client.h"
74 #include "mem_mgr_process_state_info.h"
75 #endif
76 #include "mock_session_manager_service.h"
77 #include "modal_system_dialog/modal_system_dialog_ui_extension.h"
78 #include "modal_system_ui_extension.h"
79 #include "multi_app_utils.h"
80 #include "os_account_manager_wrapper.h"
81 #include "permission_constants.h"
82 #include "preload_manager_service.h"
83 #include "process_options.h"
84 #include "rate_limiter.h"
85 #include "recovery_param.h"
86 #include "report_data_partition_usage_manager.h"
87 #include "res_sched_util.h"
88 #include "restart_app_manager.h"
89 #include "scene_board_judgement.h"
90 #include "server_constant.h"
91 #include "session_manager_lite.h"
92 #include "softbus_bus_center.h"
93 #include "start_ability_handler/start_ability_sandbox_savefile.h"
94 #include "start_ability_utils.h"
95 #include "start_options_utils.h"
96 #include "startup_util.h"
97 #include "status_bar_delegate_interface.h"
98 #include "string_wrapper.h"
99 #include "support_system_ability_permission.h"
100 #include "time_util.h"
101 #include "ui_extension_utils.h"
102 #include "ui_service_extension_connection_constants.h"
103 #include "unlock_screen_manager.h"
104 #ifdef SUPPORT_UPMS
105 #include "uri_permission_manager_client.h"
106 #endif // SUPPORT_UPMS
107 #include "uri_utils.h"
108 #include "view_data.h"
109 #include "xcollie/watchdog.h"
110 #include "config_policy_utils.h"
111 #include "uri_utils.h"
112 #include "utils/ability_permission_util.h"
113 #include "utils/dump_utils.h"
114 #include "utils/extension_permissions_util.h"
115 #include "utils/modal_system_dialog_util.h"
116 #include "utils/update_caller_info_util.h"
117 #include "utils/want_utils.h"
118 #include "utils/window_options_utils.h"
119 #include "insight_intent_execute_manager.h"
120 #ifdef SUPPORT_GRAPHICS
121 #include "dialog_session_manager.h"
122 #include "application_anr_listener.h"
123 #include "input_manager.h"
124 #include "ability_first_frame_state_observer_manager.h"
125 #include "session_manager_lite.h"
126 #include "session/host/include/zidl/session_interface.h"
127 #include "window_focus_changed_listener.h"
128 #include "wm_common.h"
129 #endif
130 #include "query_erms_manager.h"
131 #include "window_visibility_changed_listener.h"
132 #ifdef SUPPORT_SCREEN
133 #include "utils/dms_util.h"
134 #endif
135 #include "hidden_start_observer_manager.h"
136 #include "insight_intent_db_cache.h"
137 #include "sa_interceptor_manager.h"
138
139 using OHOS::AppExecFwk::ElementName;
140 using OHOS::Security::AccessToken::AccessTokenKit;
141
142 namespace OHOS {
143 using AbilityRuntime::FreezeUtil;
144 using namespace AbilityRuntime::ServerConstant;
145 namespace AAFwk {
146 using AutoStartupInfo = AbilityRuntime::AutoStartupInfo;
147 using GetExtensionAbilityInfoFlag = AppExecFwk::GetExtensionAbilityInfoFlag;
148 namespace {
149 #define CHECK_CALLER_IS_SYSTEM_APP \
150 if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
151 TAG_LOGE(AAFwkTag::ABILITYMGR, \
152 "caller no system-app, can not use system-api"); \
153 return ERR_NOT_SYSTEM_APP; \
154 }
155
156 constexpr const char* ARGS_USER_ID = "-u";
157 constexpr const char* ARGS_CLIENT = "-c";
158 constexpr const char* ILLEGAL_INFOMATION = "The arguments are illegal and you can enter '-h' for help.";
159
160 constexpr int32_t NEW_RULE_VALUE_SIZE = 6;
161 constexpr int32_t APP_ALIVE_TIME_MS = 1000; // Allow background startup within 1 second after application startup
162 constexpr int32_t REGISTER_FOCUS_DELAY = 5000;
163 constexpr size_t OFFSET = 32;
164 constexpr int32_t PENG_LAI_UID = 7655;
165 constexpr const char* IS_DELEGATOR_CALL = "isDelegatorCall";
166
167 // Startup rule switch
168 constexpr const char* COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
169 constexpr const char* BACKGROUND_JUDGE_FLAG = "component.startup.backgroundJudge.flag";
170 constexpr const char* WHITE_LIST_ASS_WAKEUP_FLAG = "component.startup.whitelist.associatedWakeUp";
171
172 // White list app
173 constexpr const char* BUNDLE_NAME_SETTINGSDATA = "com.ohos.settingsdata";
174 // UIExtension type
175 constexpr const char* UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType";
176 constexpr const char* UIEXTENSION_TARGET_TYPE_KEY = "ability.want.params.uiExtensionTargetType";
177 // Share picker params
178 constexpr char SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY[] = "const.system.sharePicker.bundleName";
179 constexpr char SHARE_PICKER_DIALOG_ABILITY_NAME_KEY[] = "const.system.sharePicker.abilityName";
180 constexpr char SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME[] = "com.ohos.sharepickerdialog";
181 constexpr char SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME[] = "PickerDialog";
182 constexpr char TOKEN_KEY[] = "ohos.ability.params.token";
183 // Developer mode param
184 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
185 constexpr char PRODUCT_APPBOOT_SETTING_ENABLED[] = "const.product.appboot.setting.enabled";
186 // Broker params key
187 constexpr const char* KEY_VISIBLE_ID = "ohos.anco.param.visible";
188 constexpr const char* START_ABILITY_TYPE = "ABILITY_INNER_START_WITH_ACCOUNT";
189 constexpr const char* BUNDLE_NAME_DIALOG = "com.ohos.amsdialog";
190 constexpr const char* STR_PHONE = "phone";
191 constexpr const char* PARAM_RESV_ANCO_CALLER_UID = "ohos.anco.param.callerUid";
192 constexpr const char* PARAM_RESV_ANCO_CALLER_BUNDLENAME = "ohos.anco.param.callerBundleName";
193 constexpr const char* PARAM_RESV_ANCO_IS_NEED_UPDATE_NAME = "ohos.anco.param.isNeedUpdateName";
194 constexpr const char* PARAM_ANCO_APP_IDENTIFIER = "persist.hmos_fusion_mgr.anco_identifier";
195 // Distributed continued session Id
196 constexpr const char* DMS_CONTINUED_SESSION_ID = "ohos.dms.continueSessionId";
197 constexpr const char* DMS_PERSISTENT_ID = "ohos.dms.persistentId";
198 constexpr const char* DMS_CALLING_UID = "ohos.dms.callingUid";
199
200 constexpr const char* DEBUG_APP = "debugApp";
201 constexpr const char* NATIVE_DEBUG = "nativeDebug";
202 constexpr const char* DEBUG_FROM = "ohos.param.debugFrom";
203 constexpr const char* AUTO_FILL_PASSWORD_TYPE = "autoFill/password";
204 constexpr const char* AUTO_FILL_SMART_TYPE = "autoFill/smart";
205 constexpr size_t INDEX_ZERO = 0;
206 constexpr size_t INDEX_ONE = 1;
207 constexpr size_t INDEX_TWO = 2;
208 constexpr size_t ARGC_THREE = 3;
209 constexpr size_t INDEX_FOUR = 4;
210 constexpr static char WANT_PARAMS_VIEW_DATA_KEY[] = "ohos.ability.params.viewData";
211 constexpr const char* WANT_PARAMS_HOST_WINDOW_ID_KEY = "ohos.extra.param.key.hostwindowid";
212
213 constexpr int32_t FOUNDATION_UID = 5523;
214 constexpr const char* FRS_BUNDLE_NAME = "com.ohos.formrenderservice";
215 constexpr const char* FOUNDATION_PROCESS_NAME = "foundation";
216 constexpr const char* RSS_PROCESS_NAME = "resource_schedule_service";
217 constexpr const char* IS_PRELOAD_UIEXTENSION_ABILITY = "ability.want.params.is_preload_uiextension_ability";
218 constexpr const char* UIEXTENSION_MODAL_TYPE = "ability.want.params.modalType";
219 constexpr const char* SUPPORT_CLOSE_ON_BLUR = "supportCloseOnBlur";
220 constexpr const char* ATOMIC_SERVICE_PREFIX = "com.atomicservice.";
221 constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohosSpecifiedProcessFlag";
222 #ifdef MEMMGR_OVERRIDE_ENABLE
223 constexpr const char* EXPECT_WINDOW_MODE = "expectWindowMode";
224 #endif
225
226 constexpr char ASSERT_FAULT_DETAIL[] = "assertFaultDialogDetail";
227 constexpr char PRODUCT_ASSERT_FAULT_DIALOG_ENABLED[] = "persisit.sys.abilityms.support_assert_fault_dialog";
228 constexpr const char* ABILITYMS_ENABLE_UISERVICE = "const.abilityms.enable_uiservice";
229
230 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
231
232 constexpr char PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED[] = "const.product.enterprisefeature.setting.enabled";
233
234 constexpr int32_t RESOURCE_SCHEDULE_UID = 1096;
235 constexpr int32_t HIVIEW_UID = 1201;
236 constexpr int32_t MEMMGR_UID = 1111;
237 constexpr int32_t UPDATE_CONFIG_FLAG_COVER = 1;
238 constexpr int32_t UPDATE_CONFIG_FLAG_APPEND = 2;
239 constexpr int32_t START_AUTO_START_APP_DELAY_TIME = 200;
240 constexpr int32_t START_AUTO_START_APP_RETRY_MAX_TIMES = 5;
241 constexpr int32_t RETRY_COUNT = 20;
242 constexpr const char* LIFE_CYCLE_STATE_FOREGROUND_DONE = "foreground done";
243 constexpr const char* LIFE_CYCLE_STATE_BACKGROUND_DONE = "background done";
244
245 const std::unordered_set<std::string> COMMON_PICKER_TYPE = {
246 "share", "action", "navigation", "mail", "finance", "flight", "express", "photoEditor"
247 };
248 std::atomic<bool> g_isDmsAlive = false;
249 constexpr int32_t PIPE_MSG_READ_BUFFER = 1024;
250 constexpr const char* APPSPAWN_STARTED = "startup.service.ctl.appspawn.pid";
251 constexpr const char* APP_LINKING_ONLY = "appLinkingOnly";
252 constexpr const char* SCREENCONFIG_SCREENMODE = "ohos.verticalpanel.screenconfig.screenmode";
253
SendAbilityEvent(const EventName & eventName,HiSysEventType type,const EventInfo & eventInfo)254 void SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo)
255 {
256 ffrt::submit([eventName, type, eventInfo]() {
257 EventReport::SendAbilityEvent(eventName, type, eventInfo);
258 }, ffrt::task_attr().timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
259 }
260
IsEmbeddableStart(int32_t screenMode)261 bool IsEmbeddableStart(int32_t screenMode)
262 {
263 return screenMode == AAFwk::EMBEDDED_FULL_SCREEN_MODE ||
264 screenMode == AAFwk::EMBEDDED_HALF_SCREEN_MODE;
265 }
266
SendUIAbilityEvent(EventInfo & eventInfo,const int32_t state)267 void SendUIAbilityEvent(EventInfo &eventInfo, const int32_t state)
268 {
269 if (state == static_cast<int32_t>(AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND)) {
270 eventInfo.lifeCycleState = LIFE_CYCLE_STATE_FOREGROUND_DONE;
271 SendAbilityEvent(EventName::ABILITY_ONFOREGROUND, HiSysEventType::BEHAVIOR, eventInfo);
272 } else if (state == static_cast<int32_t>(AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND)) {
273 eventInfo.lifeCycleState = LIFE_CYCLE_STATE_BACKGROUND_DONE;
274 SendAbilityEvent(EventName::ABILITY_ONBACKGROUND, HiSysEventType::BEHAVIOR, eventInfo);
275 }
276 }
277 } // namespace
278
279 using namespace std::chrono;
280 using namespace std::chrono_literals;
281 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
282 using namespace BackgroundTaskMgr;
283 #endif
284 const bool CONCURRENCY_MODE_FALSE = false;
285 constexpr int32_t MAIN_USER_ID = 100;
286 constexpr auto DATA_ABILITY_START_TIMEOUT = 5s;
287 constexpr int32_t NON_ANONYMIZE_LENGTH = 6;
288 constexpr uint32_t SCENE_FLAG_NORMAL = 0;
289 constexpr int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20;
290 constexpr int32_t SWITCH_ACCOUNT_TRY = 3;
291 constexpr const char* EMPTY_DEVICE_ID = "";
292 constexpr int32_t APP_MEMORY_SIZE = 512;
293 constexpr int32_t GET_PARAMETER_INCORRECT = -9;
294 constexpr int32_t GET_PARAMETER_OTHER = -1;
295 constexpr int32_t SIZE_10 = 10;
296 constexpr int32_t HIDUMPER_SERVICE_UID = 1212;
297 constexpr int32_t ACCOUNT_MGR_SERVICE_UID = 3058;
298 constexpr int32_t DMS_UID = 5522;
299 constexpr int32_t SAMGR_UID = 5555;
300 constexpr int32_t BOOTEVENT_COMPLETED_DELAY_TIME = 1000;
301 constexpr int32_t BOOTEVENT_BOOT_ANIMATION_READY_SIZE = 6;
302 constexpr const char* BUNDLE_NAME_KEY = "bundleName";
303 constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager";
304 constexpr const char* ACTION_CHOOSE = "ohos.want.action.select";
305 constexpr const char* HIGHEST_PRIORITY_ABILITY_ENTITY = "flag.home.intent.from.system";
306 constexpr const char* DMS_API_VERSION = "dmsApiVersion";
307 constexpr const char* DMS_IS_CALLER_BACKGROUND = "dmsIsCallerBackGround";
308 constexpr const char* DMS_PROCESS_NAME = "distributedsched";
309 constexpr const char* DMS_MISSION_ID = "dmsMissionId";
310 constexpr const char* BOOTEVENT_APPFWK_READY = "bootevent.appfwk.ready";
311 constexpr const char* BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed";
312 constexpr const char* BOOTEVENT_BOOT_ANIMATION_STARTED = "bootevent.bootanimation.started";
313 constexpr const char* BOOTEVENT_BOOT_ANIMATION_READY = "bootevent.bootanimation.ready";
314 constexpr const char* NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
315 constexpr const char* PERMISSIONMGR_BUNDLE_NAME = "com.ohos.permissionmanager";
316 constexpr const char* PERMISSIONMGR_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility";
317 constexpr const char* SCENEBOARD_BUNDLE_NAME = "com.ohos.sceneboard";
318 constexpr const char* SPECIFY_TOKEN_ID = "specifyTokenId";
319 constexpr const char* PROCESS_SUFFIX = "embeddable";
320 constexpr int32_t DEFAULT_DMS_MISSION_ID = -1;
321 constexpr const char* PARAM_PREVENT_STARTABILITY = "persist.sys.abilityms.prevent_startability";
322 constexpr const char* SUSPEND_SERVICE_CONFIG_FILE = "/etc/efficiency_manager/prevent_startability_whitelist.json";
323 constexpr int32_t MAX_BUFFER = 2048;
324 constexpr int32_t API12 = 12;
325 constexpr int32_t API_VERSION_MOD = 100;
326 constexpr const char* WHITE_LIST = "white_list";
327 constexpr const char* SUPPORT_COLLABORATE_INDEX = "ohos.extra.param.key.supportCollaborateIndex";
328 constexpr const char* COLLABORATE_KEY = "ohos.dms.collabToken";
329 constexpr const char* IS_CALLING_FROM_DMS = "supportCollaborativeCallingFromDmsInAAFwk";
330 constexpr int32_t CLEAR_REASON_DELAY_TIME = 3000000; // 3s
331 constexpr const char* LIFE_CYCLE_START = "start";
332 constexpr const char* LIFE_CYCLE_CONNECT = "connect";
333 constexpr const char* LIFE_CYCLE_MINIMIZE = "minimize";
334 constexpr const char* LIFE_CYCLE_TERMINATE = "terminate";
335 constexpr const char* LIFE_CYCLE_PRELOAD = "preload";
336 constexpr uint32_t TARGET_TYPE_INIT = 100;
337
338 const bool REGISTER_RESULT =
339 SystemAbility::MakeAndRegisterAbility(DelayedSingleton<AbilityManagerService>::GetInstance().get());
340 sptr<AbilityManagerService> AbilityManagerService::instance_;
341
AbilityManagerService()342 AbilityManagerService::AbilityManagerService()
343 : SystemAbility(ABILITY_MGR_SERVICE_ID, true),
344 state_(ServiceRunningState::STATE_NOT_START)
345 {}
346
~AbilityManagerService()347 AbilityManagerService::~AbilityManagerService()
348 {}
349
GetPubInstance()350 std::shared_ptr<AbilityManagerService> AbilityManagerService::GetPubInstance()
351 {
352 return DelayedSingleton<AbilityManagerService>::GetInstance();
353 }
354
OnStart()355 void AbilityManagerService::OnStart()
356 {
357 if (state_ == ServiceRunningState::STATE_RUNNING) {
358 TAG_LOGI(AAFwkTag::ABILITYMGR, "started");
359 return;
360 }
361 TAG_LOGI(AAFwkTag::ABILITYMGR, "starting");
362 if (!Init()) {
363 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed init");
364 return;
365 }
366 state_ = ServiceRunningState::STATE_RUNNING;
367 /* Publish service maybe failed, so we need call this function at the last,
368 * so it can't affect the TDD test program */
369 instance_ = DelayedSingleton<AbilityManagerService>::GetInstance().get();
370 if (instance_ == nullptr) {
371 TAG_LOGE(AAFwkTag::ABILITYMGR, "instance_ null");
372 return;
373 }
374 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
375 if (bundleMgrHelper) {
376 bundleMgrHelper->SetBmsReady(false);
377 }
378 bool ret = Publish(instance_);
379 if (!ret) {
380 TAG_LOGE(AAFwkTag::ABILITYMGR, "publish failed");
381 return;
382 }
383
384 SetParameter(BOOTEVENT_APPFWK_READY, "true");
385 bool bgTaskMgr = AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
386 bool distributedMgr = AddSystemAbilityListener(DISTRIBUTED_SCHED_SA_ID);
387 bool bundleMgr = AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
388 #ifdef SUPPORT_SCREEN
389 if (!AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID)) {
390 TAG_LOGE(AAFwkTag::ABILITYMGR, "OnStart, add listener err");
391 }
392 #endif
393 bool windowMgr = AddSystemAbilityListener(WINDOW_MANAGER_SERVICE_ID);
394 if (!bgTaskMgr || !distributedMgr || !bundleMgr || !windowMgr) {
395 TAG_LOGE(AAFwkTag::ABILITYMGR, "OnStart, add listeners err");
396 }
397 TAG_LOGI(AAFwkTag::ABILITYMGR, "onStart success");
398 auto pid = getpid();
399 std::unordered_map<std::string, std::string> payload;
400 payload["pid"] = std::to_string(pid);
401 OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload);
402 }
403
Init()404 bool AbilityManagerService::Init()
405 {
406 HiviewDFX::Watchdog::GetInstance().InitFfrtWatchdog(); // For ffrt watchdog available in foundation
407 taskHandler_ = TaskHandlerWrap::CreateQueueHandler(AbilityConfig::NAME_ABILITY_MGR_SERVICE);
408 eventHandler_ = std::make_shared<AbilityEventHandler>(taskHandler_, weak_from_this());
409 freeInstallManager_ = std::make_shared<FreeInstallManager>(weak_from_this());
410 CHECK_POINTER_RETURN_BOOL(freeInstallManager_);
411
412 // init user controller.
413 userController_ = std::make_shared<UserController>();
414 userController_->Init();
415 AmsConfigurationParameter::GetInstance().Parse();
416 TAG_LOGI(AAFwkTag::ABILITYMGR, "config parse");
417 subManagersHelper_ = std::make_shared<SubManagersHelper>(taskHandler_, eventHandler_);
418 subManagersHelper_->InitSubManagers(MAIN_USER_ID, true);
419 SwitchManagers(U0_USER_ID, false);
420 #ifdef SUPPORT_SCREEN
421 implicitStartProcessor_ = std::make_shared<ImplicitStartProcessor>();
422 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
423 InitFocusListener();
424 }
425 AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().Init();
426 #endif
427
428 DelayedSingleton<ConnectionStateManager>::GetInstance()->Init(taskHandler_);
429
430 InitInterceptor();
431 InitStartAbilityChain();
432 InitDeepLinkReserve();
433
434 abilityAutoStartupService_ = std::make_shared<AbilityRuntime::AbilityAutoStartupService>();
435 InitPushTask();
436 AbilityCacheManager::GetInstance().Init(AppUtils::GetInstance().GetLimitMaximumExtensionsPerDevice(),
437 AppUtils::GetInstance().GetLimitMaximumExtensionsPerProc());
438
439 SubscribeScreenUnlockedEvent();
440 appExitReasonHelper_ = std::make_shared<AppExitReasonHelper>(subManagersHelper_);
441 insightIntentEventMgr_ = std::make_shared<AbilityRuntime::InsightIntentEventMgr>();
442 insightIntentEventMgr_->SubscribeSysEventReceiver();
443 ReportDataPartitionUsageManager::SendReportDataPartitionUsageEvent();
444 TAG_LOGI(AAFwkTag::ABILITYMGR, "init success");
445 return true;
446 }
447
InitDeepLinkReserve()448 void AbilityManagerService::InitDeepLinkReserve()
449 {
450 if (!DeepLinkReserveConfig::GetInstance().LoadConfiguration()) {
451 TAG_LOGE(AAFwkTag::ABILITYMGR, "initDeepLinkReserve failed");
452 }
453 }
454
InitInterceptor()455 void AbilityManagerService::InitInterceptor()
456 {
457 interceptorExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
458 interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
459 interceptorExecuter_->AddInterceptor("CrowdTest", std::make_shared<CrowdTestInterceptor>());
460 interceptorExecuter_->AddInterceptor("Control", std::make_shared<ControlInterceptor>());
461 afterCheckExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
462 afterCheckExecuter_->AddInterceptor("ExtensionControl", std::make_shared<ExtensionControlInterceptor>());
463 afterCheckExecuter_->AddInterceptor("StartOtherApp", std::make_shared<StartOtherAppInterceptor>());
464 afterCheckExecuter_->AddInterceptor("DisposedRule", std::make_shared<DisposedRuleInterceptor>());
465 afterCheckExecuter_->AddInterceptor("EcologicalRule", std::make_shared<EcologicalRuleInterceptor>());
466 afterCheckExecuter_->SetTaskHandler(taskHandler_);
467 bool isAppJumpEnabled = OHOS::system::GetBoolParameter(
468 OHOS::AppExecFwk::PARAMETER_APP_JUMP_INTERCEPTOR_ENABLE, false);
469 if (isAppJumpEnabled) {
470 TAG_LOGI(AAFwkTag::ABILITYMGR, "app jump enabled, add abilityJumpInterceptor");
471 interceptorExecuter_->AddInterceptor("AbilityJump", std::make_shared<AbilityJumpInterceptor>());
472 }
473 if (AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
474 TAG_LOGI(AAFwkTag::ABILITYMGR, "add BlockAllAppStartInterceptor");
475 interceptorExecuter_->AddInterceptor("BlockAllAppStart", std::make_shared<BlockAllAppStartInterceptor>());
476 }
477 }
478
InitInterceptorForScreenUnlock()479 void AbilityManagerService::InitInterceptorForScreenUnlock()
480 {
481 if (interceptorExecuter_) {
482 interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
483 }
484 }
485
InitPushTask()486 void AbilityManagerService::InitPushTask()
487 {
488 if (taskHandler_ == nullptr) {
489 TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler_ null");
490 return;
491 }
492
493 auto initStartupFlagTask = [aams = shared_from_this()]() { aams->InitStartupFlag(); };
494 taskHandler_->SubmitTask(initStartupFlagTask, "InitStartupFlag");
495
496 auto initExtensionConfigTask = []() {
497 DelayedSingleton<ExtensionConfig>::GetInstance()->LoadExtensionConfiguration();
498 };
499 taskHandler_->SubmitTask(initExtensionConfigTask, "InitExtensionConfigTask");
500
501 auto bootCompletedTask = [handler = taskHandler_]() {
502 if (ApplicationUtil::IsBootCompleted()) {
503 auto task = []() {
504 ApplicationUtil::AppFwkBootEventCallback(BOOTEVENT_BOOT_COMPLETED, "true", nullptr);
505 };
506 CHECK_POINTER(handler);
507 handler->SubmitTaskJust(task, "BootCompletedDelayTask", BOOTEVENT_COMPLETED_DELAY_TIME);
508 } else {
509 WatchParameter(BOOTEVENT_BOOT_COMPLETED, ApplicationUtil::AppFwkBootEventCallback, nullptr);
510 TAG_LOGI(AAFwkTag::ABILITYMGR, "init call, InitPushTask suc");
511 }
512 };
513 if (!ParseJsonFromBoot(SUSPEND_SERVICE_CONFIG_FILE)) {
514 TAG_LOGE(AAFwkTag::ABILITYMGR, "parse json fail");
515 }
516 isParamStartAbilityEnable_ = system::GetBoolParameter(PARAM_PREVENT_STARTABILITY, false);
517 taskHandler_->SubmitTask(bootCompletedTask, "BootCompletedTask");
518 }
519
InitStartupFlag()520 void AbilityManagerService::InitStartupFlag()
521 {
522 startUpNewRule_ = CheckNewRuleSwitchState(COMPONENT_STARTUP_NEW_RULES);
523 backgroundJudgeFlag_ = CheckNewRuleSwitchState(BACKGROUND_JUDGE_FLAG);
524 whiteListassociatedWakeUpFlag_ = CheckNewRuleSwitchState(WHITE_LIST_ASS_WAKEUP_FLAG);
525 }
526
InitStartAbilityChain()527 void AbilityManagerService::InitStartAbilityChain()
528 {
529 auto startSandboxSaveFile = std::make_shared<StartAbilitySandboxSavefile>();
530 startAbilityChain_.emplace(startSandboxSaveFile->GetPriority(), startSandboxSaveFile);
531 }
532
OnStop()533 void AbilityManagerService::OnStop()
534 {
535 TAG_LOGI(AAFwkTag::ABILITYMGR, "stop");
536 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
537 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
538 if (bgtaskObserver_) {
539 int ret = BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver_);
540 if (ret != ERR_OK) {
541 TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bgtask failed, err:%{public}d", ret);
542 }
543 }
544 #endif
545 if (abilityBundleEventCallback_) {
546 auto bms = AbilityUtil::GetBundleManagerHelper();
547 if (bms) {
548 if (!IN_PROCESS_CALL(bms->UnregisterBundleEventCallback(abilityBundleEventCallback_))) {
549 TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bundle event failed");
550 }
551 auto pluginRet = IN_PROCESS_CALL(bms->UnregisterPluginEventCallback(abilityBundleEventCallback_));
552 if (pluginRet != ERR_OK) {
553 TAG_LOGE(AAFwkTag::ABILITYMGR, "UnregisterPluginEventCallback failed: %{public}d", pluginRet);
554 }
555 }
556 }
557 eventHandler_.reset();
558 taskHandler_.reset();
559 state_ = ServiceRunningState::STATE_NOT_START;
560 }
561
QueryServiceState() const562 ServiceRunningState AbilityManagerService::QueryServiceState() const
563 {
564 return state_;
565 }
566
StartAbility(const Want & want,int32_t userId,int requestCode)567 int AbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode)
568 {
569 if (AppUtils::GetInstance().IsForbidStart()) {
570 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
571 return INNER_ERR;
572 }
573 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
574 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
575 bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
576 bool isNativeDebugApp = want.GetBoolParam(NATIVE_DEBUG, false);
577 bool hasWindowOptions = (want.HasParameter(Want::PARAM_RESV_WINDOW_LEFT) ||
578 want.HasParameter(Want::PARAM_RESV_WINDOW_TOP) ||
579 want.HasParameter(Want::PARAM_RESV_WINDOW_HEIGHT) ||
580 want.HasParameter(Want::PARAM_RESV_WINDOW_WIDTH));
581 bool isDebugFromLocal = want.GetBoolParam(DEBUG_FROM, false);
582 TAG_LOGD(AAFwkTag::ABILITYMGR,
583 "isDebugApp=%{public}d, hasWindowOptions=%{public}d, isNativeDebugApp=%{public}d, isDebugFromLocal=%{public}d",
584 static_cast<int>(isDebugApp), static_cast<int>(hasWindowOptions), static_cast<int>(isNativeDebugApp),
585 isDebugFromLocal);
586 bool checkDeveloperModeFlag = (isDebugApp || hasWindowOptions || isNativeDebugApp || isDebugFromLocal);
587 if (checkDeveloperModeFlag) {
588 if (isDebugFromLocal &&
589 !AAFwk::PermissionVerification::GetInstance()->VerifyStartLocalDebug(IPCSkeleton::GetCallingTokenID())) {
590 TAG_LOGE(AAFwkTag::ABILITYMGR, "local debugging, permission denied");
591 return CHECK_PERMISSION_FAILED;
592 } else if (!isDebugFromLocal && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
593 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
594 return ERR_NOT_DEVELOPER_MODE;
595 }
596 int32_t err = ERR_OK;
597 if (userId == DEFAULT_INVAL_VALUE) {
598 userId = GetValidUserId(userId);
599 }
600 if ((err = StartAbilityUtils::CheckAppProvisionMode(want, userId)) != ERR_OK) {
601 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkAppProvisionMode returns errcode=%{public}d", err);
602 return err;
603 }
604 }
605 if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
606 TAG_LOGE(AAFwkTag::ABILITYMGR, "need passord to unlock");
607 return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
608 }
609 TAG_LOGD(AAFwkTag::ABILITYMGR, "coldStart:%{public}d", want.GetBoolParam("coldStart", false));
610 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
611 if (startWithAccount || IsCrossUserCall(userId)) {
612 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
613 CHECK_CALLER_IS_SYSTEM_APP;
614 }
615 if (hasWindowOptions && !AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
616 TAG_LOGE(AAFwkTag::ABILITYMGR, "window options not supported");
617 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
618 }
619 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
620 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
621 EventInfo eventInfo = BuildEventInfo(want, userId);
622 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
623 #ifdef SUPPORT_SCREEN
624 DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
625 #endif
626 int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
627 AAFWK::ContinueRadar::GetInstance().ClickIconStartAbility("StartAbilityWrap", want.GetFlags(), ret);
628 if (ret != ERR_OK) {
629 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbilityError:%{public}d", eventInfo.errCode);
630 }
631 return ret;
632 }
633
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)634 int AbilityManagerService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
635 int32_t userId, int requestCode)
636 {
637 return StartAbilityWithRemoveIntentFlag(want, callerToken, userId, requestCode, true);
638 }
639
StartAbilityWithRemoveIntentFlag(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode,bool removeInsightIntentFlag)640 int AbilityManagerService::StartAbilityWithRemoveIntentFlag(const Want &want, const sptr<IRemoteObject> &callerToken,
641 int32_t userId, int requestCode, bool removeInsightIntentFlag)
642 {
643 if (AppUtils::GetInstance().IsForbidStart()) {
644 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
645 return INNER_ERR;
646 }
647 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
648 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
649 TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability with caller");
650 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
651 //intent openlink do not RemoveInsightIntent
652 if (removeInsightIntentFlag) {
653 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
654 }
655 #ifdef SUPPORT_SCREEN
656 DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
657 #endif
658 return StartAbilityByFreeInstall(want, callerToken, userId, requestCode);
659 }
660
StartAbilityByFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int32_t requestCode)661 int32_t AbilityManagerService::StartAbilityByFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
662 int32_t userId, int32_t requestCode)
663 {
664 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
665 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
666 if (startWithAccount || IsCrossUserCall(userId)) {
667 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
668 CHECK_CALLER_IS_SYSTEM_APP;
669 }
670 auto flags = want.GetFlags();
671 EventInfo eventInfo = BuildEventInfo(want, userId);
672 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
673 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
674 TAG_LOGE(AAFwkTag::ABILITYMGR, "not allow startAbility with continuation flags:%{public}d",
675 ERR_INVALID_CONTINUATION_FLAG);
676 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CONTINUATION_FLAG,
677 "continuation flags not allowed");
678 return ERR_INVALID_CONTINUATION_FLAG;
679 }
680
681 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d",
682 want.GetElement().GetAbilityName().c_str(), userId);
683
684 int32_t ret = StartAbilityWrap(want, callerToken, requestCode, false, userId);
685 if (ret != ERR_OK) {
686 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbilityByFreeInstall error:%{public}d", ret);
687 }
688 return ret;
689 }
690
StartAbilityWithSpecifyTokenId(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,int32_t userId,int requestCode)691 int AbilityManagerService::StartAbilityWithSpecifyTokenId(const Want &want, const sptr<IRemoteObject> &callerToken,
692 uint32_t specifyTokenId, int32_t userId, int requestCode)
693 {
694 if (AppUtils::GetInstance().IsForbidStart()) {
695 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
696 return INNER_ERR;
697 }
698 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
699 if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
700 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with specialId, current process not foundation process");
701 return CHECK_PERMISSION_FAILED;
702 }
703 return StartAbilityWithSpecifyTokenIdInner(want, callerToken, specifyTokenId, false, userId, requestCode);
704 }
705
StartAbilityWithSpecifyTokenIdInner(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,bool isPendingWantCaller,int32_t userId,int requestCode)706 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const sptr<IRemoteObject> &callerToken,
707 uint32_t specifyTokenId, bool isPendingWantCaller, int32_t userId, int requestCode)
708 {
709 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
710 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
711 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
712 auto flags = want.GetFlags();
713 EventInfo eventInfo = BuildEventInfo(want, userId);
714 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
715 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
716 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with continuation flags not allowed:%{public}d",
717 ERR_INVALID_CONTINUATION_FLAG);
718 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CONTINUATION_FLAG,
719 "continuation flags not allowed");
720 return ERR_INVALID_CONTINUATION_FLAG;
721 }
722
723 TAG_LOGI(AAFwkTag::ABILITYMGR,
724 "start ability come, ability:%{public}s, userId:%{public}d, specifyTokenId:%{public}u",
725 want.GetElement().GetAbilityName().c_str(), userId, specifyTokenId);
726 int32_t ret = StartAbilityWrap(want, callerToken, requestCode, isPendingWantCaller, userId, false, specifyTokenId);
727 if (ret != ERR_OK) {
728 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with specified token error:%{public}d", ret);
729 }
730 return ret;
731 }
732
StartAbilityWithSpecifyTokenIdInner(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId)733 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const StartOptions &startOptions,
734 const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller,
735 int32_t userId, int requestCode, uint32_t callerTokenId)
736 {
737 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions by trigger.");
738 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
739 return StartUIAbilityForOptionWrap(
740 want, startOptions, callerToken, isPendingWantCaller, userId, requestCode, callerTokenId);
741 }
742
StartAbilityByInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,uint64_t intentId,int32_t userId)743 int32_t AbilityManagerService::StartAbilityByInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken,
744 uint64_t intentId, int32_t userId)
745 {
746 if (AppUtils::GetInstance().IsForbidStart()) {
747 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
748 return INNER_ERR;
749 }
750 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
751 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
752 std::string bundleNameFromWant = want.GetElement().GetBundleName();
753 std::string bundleNameFromIntentMgr = "";
754 if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->
755 GetBundleName(intentId, bundleNameFromIntentMgr) != ERR_OK) {
756 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched intentId");
757 return ERR_INVALID_VALUE;
758 }
759 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
760 if (abilityRecord == nullptr) {
761 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched token");
762 return ERR_INVALID_VALUE;
763 }
764 std::string bundleNameFromAbilityRecord = abilityRecord->GetAbilityInfo().bundleName;
765 if (!bundleNameFromWant.empty() && bundleNameFromWant == bundleNameFromIntentMgr &&
766 bundleNameFromWant == bundleNameFromAbilityRecord) {
767 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
768 TAG_LOGI(AAFwkTag::ABILITYMGR, "bundleName match");
769 return StartAbility(want, callerToken, userId, -1);
770 }
771 TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleName not match");
772 return ERR_INSIGHT_INTENT_START_INVALID_COMPONENT;
773 }
774
StartAbilityByUIContentSession(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)775 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const sptr<IRemoteObject> &callerToken,
776 const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
777 {
778 if (AppUtils::GetInstance().IsForbidStart()) {
779 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
780 return INNER_ERR;
781 }
782 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
783 if (!callerToken || !sessionInfo) {
784 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo null");
785 return ERR_INVALID_VALUE;
786 }
787 sptr<IRemoteObject> token;
788 #ifdef SUPPORT_SCREEN
789 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
790 Rosen::FocusChangeInfo focusChangeInfo;
791 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
792 token = focusChangeInfo.abilityToken_;
793 } else {
794 if (!wmsHandler_) {
795 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
796 return ERR_INVALID_VALUE;
797 }
798 wmsHandler_->GetFocusWindow(token);
799 }
800 #endif // SUPPORT_SCREEN
801 if (!token) {
802 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
803 return ERR_INVALID_VALUE;
804 }
805
806 if (token != sessionInfo->callerToken) {
807 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken unequal to top ability token");
808 return NOT_TOP_ABILITY;
809 }
810 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
811 return StartAbility(want, callerToken, userId, requestCode);
812 }
813
StartAbilityByUIContentSession(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)814 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const StartOptions &startOptions,
815 const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
816 {
817 if (AppUtils::GetInstance().IsForbidStart()) {
818 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
819 return INNER_ERR;
820 }
821 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
822 if (!callerToken || !sessionInfo) {
823 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo null");
824 return ERR_INVALID_VALUE;
825 }
826 sptr<IRemoteObject> token;
827 #ifdef SUPPORT_SCREEN
828 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
829 Rosen::FocusChangeInfo focusChangeInfo;
830 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
831 token = focusChangeInfo.abilityToken_;
832 } else {
833 if (!wmsHandler_) {
834 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
835 return ERR_INVALID_VALUE;
836 }
837 wmsHandler_->GetFocusWindow(token);
838 }
839 #endif // SUPPORT_SCREEN
840
841 if (!token) {
842 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
843 return ERR_INVALID_VALUE;
844 }
845
846 if (token != sessionInfo->callerToken) {
847 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken unequal to top ability token");
848 return NOT_TOP_ABILITY;
849 }
850 return StartAbility(want, startOptions, callerToken, userId, requestCode);
851 }
852
StartAbilityOnlyUIAbility(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId)853 int AbilityManagerService::StartAbilityOnlyUIAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
854 uint32_t specifyTokenId)
855 {
856 if (AppUtils::GetInstance().IsForbidStart()) {
857 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
858 return INNER_ERR;
859 }
860 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
861 if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
862 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with specialId, process not foundation process");
863 return CHECK_PERMISSION_FAILED;
864 }
865
866 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
867 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
868 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
869 auto flags = want.GetFlags();
870 EventInfo eventInfo = BuildEventInfo(want, DEFAULT_INVAL_VALUE);
871 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
872 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
873 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility not allowed:%{public}d", ERR_INVALID_CONTINUATION_FLAG);
874 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CONTINUATION_FLAG, "not allowed");
875 return ERR_INVALID_CONTINUATION_FLAG;
876 }
877
878 TAG_LOGI(AAFwkTag::ABILITYMGR,
879 "start, ability: %{public}s, userId: %{public}d, specifyTokenId: %{public}u",
880 want.GetElement().GetAbilityName().c_str(), DEFAULT_INVAL_VALUE, specifyTokenId);
881
882 int32_t ret = StartAbilityWrap(want, callerToken, DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, specifyTokenId, false, false, true);
883 if (ret != ERR_OK) {
884 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbilityOnlyUIAbility error:%{public}d", ret);
885 }
886 return ret;
887 }
888
StartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)889 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
890 sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
891 {
892 if (AppUtils::GetInstance().IsForbidStart()) {
893 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
894 return INNER_ERR;
895 }
896 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
897 return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, requestCode);
898 }
899
ImplicitStartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)900 int AbilityManagerService::ImplicitStartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
901 sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
902 {
903 if (AppUtils::GetInstance().IsForbidStart()) {
904 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
905 return INNER_ERR;
906 }
907 return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId,
908 requestCode, true);
909 }
910
StartAbilityAsCallerDetails(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode,bool isImplicit)911 int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const sptr<IRemoteObject> &callerToken,
912 sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode, bool isImplicit)
913 {
914 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
915 CHECK_CALLER_IS_SYSTEM_APP;
916 auto flags = want.GetFlags();
917 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
918 EventInfo eventInfo = BuildEventInfo(want, userId);
919 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
920 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
921 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with continuation flags not allowed:%{public}d",
922 ERR_INVALID_CONTINUATION_FLAG);
923 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CONTINUATION_FLAG,
924 "continuation flags not allowed");
925 return ERR_INVALID_CONTINUATION_FLAG;
926 }
927
928 AAFwk::Want newWant = want;
929 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
930 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability come, ability:%{public}s, userId:%{public}d",
931 want.GetElement().GetAbilityName().c_str(), userId);
932 std::string callerPkg;
933 std::string targetPkg;
934 if (AbilityUtil::CheckJumpInterceptorWant(newWant, callerPkg, targetPkg)) {
935 TAG_LOGI(AAFwkTag::ABILITYMGR,
936 "call from interceptor dialog, callerPkg:%{public}s, targetPkg:%{public}s",
937 callerPkg.c_str(), targetPkg.c_str());
938 AbilityUtil::AddAbilityJumpRuleToBms(callerPkg, targetPkg, GetUserId());
939 }
940 int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true,
941 0, false, isImplicit, false);
942 if (ret != ERR_OK) {
943 TAG_LOGE(AAFwkTag::ABILITYMGR, "start ability as caller failed:%{public}d", ret);
944 }
945 return ret;
946 }
947
StartAbilityPublicPrechainCheck(StartAbilityParams & params)948 int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams ¶ms)
949 {
950 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
951 // 1. CheckCallerToken
952 if (params.callerToken != nullptr && !VerificationAllToken(params.callerToken)) {
953 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
954 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
955 if (!isSpecificSA) {
956 TAG_LOGE(AAFwkTag::ABILITYMGR, "verificationAllToken failed");
957 return ERR_INVALID_CALLER;
958 }
959 TAG_LOGI(AAFwkTag::ABILITYMGR, "caller specific system ability");
960 }
961
962 // 2. validUserId, multi-user
963 if (!JudgeMultiUserConcurrency(params.GetValidUserId())) {
964 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
965 return ERR_CROSS_USER;
966 }
967
968 return ERR_OK;
969 }
970
StartAbilityPrechainInterceptor(StartAbilityParams & params)971 int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams ¶ms)
972 {
973 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
974 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
975 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(params.want, params.requestCode,
976 GetUserId(), true, nullptr, shouldBlockFunc);
977 auto interceptorResult = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
978 interceptorExecuter_->DoProcess(interceptorParam);
979 if (interceptorResult != ERR_OK) {
980 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
981 return interceptorResult;
982 }
983
984 return ERR_OK;
985 }
986
StartAbilityInChain(StartAbilityParams & params,int & result)987 bool AbilityManagerService::StartAbilityInChain(StartAbilityParams ¶ms, int &result)
988 {
989 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
990 std::shared_ptr<StartAbilityHandler> reqHandler;
991 for (const auto &item : startAbilityChain_) {
992 if (item.second != nullptr && item.second->MatchStartRequest(params)) {
993 reqHandler = item.second;
994 break;
995 }
996 }
997
998 if (!reqHandler) {
999 return false;
1000 }
1001
1002 result = StartAbilityPublicPrechainCheck(params);
1003 if (result != ERR_OK) {
1004 return true;
1005 }
1006 result = StartAbilityPrechainInterceptor(params);
1007 if (result != ERR_OK) {
1008 return true;
1009 }
1010 result = reqHandler->HandleStartRequest(params);
1011 return true;
1012 }
1013
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)1014 int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr<IRemoteObject> &callerToken,
1015 int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyToken,
1016 bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
1017 {
1018 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1019 StartAbilityParams startParams(const_cast<Want &>(want));
1020 startParams.callerToken = callerToken;
1021 startParams.userId = userId;
1022 startParams.requestCode = requestCode;
1023 startParams.isStartAsCaller = isStartAsCaller;
1024 startParams.SetValidUserId(GetValidUserId(userId));
1025
1026 int result = ERR_OK;
1027 if (StartAbilityInChain(startParams, result)) {
1028 return result;
1029 }
1030
1031 return StartAbilityInner(want, callerToken, requestCode, isPendingWantCaller, userId, isStartAsCaller, specifyToken,
1032 isForegroundToRestartApp, isImplicit, isUIAbilityOnly);
1033 }
1034
SetReserveInfo(const std::string & linkString,AbilityRequest & abilityRequest)1035 void AbilityManagerService::SetReserveInfo(const std::string &linkString, AbilityRequest& abilityRequest)
1036 {
1037 if (!linkString.size()) {
1038 return;
1039 }
1040
1041 #ifdef SUPPORT_SCREEN
1042 abilityRequest.uriReservedFlag =
1043 DeepLinkReserveConfig::GetInstance().IsLinkReserved(linkString, abilityRequest.reservedBundleName);
1044 #endif // SUPPORT_SCREEN
1045 }
1046
CheckExtensionCallPermission(const Want & want,const AbilityRequest & abilityRequest,uint32_t specifyTokenId)1047 int AbilityManagerService::CheckExtensionCallPermission(const Want& want, const AbilityRequest& abilityRequest,
1048 uint32_t specifyTokenId)
1049 {
1050 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "startExtensionCheck");
1051 auto isSACall = AAFwk::PermissionVerification::GetInstance()->IsSACallByTokenId(specifyTokenId);
1052 auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCallByTokenId(specifyTokenId);
1053 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCallByTokenId(specifyTokenId);
1054 auto isToPermissionMgr = IsTargetPermission(want);
1055 if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) {
1056 TAG_LOGE(AAFwkTag::ABILITYMGR,
1057 "cannot start, use startServiceExtensionAbility");
1058 return ERR_WRONG_INTERFACE_CALL;
1059 }
1060 int result = CheckCallServicePermission(abilityRequest);
1061 if (result != ERR_OK) {
1062 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
1063 }
1064 return result;
1065 }
1066
CheckServiceCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)1067 int AbilityManagerService::CheckServiceCallPermission(const AbilityRequest& abilityRequest,
1068 const AppExecFwk::AbilityInfo& abilityInfo)
1069 {
1070 TAG_LOGD(AAFwkTag::ABILITYMGR,
1071 "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
1072 int result = CheckCallServicePermission(abilityRequest);
1073 if (result != ERR_OK) {
1074 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
1075 }
1076 return result;
1077 }
1078
CheckBrokerCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)1079 int AbilityManagerService::CheckBrokerCallPermission(const AbilityRequest& abilityRequest,
1080 const AppExecFwk::AbilityInfo& abilityInfo)
1081 {
1082 // temp add for broker, remove when delete issacall
1083 if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) {
1084 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check permission failed");
1085 return CHECK_PERMISSION_FAILED;
1086 }
1087 TAG_LOGD(AAFwkTag::ABILITYMGR,
1088 "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
1089 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
1090 if (collaborator == nullptr) {
1091 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator null");
1092 return CHECK_PERMISSION_FAILED;
1093 }
1094 int result = collaborator->CheckCallAbilityPermission(abilityRequest.want);
1095 if (result != ERR_OK) {
1096 TAG_LOGE(AAFwkTag::ABILITYMGR, "check broker permission failed");
1097 return CHECK_PERMISSION_FAILED;
1098 }
1099 return result;
1100 }
1101
CheckAbilityCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,uint32_t specifyTokenId)1102 int AbilityManagerService::CheckAbilityCallPermission(const AbilityRequest& abilityRequest,
1103 const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId)
1104 {
1105 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
1106 if (AbilityPermissionUtil::GetInstance().IsStartSelfUIAbility()) {
1107 TAG_LOGI(AAFwkTag::ABILITYMGR, "call from capi, already checked");
1108 return ERR_OK;
1109 }
1110 int result = CheckCallAbilityPermission(abilityRequest, specifyTokenId);
1111 if (result != ERR_OK) {
1112 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
1113 }
1114 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1115 }
1116
CheckCallPermission(const Want & want,const AppExecFwk::AbilityInfo & abilityInfo,const AbilityRequest & abilityRequest,bool isForegroundToRestartApp,bool isSendDialogResult,uint32_t specifyTokenId,const std::string & callerBundleName)1117 int AbilityManagerService::CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
1118 const AbilityRequest& abilityRequest, bool isForegroundToRestartApp,
1119 bool isSendDialogResult, uint32_t specifyTokenId,
1120 const std::string& callerBundleName)
1121 {
1122 auto type = abilityInfo.type;
1123 if (type == AppExecFwk::AbilityType::DATA) {
1124 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot start data ability by start ability");
1125 return ERR_WRONG_INTERFACE_CALL;
1126 }
1127 if (type == AppExecFwk::AbilityType::EXTENSION) {
1128 return CheckExtensionCallPermission(want, abilityRequest, specifyTokenId);
1129 }
1130 if (type == AppExecFwk::AbilityType::SERVICE) {
1131 return CheckServiceCallPermission(abilityRequest, abilityInfo);
1132 }
1133 if ((callerBundleName == AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
1134 AppUtils::GetInstance().IsSupportAncoApp()) ||
1135 IPCSkeleton::GetCallingUid() == AppUtils::GetInstance().GetCollaboratorBrokerUID()) {
1136 return CheckBrokerCallPermission(abilityRequest, abilityInfo);
1137 }
1138 if (!isForegroundToRestartApp && (!isSendDialogResult || want.GetBoolParam("isSelector", false))) {
1139 return CheckAbilityCallPermission(abilityRequest, abilityInfo, specifyTokenId);
1140 }
1141 return ERR_OK;
1142 }
1143
CheckExtensionRateLimit()1144 void AbilityManagerService::CheckExtensionRateLimit()
1145 {
1146 if (AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
1147 return;
1148 }
1149 auto uid = IPCSkeleton::GetCallingUid();
1150 if (!RateLimiter::GetInstance().CheckExtensionLimit(uid)) {
1151 return;
1152 }
1153 TAG_LOGE(AAFwkTag::SERVICE_EXT, "Reach max request limit, uid:%{public}d", uid);
1154 if (RateLimiter::GetInstance().CheckReportLimit(uid)) {
1155 return;
1156 }
1157 std::string callerBundleName;
1158 auto bms = AbilityUtil::GetBundleManagerHelper();
1159 CHECK_POINTER(bms)
1160 IN_PROCESS_CALL(bms->GetNameForUid(uid, callerBundleName));
1161 if (callerBundleName.empty()) {
1162 TAG_LOGE(AAFwkTag::SERVICE_EXT, "callerBundleName empty, uid:%{public}d", uid);
1163 return;
1164 }
1165 EventInfo eventInfo;
1166 eventInfo.abilityName = "ReachLimit";
1167 eventInfo.callerBundleName = callerBundleName;
1168 EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
1169 }
1170
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)1171 int AbilityManagerService::StartAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
1172 int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyTokenId,
1173 bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
1174 {
1175 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1176 if (!isStartAsCaller || isImplicit) {
1177 (const_cast<Want &>(want)).RemoveParam("ability.params.picker.erms.policy");
1178 }
1179 std::string dialogSessionId = want.GetStringParam("dialogSessionId");
1180 bool isSendDialogResult = false;
1181 #ifdef SUPPORT_SCREEN
1182 if (!dialogSessionId.empty() &&
1183 DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId) != nullptr) {
1184 isSendDialogResult = true;
1185 }
1186 #endif // SUPPORT_SCREEN
1187
1188 EventInfo eventInfo = BuildEventInfo(want, userId);
1189 int result = ERR_OK;
1190 // prevent the app from dominating the screen
1191 if (callerToken == nullptr && !IsCallerSceneBoard() && !isSendDialogResult && !isForegroundToRestartApp &&
1192 AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1193 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
1194 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CALLER, "caller invalid");
1195 return ERR_INVALID_CALLER;
1196 }
1197 {
1198 #ifdef WITH_DLP
1199 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1200 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1201 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1202 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1203 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
1204 eventHelper_.SendStartAbilityErrorEvent(eventInfo, CHECK_PERMISSION_FAILED,
1205 "dlp permission verification failed");
1206 return CHECK_PERMISSION_FAILED;
1207 }
1208
1209 if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1210 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1211 result = StartExtensionAbilityInner(want, callerToken, userId,
1212 AppExecFwk::ExtensionAbilityType::SERVICE, false, false, true, isStartAsCaller);
1213 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "StartExtensionAbilityInner failed");
1214 return result;
1215 }
1216 #endif // WITH_DLP
1217 }
1218 if (auto pluginRet = CheckStartPlugin(want, callerToken); pluginRet != ERR_OK) {
1219 eventHelper_.SendStartAbilityErrorEvent(eventInfo, pluginRet, "CheckStartPlugin failed");
1220 return AbilityErrorUtil::ConvertToOriginErrorCode(pluginRet);
1221 }
1222
1223 AbilityUtil::RemoveWindowModeKey(const_cast<Want &>(want));
1224 if (callerToken != nullptr && !VerificationAllToken(callerToken) && !isSendDialogResult) {
1225 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
1226 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME) ||
1227 AAFwk::PermissionVerification::GetInstance()->VerifyFusionAccessPermission();
1228 if (!isSpecificSA) {
1229 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
1230 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_IS_NOT_SPECIFIED_SA, "verificationAllToken failed");
1231 return ERR_INVALID_CALLER;
1232 }
1233 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:caller specific system ability", __func__);
1234 }
1235
1236 int32_t oriValidUserId = GetValidUserId(userId);
1237 int32_t validUserId = oriValidUserId;
1238 StartAbilityUtils::SetTargetCloneIndexInSameBundle(want, callerToken);
1239 int32_t appIndex = 0;
1240 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1241 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_APP_CLONE_INDEX_INVALID, "GetAppIndex failed");
1242 return ERR_APP_CLONE_INDEX_INVALID;
1243 }
1244 if (!isForegroundToRestartApp) {
1245 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1246 validUserId, appIndex, callerToken, false);
1247 if (checkRet != ERR_OK) {
1248 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckMultiInstanceAndAppClone failed: %{public}d", checkRet);
1249 eventHelper_.SendStartAbilityErrorEvent(eventInfo, checkRet, "CheckMultiInstanceAndAppClone failed");
1250 return checkRet;
1251 }
1252 }
1253 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1254 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1255 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1256 true, nullptr, shouldBlockFunc);
1257 result = interceptorExecuter_ == nullptr ? ERR_NULL_INTERCEPTOR_EXECUTER :
1258 interceptorExecuter_->DoProcess(interceptorParam);
1259 if (result != ERR_OK) {
1260 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
1261 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "DoProcess error");
1262 return result;
1263 }
1264
1265 if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1266 IPCSkeleton::GetCallingUid() != DMS_UID) {
1267 TAG_LOGE(AAFwkTag::ABILITYMGR, "flag only support DMS, flag:%{public}d", want.GetFlags());
1268 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CONTINUATION_FLAG, "flag only support DMS");
1269 return ERR_INVALID_CONTINUATION_FLAG;
1270 }
1271
1272 if (callerToken != nullptr && CheckIfOperateRemote(want)) {
1273 TAG_LOGI(AAFwkTag::ABILITYMGR, "try to StartRemoteAbility");
1274 result = StartRemoteAbility(want, requestCode, validUserId, callerToken);
1275 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "StartRemoteAbility failed");
1276 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1277 }
1278
1279 if (!JudgeMultiUserConcurrency(validUserId)) {
1280 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
1281 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_CROSS_USER, "multi-user non-concurrent unsatisfied");
1282 return ERR_CROSS_USER;
1283 }
1284
1285 AbilityRequest abilityRequest;
1286 #ifdef SUPPORT_SCREEN
1287 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1288 TAG_LOGD(AAFwkTag::ABILITYMGR, "is implicit start action");
1289 auto checkResult = AbilityUtil::CheckInstanceKey(want);
1290 if (checkResult != ERR_OK) {
1291 eventHelper_.SendStartAbilityErrorEvent(eventInfo, checkResult, "CheckInstanceKey failed");
1292 return checkResult;
1293 }
1294 abilityRequest.Voluation(want, requestCode, callerToken);
1295 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1296 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1297 } else if (!isStartAsCaller) {
1298 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1299 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1300 } else {
1301 TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1302 }
1303 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1304 SetReserveInfo(want.GetUriString(), abilityRequest);
1305 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1306 if (result != ERR_OK) {
1307 TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error:%{public}d", result);
1308 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "implicit start error");
1309 }
1310 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1311 }
1312 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1313 result = ShowPickerDialog(want, validUserId, callerToken);
1314 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "ShowPickerDialog failed");
1315 return result;
1316 }
1317 #endif
1318 std::string identifier = system::GetParameter(PARAM_ANCO_APP_IDENTIFIER, "");
1319 std::string targetBundleName = want.GetBundle();
1320 if (!identifier.empty() && !targetBundleName.empty() && identifier.find(targetBundleName) != std::string::npos) {
1321 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
1322 if (collaborator != nullptr) {
1323 Want tempWant = want;
1324 int32_t ret = collaborator->UpdateTargetIfNeed(tempWant);
1325 TAG_LOGI(AAFwkTag::ABILITYMGR, "UpdateTargetIfNeed end,ret:%{public}d", ret);
1326 (const_cast<Want &>(want)).SetElement(tempWant.GetElement());
1327 } else {
1328 TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateTargetIfNeed error due to collaborator is nullptr");
1329 }
1330 }
1331 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1332 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1333 std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
1334 bool selfFreeInstallEnable = (result == RESOLVE_ABILITY_ERR && want.GetElement().GetModuleName() != "" &&
1335 want.GetElement().GetBundleName() == callerBundleName);
1336 bool isStartFreeInstallByWant = AbilityUtil::IsStartFreeInstall(want);
1337 if (isStartFreeInstallByWant || selfFreeInstallEnable) {
1338 TAG_LOGD(AAFwkTag::ABILITYMGR, "selfFreeInstallEnable: %{public}d, isStartFreeInstallByWant: %{public}d",
1339 selfFreeInstallEnable, isStartFreeInstallByWant);
1340 Want localWant;
1341 auto freeInstallResult = PreStartFreeInstall(want, callerToken, specifyTokenId, isStartAsCaller, localWant);
1342 if (freeInstallResult != ERR_OK) {
1343 TAG_LOGE(AAFwkTag::ABILITYMGR, "preStartFreeInstall failed");
1344 eventHelper_.SendStartAbilityErrorEvent(eventInfo, freeInstallResult, "preStartFreeInstall failed");
1345 return AbilityErrorUtil::ConvertToOriginErrorCode(freeInstallResult);
1346 }
1347 CHECK_POINTER_AND_RETURN(freeInstallManager_, ERR_INVALID_VALUE);
1348
1349 if (isStartFreeInstallByWant) {
1350 auto param = std::make_shared<FreeInstallParams>();
1351 param->isAsync = true;
1352 param->specifyTokenId = specifyTokenId;
1353 result = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, param);
1354 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "StartFreeInstall failed");
1355 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1356 }
1357 int32_t ret = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken);
1358 if (ret == ERR_OK) {
1359 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1360 }
1361 }
1362
1363 if (result != ERR_OK) {
1364 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error:%{public}d", result);
1365 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "GenerateAbilityRequest error");
1366 return result;
1367 }
1368
1369 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1370 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1371 } else if (!isStartAsCaller) {
1372 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1373 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1374 } else if (callerBundleName == BUNDLE_NAME_DIALOG ||
1375 (isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1376 #ifdef SUPPORT_SCREEN
1377 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1378 int32_t flag = false;
1379 if (callerBundleName == BUNDLE_NAME_DIALOG) {
1380 flag = true;
1381 }
1382 implicitStartProcessor_->ResetCallingIdentityAsCaller(
1383 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), flag);
1384 #endif // SUPPORT_SCREEN
1385 }
1386
1387 auto abilityInfo = abilityRequest.abilityInfo;
1388 if (isUIAbilityOnly && abilityInfo.type != AbilityType::PAGE) {
1389 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability type no UIAbility");
1390 eventHelper_.SendStartAbilityErrorEvent(eventInfo, RESOLVE_CALL_ABILITY_TYPE_ERR, "ability type no UIAbility");
1391 return ERR_INVALID_VALUE;
1392 }
1393 if (abilityInfo.type != AbilityType::PAGE) {
1394 AbilityStartWithWaitObserverManager::GetInstance().NotifyAATerminateWait(
1395 const_cast<Want &>(want), TerminateReason::TERMINATE_FOR_NON_UI_ABILITY);
1396 }
1397 validUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
1398 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
1399 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1400
1401 if ((isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1402 isImplicit = true;
1403 }
1404 result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1405 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1406 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1407 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
1408 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_STATIC_CFG_PERMISSION,
1409 "checkStaticCfgPermission error");
1410 return ERR_STATIC_CFG_PERMISSION;
1411 }
1412
1413 if (!isSendDialogResult || !want.GetBoolParam("isSelector", false)) {
1414 result = CheckCallPermission(want, abilityInfo, abilityRequest, isForegroundToRestartApp,
1415 isSendDialogResult, specifyTokenId, callerBundleName);
1416 if (result != ERR_OK) {
1417 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkCallPermission error, result:%{public}d", result);
1418 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "checkCallPermission error");
1419 return result;
1420 }
1421 if (!HandleExecuteSAInterceptor(want, callerToken, abilityRequest, result)) {
1422 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkCallPermission error, result:%{public}d", result);
1423 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "HandleExecuteSAInterceptor failed");
1424 return result;
1425 }
1426 }
1427 Want newWant = abilityRequest.want;
1428 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1429 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1430 result = afterCheckExecuter_ == nullptr ? ERR_NULL_AFTER_CHECK_EXECUTER :
1431 afterCheckExecuter_->DoProcess(afterCheckParam);
1432 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1433 newWant.RemoveParam("queryWantFromErms");
1434 if (result != ERR_OK && isReplaceWantExist == false) {
1435 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
1436 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "doProcess failed or replaceWant absent");
1437 return result;
1438 }
1439 #ifdef SUPPORT_SCREEN
1440 if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
1441 result = DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1442 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "HandleErmsResult failed");
1443 return result;
1444 }
1445 if (result == ERR_OK &&
1446 DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1447 TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1448 result = CreateCloneSelectorDialog(abilityRequest, GetUserId());
1449 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "CreateCloneSelectorDialog failed");
1450 return result;
1451 }
1452 #endif // SUPPORT_SCREEN
1453
1454 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1455 TAG_LOGD(AAFwkTag::ABILITYMGR, "PreLoadAppDataAbilities:%{public}s.", abilityInfo.bundleName.c_str());
1456 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1457 if (result != ERR_OK) {
1458 TAG_LOGE(AAFwkTag::ABILITYMGR,
1459 "startAbility:app data ability preloading failed, '%{public}s', %{public}d",
1460 abilityInfo.bundleName.c_str(), result);
1461 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_PRELOAD_APP_DATA_ABILITIES_FAILED,
1462 "app data ability preloading failed");
1463 return result;
1464 }
1465 }
1466 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
1467 RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerTokenId);
1468 if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
1469 abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
1470 SendStartAbilityOtherExtensionEvent(abilityInfo, abilityRequest.want, specifyTokenId);
1471 result = StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
1472 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "StartAbilityByConnectManager failed");
1473 return result;
1474 }
1475
1476 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1477 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", abilityInfo.bundleName.c_str());
1478 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_WOULD_BLOCK, "isAbilityControllerStart failed");
1479 return ERR_WOULD_BLOCK;
1480 }
1481
1482 auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1483 UpdateCallerInfoUtil::GetInstance().UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1484 StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1485
1486 abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1487 if (specifyTokenId > 0) {
1488 TAG_LOGD(AAFwkTag::ABILITYMGR, "set specifyTokenId, the specifyTokenId is %{public}d", specifyTokenId);
1489 abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1490 abilityRequest.specifyTokenId = specifyTokenId;
1491 }
1492 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1493 // sceneboard
1494 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1495 abilityRequest.userId = oriValidUserId;
1496 abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
1497 // other sa or shell can not use continueSessionId and persistentId
1498 auto abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
1499 if (abilityRecord == nullptr &&
1500 !PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
1501 TAG_LOGW(AAFwkTag::ABILITYMGR, "startAbilityInner, remove continueSessionId and persistentId");
1502 abilityRequest.want.RemoveParam(DMS_CONTINUED_SESSION_ID);
1503 abilityRequest.want.RemoveParam(DMS_PERSISTENT_ID);
1504 }
1505 if (abilityRequest.want.GetBoolParam(PARAM_RESV_ANCO_IS_NEED_UPDATE_NAME, false) &&
1506 PermissionVerification::GetInstance()->VerifyFusionAccessPermission()) {
1507 TAG_LOGI(AAFwkTag::ABILITYMGR, "startAbilityInner, update name for fusion");
1508 abilityRequest.want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, std::string(""));
1509 abilityRequest.want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, std::string(""));
1510 }
1511 if (StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
1512 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
1513 if (collaborator != nullptr) {
1514 int32_t ret = collaborator->UpdateCallerIfNeed(abilityRequest.want);
1515 TAG_LOGI(AAFwkTag::ABILITYMGR, "UpdateCallerIfNeed end,ret:%{public}d", ret);
1516 } else {
1517 TAG_LOGI(AAFwkTag::ABILITYMGR, "UpdateCallerIfNeed error due to collaborator is nullptr");
1518 }
1519 }
1520 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1521 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1522 result = uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1523 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "NotifySCBToStartUIAbility failed");
1524 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1525 }
1526
1527 auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1528 if (missionListManager == nullptr) {
1529 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", validUserId);
1530 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_VALUE, "missionListManager null");
1531 return ERR_INVALID_VALUE;
1532 }
1533
1534 ReportAbilityStartInfoToRSS(abilityInfo);
1535 ReportEventToRSS(abilityInfo, callerToken);
1536 TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability, name is %{public}s", abilityInfo.name.c_str());
1537 result = missionListManager->StartAbility(abilityRequest);
1538 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "missionListManager StartAbility failed");
1539 return result;
1540 }
1541
PreStartFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,uint32_t specifyTokenId,bool isStartAsCaller,Want & localWant)1542 int AbilityManagerService::PreStartFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
1543 uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant)
1544 {
1545 if (freeInstallManager_ == nullptr) {
1546 return ERR_NULL_FREE_INSTALL_MANAGER;
1547 }
1548 (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1549 localWant = want;
1550 if (!localWant.GetDeviceId().empty()) {
1551 localWant.SetDeviceId("");
1552 }
1553 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1554 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(localWant, callerToken);
1555 } else if (!isStartAsCaller) {
1556 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1557 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1558 } else {
1559 TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1560 }
1561 return ERR_OK;
1562 }
1563
StartAbilityByConnectManager(const Want & want,const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,int validUserId,sptr<IRemoteObject> callerToken)1564 int AbilityManagerService::StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest,
1565 const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr<IRemoteObject> callerToken)
1566 {
1567 auto connectManager = GetConnectManagerByUserId(validUserId);
1568 if (!connectManager) {
1569 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
1570 return CONNECT_MAMAGER_NOT_FIND_BY_USERID;
1571 }
1572 TAG_LOGD(AAFwkTag::ABILITYMGR, "start service or extension, name is %{public}s", abilityInfo.name.c_str());
1573 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1574 return connectManager->StartAbility(abilityRequest);
1575 }
1576
StartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1577 int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1578 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1579 {
1580 if (AppUtils::GetInstance().IsForbidStart()) {
1581 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
1582 return INNER_ERR;
1583 }
1584 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1585 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
1586 #ifdef SUPPORT_SCREEN
1587 DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
1588 #endif
1589 return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode);
1590 }
1591
ImplicitStartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1592 int AbilityManagerService::ImplicitStartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1593 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1594 {
1595 return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode, true);
1596 }
1597
StartAbilityDetails(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode,bool isImplicit)1598 int AbilityManagerService::StartAbilityDetails(const Want &want, const AbilityStartSetting &abilityStartSetting,
1599 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isImplicit)
1600 {
1601 EventInfo eventInfo = BuildEventInfo(want, userId);
1602 if (want.GetBoolParam(DEBUG_APP, false)) {
1603 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
1604 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
1605 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_NOT_DEVELOPER_MODE, "not developer Mode");
1606 return ERR_NOT_DEVELOPER_MODE;
1607 }
1608 int32_t err = ERR_OK;
1609 if (userId == DEFAULT_INVAL_VALUE) {
1610 userId = GetValidUserId(userId);
1611 }
1612 if ((err = StartAbilityUtils::CheckAppProvisionMode(want, userId)) != ERR_OK) {
1613 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkAppProvisionMode returns errcode=%{public}d", err);
1614 eventHelper_.SendStartAbilityErrorEvent(eventInfo, err, "checkAppProvisionMode failed");
1615 return err;
1616 }
1617 }
1618 if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
1619 TAG_LOGE(AAFwkTag::ABILITYMGR, "screen need passord unlock");
1620 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE,
1621 "screen need passord unlock");
1622 return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
1623 }
1624 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1625 StartAbilityParams startParams(const_cast<Want &>(want));
1626 startParams.callerToken = callerToken;
1627 startParams.userId = userId;
1628 startParams.requestCode = requestCode;
1629 startParams.SetValidUserId(GetValidUserId(userId));
1630
1631 int result = ERR_OK;
1632 if (StartAbilityInChain(startParams, result)) {
1633 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "StartAbilityInChain failed");
1634 return result;
1635 }
1636
1637 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1638 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability setting.");
1639 if (IsCrossUserCall(userId)) {
1640 CHECK_CALLER_IS_SYSTEM_APP;
1641 }
1642 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1643
1644 #ifdef WITH_DLP
1645 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1646 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1647 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1648 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed:%{public}d",
1649 __func__, CHECK_PERMISSION_FAILED);
1650 eventHelper_.SendStartAbilityErrorEvent(eventInfo, CHECK_PERMISSION_FAILED,
1651 "permission verification failed");
1652 return CHECK_PERMISSION_FAILED;
1653 }
1654 #endif // WITH_DLP
1655 if (auto pluginRet = CheckStartPlugin(want, callerToken); pluginRet != ERR_OK) {
1656 eventHelper_.SendStartAbilityErrorEvent(eventInfo, pluginRet, "CheckStartPlugin failed");
1657 return AbilityErrorUtil::ConvertToOriginErrorCode(pluginRet);
1658 }
1659
1660 if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1661 IPCSkeleton::GetCallingUid() != DMS_UID) {
1662 TAG_LOGE(AAFwkTag::ABILITYMGR, "The flag only support for DMS, flag:%{public}d, error:%{public}d",
1663 want.GetFlags(), ERR_INVALID_CONTINUATION_FLAG);
1664 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CONTINUATION_FLAG, "flags not allowed");
1665 return ERR_INVALID_CONTINUATION_FLAG;
1666 }
1667
1668 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1669 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify callerToken failed:%{public}d", ERR_INVALID_CALLER);
1670 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CALLER, "verify callerToken failed");
1671 return ERR_INVALID_CALLER;
1672 }
1673
1674 int32_t oriValidUserId = GetValidUserId(userId);
1675 int32_t validUserId = oriValidUserId;
1676 int32_t appIndex = 0;
1677 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1678 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_APP_CLONE_INDEX_INVALID, "GetAppIndex failed");
1679 return ERR_APP_CLONE_INDEX_INVALID;
1680 }
1681 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1682 validUserId, appIndex, callerToken, false);
1683 if (checkRet != ERR_OK) {
1684 eventHelper_.SendStartAbilityErrorEvent(eventInfo, checkRet, "CheckMultiInstanceAndAppClone failed");
1685 return checkRet;
1686 }
1687 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1688 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1689 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1690 true, nullptr, shouldBlockFunc);
1691 result = interceptorExecuter_ == nullptr ? ERR_NULL_INTERCEPTOR_EXECUTER :
1692 interceptorExecuter_->DoProcess(interceptorParam);
1693 if (result != ERR_OK) {
1694 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error:%{public}d", result);
1695 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "doProcess error");
1696 return result;
1697 }
1698
1699 if (AbilityUtil::IsStartFreeInstall(want)) {
1700 if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1701 TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1702 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_FREE_INSTALL_REMOTE_WANT,
1703 "can not start remote free install");
1704 return ERR_INVALID_VALUE;
1705 }
1706 (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1707 Want localWant = want;
1708 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1709 auto param = std::make_shared<FreeInstallParams>();
1710 param->isAsync = true;
1711 result = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, param);
1712 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "StartFreeInstall failed");
1713 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1714 }
1715
1716 if (!JudgeMultiUserConcurrency(validUserId)) {
1717 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied:%{publid}d", ERR_CROSS_USER);
1718 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_CROSS_USER, "multi-user non-concurrent unsatisfied");
1719 return ERR_CROSS_USER;
1720 }
1721
1722 AbilityRequest abilityRequest;
1723 #ifdef SUPPORT_SCREEN
1724 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1725 TAG_LOGD(AAFwkTag::ABILITYMGR, "is implicit start action");
1726 auto checkResult = AbilityUtil::CheckInstanceKey(want);
1727 if (checkResult != ERR_OK) {
1728 eventHelper_.SendStartAbilityErrorEvent(eventInfo, checkResult, "CheckInstanceKey failed");
1729 return checkResult;
1730 }
1731 abilityRequest.Voluation(
1732 want, requestCode, callerToken, std::make_shared<AbilityStartSetting>(abilityStartSetting));
1733 abilityRequest.callType = AbilityCallType::START_SETTINGS_TYPE;
1734 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1735 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1736 if (result != ERR_OK) {
1737 TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error:%{public}d", result);
1738 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "implicit start error");
1739 }
1740 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1741 }
1742 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1743 result = ShowPickerDialog(want, validUserId, callerToken);
1744 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "ShowPickerDialog failed");
1745 return result;
1746 }
1747 #endif
1748 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1749 if (result != ERR_OK) {
1750 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error:%{public}d", result);
1751 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "GenerateAbilityRequest error");
1752 return result;
1753 }
1754 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1755
1756 auto abilityInfo = abilityRequest.abilityInfo;
1757 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1758 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1759 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1760
1761 result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
1762 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1763 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
1764 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "checkStaticCfgPermission error");
1765 return ERR_STATIC_CFG_PERMISSION;
1766 }
1767 result = CheckCallAbilityPermission(abilityRequest);
1768 if (result != ERR_OK) {
1769 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s checkCallAbilityPermission error:%{public}d",
1770 __func__, result);
1771 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "checkCallAbilityPermission error");
1772 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1773 }
1774
1775 abilityRequest.startSetting = std::make_shared<AbilityStartSetting>(abilityStartSetting);
1776
1777 if (abilityInfo.type == AppExecFwk::AbilityType::DATA) {
1778 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot start data ability, use 'AcquireDataAbility()':%{public}d",
1779 ERR_WRONG_INTERFACE_CALL);
1780 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_WRONG_INTERFACE_CALL,
1781 "cannot start data ability");
1782 return ERR_WRONG_INTERFACE_CALL;
1783 }
1784
1785 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
1786 GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
1787 result = afterCheckExecuter_ == nullptr ? ERR_NULL_AFTER_CHECK_EXECUTER :
1788 afterCheckExecuter_->DoProcess(afterCheckParam);
1789 if (result != ERR_OK) {
1790 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
1791 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "afterCheckExecuter_ null or doProcess error");
1792 return result;
1793 }
1794
1795 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1796 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1797 if (result != ERR_OK) {
1798 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility:app data ability preloading failed, '%{public}s', %{public}d",
1799 abilityInfo.bundleName.c_str(), result);
1800 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_PRELOAD_APP_DATA_ABILITIES_FAILED,
1801 "app data ability preloading failed");
1802 return result;
1803 }
1804 }
1805 #ifdef SUPPORT_GRAPHICS
1806 if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1807 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability:%{public}d", ERR_WRONG_INTERFACE_CALL);
1808 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_WRONG_INTERFACE_CALL, "only support page ability");
1809 return ERR_WRONG_INTERFACE_CALL;
1810 }
1811 #endif
1812 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1813 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability controller start failed:%{public}d", ERR_WOULD_BLOCK);
1814 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_WOULD_BLOCK, "ability controller start failed");
1815 return ERR_WOULD_BLOCK;
1816 }
1817 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
1818 RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerTokenId);
1819 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1820 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1821 abilityRequest.userId = oriValidUserId;
1822 abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
1823 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1824 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1825 result = uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1826 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "NotifySCBToStartUIAbility failed");
1827 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
1828 }
1829 auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1830 if (missionListManager == nullptr) {
1831 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d, error:%{public}d",
1832 validUserId, ERR_NULL_MISSION_LIST_MANAGER);
1833 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_NULL_MISSION_LIST_MANAGER, "missionListManager null");
1834 return ERR_NULL_MISSION_LIST_MANAGER;
1835 }
1836 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1837 auto ret = missionListManager->StartAbility(abilityRequest);
1838 if (ret != ERR_OK) {
1839 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionlist start ability error:%{public}d", ret);
1840 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ret, "missionlist start ability error");
1841 }
1842 return ret;
1843 }
1844
StartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1845 int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions,
1846 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1847 {
1848 if (AppUtils::GetInstance().IsForbidStart()) {
1849 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
1850 return INNER_ERR;
1851 }
1852 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
1853 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1854 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions.");
1855 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1856 #ifdef SUPPORT_SCREEN
1857 DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
1858 #endif
1859 return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode);
1860 }
1861
ImplicitStartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1862 int AbilityManagerService::ImplicitStartAbility(const Want &want, const StartOptions &startOptions,
1863 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1864 {
1865 TAG_LOGD(AAFwkTag::ABILITYMGR, "Implicit Start ability with startOptions.");
1866 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1867 return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode, 0, true);
1868 }
1869
StartUIAbilityForOptionWrap(const Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId,bool isImplicit,bool isCallByShortcut)1870 int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options,
1871 sptr<IRemoteObject> callerToken, bool isPendingWantCaller, int32_t userId,
1872 int requestCode, uint32_t callerTokenId, bool isImplicit,
1873 bool isCallByShortcut)
1874 {
1875 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1876 int32_t ret = ERR_OK;
1877 if ((ret = StartOptionsUtils::CheckProcessOptions(want, options, userId)) != ERR_OK) {
1878 TAG_LOGE(AAFwkTag::ABILITYMGR, "check process oprions failed: %{public}d", ret);
1879 return ret;
1880 }
1881 return StartAbilityForOptionWrap(want, options, callerToken, isPendingWantCaller, userId, requestCode, false,
1882 callerTokenId, isImplicit, isCallByShortcut);
1883 }
1884
StartAbilityAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)1885 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOptions &startOptions,
1886 const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken,
1887 int32_t userId, int requestCode)
1888 {
1889 if (AppUtils::GetInstance().IsForbidStart()) {
1890 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
1891 return INNER_ERR;
1892 }
1893 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
1894 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability as caller with startOptions.");
1895 CHECK_CALLER_IS_SYSTEM_APP;
1896
1897 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1898 AAFwk::Want newWant = want;
1899 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1900 return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1901 }
1902
StartAbilityForResultAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1903 int AbilityManagerService::StartAbilityForResultAsCaller(
1904 const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1905 {
1906 if (AppUtils::GetInstance().IsForbidStart()) {
1907 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
1908 return INNER_ERR;
1909 }
1910 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
1911 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1912 CHECK_CALLER_IS_SYSTEM_APP;
1913
1914 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1915 AAFwk::Want newWant = want;
1916 auto connectManager = GetCurrentConnectManager();
1917 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1918 auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1919 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1920 return StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true);
1921 }
1922
StartAbilityForResultAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1923 int AbilityManagerService::StartAbilityForResultAsCaller(const Want &want, const StartOptions &startOptions,
1924 const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1925 {
1926 if (AppUtils::GetInstance().IsForbidStart()) {
1927 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
1928 return INNER_ERR;
1929 }
1930 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
1931 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1932 CHECK_CALLER_IS_SYSTEM_APP;
1933
1934 AAFwk::Want newWant = want;
1935 auto connectManager = GetCurrentConnectManager();
1936 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1937 auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1938 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1939 return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1940 }
1941
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)1942 int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const StartOptions &startOptions,
1943 const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1944 bool isStartAsCaller, uint32_t callerTokenId, bool isImplicit, bool isCallByShortcut)
1945 {
1946 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1947 StartAbilityParams startParams(const_cast<Want &>(want));
1948 startParams.callerToken = callerToken;
1949 startParams.userId = userId;
1950 startParams.requestCode = requestCode;
1951 startParams.isStartAsCaller = isStartAsCaller;
1952 startParams.startOptions = &startOptions;
1953 startParams.SetValidUserId(GetValidUserId(userId));
1954
1955 int result = ERR_OK;
1956 if (StartAbilityInChain(startParams, result)) {
1957 return result;
1958 }
1959
1960 return StartAbilityForOptionInner(want, startOptions, callerToken, isPendingWantCaller, userId, requestCode,
1961 isStartAsCaller, callerTokenId, isImplicit, isCallByShortcut);
1962 }
1963
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)1964 int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const StartOptions &startOptions,
1965 const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1966 bool isStartAsCaller, uint32_t specifyTokenId, bool isImplicit, bool isCallByShortcut)
1967 {
1968 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1969 EventInfo eventInfo = BuildEventInfo(want, userId);
1970 // prevent the app from dominating the screen
1971 if (callerToken == nullptr && !IsCallerSceneBoard() && !isCallByShortcut &&
1972 AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1973 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
1974 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CALLER, "caller invalid");
1975 return ERR_INVALID_CALLER;
1976 }
1977
1978 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
1979 if (startWithAccount || IsCrossUserCall(userId)) {
1980 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
1981 CHECK_CALLER_IS_SYSTEM_APP;
1982 }
1983 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1984 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1985
1986 #ifdef WITH_DLP
1987 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1988 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1989 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1990 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed:%{public}d", CHECK_PERMISSION_FAILED);
1991 eventHelper_.SendStartAbilityErrorEvent(eventInfo, CHECK_PERMISSION_FAILED,
1992 "permission verify failed");
1993 return CHECK_PERMISSION_FAILED;
1994 }
1995 #endif // WITH_DLP
1996 if (auto pluginRet = CheckStartPlugin(want, callerToken); pluginRet != ERR_OK) {
1997 eventHelper_.SendStartAbilityErrorEvent(eventInfo, pluginRet, "CheckStartPlugin failed");
1998 return AbilityErrorUtil::ConvertToOriginErrorCode(pluginRet);
1999 }
2000
2001 if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
2002 IPCSkeleton::GetCallingUid() != DMS_UID) {
2003 TAG_LOGE(AAFwkTag::ABILITYMGR, "The flag only support for DMS, flag:%{public}d, error:%{publicd}d",
2004 want.GetFlags(), ERR_INVALID_CONTINUATION_FLAG);
2005 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CONTINUATION_FLAG, "flags not allowed");
2006 return ERR_INVALID_CONTINUATION_FLAG;
2007 }
2008
2009 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2010 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify callerToken failed:%{public}d", ERR_INVALID_CALLER);
2011 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CALLER, "verify callerToken failed");
2012 return ERR_INVALID_CALLER;
2013 }
2014
2015 int32_t oriValidUserId = GetValidUserId(userId);
2016 int32_t validUserId = oriValidUserId;
2017 StartAbilityUtils::SetTargetCloneIndexInSameBundle(want, callerToken);
2018 int32_t appIndex = 0;
2019 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
2020 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_APP_CLONE_INDEX_INVALID, "GetAppIndex failed");
2021 return ERR_APP_CLONE_INDEX_INVALID;
2022 }
2023 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
2024 validUserId, appIndex, callerToken, false);
2025 if (checkRet != ERR_OK) {
2026 eventHelper_.SendStartAbilityErrorEvent(eventInfo, checkRet, "CheckMultiInstanceAndAppClone failed");
2027 return checkRet;
2028 }
2029 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
2030 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2031 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
2032 true, nullptr, shouldBlockFunc);
2033 auto result = interceptorExecuter_ == nullptr ? ERR_NULL_INTERCEPTOR_EXECUTER :
2034 interceptorExecuter_->DoProcess(interceptorParam);
2035 if (result != ERR_OK) {
2036 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error:%{public}d", result);
2037 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "doProcess error");
2038 return result;
2039 }
2040
2041 if (AbilityUtil::IsStartFreeInstall(want)) {
2042 if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
2043 TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
2044 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_VALUE, "can not start remote free install");
2045 return ERR_INVALID_VALUE;
2046 }
2047 (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
2048 Want localWant = want;
2049 if (!isStartAsCaller) {
2050 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
2051 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
2052 }
2053 TAG_LOGD(AAFwkTag::ABILITYMGR, "is start free install");
2054 auto param = std::make_shared<FreeInstallParams>();
2055 param->isAsync = true;
2056 param->specifyTokenId = specifyTokenId;
2057 param->startOptions = std::make_shared<AAFwk::StartOptions>(startOptions);
2058 result = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, param);
2059 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "StartFreeInstall failed");
2060 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
2061 }
2062 if (!JudgeMultiUserConcurrency(validUserId)) {
2063 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied:%{publid}d", ERR_CROSS_USER);
2064 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_CROSS_USER, "multi-user non-concurrent unsatisfied");
2065 return ERR_CROSS_USER;
2066 }
2067
2068 AbilityRequest abilityRequest;
2069 abilityRequest.startOptions = startOptions;
2070 #ifdef SUPPORT_SCREEN
2071 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
2072 TAG_LOGD(AAFwkTag::ABILITYMGR, "is implicit start action");
2073 auto checkResult = AbilityUtil::CheckInstanceKey(want);
2074 if (checkResult != ERR_OK) {
2075 eventHelper_.SendStartAbilityErrorEvent(eventInfo, checkResult, "CheckInstanceKey failed");
2076 return checkResult;
2077 }
2078 abilityRequest.Voluation(want, requestCode, callerToken);
2079 if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
2080 bool windowFocused = startOptions.GetWindowFocused();
2081 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowFocused);
2082 } else {
2083 abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
2084 }
2085 if (startOptions.GetDisplayID() == 0) {
2086 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
2087 DisplayUtil::GetDefaultDisplayId());
2088 } else {
2089 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
2090 }
2091 WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
2092 abilityRequest.callType = AbilityCallType::START_OPTIONS_TYPE;
2093 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
2094 if (specifyTokenId > 0 && callerToken) { // for sa specify tokenId and caller token
2095 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
2096 } else if (!isStartAsCaller) {
2097 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
2098 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
2099 }
2100 TAG_LOGD(AAFwkTag::ABILITYMGR, "implicit start ability");
2101 abilityRequest.want.RemoveParam(KEY_REQUEST_ID);
2102 if (!startOptions.requestId_.empty()) {
2103 TAG_LOGI(AAFwkTag::ABILITYMGR, "set implicit requestId:%{public}s", startOptions.requestId_.c_str());
2104 abilityRequest.want.SetParam(KEY_REQUEST_ID, startOptions.requestId_);
2105 }
2106 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId,
2107 startOptions.GetWindowMode());
2108 if (result != ERR_OK) {
2109 TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error:%{public}d", result);
2110 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "implicit start error");
2111 }
2112 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
2113 }
2114 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
2115 result = ShowPickerDialog(want, validUserId, callerToken);
2116 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "ShowPickerDialog failed");
2117 return result;
2118 }
2119 #endif
2120 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
2121 if (result != ERR_OK) {
2122 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error:%{public}d", result);
2123 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "GenerateAbilityRequest error");
2124 return result;
2125 }
2126
2127 if (!HandleExecuteSAInterceptor(want, callerToken, abilityRequest, result)) {
2128 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "HandleExecuteSAInterceptor failed");
2129 return result;
2130 }
2131
2132 if (!isStartAsCaller) {
2133 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
2134 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
2135 }
2136 auto abilityInfo = abilityRequest.abilityInfo;
2137 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2138 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
2139 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2140
2141 if (startOptions.processOptions != nullptr &&
2142 abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
2143 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2144 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2145 auto abilityRecords = uiAbilityManager->GetAbilityRecordsByName(want.GetElement());
2146 if (!abilityRecords.empty() && abilityRecords[0] &&
2147 !startOptions.processOptions->isRestartKeepAlive &&
2148 !ProcessOptions::IsAttachToStatusBarItemMode(startOptions.processOptions->processMode) &&
2149 !startOptions.processOptions->isStartFromNDK) {
2150 TAG_LOGE(AAFwkTag::ABILITYMGR, "processMode is not attach to status bar item.");
2151 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_ABILITY_ALREADY_RUNNING,
2152 "processMode is not attach to status bar item");
2153 return ERR_ABILITY_ALREADY_RUNNING;
2154 }
2155 }
2156
2157 result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
2158 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
2159 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2160 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result=%{public}d", result);
2161 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "checkStaticCfgPermission error");
2162 return ERR_STATIC_CFG_PERMISSION;
2163 }
2164 result = CheckCallAbilityPermission(abilityRequest, 0, isCallByShortcut);
2165 if (result != ERR_OK) {
2166 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error:%{public}d",
2167 __func__, result);
2168 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "CheckCallAbilityPermission error");
2169 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
2170 }
2171
2172 if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
2173 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability:%{public}d", ERR_ABILITY_TYPE_INVALID);
2174 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_ABILITY_TYPE_INVALID, "only support page ability");
2175 return ERR_ABILITY_TYPE_INVALID;
2176 }
2177
2178 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
2179 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
2180 if (result != ERR_OK) {
2181 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility:app data ability preloading failed, '%{public}s', %{public}d",
2182 abilityInfo.bundleName.c_str(), result);
2183 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_PRELOAD_APP_DATA_ABILITIES_FAILED,
2184 "app data ability preloading failed");
2185 return result;
2186 }
2187 }
2188
2189 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
2190 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability controller start failed:%{public}d", ERR_WOULD_BLOCK);
2191 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_WOULD_BLOCK, "controller start failed");
2192 return ERR_WOULD_BLOCK;
2193 }
2194 #ifdef SUPPORT_SCREEN
2195 if (abilityInfo.isStageBasedModel && !CheckWindowMode(startOptions.GetWindowMode(), abilityInfo.windowModes)) {
2196 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_AAFWK_INVALID_WINDOW_MODE, "CheckWindowMode failed");
2197 return ERR_AAFWK_INVALID_WINDOW_MODE;
2198 }
2199 #endif
2200 if (startOptions.GetDisplayID() == 0) {
2201 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
2202 DisplayUtil::GetDefaultDisplayId());
2203 } else {
2204 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
2205 }
2206 abilityRequest.want.RemoveParam(KEY_REQUEST_ID);
2207 if (!startOptions.requestId_.empty()) {
2208 abilityRequest.want.SetParam(KEY_REQUEST_ID, startOptions.requestId_);
2209 }
2210 AbilityUtil::ProcessWindowMode(abilityRequest.want, abilityInfo.applicationInfo.accessTokenId,
2211 startOptions.GetWindowMode());
2212
2213 WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
2214
2215 if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
2216 bool focused = abilityRequest.want.GetBoolParam(Want::PARAM_RESV_WINDOW_FOCUSED, true);
2217 if (focused) {
2218 bool windowfocused = startOptions.GetWindowFocused();
2219 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowfocused);
2220 }
2221 } else {
2222 abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
2223 }
2224
2225 Want newWant = abilityRequest.want;
2226 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
2227 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
2228 result = afterCheckExecuter_ == nullptr ? ERR_NULL_AFTER_CHECK_EXECUTER :
2229 afterCheckExecuter_->DoProcess(afterCheckParam);
2230 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2231 newWant.RemoveParam("queryWantFromErms");
2232 if (result != ERR_OK && isReplaceWantExist == false) {
2233 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
2234 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "doProcess failed or replaceWant absent");
2235 return result;
2236 }
2237 #ifdef SUPPORT_SCREEN
2238 if (result != ERR_OK && isReplaceWantExist) {
2239 result = DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
2240 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "HandleErmsResult failed");
2241 return result;
2242 }
2243 if (result == ERR_OK &&
2244 DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
2245 TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
2246 result = CreateCloneSelectorDialog(abilityRequest, GetUserId());
2247 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "CreateCloneSelectorDialog failed");
2248 return result;
2249 }
2250 #endif // SUPPORT_GRAPHICS
2251 auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
2252 UpdateCallerInfoUtil::GetInstance().UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
2253 StartAbilityUtils::ermsSupportBackToCallerFlag = false;
2254
2255 abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
2256 if (specifyTokenId > 0) {
2257 TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
2258 abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
2259 abilityRequest.specifyTokenId = specifyTokenId;
2260 }
2261 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
2262 RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerTokenId);
2263 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
2264 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2265 abilityRequest.userId = oriValidUserId;
2266 abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
2267 abilityRequest.processOptions = startOptions.processOptions;
2268 if (IPCSkeleton::GetCallingTokenID() == abilityRequest.appInfo.accessTokenId ||
2269 AbilityPermissionUtil::GetInstance().IsStartSelfUIAbility()) {
2270 abilityRequest.startWindowOption = startOptions.startWindowOption;
2271 }
2272 abilityRequest.supportWindowModes = startOptions.supportWindowModes_;
2273 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2274 std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
2275 if (abilityRequest.want.GetElement().GetBundleName() == callerBundleName) {
2276 abilityRequest.hideStartWindow = startOptions.GetHideStartWindow();
2277 }
2278 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
2279 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_NULL_UI_ABILITY_MANAGER);
2280 result = uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
2281 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "NotifySCBToStartUIAbility failed");
2282 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
2283 }
2284 auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
2285 if (missionListManager == nullptr) {
2286 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d, errror:%{public}d",
2287 oriValidUserId, ERR_NULL_MISSION_LIST_MANAGER);
2288 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_NULL_MISSION_LIST_MANAGER, "missionListManager null");
2289 return ERR_NULL_MISSION_LIST_MANAGER;
2290 }
2291 if (startOptions.GetDisplayID() == -1) {
2292 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
2293 DisplayUtil::GetDefaultDisplayId());
2294 }
2295 auto ret = missionListManager->StartAbility(abilityRequest);
2296 if (ret != ERR_OK) {
2297 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager start ability errror:%{public}d", ret);
2298 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ret, "missionListManager start errror");
2299 }
2300 return ret;
2301 }
2302
StartUIAbilities(const std::vector<AAFwk::Want> & wantList,const std::string & requestKey,sptr<IRemoteObject> callerToken)2303 ErrCode AbilityManagerService::StartUIAbilities(const std::vector<AAFwk::Want> &wantList,
2304 const std::string &requestKey, sptr<IRemoteObject> callerToken)
2305 {
2306 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2307 XCOLLIE_TIMER_DEFAULT(__PRETTY_FUNCTION__);
2308 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call StartUIAbilities");
2309 std::vector<AbilityRequest> abilityRequestList;
2310 int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
2311
2312 if (!AppUtils::GetInstance().IsSupportStartAbilities() ||
2313 !Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2314 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities is not supported");
2315 return ERR_CAPABILITY_NOT_SUPPORT;
2316 }
2317
2318 if (wantList.size() < INDEX_ONE || wantList.size() > INDEX_FOUR) {
2319 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities wantList size not support");
2320 return START_UI_ABILITIES_WANT_LIST_SIZE_ERROR;
2321 }
2322
2323 if (callerToken == nullptr || !VerificationAllToken(callerToken)) {
2324 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities %{public}s verificationAllToken failed", __func__);
2325 return ERR_INVALID_CALLER;
2326 }
2327
2328 for (const Want &want : wantList) {
2329 int32_t ret = StartUIAbilitiesHandleWant(want, callerToken, abilityRequestList);
2330 if (ret != ERR_OK) {
2331 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities want process block");
2332 return ret;
2333 }
2334 }
2335
2336 TAG_LOGD(AAFwkTag::ABILITYMGR, "StartUIAbilities ready to NotifySCBToStartUIAbilities");
2337 for (AbilityRequest &abilityRequest : abilityRequestList) {
2338 auto abilityInfo = abilityRequest.abilityInfo;
2339 ReportEventToRSS(abilityInfo, abilityRequest.callerToken);
2340 abilityRequest.userId = oriValidUserId;
2341 abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
2342 }
2343 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
2344 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2345 return uiAbilityManager->NotifySCBToStartUIAbilities(abilityRequestList, requestKey);
2346 }
2347
StartUIAbilitiesHandleWant(const Want & want,sptr<IRemoteObject> callerToken,std::vector<AbilityRequest> & abilityRequestList)2348 int32_t AbilityManagerService::StartUIAbilitiesHandleWant(const Want &want, sptr<IRemoteObject> callerToken,
2349 std::vector<AbilityRequest> &abilityRequestList)
2350 {
2351 int32_t userId = DEFAULT_INVAL_VALUE;
2352 int32_t validUserId = GetValidUserId(userId);
2353 uint32_t specifyTokenId = 0;
2354 int32_t requestCode = DEFAULT_INVAL_VALUE;
2355
2356 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
2357
2358 if (!want.HasParameter(AppExecFwk::INSIGHT_INTENT_EXECUTE_OPENLINK_FLAG)) {
2359 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2360 }
2361
2362 #ifdef SUPPORT_SCREEN
2363 DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
2364 #endif
2365
2366 if (AbilityRuntime::StartupUtil::IsStartPlugin(want)) {
2367 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities not support StartPlugin");
2368 return START_UI_ABILITIES_NOT_SUPPORT_START_PLUGIN;
2369 }
2370
2371 AbilityUtil::RemoveWindowModeKey(const_cast<Want &>(want));
2372
2373 if (want.GetBoolParam(Want::CREATE_APP_INSTANCE_KEY, false)) {
2374 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities not support CREATE_APP_INSTANCE_KEY");
2375 return START_UI_ABILITIES_NOT_SUPPORT_CREATE_APP_INSTANCE_KEY;
2376 }
2377
2378 int32_t ret = StartUIAbilitiesCheckDlp(want, callerToken, validUserId);
2379 if (ret != ERR_OK) {
2380 return ret;
2381 }
2382
2383 int32_t appIndex = 0;
2384 ret = StartAbilityUtils::StartUIAbilitiesProcessAppIndex(const_cast<Want &>(want), callerToken, appIndex);
2385 if (ret != ERR_OK) {
2386 return ret;
2387 }
2388 ret = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(
2389 const_cast<Want &>(want), validUserId, appIndex, callerToken, false);
2390 if (ret != ERR_OK) {
2391 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities CheckMultiInstanceAndAppClone failed");
2392 return ret;
2393 }
2394
2395 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
2396
2397 if (CheckIfOperateRemote(want)) {
2398 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities not support StartRemoteAbility");
2399 return START_UI_ABILITIES_NOT_SUPPORT_OPERATE_REMOTE;
2400 }
2401
2402 if (!JudgeMultiUserConcurrency(validUserId)) {
2403 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities multi-user non-concurrent unsatisfied");
2404 return START_UI_ABILITIES_NOT_SUPPORT_CROSS_USER;
2405 }
2406 #ifdef SUPPORT_SCREEN
2407 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
2408 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities not support implicit start");
2409 return START_UI_ABILITIES_NOT_SUPPORT_IMPLICIT_START;
2410 }
2411 #endif
2412 AbilityRequest abilityRequest;
2413 auto result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
2414 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2415 std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
2416 if (result != ERR_OK) {
2417 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
2418 return result;
2419 }
2420
2421 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
2422
2423 auto abilityInfo = abilityRequest.abilityInfo;
2424 if (abilityInfo.type != AbilityType::PAGE) {
2425 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities only support UIAbility");
2426 return START_UI_ABILITIES_ONLY_SUPPORT_UI_ABILITY;
2427 }
2428
2429 result = CheckStaticCfgPermission(abilityRequest, false,
2430 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false);
2431 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2432 TAG_LOGE(AAFwkTag::ABILITYMGR,
2433 "StartUIAbilities checkStaticCfgPermission error, result:%{public}d", result);
2434 return ERR_STATIC_CFG_PERMISSION;
2435 }
2436 result = CheckCallPermission(want, abilityInfo, abilityRequest, false,
2437 false, specifyTokenId, callerBundleName);
2438 if (result != ERR_OK) {
2439 TAG_LOGE(AAFwkTag::ABILITYMGR,
2440 "StartUIAbilities checkCallPermission error, result:%{public}d", result);
2441 return result;
2442 }
2443
2444 result = StartUIAbilitiesInterceptorCheck(want, abilityRequest, callerToken, appIndex);
2445 if (result != ERR_OK) {
2446 return result;
2447 }
2448
2449 Want newWant = abilityRequest.want;
2450 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2451 newWant.RemoveParam("queryWantFromErms");
2452
2453 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
2454 RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerTokenId);
2455
2456 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
2457 TAG_LOGE(AAFwkTag::ABILITYMGR,
2458 "StartUIAbilities isAbilityControllerStart failed:%{public}s", abilityInfo.bundleName.c_str());
2459 return ERR_WOULD_BLOCK;
2460 }
2461 abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
2462 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
2463 abilityRequestList.emplace_back(abilityRequest);
2464 return ERR_OK;
2465 }
2466
StartUIAbilitiesCheckDlp(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId)2467 int32_t AbilityManagerService::StartUIAbilitiesCheckDlp(const Want &want, sptr<IRemoteObject> callerToken,
2468 int32_t userId)
2469 {
2470 #ifdef WITH_DLP
2471 if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
2472 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities not support Dlp");
2473 return START_UI_ABILITIES_NOT_SUPPORT_DLP;
2474 }
2475 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
2476 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
2477 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
2478 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
2479 TAG_LOGE(AAFwkTag::ABILITYMGR,
2480 "StartUIAbilities Dlp %{public}s: permission verification failed", __func__);
2481 return CHECK_PERMISSION_FAILED;
2482 }
2483 #endif // WITH_DLP
2484 return ERR_OK;
2485 }
2486
StartUIAbilitiesInterceptorCheck(const Want & want,AbilityRequest & abilityRequest,sptr<IRemoteObject> callerToken,int32_t appIndex)2487 int32_t AbilityManagerService::StartUIAbilitiesInterceptorCheck(const Want &want, AbilityRequest &abilityRequest,
2488 sptr<IRemoteObject> callerToken, int32_t appIndex)
2489 {
2490 int32_t requestCode = DEFAULT_INVAL_VALUE;
2491 Want newWant = abilityRequest.want;
2492 auto abilityInfo = abilityRequest.abilityInfo;
2493 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2494 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
2495 true, nullptr, shouldBlockFunc);
2496 int32_t result = interceptorExecuter_ == nullptr ? ERR_NULL_INTERCEPTOR_EXECUTER :
2497 interceptorExecuter_->DoProcess(interceptorParam);
2498 if (result == ERR_CROWDTEST_EXPIRED) {
2499 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities ERR_CROWDTEST_EXPIRED");
2500 return result;
2501 }
2502 if (result != ERR_OK) {
2503 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities interceptorExecuter_ null or DoProcess error");
2504 return START_UI_ABILITIES_INTERCEPTOR_CHECK_FAILED;
2505 }
2506
2507 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
2508 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2509 result = afterCheckExecuter_ == nullptr ? ERR_NULL_AFTER_CHECK_EXECUTER :
2510 afterCheckExecuter_->DoProcess(afterCheckParam);
2511 if (result == ERR_CROWDTEST_EXPIRED) {
2512 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities ERR_CROWDTEST_EXPIRED");
2513 return result;
2514 }
2515 if (result != ERR_OK) {
2516 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilities afterCheckExecuter_ null or DoProcess error");
2517 return START_UI_ABILITIES_INTERCEPTOR_CHECK_FAILED;
2518 }
2519 return ERR_OK;
2520 }
2521
RequestDialogService(const Want & want,const sptr<IRemoteObject> & callerToken)2522 int32_t AbilityManagerService::RequestDialogService(const Want &want, const sptr<IRemoteObject> &callerToken)
2523 {
2524 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2525 auto flags = want.GetFlags();
2526 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
2527 TAG_LOGE(AAFwkTag::ABILITYMGR, "requestDialogService with continuation flags not allowed");
2528 return ERR_INVALID_CONTINUATION_FLAG;
2529 }
2530
2531 TAG_LOGI(AAFwkTag::ABILITYMGR, "request dialog service, target:%{public}s", want.GetElement().GetURI().c_str());
2532 return RequestDialogServiceInner(want, callerToken, -1, -1);
2533 }
2534
ReportDrawnCompleted(const sptr<IRemoteObject> & callerToken)2535 int32_t AbilityManagerService::ReportDrawnCompleted(const sptr<IRemoteObject> &callerToken)
2536 {
2537 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
2538 if (callerToken == nullptr) {
2539 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken null");
2540 return INNER_ERR;
2541 }
2542
2543 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2544 if (abilityRecord == nullptr) {
2545 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
2546 return INNER_ERR;
2547 }
2548 auto abilityInfo = abilityRecord->GetAbilityInfo();
2549
2550 EventInfo eventInfo;
2551 eventInfo.userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2552 eventInfo.pid = IPCSkeleton::GetCallingPid();
2553 eventInfo.bundleName = abilityInfo.bundleName;
2554 eventInfo.moduleName = abilityInfo.moduleName;
2555 eventInfo.abilityName = abilityInfo.name;
2556 EventReport::SendAppEvent(EventName::DRAWN_COMPLETED, HiSysEventType::BEHAVIOR, eventInfo);
2557 return ERR_OK;
2558 }
2559
RequestDialogServiceInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)2560 int32_t AbilityManagerService::RequestDialogServiceInner(const Want &want, const sptr<IRemoteObject> &callerToken,
2561 int requestCode, int32_t userId)
2562 {
2563 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2564 if (callerToken == nullptr || !VerificationAllToken(callerToken)) {
2565 TAG_LOGW(AAFwkTag::ABILITYMGR, "caller invalid");
2566 return ERR_INVALID_CALLER;
2567 }
2568
2569 {
2570 #ifdef WITH_DLP
2571 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
2572 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
2573 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
2574 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
2575 return CHECK_PERMISSION_FAILED;
2576 }
2577
2578 if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
2579 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot handle dlp by requestDialogService");
2580 return ERR_WRONG_INTERFACE_CALL;
2581 }
2582 #endif // WITH_DLP
2583 }
2584
2585 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
2586 int32_t validUserId = GetValidUserId(userId);
2587 StartAbilityInfoWrap threadLocalInfo;
2588 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2589 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
2590 true, nullptr, shouldBlockFunc);
2591 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2592 interceptorExecuter_->DoProcess(interceptorParam);
2593 if (result != ERR_OK) {
2594 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
2595 return result;
2596 }
2597
2598 if (!JudgeMultiUserConcurrency(validUserId)) {
2599 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
2600 return ERR_CROSS_USER;
2601 }
2602 AbilityRequest abilityRequest;
2603 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2604 if (result != ERR_OK) {
2605 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error when requestDialogService");
2606 return result;
2607 }
2608 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
2609
2610 auto abilityInfo = abilityRequest.abilityInfo;
2611 threadLocalInfo.SetStartAbilityInfo(abilityInfo);
2612 validUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
2613 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
2614 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2615
2616 result = CheckStaticCfgPermission(abilityRequest, false, -1);
2617 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2618 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
2619 return ERR_STATIC_CFG_PERMISSION;
2620 }
2621
2622 auto type = abilityInfo.type;
2623 if (type == AppExecFwk::AbilityType::EXTENSION &&
2624 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
2625 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
2626 result = CheckCallServicePermission(abilityRequest);
2627 if (result != ERR_OK) {
2628 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
2629 return result;
2630 }
2631 } else {
2632 TAG_LOGE(AAFwkTag::ABILITYMGR, "requestDialogService no support other component");
2633 return ERR_WRONG_INTERFACE_CALL;
2634 }
2635
2636 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
2637 GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
2638 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2639 afterCheckExecuter_->DoProcess(afterCheckParam);
2640 if (result != ERR_OK) {
2641 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or DoProcess error");
2642 return result;
2643 }
2644
2645 auto connectManager = GetConnectManagerByUserId(validUserId);
2646 if (!connectManager) {
2647 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
2648 return ERR_INVALID_VALUE;
2649 }
2650 TAG_LOGD(AAFwkTag::ABILITYMGR,
2651 "request dialog service, start service extension,name is %{public}s.", abilityInfo.name.c_str());
2652 return connectManager->StartAbility(abilityRequest);
2653 }
2654
OpenAtomicService(AAFwk::Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,int32_t requestCode,int32_t userId)2655 int32_t AbilityManagerService::OpenAtomicService(AAFwk::Want& want, const StartOptions &options,
2656 sptr<IRemoteObject> callerToken, int32_t requestCode, int32_t userId)
2657 {
2658 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2659 auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
2660 if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
2661 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not hap");
2662 return CHECK_PERMISSION_FAILED;
2663 }
2664 want.SetParam(AAFwk::SCREEN_MODE_KEY, AAFwk::ScreenMode::JUMP_SCREEN_MODE);
2665 return StartUIAbilityForOptionWrap(want, options, callerToken, false, userId, requestCode);
2666 }
2667
SetWantForSessionInfo(sptr<SessionInfo> sessionInfo)2668 int AbilityManagerService::SetWantForSessionInfo(sptr<SessionInfo> sessionInfo)
2669 {
2670 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
2671 if (!(sessionInfo->want).GetElement().GetAbilityName().empty() &&
2672 !(sessionInfo->want).GetElement().GetModuleName().empty()) {
2673 return ERR_OK;
2674 }
2675 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
2676 CHECK_POINTER_AND_RETURN(bundleMgrHelper, ERR_INVALID_VALUE);
2677 Want launchWant;
2678 TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName:%{public}s, userId:%{public}d", sessionInfo->want.GetBundle().c_str(),
2679 GetValidUserId(sessionInfo->userId));
2680 auto errCode = IN_PROCESS_CALL(bundleMgrHelper->GetLaunchWantForBundle(
2681 (sessionInfo->want).GetBundle(), launchWant, GetValidUserId(sessionInfo->userId)));
2682 if (errCode != ERR_OK) {
2683 TAG_LOGE(AAFwkTag::ABILITYMGR, "getLaunchWantForBundle returns %{public}d", errCode);
2684 return errCode;
2685 }
2686 (sessionInfo->want).SetElement(launchWant.GetElement());
2687 return ERR_OK;
2688 }
2689
StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo,bool & isColdStart,uint32_t sceneFlag)2690 int AbilityManagerService::StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo, bool &isColdStart, uint32_t sceneFlag)
2691 {
2692 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2693 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
2694 TAG_LOGI(AAFwkTag::ABILITYMGR, "call, sceneFlag:%{public}u", sceneFlag);
2695 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
2696 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
2697 return ERR_INVALID_VALUE;
2698 }
2699 EventInfo eventInfo = BuildEventInfo(sessionInfo->want, -1);
2700 #ifdef MEMMGR_OVERRIDE_ENABLE
2701 WantParams wantParams = (sessionInfo->want).GetParams();
2702 std::string bundleName = (sessionInfo->want).GetElement().GetBundleName();
2703 int windowMode = wantParams.GetIntParam(EXPECT_WINDOW_MODE, 0);
2704 if (AppUtils::GetInstance().IsRequireBigMemoryProcess(bundleName) &&
2705 wantParams.HasParam(EXPECT_WINDOW_MODE) &&
2706 (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_FLOATING ||
2707 windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_PRIMARY ||
2708 windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_SECONDARY)) {
2709 TAG_LOGD(AAFwkTag::ABILITYMGR, "App start ability from with no fullscreen.");
2710 Memory::MemMgrProcessStateInfo info;
2711 info.noFullScreenStart = 1;
2712 int32_t result = Memory::MemMgrClient::GetInstance().NotifyProcessStateChangedAsync(info);
2713 if (result != ERR_OK) {
2714 TAG_LOGE(AAFwkTag::ABILITYMGR, "NotifyProcessStateChangedAsync error. result: %{public}d", result);
2715 }
2716 }
2717 #endif
2718 if (!IsCallerSceneBoard()) {
2719 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
2720 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_WRONG_INTERFACE_CALL,
2721 "not sceneboard", true);
2722 return ERR_WRONG_INTERFACE_CALL;
2723 }
2724
2725 if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
2726 return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2727 }
2728
2729 std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
2730 if (sessionId.empty()) {
2731 return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2732 }
2733
2734 TAG_LOGI(AAFwkTag::ABILITYMGR, "sessionId=%{public}s", sessionId.c_str());
2735
2736 if (freeInstallManager_ == nullptr) {
2737 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
2738 return ERR_INVALID_VALUE;
2739 }
2740 FreeInstallInfo taskInfo;
2741 if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
2742 TAG_LOGW(AAFwkTag::ABILITYMGR, "failed find free install task");
2743 auto err = SetWantForSessionInfo(sessionInfo);
2744 if (err != ERR_OK) {
2745 TAG_LOGE(AAFwkTag::ABILITYMGR, "SetWantForSessionInfo failed");
2746 return err;
2747 }
2748 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2749 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2750 if (uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo) == nullptr) {
2751 TAG_LOGI(AAFwkTag::ABILITYMGR, "first time open");
2752 return StartUIAbilityByPreInstallInner(sessionInfo, 0, sceneFlag, isColdStart);
2753 }
2754 return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2755 }
2756
2757 if (taskInfo.isFreeInstallFinished) {
2758 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
2759 if (!taskInfo.isInstalled) {
2760 TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
2761 taskInfo.resultCode);
2762 return taskInfo.resultCode;
2763 }
2764 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeds");
2765 return StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, sceneFlag, isColdStart);
2766 }
2767
2768 {
2769 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
2770 preStartSessionMap_[sessionId] = sessionInfo;
2771 }
2772
2773 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task in progress");
2774 const Want& want = sessionInfo->want;
2775 freeInstallManager_->SetSCBCallStatus(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(),
2776 want.GetStringParam(Want::PARAM_RESV_START_TIME), true);
2777 return ERR_OK;
2778 }
2779
StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2780 int AbilityManagerService::StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo, uint32_t sceneFlag,
2781 bool &isColdStart)
2782 {
2783 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2784 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
2785
2786 auto currentUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2787 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_NULL_SESSION_INFO);
2788 if (sessionInfo->userId == DEFAULT_INVAL_VALUE) {
2789 sessionInfo->userId = currentUserId;
2790 }
2791
2792 (sessionInfo->want).RemoveParam(AAFwk::SCREEN_MODE_KEY);
2793 EventInfo eventInfo = BuildEventInfo(sessionInfo->want, currentUserId);
2794 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
2795
2796 auto requestCode = sessionInfo->requestCode;
2797 int32_t appIndex = 0;
2798 if (!StartAbilityUtils::GetAppIndex(sessionInfo->want, sessionInfo->callerToken, appIndex)) {
2799 return ERR_APP_CLONE_INDEX_INVALID;
2800 }
2801 StartAbilityInfoWrap threadLocalInfo(sessionInfo->want, currentUserId, appIndex, sessionInfo->callerToken);
2802 AbilityRequest abilityRequest;
2803 abilityRequest.processOptions = sessionInfo->processOptions;
2804 auto result = GenerateAbilityRequest(sessionInfo->want, requestCode, abilityRequest,
2805 sessionInfo->callerToken, currentUserId);
2806 if (result != ERR_OK) {
2807 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
2808 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result,
2809 "generate ability request local error", true);
2810 return result;
2811 }
2812 if (sessionInfo->want.GetBoolParam(ServerConstant::IS_CALL_BY_SCB, true)) {
2813 TAG_LOGD(AAFwkTag::ABILITYMGR, "interceptorExecuter_ called");
2814 (sessionInfo->want).RemoveParam(IS_CALLING_FROM_DMS);
2815 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2816 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(sessionInfo->want, requestCode,
2817 currentUserId, true, nullptr, shouldBlockFunc);
2818 auto result = interceptorExecuter_ == nullptr ? ERR_NULL_INTERCEPTOR_EXECUTER :
2819 interceptorExecuter_->DoProcess(interceptorParam);
2820 if (result != ERR_OK) {
2821 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error:%{public}d", result);
2822 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result, "DoProcess error");
2823 return result;
2824 }
2825 if (!HandleExecuteSAInterceptor(sessionInfo->want, sessionInfo->callerToken, abilityRequest, result)) {
2826 return result;
2827 }
2828 }
2829
2830 if (sessionInfo->want.GetBoolParam(ServerConstant::IS_CALL_BY_SCB, true)) {
2831 if (sessionInfo->startSetting != nullptr) {
2832 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb, last not.");
2833 sessionInfo->startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2834 }
2835
2836 if (abilityRequest.startSetting != nullptr) {
2837 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb.");
2838 abilityRequest.startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2839 }
2840 }
2841
2842 abilityRequest.collaboratorType = sessionInfo->collaboratorType;
2843 uint32_t specifyTokenId = static_cast<uint32_t>(sessionInfo->want.GetIntParam(SPECIFY_TOKEN_ID, 0));
2844 (sessionInfo->want).RemoveParam(SPECIFY_TOKEN_ID);
2845 abilityRequest.specifyTokenId = specifyTokenId;
2846
2847 auto abilityInfo = abilityRequest.abilityInfo;
2848 if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall() &&
2849 abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
2850 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability");
2851 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_VALUE,
2852 "only support page type ability", true);
2853 return ERR_INVALID_VALUE;
2854 }
2855
2856 if (sessionInfo->want.GetBoolParam(ServerConstant::IS_CALL_BY_SCB, true)) {
2857 TAG_LOGD(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ called");
2858 if (sessionInfo->want.GetBoolParam("ohos.ability.params.isSkipErmsFromSCB", false)) {
2859 abilityRequest.want.RemoveParam("ohos.ability.params.isSkipErmsFromSCB");
2860 StartAbilityUtils::skipErms = true;
2861 }
2862 Want newWant = abilityRequest.want;
2863 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
2864 RemoveUnauthorizedLaunchReasonMessage(sessionInfo->want, abilityRequest, callerTokenId);
2865 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(), true,
2866 sessionInfo->callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2867 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2868 afterCheckExecuter_->DoProcess(afterCheckParam);
2869 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2870 newWant.RemoveParam("queryWantFromErms");
2871 if (result != ERR_OK) {
2872 if (isReplaceWantExist == false) {
2873 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
2874 eventHelper_.SendStartAbilityErrorEvent(eventInfo, result,
2875 "doProcess failed or replaceWant absent", true);
2876 return result;
2877 }
2878 return DialogSessionManager::GetInstance().HandleErmsResultBySCB(abilityRequest, newWant);
2879 }
2880 }
2881
2882 return StartUIAbilityBySCBDefaultCommon(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2883 }
2884
StartUIAbilityBySCBDefaultCommon(AbilityRequest & abilityRequest,sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2885 int32_t AbilityManagerService::StartUIAbilityBySCBDefaultCommon(AbilityRequest &abilityRequest,
2886 sptr<SessionInfo> sessionInfo, uint32_t sceneFlag, bool &isColdStart)
2887 {
2888 auto abilityInfo = abilityRequest.abilityInfo;
2889 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
2890 int32_t result = PreLoadAppDataAbilities(abilityInfo.bundleName, IPCSkeleton::GetCallingUid() / BASE_USER_RANGE);
2891 if (result != ERR_OK) {
2892 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility: app data ability preloading failed, '%{public}s', %{public}d",
2893 abilityInfo.bundleName.c_str(), result);
2894 return result;
2895 }
2896 }
2897
2898 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
2899 ReportAbilityStartInfoToRSS(abilityInfo);
2900 ReportAbilityAssociatedStartInfoToRSS(abilityInfo, RES_TYPE_SCB_START_ABILITY, sessionInfo->callerToken);
2901 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2902 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2903 return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2904 }
2905
NotifySCBToRecoveryAfterInterception(const AbilityRequest & abilityRequest)2906 int32_t AbilityManagerService::NotifySCBToRecoveryAfterInterception(const AbilityRequest &abilityRequest)
2907 {
2908 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2909 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2910 return uiAbilityManager->NotifySCBToRecoveryAfterInterception(abilityRequest);
2911 }
2912
CheckCallingTokenId(const std::string & bundleName,int32_t userId,int32_t appIndex)2913 bool AbilityManagerService::CheckCallingTokenId(const std::string &bundleName, int32_t userId, int32_t appIndex)
2914 {
2915 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2916 auto bundleMgrHelper = DelayedSingleton<AppExecFwk::BundleMgrHelper>::GetInstance();
2917 CHECK_POINTER_AND_RETURN(bundleMgrHelper, false);
2918 auto validUserId = GetValidUserId(userId);
2919 TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, userId: %{public}d, appIndex: %{public}d",
2920 bundleName.c_str(), validUserId, appIndex);
2921 AppExecFwk::ApplicationInfo appInfo;
2922 IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->GetApplicationInfoWithAppIndex(bundleName,
2923 appIndex, validUserId, appInfo));
2924 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2925 if (accessTokenId != appInfo.accessTokenId) {
2926 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
2927 return false;
2928 }
2929 return true;
2930 }
2931
IsCallerSceneBoard()2932 bool AbilityManagerService::IsCallerSceneBoard()
2933 {
2934 int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2935 auto connectManager = GetConnectManagerByUserId(userId);
2936 CHECK_POINTER_AND_RETURN(connectManager, false);
2937 auto sceneBoardTokenId = connectManager->GetSceneBoardTokenId();
2938 return sceneBoardTokenId != 0 && IPCSkeleton::GetCallingTokenID() == sceneBoardTokenId;
2939 }
2940
IsBackgroundTaskUid(const int uid)2941 bool AbilityManagerService::IsBackgroundTaskUid(const int uid)
2942 {
2943 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2944 std::lock_guard<ffrt::mutex> lock(bgtaskObserverMutex_);
2945 if (bgtaskObserver_) {
2946 return bgtaskObserver_->IsBackgroundTaskUid(uid);
2947 }
2948 return false;
2949 #else
2950 return false;
2951 #endif
2952 }
2953
IsDmsAlive() const2954 bool AbilityManagerService::IsDmsAlive() const
2955 {
2956 return g_isDmsAlive.load();
2957 }
2958
AppUpgradeCompleted(int32_t uid)2959 void AbilityManagerService::AppUpgradeCompleted(int32_t uid)
2960 {
2961 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2962 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
2963 return;
2964 }
2965
2966 auto bms = AbilityUtil::GetBundleManagerHelper();
2967 CHECK_POINTER(bms);
2968 auto userId = uid / BASE_USER_RANGE;
2969 if (userId != U0_USER_ID && userId != U1_USER_ID && userId != GetUserId()) {
2970 TAG_LOGI(AAFwkTag::ABILITYMGR, "not current user");
2971 return;
2972 }
2973
2974 AppExecFwk::BundleInfo bundleInfo;
2975 std::string bundleName;
2976 int32_t appIndex;
2977 if (IN_PROCESS_CALL(bms->GetNameAndIndexForUid(uid, bundleName, appIndex)) != ERR_OK) {
2978 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get appIndex for %{public}s", bundleName.c_str());
2979 return;
2980 }
2981 auto flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION)
2982 | static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE)
2983 | static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY)
2984 | static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY);
2985 TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, userId: %{public}d, appIndex: %{public}d",
2986 bundleName.c_str(), userId, appIndex);
2987 if (IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName, flags, appIndex, bundleInfo, userId)) != ERR_OK) {
2988 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundle info for %{public}s", bundleName.c_str());
2989 return;
2990 }
2991
2992 KeepAliveType type = KeepAliveType::UNSPECIFIED;
2993 if (!KeepAliveUtils::IsKeepAliveBundle(bundleInfo, userId, type)) {
2994 TAG_LOGW(AAFwkTag::ABILITYMGR, "not keep-alive application");
2995 return;
2996 }
2997
2998 std::vector<AppExecFwk::BundleInfo> bundleInfos = { bundleInfo };
2999 if (type == KeepAliveType::THIRD_PARTY) {
3000 KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfos, userId);
3001 if (IN_PROCESS_CALL(KeepAliveProcessManager::GetInstance().CheckNeedRestartAfterUpgrade(uid))) {
3002 IN_PROCESS_CALL_WITHOUT_RET(
3003 KeepAliveProcessManager::GetInstance().StartKeepAliveAppServiceExtension(bundleInfos));
3004 }
3005 } else if (type == KeepAliveType::RESIDENT_PROCESS) {
3006 auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
3007 CHECK_POINTER(residentProcessManager);
3008 residentProcessManager->StartResidentProcessWithMainElement(bundleInfos, userId);
3009 if (!bundleInfos.empty()) {
3010 residentProcessManager->StartResidentProcess(bundleInfos);
3011 }
3012 }
3013 }
3014
RecordAppExitReason(const ExitReason & exitReason)3015 int32_t AbilityManagerService::RecordAppExitReason(const ExitReason &exitReason)
3016 {
3017 TAG_LOGD(AAFwkTag::ABILITYMGR, "recordAppExitReason reason:%{public}d, exitMsg:%{public}s", exitReason.reason,
3018 exitReason.exitMsg.c_str());
3019
3020 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
3021 return appExitReasonHelper_->RecordAppExitReason(exitReason);
3022 }
3023
RecordProcessExitReason(const int32_t pid,const ExitReason & exitReason)3024 int32_t AbilityManagerService::RecordProcessExitReason(const int32_t pid, const ExitReason &exitReason)
3025 {
3026 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3027 auto callerPid = IPCSkeleton::GetCallingPid();
3028 TAG_LOGI(AAFwkTag::ABILITYMGR,
3029 "recordProcessExitReason pid:%{public}d, reason:%{public}d, exitMsg:%{public}s, callerPid:%{public}d",
3030 pid, exitReason.reason, exitReason.exitMsg.c_str(), callerPid);
3031
3032 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
3033 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
3034 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
3035 return ERR_PERMISSION_DENIED;
3036 }
3037
3038 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
3039 return appExitReasonHelper_->RecordProcessExitReason(pid, exitReason, false);
3040 }
3041
RecordProcessExitReason(int32_t pid,int32_t uid,const ExitReason & exitReason)3042 int32_t AbilityManagerService::RecordProcessExitReason(int32_t pid, int32_t uid, const ExitReason &exitReason)
3043 {
3044 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3045 if (IPCSkeleton::GetCallingUid() != HIVIEW_UID && IPCSkeleton::GetCallingUid() != MEMMGR_UID) {
3046 TAG_LOGE(AAFwkTag::ABILITYMGR, "not expected caller");
3047 return ERR_NO_PERMISSION_CALLER;
3048 }
3049
3050 auto callerPid = IPCSkeleton::GetCallingPid();
3051 TAG_LOGI(AAFwkTag::ABILITYMGR,
3052 "[EXIT_REASON_TAG] pid:%{public}d, reason:%{public}d, exitMsg:%{public}s, callerPid:%{public}d",
3053 pid, exitReason.reason, exitReason.exitMsg.c_str(), callerPid);
3054
3055 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_APP_EXIT_REASON_HELPER);
3056 return appExitReasonHelper_->RecordProcessExitReason(pid, uid, exitReason);
3057 }
3058
ForceExitApp(const int32_t pid,const ExitReason & exitReason)3059 int32_t AbilityManagerService::ForceExitApp(const int32_t pid, const ExitReason &exitReason)
3060 {
3061 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3062 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
3063 TAG_LOGI(AAFwkTag::ABILITYMGR, "forceExitApp pid:%{public}d, reason:%{public}d, exitMsg:%{public}s",
3064 pid, exitReason.reason, exitReason.exitMsg.c_str());
3065
3066 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
3067 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
3068 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa or shell call");
3069 return ERR_PERMISSION_DENIED;
3070 }
3071
3072 AppExecFwk::ApplicationInfo application;
3073 bool debug = false;
3074 auto ret = IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->GetApplicationInfoByProcessID(pid,
3075 application, debug));
3076 if (ret != ERR_OK) {
3077 TAG_LOGE(AAFwkTag::ABILITYMGR, "getApplicationInfoByProcessID failed");
3078 return ret;
3079 }
3080
3081 std::string bundleName = application.bundleName;
3082 int32_t uid = application.uid;
3083 int32_t appIndex = application.appIndex;
3084
3085 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
3086 appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
3087
3088 return DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName, false, appIndex);
3089 }
3090
GetConfiguration(AppExecFwk::Configuration & config)3091 int32_t AbilityManagerService::GetConfiguration(AppExecFwk::Configuration& config)
3092 {
3093 auto appMgr = AppMgrUtil::GetAppMgr();
3094 if (appMgr == nullptr) {
3095 TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
3096 return -1;
3097 }
3098
3099 return appMgr->GetConfiguration(config);
3100 }
3101
CheckOptExtensionAbility(const Want & want,AbilityRequest & abilityRequest,int32_t validUserId,AppExecFwk::ExtensionAbilityType extensionType,bool isImplicit,bool isStartAsCaller)3102 int AbilityManagerService::CheckOptExtensionAbility(const Want &want, AbilityRequest &abilityRequest,
3103 int32_t validUserId, AppExecFwk::ExtensionAbilityType extensionType, bool isImplicit, bool isStartAsCaller)
3104 {
3105 auto abilityInfo = abilityRequest.abilityInfo;
3106 auto type = abilityInfo.type;
3107 if (type != AppExecFwk::AbilityType::EXTENSION) {
3108 TAG_LOGE(AAFwkTag::ABILITYMGR, "not extension ability");
3109 return ERR_WRONG_INTERFACE_CALL;
3110 }
3111 if (extensionType != AppExecFwk::ExtensionAbilityType::UNSPECIFIED &&
3112 extensionType != abilityInfo.extensionAbilityType) {
3113 TAG_LOGE(AAFwkTag::ABILITYMGR, "extension ability type not match, set type:%{public}d, real type: %{public}d",
3114 static_cast<int32_t>(extensionType), static_cast<int32_t>(abilityInfo.extensionAbilityType));
3115 return ERR_WRONG_INTERFACE_CALL;
3116 }
3117
3118 auto result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
3119 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
3120 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result=%{public}d", result);
3121 return ERR_STATIC_CFG_PERMISSION;
3122 }
3123
3124 if (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
3125 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE ||
3126 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3127 result = CheckCallServiceExtensionPermission(abilityRequest);
3128 if (result != ERR_OK) {
3129 return result;
3130 }
3131 } else if (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::APP_SERVICE) {
3132 result = CheckCallAppServiceExtensionPermission(abilityRequest, nullptr, false);
3133 if (result != ERR_OK) {
3134 return result;
3135 }
3136 } else {
3137 result = CheckCallOtherExtensionPermission(abilityRequest);
3138 if (result != ERR_OK) {
3139 return result;
3140 }
3141 }
3142 if (!isStartAsCaller) {
3143 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
3144 }
3145 return ERR_OK;
3146 }
3147
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)3148 void AbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
3149 {
3150 TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d add", systemAbilityId);
3151 switch (systemAbilityId) {
3152 case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
3153 SubscribeBackgroundTask();
3154 break;
3155 }
3156 case DISTRIBUTED_SCHED_SA_ID: {
3157 g_isDmsAlive.store(true);
3158 break;
3159 }
3160 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
3161 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
3162 if (bundleMgrHelper) {
3163 bundleMgrHelper->SetBmsReady(true);
3164 }
3165 SubscribeBundleEventCallback();
3166 break;
3167 }
3168 #ifdef SUPPORT_SCREEN
3169 case MULTIMODAL_INPUT_SERVICE_ID: {
3170 auto anrListener = std::make_shared<ApplicationAnrListener>();
3171 MMI::InputManager::GetInstance()->SetAnrObserver(anrListener);
3172 break;
3173 }
3174 #endif
3175 case WINDOW_MANAGER_SERVICE_ID: {
3176 InitWindowVisibilityChangedListener();
3177 break;
3178 }
3179 default:
3180 break;
3181 }
3182 }
3183
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)3184 void AbilityManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
3185 {
3186 TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d remove", systemAbilityId);
3187 switch (systemAbilityId) {
3188 case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
3189 UnSubscribeBackgroundTask();
3190 break;
3191 }
3192 case DISTRIBUTED_SCHED_SA_ID: {
3193 g_isDmsAlive.store(false);
3194 break;
3195 }
3196 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
3197 UnsubscribeBundleEventCallback();
3198 break;
3199 }
3200 case WINDOW_MANAGER_SERVICE_ID: {
3201 FreeWindowVisibilityChangedListener();
3202 break;
3203 }
3204 default:
3205 break;
3206 }
3207 }
3208
SubscribeBackgroundTask()3209 void AbilityManagerService::SubscribeBackgroundTask()
3210 {
3211 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
3212 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
3213 if (!bgtaskObserver_) {
3214 bgtaskObserver_ = std::make_shared<BackgroundTaskObserver>();
3215 }
3216 int ret = BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver_);
3217 if (ret != ERR_OK) {
3218 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s failed, err:%{public}d", __func__, ret);
3219 return;
3220 }
3221 bgtaskObserver_->GetContinuousTaskApps();
3222 bgtaskObserver_->GetEfficiencyResourcesTaskApps();
3223 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success", __func__);
3224 #endif
3225 }
3226
UnSubscribeBackgroundTask()3227 void AbilityManagerService::UnSubscribeBackgroundTask()
3228 {
3229 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
3230 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
3231 if (!bgtaskObserver_) {
3232 return;
3233 }
3234 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success", __func__);
3235 #endif
3236 }
3237
SubscribeBundleEventCallback()3238 void AbilityManagerService::SubscribeBundleEventCallback()
3239 {
3240 TAG_LOGI(AAFwkTag::ABILITYMGR, "subscribeBundleEventCallback begin");
3241 if (taskHandler_) {
3242 TAG_LOGI(AAFwkTag::ABILITYMGR, "submit startResidentApps task");
3243 auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(U0_USER_ID); };
3244 taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps");
3245 }
3246
3247 if (abilityBundleEventCallback_) {
3248 return;
3249 }
3250
3251 // Register abilityBundleEventCallback to receive hap updates
3252 abilityBundleEventCallback_ =
3253 new (std::nothrow) AbilityBundleEventCallback(taskHandler_, abilityAutoStartupService_);
3254 auto bms = AbilityUtil::GetBundleManagerHelper();
3255 if (bms) {
3256 bool ret = IN_PROCESS_CALL(bms->RegisterBundleEventCallback(abilityBundleEventCallback_));
3257 if (!ret) {
3258 TAG_LOGE(AAFwkTag::ABILITYMGR, "registerBundleEventCallback failed");
3259 }
3260 auto pluginRet = IN_PROCESS_CALL(bms->RegisterPluginEventCallback(abilityBundleEventCallback_));
3261 if (pluginRet != ERR_OK) {
3262 TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterPluginEventCallback failed %{public}d", pluginRet);
3263 }
3264 } else {
3265 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundleManager failed");
3266 }
3267 TAG_LOGD(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback success.");
3268 }
3269
UnsubscribeBundleEventCallback()3270 void AbilityManagerService::UnsubscribeBundleEventCallback()
3271 {
3272 if (!abilityBundleEventCallback_) {
3273 return;
3274 }
3275 abilityBundleEventCallback_ = nullptr;
3276 TAG_LOGD(AAFwkTag::ABILITYMGR, "UnsubscribeBundleEventCallback success.");
3277 }
3278
ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo)3279 void AbilityManagerService::ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo)
3280 {
3281 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3282 if (abilityInfo.type == AppExecFwk::AbilityType::PAGE &&
3283 abilityInfo.launchMode != AppExecFwk::LaunchMode::SPECIFIED) {
3284 std::vector<AppExecFwk::RunningProcessInfo> runningProcessInfos;
3285 if (IN_PROCESS_CALL(GetProcessRunningInfos(runningProcessInfos)) != ERR_OK) {
3286 return;
3287 }
3288 bool isColdStart = true;
3289 int32_t pid = 0;
3290 bool supportWarmSmartGC = false;
3291 for (auto const &info : runningProcessInfos) {
3292 if (info.uid_ == abilityInfo.applicationInfo.uid &&
3293 info.processType_ == AppExecFwk::ProcessType::NORMAL &&
3294 std::find(info.bundleNames.begin(), info.bundleNames.end(),
3295 abilityInfo.applicationInfo.bundleName) != info.bundleNames.end()) {
3296 isColdStart = info.isExiting ? true : info.preloadMode_ == AppExecFwk::PreloadMode::PRESS_DOWN;
3297 pid = info.isExiting ? 0 : info.pid_;
3298 AppExecFwk::PreloadMode mode = info.preloadMode_;
3299 bool isSuggestCache = info.isCached;
3300 bool supportWarmSmartGC = (isSuggestCache ||
3301 mode == AppExecFwk::PreloadMode::PRE_MAKE ||
3302 mode == AppExecFwk::PreloadMode::PRELOAD_MODULE);
3303 TAG_LOGI(AAFwkTag::ABILITYMGR, "SmartGC: Process %{public}d report to RSS, start type: %{public}d, isCached: %{public}d, supportWarmGC: %{public}d",
3304 pid, static_cast<int32_t>(mode), static_cast<int32_t>(isSuggestCache), static_cast<int32_t>(supportWarmSmartGC));
3305 break;
3306 }
3307 }
3308 ResSchedUtil::GetInstance().ReportAbilityStartInfoToRSS(abilityInfo, pid, isColdStart, supportWarmSmartGC);
3309 }
3310 }
3311
ReportAbilityAssociatedStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo,int64_t type,const sptr<IRemoteObject> & callerToken)3312 void AbilityManagerService::ReportAbilityAssociatedStartInfoToRSS(
3313 const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr<IRemoteObject> &callerToken)
3314 {
3315 CHECK_POINTER_LOG(callerToken, "null callerToken");
3316 auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
3317 CHECK_POINTER_LOG(callerAbility, "null callerAbility");
3318 int32_t callerUid = callerAbility->GetUid();
3319 int32_t callerPid = callerAbility->GetPid();
3320 ResSchedUtil::GetInstance().ReportAbilityAssociatedStartInfoToRSS(abilityInfo, type, callerUid, callerPid);
3321 }
3322
ReportEventToRSS(const AppExecFwk::AbilityInfo & abilityInfo,sptr<IRemoteObject> callerToken)3323 void AbilityManagerService::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo,
3324 sptr<IRemoteObject> callerToken)
3325 {
3326 CHECK_POINTER_LOG(taskHandler_, "taskhandler null");
3327 std::string reason = ResSchedUtil::GetInstance().GetThawReasonByAbilityType(abilityInfo);
3328 const auto uid = abilityInfo.applicationInfo.uid;
3329 const auto bundleName = abilityInfo.applicationInfo.bundleName;
3330 auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
3331 const int32_t callerPid = (callerAbility != nullptr) ? callerAbility->GetPid() : IPCSkeleton::GetCallingPid();
3332 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}d_%{public}s reason=%{public}s callerPid=%{public}d", uid,
3333 bundleName.c_str(), reason.c_str(), callerPid);
3334 taskHandler_->SubmitTask([reason, uid, bundleName, callerPid]() {
3335 ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason, -1, callerPid);
3336 });
3337 }
3338
ReportAppConnectOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want)3339 void AbilityManagerService::ReportAppConnectOtherExtensionEvent(const AppExecFwk::AbilityInfo &abilityInfo,
3340 const Want &want)
3341 {
3342 if (PermissionVerification::GetInstance()->IsSACall()) {
3343 return;
3344 }
3345 const std::unordered_set<AppExecFwk::ExtensionAbilityType> extensionSet {
3346 AppExecFwk::ExtensionAbilityType::FORM,
3347 AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER,
3348 AppExecFwk::ExtensionAbilityType::INPUTMETHOD,
3349 AppExecFwk::ExtensionAbilityType::ACCESSIBILITY,
3350 AppExecFwk::ExtensionAbilityType::STATICSUBSCRIBER,
3351 AppExecFwk::ExtensionAbilityType::WALLPAPER,
3352 AppExecFwk::ExtensionAbilityType::BACKUP,
3353 AppExecFwk::ExtensionAbilityType::ENTERPRISE_ADMIN,
3354 AppExecFwk::ExtensionAbilityType::PRINT,
3355 AppExecFwk::ExtensionAbilityType::VPN,
3356 AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION,
3357 AppExecFwk::ExtensionAbilityType::REMOTE_NOTIFICATION,
3358 AppExecFwk::ExtensionAbilityType::REMOTE_LOCATION,
3359 AppExecFwk::ExtensionAbilityType::PUSH,
3360 AppExecFwk::ExtensionAbilityType::VOIP
3361 };
3362 if (extensionSet.find(abilityInfo.extensionAbilityType) != extensionSet.end()) {
3363 EventInfo eventInfo;
3364 eventInfo.bundleName = abilityInfo.bundleName;
3365 eventInfo.moduleName = abilityInfo.moduleName;
3366 eventInfo.abilityName = abilityInfo.name;
3367 eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
3368 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
3369 if (eventInfo.callerBundleName.empty()) {
3370 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
3371 }
3372 // Add prefix to distinguish reporting scenarios
3373 eventInfo.callerBundleName = "Connect:" + eventInfo.callerBundleName;
3374 EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
3375 }
3376 }
3377
StartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)3378 int32_t AbilityManagerService::StartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
3379 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
3380 {
3381 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3382 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3383 if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
3384 TAG_LOGE(AAFwkTag::SERVICE_EXT, "uiServiceExtensionAbility disable");
3385 return ERR_CAPABILITY_NOT_SUPPORT;
3386 }
3387 }
3388 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
3389 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN ||
3390 extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE ||
3391 extensionType == AppExecFwk::ExtensionAbilityType::APP_SERVICE) {
3392 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false);
3393 }
3394 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true);
3395 }
3396
ImplicitStartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)3397 int AbilityManagerService::ImplicitStartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
3398 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
3399 {
3400 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
3401 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
3402 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false, true);
3403 }
3404 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true, true);
3405 }
3406
PreloadUIExtensionAbility(const Want & want,std::string & bundleName,int32_t userId,int32_t hostPid)3407 int AbilityManagerService::PreloadUIExtensionAbility(const Want &want, std::string &bundleName,
3408 int32_t userId, int32_t hostPid)
3409 {
3410 if (AppUtils::GetInstance().IsForbidStart()) {
3411 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
3412 return INNER_ERR;
3413 }
3414 TAG_LOGI(AAFwkTag::UI_EXT, "callerBundle: %{public}s", bundleName.c_str());
3415 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3416 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
3417 // check preload ui extension permission.
3418 CHECK_CALLER_IS_SYSTEM_APP;
3419 if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
3420 PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
3421 TAG_LOGE(AAFwkTag::UI_EXT, "permission %{public}s verification failed",
3422 PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
3423 return ERR_PERMISSION_DENIED;
3424 }
3425 return PreloadUIExtensionAbilityInner(want, bundleName, userId, hostPid);
3426 }
3427
PreloadUIExtensionAbilityInner(const Want & want,std::string & hostBundleName,int32_t userId,int32_t hostPid)3428 int AbilityManagerService::PreloadUIExtensionAbilityInner(const Want &want, std::string &hostBundleName,
3429 int32_t userId, int32_t hostPid)
3430 {
3431 TAG_LOGD(AAFwkTag::UI_EXT, "PreloadUIExtension called, elementName: %{public}s.",
3432 want.GetElement().GetURI().c_str());
3433 int32_t validUserId = GetValidUserId(userId);
3434 AbilityRequest abilityRequest;
3435 ErrCode result = ERR_OK;
3436 EventInfo eventInfo = BuildEventInfo(want, userId);
3437 eventInfo.lifeCycle = LIFE_CYCLE_PRELOAD;
3438 result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, validUserId);
3439 if (result != ERR_OK) {
3440 TAG_LOGE(AAFwkTag::UI_EXT, "generate abilityReq error");
3441 return result;
3442 }
3443 abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
3444 abilityRequest.want.SetParam(IS_PRELOAD_UIEXTENSION_ABILITY, true);
3445 auto abilityInfo = abilityRequest.abilityInfo;
3446 auto res = JudgeAbilityVisibleControl(abilityInfo);
3447 if (res != ERR_OK) {
3448 TAG_LOGE(AAFwkTag::UI_EXT, "target ability invisible");
3449 return res;
3450 }
3451 auto connectManager = GetConnectManagerByUserId(validUserId);
3452 if (connectManager == nullptr) {
3453 TAG_LOGE(AAFwkTag::UI_EXT, "connectManager null, userId:%{public}d", validUserId);
3454 eventInfo.errReason = "get connectManager by userId failed";
3455 SendExtensionReport(eventInfo, CONNECT_MAMAGER_NOT_FIND_BY_USERID);
3456 return ERR_INVALID_VALUE;
3457 }
3458 result = connectManager->PreloadUIExtensionAbilityLocked(abilityRequest, hostBundleName, hostPid);
3459 if (result != ERR_OK) {
3460 eventInfo.errReason = "PreloadUIExtensionAbilityLocked error";
3461 SendExtensionReport(eventInfo, result);
3462 }
3463 return result;
3464 }
3465
UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> & abilityRecord,std::string & hostBundleName)3466 int AbilityManagerService::UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> &abilityRecord,
3467 std::string &hostBundleName)
3468 {
3469 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
3470 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3471 auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
3472 if (connectManager == nullptr) {
3473 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null");
3474 return ERR_INVALID_VALUE;
3475 }
3476 return connectManager->UnloadUIExtensionAbility(abilityRecord, hostBundleName);
3477 }
3478
RequestModalUIExtension(const Want & want)3479 int AbilityManagerService::RequestModalUIExtension(const Want &want)
3480 {
3481 CHECK_CALLER_IS_SYSTEM_APP;
3482 return RequestModalUIExtensionInner(want);
3483 }
3484
RequestModalUIExtensionInner(Want want)3485 int AbilityManagerService::RequestModalUIExtensionInner(Want want)
3486 {
3487 sptr<IRemoteObject> token = nullptr;
3488 int ret = IN_PROCESS_CALL(GetTopAbility(token));
3489 if (ret == ERR_OK && token != nullptr) {
3490 // Gets the record corresponding to the current focus appliaction
3491 auto record = Token::GetAbilityRecordByToken(token);
3492 if (!record) {
3493 TAG_LOGE(AAFwkTag::ABILITYMGR, "record null");
3494 return ERR_INVALID_VALUE;
3495 }
3496
3497 // Gets the bundleName corresponding to the
3498 // current focus appliaction
3499 std::string focusName = record->GetAbilityInfo().bundleName;
3500
3501 // Gets the bundleName corresponding to the
3502 // current focus appliaction
3503 std::string callerName = want.GetParams().GetStringParam("bundleName");
3504
3505 TAG_LOGI(AAFwkTag::ABILITYMGR,
3506 "focusbundlename: %{public}s, callerbundlename: %{public}s",
3507 focusName.c_str(), callerName.c_str());
3508
3509 // Compare
3510 if (record->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
3511 focusName == callerName) {
3512 TAG_LOGD(AAFwkTag::ABILITYMGR, "CreateModalUIExtension is called!");
3513 return record->CreateModalUIExtension(want);
3514 }
3515 } else {
3516 TAG_LOGW(AAFwkTag::ABILITYMGR, "token null");
3517 }
3518
3519 TAG_LOGD(AAFwkTag::ABILITYMGR, "Window Modal System Create UIExtension is called!");
3520 want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
3521 auto connection = std::make_shared<Rosen::ModalSystemUiExtension>();
3522 return connection->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR;
3523 }
3524
ChangeAbilityVisibility(sptr<IRemoteObject> token,bool isShow)3525 int AbilityManagerService::ChangeAbilityVisibility(sptr<IRemoteObject> token, bool isShow)
3526 {
3527 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
3528 bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
3529 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
3530 TAG_LOGE(AAFwkTag::ABILITYMGR, "capability not support");
3531 return ERR_CAPABILITY_NOT_SUPPORT;
3532 }
3533 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3534 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3535 return uiAbilityManager->ChangeAbilityVisibility(token, isShow);
3536 }
3537
ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo,bool isShow)3538 int AbilityManagerService::ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo, bool isShow)
3539 {
3540 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
3541 if (!IsCallerSceneBoard()) {
3542 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3543 return ERR_WRONG_INTERFACE_CALL;
3544 }
3545 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3546 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3547 return uiAbilityManager->ChangeUIAbilityVisibilityBySCB(sessionInfo, isShow);
3548 }
3549
CheckWorkSchedulerPermission(const sptr<IRemoteObject> & callerToken,const uint32_t uid)3550 bool AbilityManagerService::CheckWorkSchedulerPermission(const sptr<IRemoteObject> &callerToken, const uint32_t uid)
3551 {
3552 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
3553 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
3554 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
3555 if (bgtaskObserver_ && abilityRecord) {
3556 auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
3557 if (callerAbilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER) {
3558 return true;
3559 }
3560
3561 if (!bgtaskObserver_->IsEfficiencyResourcesTaskUid(uid)) {
3562 TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to start extension by WorkScheduler");
3563 return false;
3564 }
3565 }
3566 #endif
3567 return true;
3568 }
3569
StartExtensionAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType,bool checkSystemCaller,bool isImplicit,bool isDlp,bool isStartAsCaller)3570 int32_t AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
3571 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller, bool isImplicit,
3572 bool isDlp, bool isStartAsCaller)
3573 {
3574 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3575 TAG_LOGI(AAFwkTag::SERVICE_EXT,
3576 "Start extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
3577 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3578 CheckExtensionRateLimit();
3579 if (checkSystemCaller) {
3580 CHECK_CALLER_IS_SYSTEM_APP;
3581 }
3582 EventInfo eventInfo = BuildEventInfo(want, userId);
3583 eventInfo.extensionType = static_cast<int32_t>(extensionType);
3584 eventInfo.lifeCycle = LIFE_CYCLE_START;
3585
3586 int result;
3587 #ifdef WITH_DLP
3588 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::START_EXTENSION_ERROR);
3589 if (result != ERR_OK) {
3590 TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckDlpForExtension error");
3591 return result;
3592 }
3593 #endif // WITH_DLP
3594
3595 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3596 TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s verificationAllToken failed", __func__);
3597 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3598 eventInfo.errReason = "verificationAllToken error";
3599 SendExtensionReport(eventInfo, INVALID_CALLER_TOKEN, true);
3600 } else {
3601 eventInfo.errCode = ERR_INVALID_VALUE;
3602 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3603 }
3604 return ERR_INVALID_CALLER;
3605 }
3606
3607 int32_t validUserId = GetValidUserId(userId);
3608 int32_t appIndex = 0;
3609 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
3610 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3611 eventInfo.errReason = "GetAppIndex error";
3612 SendExtensionReport(eventInfo, ERR_APP_CLONE_INDEX_INVALID, true);
3613 } else {
3614 eventInfo.errCode = ERR_APP_CLONE_INDEX_INVALID;
3615 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3616 }
3617 return ERR_APP_CLONE_INDEX_INVALID;
3618 }
3619 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken, true);
3620 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
3621 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
3622 shouldBlockFunc);
3623 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3624 interceptorExecuter_->DoProcess(interceptorParam);
3625 if (result != ERR_OK) {
3626 TAG_LOGE(AAFwkTag::SERVICE_EXT, "interceptorExecuter_ null or doProcess error");
3627 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3628 eventInfo.errReason = "interceptorExecuter_ null or doProcess error";
3629 eventInfo.appIndex = appIndex;
3630 SendExtensionReport(eventInfo, result, true);
3631 } else {
3632 eventInfo.errCode = result;
3633 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3634 }
3635 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
3636 }
3637
3638 if (!JudgeMultiUserConcurrency(validUserId)) {
3639 TAG_LOGE(AAFwkTag::SERVICE_EXT, "multi-user non-concurrent unsatisfied");
3640 eventInfo.errCode = ERR_CROSS_USER;
3641 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3642 return ERR_CROSS_USER;
3643 }
3644
3645 AbilityRequest abilityRequest;
3646 #ifdef SUPPORT_SCREEN
3647 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
3648 TAG_LOGD(AAFwkTag::SERVICE_EXT, "is implicit start action");
3649 abilityRequest.Voluation(want, DEFAULT_INVAL_VALUE, callerToken);
3650 abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
3651 abilityRequest.extensionType = extensionType;
3652 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
3653 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
3654 if (result != ERR_OK) {
3655 TAG_LOGE(AAFwkTag::SERVICE_EXT, "implicit start ability error:%{public}d", result);
3656 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3657 eventInfo.errReason = "implicit start ability error";
3658 eventInfo.appIndex = appIndex;
3659 SendExtensionReport(eventInfo, result, true);
3660 } else {
3661 eventInfo.errCode = result;
3662 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3663 }
3664 }
3665 return AbilityErrorUtil::ConvertToOriginErrorCode(result);
3666 }
3667 #endif
3668 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
3669 if (result != ERR_OK) {
3670 TAG_LOGE(AAFwkTag::SERVICE_EXT, "generate ability request local error");
3671 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3672 eventInfo.errReason = "generate ability request local error";
3673 eventInfo.appIndex = appIndex;
3674 SendExtensionReport(eventInfo, result, true);
3675 } else {
3676 eventInfo.errCode = result;
3677 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3678 }
3679 return result;
3680 }
3681
3682 if (!HandleExecuteSAInterceptor(want, callerToken, abilityRequest, result)) {
3683 return result;
3684 }
3685
3686 if (!CheckWorkSchedulerPermission(callerToken, abilityRequest.abilityInfo.applicationInfo.uid)) {
3687 return CHECK_PERMISSION_FAILED;
3688 }
3689 auto abilityInfo = abilityRequest.abilityInfo;
3690 validUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
3691 TAG_LOGD(AAFwkTag::SERVICE_EXT, "userId is : %{public}d, singleton is : %{public}d",
3692 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3693
3694 result = isDlp ? IN_PROCESS_CALL(
3695 CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller)) :
3696 CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller);
3697 if (result != ERR_OK) {
3698 TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkOptExtensionAbility error");
3699 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3700 eventInfo.errReason = "checkOptExtensionAbility error";
3701 eventInfo.appIndex = appIndex;
3702 SendExtensionReport(eventInfo, result, true);
3703 } else {
3704 eventInfo.errCode = result;
3705 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3706 }
3707 return result;
3708 }
3709
3710 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
3711 false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
3712 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
3713 afterCheckExecuter_->DoProcess(afterCheckParam);
3714 if (result != ERR_OK) {
3715 TAG_LOGE(AAFwkTag::SERVICE_EXT, "afterCheckExecuter_ null or doProcess error");
3716 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3717 eventInfo.errReason = "afterCheckExecuter_ null or doProcess error";
3718 eventInfo.appIndex = appIndex;
3719 SendExtensionReport(eventInfo, result, true);
3720 } else {
3721 eventInfo.errCode = result;
3722 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3723 }
3724 return result;
3725 }
3726
3727 auto connectManager = GetConnectManagerByUserId(validUserId);
3728 if (!connectManager) {
3729 TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", validUserId);
3730 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3731 eventInfo.errReason = "get connectManager by userId failed";
3732 eventInfo.appIndex = appIndex;
3733 SendExtensionReport(eventInfo, CONNECT_MAMAGER_NOT_FIND_BY_USERID, true);
3734 } else {
3735 eventInfo.errCode = ERR_INVALID_VALUE;
3736 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3737 }
3738 return ERR_INVALID_VALUE;
3739 }
3740 if (!isStartAsCaller) {
3741 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
3742 }
3743
3744 TAG_LOGD(AAFwkTag::SERVICE_EXT, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
3745 SetAbilityRequestSessionInfo(abilityRequest, extensionType);
3746 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
3747 if (eventInfo.errCode != ERR_OK) {
3748 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3749 eventInfo.errReason = "StartAbility error";
3750 eventInfo.appIndex = appIndex;
3751 SendExtensionReport(eventInfo, eventInfo.errCode, true);
3752 } else {
3753 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3754 }
3755 }
3756 ReportAbilityAssociatedStartInfoToRSS(abilityRequest.abilityInfo, RES_TYPE_EXTENSION_START_ABILITY, callerToken);
3757 return eventInfo.errCode;
3758 }
3759
JudgeSystemParamsForPicker(const WantParams & parameters)3760 bool AbilityManagerService::JudgeSystemParamsForPicker(const WantParams ¶meters)
3761 {
3762 auto systemParamsForPickerMap = parameters.GetParams();
3763 if (systemParamsForPickerMap.find(SCREENCONFIG_SCREENMODE) == systemParamsForPickerMap.end()) {
3764 return true;
3765 }
3766
3767 if (AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
3768 return true;
3769 }
3770 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller no system-app, can not use system-api");
3771 return false;
3772 }
3773
SetPickerElementNameAndParams(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)3774 void AbilityManagerService::SetPickerElementNameAndParams(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
3775 {
3776 CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
3777 std::string targetType = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TARGET_TYPE_KEY);
3778 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
3779 extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
3780 extensionSessionInfo->want.GetElement().GetAbilityName().empty() &&
3781 COMMON_PICKER_TYPE.find(targetType) != COMMON_PICKER_TYPE.end()) {
3782 std::string abilityName = "CommonSelectPickerAbility";
3783 std::string bundleName = "com.ohos.amsdialog";
3784 extensionSessionInfo->want.SetElementName(bundleName, abilityName);
3785 WantParams ¶meters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
3786 parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box("sys/commonUI"));
3787 if (!JudgeSystemParamsForPicker(parameters)) {
3788 TAG_LOGI(AAFwkTag::ABILITYMGR, "parames include systemApi but not a systemAPP");
3789 extensionSessionInfo->want.RemoveParam(SCREENCONFIG_SCREENMODE);
3790 }
3791 extensionSessionInfo->want.SetParams(parameters);
3792 return;
3793 }
3794 if (extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
3795 extensionSessionInfo->want.GetElement().GetAbilityName().empty() && !targetType.empty()) {
3796 std::string abilityName;
3797 std::string bundleName;
3798 std::string pickerType;
3799 std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
3800 auto pickerMap = AmsConfigurationParameter::GetInstance().GetPickerMap();
3801 auto it = pickerMap.find(targetType);
3802 if (it == pickerMap.end()) {
3803 TAG_LOGE(AAFwkTag::ABILITYMGR, "can not find targetType:%{public}s", targetType.c_str());
3804 return;
3805 }
3806 pickerType = it->second;
3807 auto bms = AbilityUtil::GetBundleManagerHelper();
3808 CHECK_POINTER(bms);
3809 int32_t validUserId = GetValidUserId(userId);
3810 TAG_LOGI(AAFwkTag::ABILITYMGR, "targetType: %{public}s, pickerType: %{public}s, userId: %{public}d",
3811 targetType.c_str(), pickerType.c_str(), validUserId);
3812 auto flags = static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION) |
3813 static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_BY_TYPE_NAME);
3814 auto ret = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfosOnlyWithTypeName(pickerType,
3815 flags,
3816 validUserId,
3817 extensionInfos));
3818 if (ret != ERR_OK) {
3819 TAG_LOGE(AAFwkTag::ABILITYMGR, "queryExtensionAbilityInfosOnlyWithTypeName failed");
3820 return;
3821 }
3822 abilityName = extensionInfos[0].name;
3823 bundleName = extensionInfos[0].bundleName;
3824 TAG_LOGI(AAFwkTag::ABILITYMGR,
3825 "abilityName: %{public}s, bundleName: %{public}s", abilityName.c_str(), bundleName.c_str());
3826 extensionSessionInfo->want.SetElementName(bundleName, abilityName);
3827 WantParams ¶meters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
3828 parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box(pickerType));
3829
3830 if (!JudgeSystemParamsForPicker(parameters)) {
3831 TAG_LOGI(AAFwkTag::ABILITYMGR, "parames include systemApi but not a systemAPP");
3832 extensionSessionInfo->want.RemoveParam(SCREENCONFIG_SCREENMODE);
3833 }
3834 extensionSessionInfo->want.SetParams(parameters);
3835 }
3836 }
3837
SetAutoFillElementName(const sptr<SessionInfo> & extensionSessionInfo)3838 void AbilityManagerService::SetAutoFillElementName(const sptr<SessionInfo> &extensionSessionInfo)
3839 {
3840 #ifdef SUPPORT_AUTO_FILL
3841 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
3842 CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
3843 std::vector<std::string> argList;
3844 if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_PASSWORD_TYPE) {
3845 SplitStr(KEY_AUTO_FILL_ABILITY, "/", argList);
3846 } else if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_SMART_TYPE) {
3847 SplitStr(KEY_SMART_AUTO_FILL_ABILITY, "/", argList);
3848 } else {
3849 TAG_LOGW(AAFwkTag::ABILITYMGR, "not autofill");
3850 return;
3851 }
3852
3853 if (argList.size() != ARGC_THREE) {
3854 TAG_LOGE(AAFwkTag::ABILITYMGR, "parse extension element name failed");
3855 return;
3856 }
3857 extensionSessionInfo->want.SetElementName(argList[INDEX_ZERO], argList[INDEX_TWO]);
3858 extensionSessionInfo->want.SetModuleName(argList[INDEX_ONE]);
3859 #endif // SUPPORT_AUTO_FILL
3860 }
3861
CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,AppExecFwk::ExtensionAbilityType extensionType)3862 int AbilityManagerService::CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,
3863 AppExecFwk::ExtensionAbilityType extensionType)
3864 {
3865 if (uiExtensionUsage == UIExtensionUsage::EMBEDDED &&
3866 !AAFwk::UIExtensionUtils::IsPublicForEmbedded(extensionType)) {
3867 CHECK_CALLER_IS_SYSTEM_APP;
3868 }
3869
3870 if (uiExtensionUsage == UIExtensionUsage::CONSTRAINED_EMBEDDED &&
3871 !AAFwk::UIExtensionUtils::IsPublicForConstrainedEmbedded(extensionType)) {
3872 TAG_LOGE(AAFwkTag::ABILITYMGR, "secureConstrainedEmbedded extension type error:%u.", extensionType);
3873 return ERR_INVALID_VALUE;
3874 }
3875
3876 if (AAFwk::UIExtensionUtils::IsOnlyForModal(extensionType) &&
3877 uiExtensionUsage != UIExtensionUsage::MODAL) {
3878 TAG_LOGE(AAFwkTag::ABILITYMGR, "secureModal extension type error:%u.", extensionType);
3879 return ERR_INVALID_VALUE;
3880 }
3881
3882 if (uiExtensionUsage == UIExtensionUsage::PRE_VIEW_EMBEDDED &&
3883 !AAFwk::UIExtensionUtils::IsSystemUIExtension(extensionType)) {
3884 TAG_LOGE(AAFwkTag::ABILITYMGR, "target not system app");
3885 return ERR_INVALID_VALUE;
3886 }
3887
3888 return ERR_OK;
3889 }
3890
StartUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)3891 int AbilityManagerService::StartUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
3892 {
3893 if (AppUtils::GetInstance().IsForbidStart()) {
3894 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start uiext");
3895 return INNER_ERR;
3896 }
3897 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3898 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
3899 TAG_LOGD(AAFwkTag::UI_EXT, "StartUIExtensionAbility begin");
3900 CheckExtensionRateLimit();
3901 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3902 SetPickerElementNameAndParams(extensionSessionInfo, userId);
3903 SetAutoFillElementName(extensionSessionInfo);
3904 EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, userId);
3905 eventInfo.persistentId = extensionSessionInfo->persistentId;
3906 eventInfo.lifeCycle = LIFE_CYCLE_START;
3907 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3908
3909 if (extensionSessionInfo->want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
3910 int32_t screenMode = extensionSessionInfo->want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
3911 if (!IsEmbeddableStart(screenMode)) {
3912 TAG_LOGE(AAFwkTag::UI_EXT, "only support embedded pull-ups");
3913 return ERR_INVALID_VALUE;
3914 }
3915 auto bms = AbilityUtil::GetBundleManagerHelper();
3916 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3917 TAG_LOGD(AAFwkTag::UI_EXT, "bundleName: %{public}s, userId: %{public}d",
3918 extensionSessionInfo->want.GetBundle().c_str(), GetValidUserId(userId));
3919 AppExecFwk::BundleInfo bundleInfo;
3920 if (!IN_PROCESS_CALL(bms->GetBundleInfo(extensionSessionInfo->want.GetBundle(),
3921 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, GetValidUserId(userId)))) {
3922 TAG_LOGE(AAFwkTag::UI_EXT, "verifyPermission failed get application info");
3923 return CHECK_PERMISSION_FAILED;
3924 }
3925 if (bundleInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE) {
3926 TAG_LOGE(AAFwkTag::UI_EXT, "only support atomicService");
3927 return ERR_INVALID_CALLER;
3928 }
3929 if (extensionSessionInfo->want.GetElement().GetAbilityName().empty()) {
3930 if (bundleInfo.abilityInfos.empty()) {
3931 TAG_LOGE(AAFwkTag::UI_EXT, "failed get abilityInfos");
3932 eventInfo.errReason = "failed get abilityInfos";
3933 SendExtensionReport(eventInfo, EXTENSION_ABILITY_NOT_EXIST);
3934 return ERR_INVALID_VALUE;
3935 }
3936 extensionSessionInfo->want.SetElementName(bundleInfo.name, bundleInfo.abilityInfos.begin()->name);
3937 }
3938 extensionSessionInfo->want.SetParam("send_to_erms_embedded", 1);
3939 }
3940 std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY);
3941 AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ?
3942 AppExecFwk::ExtensionAbilityType::UI : AppExecFwk::ConvertToExtensionAbilityType(extensionTypeStr);
3943 if (extensionType == AppExecFwk::ExtensionAbilityType::UNSPECIFIED) {
3944 TAG_LOGE(AAFwkTag::UI_EXT, "input extension ability type invalid");
3945 return ERR_INVALID_VALUE;
3946 }
3947 eventInfo.extensionType = static_cast<int32_t>(extensionType);
3948
3949 auto ret = CheckUIExtensionUsage(extensionSessionInfo->uiExtensionUsage, extensionType);
3950 if (ret != ERR_OK) {
3951 TAG_LOGE(AAFwkTag::UI_EXT, "check usage failed");
3952 return ret;
3953 }
3954
3955 if (InsightIntentExecuteParam::IsInsightIntentExecute(extensionSessionInfo->want)) {
3956 auto callerBundlename = InsightIntentGetcallerBundleName();
3957 if (callerBundlename.empty()) {
3958 TAG_LOGD(AAFwkTag::ABILITYMGR, "insightIntent get callerBundlename failed");
3959 }
3960 TAG_LOGI(AAFwkTag::ABILITYMGR, "start uiExtension ability, bundlename: %{public}s", callerBundlename.c_str());
3961 int32_t result = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateWant(
3962 extensionSessionInfo->want, AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY, callerBundlename);
3963 if (result != ERR_OK) {
3964 eventInfo.errReason = "CheckAndUpdateWant error";
3965 SendExtensionReport(eventInfo, result);
3966 return result;
3967 }
3968 }
3969
3970 sptr<IRemoteObject> callerToken = extensionSessionInfo->callerToken;
3971
3972 #ifdef WITH_DLP
3973 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, extensionSessionInfo->want) ||
3974 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
3975 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, extensionSessionInfo->want)) {
3976 TAG_LOGE(AAFwkTag::UI_EXT, "startUIExtensionAbility: permission verification failed");
3977 return CHECK_PERMISSION_FAILED;
3978 }
3979 #endif // WITH_DLP
3980
3981 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3982 TAG_LOGE(AAFwkTag::UI_EXT, "startUIExtensionAbility verificationAllToken failed");
3983 eventInfo.errReason = "not containsAbility or not find abilityRecord by callerToken";
3984 SendExtensionReport(eventInfo, INVALID_CALLER_TOKEN);
3985 return ERR_INVALID_CALLER;
3986 }
3987
3988 auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
3989 if (callerRecord == nullptr || !JudgeSelfCalled(callerRecord)) {
3990 TAG_LOGE(AAFwkTag::UI_EXT, "invalid callerToken");
3991 eventInfo.errReason = "get ability record by callerToken failed";
3992 SendExtensionReport(eventInfo, INVALID_CALLER_TOKEN);
3993 return ERR_INVALID_CALLER;
3994 }
3995 StartAbilityInfoWrap threadLocalInfo;
3996
3997 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
3998 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(extensionSessionInfo->want, 0, GetUserId(),
3999 true, nullptr, shouldBlockFunc);
4000 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4001 interceptorExecuter_->DoProcess(interceptorParam);
4002 if (result != ERR_OK) {
4003 TAG_LOGE(AAFwkTag::UI_EXT, "interceptorExecuter_ null or doProcess error");
4004 eventInfo.errReason = "interceptorExecuter_ null or doProcess error";
4005 SendExtensionReport(eventInfo, result);
4006 return result;
4007 }
4008
4009 int32_t validUserId = GetValidUserId(userId);
4010 if (!JudgeMultiUserConcurrency(validUserId)) {
4011 TAG_LOGE(AAFwkTag::UI_EXT, "multi-user non-concurrent unsatisfied");
4012 eventInfo.errReason = "multi-user non-concurrent unsatisfied";
4013 SendExtensionReport(eventInfo, ERR_CROSS_USER);
4014 return ERR_INVALID_VALUE;
4015 }
4016 #ifdef SUPPORT_GRAPHICS
4017 if (ImplicitStartProcessor::IsImplicitStartAction(extensionSessionInfo->want)) {
4018 TAG_LOGE(AAFwkTag::UI_EXT, "UI extension ability not support implicit start");
4019 return ERR_INVALID_VALUE;
4020 }
4021 #endif // SUPPORT_GRAPHICS
4022 AbilityRequest abilityRequest;
4023 abilityRequest.Voluation(extensionSessionInfo->want, DEFAULT_INVAL_VALUE, callerToken);
4024 abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
4025 abilityRequest.sessionInfo = extensionSessionInfo;
4026 result = GenerateEmbeddableUIAbilityRequest(extensionSessionInfo->want, abilityRequest, callerToken, validUserId);
4027 CHECK_POINTER_AND_RETURN(abilityRequest.sessionInfo, ERR_INVALID_VALUE);
4028 abilityRequest.sessionInfo->uiExtensionComponentId = (
4029 static_cast<uint64_t>(callerRecord->GetRecordId()) << OFFSET) |
4030 static_cast<uint64_t>(abilityRequest.sessionInfo->persistentId);
4031 TAG_LOGI(AAFwkTag::UI_EXT, "StartUIExtension: persistentId: %{public}d, element: %{public}s.",
4032 abilityRequest.sessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
4033 if (result != ERR_OK) {
4034 TAG_LOGE(AAFwkTag::UI_EXT, "generate ability request local error");
4035 eventInfo.errReason = "generate ability request local error";
4036 SendExtensionReport(eventInfo, result);
4037 return result;
4038 }
4039 abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
4040
4041 if (!HandleExecuteSAInterceptor(extensionSessionInfo->want, callerToken, abilityRequest, result)) {
4042 return result;
4043 }
4044 auto abilityInfo = abilityRequest.abilityInfo;
4045 threadLocalInfo.SetStartAbilityInfo(abilityInfo);
4046 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
4047 TAG_LOGD(AAFwkTag::UI_EXT, "userId is : %{public}d, singleton is : %{public}d",
4048 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
4049
4050 result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType);
4051 if (result != ERR_OK) {
4052 TAG_LOGE(AAFwkTag::UI_EXT, "checkOptExtensionAbility error");
4053 eventInfo.errReason = "checkOptExtensionAbility error";
4054 SendExtensionReport(eventInfo, result);
4055 return result;
4056 }
4057
4058 sptr<IRemoteObject> parentToken = extensionSessionInfo->parentToken;
4059 if (parentToken && parentToken != callerToken) {
4060 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, parentToken);
4061 }
4062
4063 result = JudgeAbilityVisibleControl(abilityInfo);
4064 if (result != ERR_OK) {
4065 TAG_LOGE(AAFwkTag::UI_EXT, "judgeAbilityVisibleControl error");
4066 return result;
4067 }
4068
4069 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
4070 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
4071 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
4072 afterCheckExecuter_->DoProcess(afterCheckParam);
4073 if (result != ERR_OK) {
4074 TAG_LOGE(AAFwkTag::UI_EXT, "afterCheckExecuter_ null or doProcess error");
4075 eventInfo.errReason = "afterCheckExecuter_ null or doProcess error";
4076 SendExtensionReport(eventInfo, result);
4077 return result;
4078 }
4079
4080 auto connectManager = GetConnectManagerByUserId(validUserId);
4081 if (!connectManager) {
4082 TAG_LOGE(AAFwkTag::UI_EXT, "connectManager null userId=%{public}d", validUserId);
4083 eventInfo.errReason = "get connectManager by userId failed";
4084 SendExtensionReport(eventInfo, CONNECT_MAMAGER_NOT_FIND_BY_USERID);
4085 return ERR_INVALID_VALUE;
4086 }
4087 TAG_LOGD(AAFwkTag::UI_EXT, "name:%{public}s", abilityInfo.name.c_str());
4088 #ifdef SUPPORT_GRAPHICS
4089 // for implicit system selector modal dialog
4090 bool isSCBCall = (callerRecord->GetApplicationInfo().bundleName == AbilityConfig::SCENEBOARD_BUNDLE_NAME);
4091 DialogSessionManager::GetInstance().UpdateExtensionWantWithDialogCallerInfo(abilityRequest, callerToken,
4092 isSCBCall);
4093 #endif // SUPPORT_GRAPHICS
4094 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
4095 if (eventInfo.errCode != ERR_OK) {
4096 eventInfo.errReason = "StartAbility error";
4097 SendExtensionReport(eventInfo, eventInfo.errCode);
4098 }
4099 return eventInfo.errCode;
4100 }
4101
StopExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)4102 int AbilityManagerService::StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
4103 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
4104 {
4105 TAG_LOGI(AAFwkTag::SERVICE_EXT,
4106 "bundlename:%{public}s, ability:%{public}s, userId:%{public}d",
4107 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
4108 if (extensionType != AppExecFwk::ExtensionAbilityType::VPN &&
4109 extensionType != AppExecFwk::ExtensionAbilityType::APP_SERVICE) {
4110 CHECK_CALLER_IS_SYSTEM_APP;
4111 }
4112 EventInfo eventInfo = BuildEventInfo(want, userId);
4113 eventInfo.extensionType = static_cast<int32_t>(extensionType);
4114
4115 int result;
4116 #ifdef WITH_DLP
4117 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::STOP_EXTENSION_ERROR);
4118 if (result != ERR_OK) {
4119 TAG_LOGE(AAFwkTag::SERVICE_EXT, "CheckDlpForExtension error");
4120 return result;
4121 }
4122 #endif // WITH_DLP
4123
4124 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
4125 TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s verificationAllToken failed", __func__);
4126 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
4127 TAG_LOGE(AAFwkTag::SERVICE_EXT, "verificationAllToken failed");
4128 eventInfo.errCode = ERR_INVALID_VALUE;
4129 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4130 return ERR_INVALID_CALLER;
4131 }
4132 TAG_LOGD(AAFwkTag::SERVICE_EXT, "Caller is specific system ability.");
4133 }
4134
4135 int32_t validUserId = GetValidUserId(userId);
4136 if (!JudgeMultiUserConcurrency(validUserId)) {
4137 TAG_LOGE(AAFwkTag::SERVICE_EXT, "multi-user non-concurrent unsatisfied");
4138 eventInfo.errCode = ERR_INVALID_VALUE;
4139 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4140 return ERR_CROSS_USER;
4141 }
4142
4143 if (callerToken != nullptr && CheckIfOperateRemote(want)) {
4144 auto callerUid = IPCSkeleton::GetCallingUid();
4145 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4146 DistributedClient dmsClient;
4147 return dmsClient.StopRemoteExtensionAbility(want, callerUid, accessToken, eventInfo.extensionType);
4148 }
4149
4150 AbilityRequest abilityRequest;
4151 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
4152 if (result != ERR_OK) {
4153 TAG_LOGE(AAFwkTag::SERVICE_EXT, "generate ability request local error");
4154 eventInfo.errCode = result;
4155 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4156 return result;
4157 }
4158
4159 auto abilityInfo = abilityRequest.abilityInfo;
4160 validUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
4161 TAG_LOGD(AAFwkTag::SERVICE_EXT, "userId is : %{public}d, singleton is : %{public}d",
4162 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
4163
4164 result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
4165 if (result != ERR_OK) {
4166 TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkOptExtensionAbility error");
4167 eventInfo.errCode = result;
4168 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4169 return result;
4170 }
4171
4172 auto connectManager = GetConnectManagerByUserId(validUserId);
4173 if (!connectManager) {
4174 TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", validUserId);
4175 eventInfo.errCode = ERR_INVALID_VALUE;
4176 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4177 return ERR_INVALID_VALUE;
4178 }
4179 TAG_LOGD(AAFwkTag::SERVICE_EXT, "Stop extension begin, name:%{public}s", abilityInfo.name.c_str());
4180 eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
4181 if (eventInfo.errCode != ERR_OK) {
4182 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4183 }
4184 return eventInfo.errCode;
4185 }
4186
StopSwitchUserDialog()4187 void AbilityManagerService::StopSwitchUserDialog()
4188 {
4189 TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog extension ability come");
4190 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4191 TAG_LOGE(AAFwkTag::ABILITYMGR, "scene board enabled");
4192 return;
4193 }
4194
4195 if (userController_ == nullptr || userController_->GetFreezingNewUserId() == DEFAULT_INVAL_VALUE) {
4196 TAG_LOGE(AAFwkTag::ABILITYMGR, "get last userId error");
4197 return;
4198 }
4199 #ifdef SUPPORT_GRAPHICS
4200 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
4201 if (sysDialog == nullptr) {
4202 TAG_LOGE(AAFwkTag::ABILITYMGR, "system dialog scheduler instance null");
4203 return;
4204 }
4205 Want stopWant = sysDialog->GetSwitchUserDialogWant();
4206 StopSwitchUserDialogInner(stopWant, userController_->GetFreezingNewUserId());
4207 #endif // SUPPORT_GRAPHICS
4208 userController_->SetFreezingNewUserId(DEFAULT_INVAL_VALUE);
4209 return;
4210 }
4211
StopSwitchUserDialogInner(const Want & want,const int32_t lastUserId)4212 void AbilityManagerService::StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)
4213 {
4214 TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog inner come");
4215 EventInfo eventInfo = BuildEventInfo(want, lastUserId);
4216 eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
4217 AbilityRequest abilityRequest;
4218 auto result =
4219 GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
4220 if (result != ERR_OK) {
4221 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
4222 eventInfo.errCode = result;
4223 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4224 return;
4225 }
4226
4227 auto abilityInfo = abilityRequest.abilityInfo;
4228 auto stopUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
4229 result = CheckOptExtensionAbility(want, abilityRequest, stopUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
4230 if (result != ERR_OK) {
4231 TAG_LOGE(AAFwkTag::ABILITYMGR, "check extensionAbility type error");
4232 eventInfo.errCode = result;
4233 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4234 return;
4235 }
4236
4237 auto connectManager = GetConnectManagerByUserId(stopUserId);
4238 if (connectManager == nullptr) {
4239 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId:%{public}d", stopUserId);
4240 eventInfo.errCode = ERR_INVALID_VALUE;
4241 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4242 return;
4243 }
4244
4245 eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
4246 if (eventInfo.errCode != ERR_OK) {
4247 TAG_LOGE(AAFwkTag::ABILITYMGR, "eventInfo errCode=%{public}d", eventInfo.errCode);
4248 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
4249 }
4250 }
4251
MoveAbilityToBackground(const sptr<IRemoteObject> & token)4252 int AbilityManagerService::MoveAbilityToBackground(const sptr<IRemoteObject> &token)
4253 {
4254 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4255 TAG_LOGD(AAFwkTag::ABILITYMGR, "Move ability to background begin");
4256 if (!VerificationAllToken(token)) {
4257 return ERR_INVALID_VALUE;
4258 }
4259 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4260 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4261 if (!JudgeSelfCalled(abilityRecord)) {
4262 return CHECK_PERMISSION_FAILED;
4263 }
4264
4265 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4266 return ERR_WOULD_BLOCK;
4267 }
4268
4269 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
4270 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
4271 if (!missionListManager) {
4272 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null ownerUserId=%{public}d", ownerUserId);
4273 return ERR_INVALID_VALUE;
4274 }
4275 return missionListManager->MoveAbilityToBackground(abilityRecord);
4276 }
4277
MoveUIAbilityToBackground(const sptr<IRemoteObject> token)4278 int32_t AbilityManagerService::MoveUIAbilityToBackground(const sptr<IRemoteObject> token)
4279 {
4280 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4281 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
4282 if (!AppUtils::GetInstance().EnableMoveUIAbilityToBackgroundApi()) {
4283 return ERR_OPERATION_NOT_SUPPORTED_ON_CURRENT_DEVICE;
4284 }
4285 if (!VerificationAllToken(token)) {
4286 return ERR_INVALID_VALUE;
4287 }
4288 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4289 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4290 if (!IsAppSelfCalled(abilityRecord)) {
4291 return CHECK_PERMISSION_FAILED;
4292 }
4293 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4294 TAG_LOGE(AAFwkTag::ABILITYMGR, "move ability background failed in wukong mode");
4295 return ERR_WUKONG_MODE_CANT_MOVE_STATE;
4296 }
4297 if (!abilityRecord->IsAbilityState(FOREGROUND) && !abilityRecord->IsAbilityState(FOREGROUNDING)) {
4298 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability not foregorund state");
4299 return ERR_ABILITY_NOT_FOREGROUND;
4300 }
4301 if (abilityRecord->GetAbilityInfo().type != AppExecFwk::AbilityType::PAGE) {
4302 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot background non UIAbility");
4303 return RESOLVE_CALL_ABILITY_TYPE_ERR;
4304 }
4305 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
4306 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4307 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
4308 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4309 return uiAbilityManager->NotifySCBToMinimizeUIAbility(token);
4310 }
4311
4312 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
4313 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
4314 return missionListManager->MoveAbilityToBackground(abilityRecord);
4315 }
4316
TerminateAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)4317 int AbilityManagerService::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
4318 {
4319 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4320 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4321 if (!abilityRecord) {
4322 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
4323 return ERR_INVALID_VALUE;
4324 }
4325 auto elementName = abilityRecord->GetWant().GetElement();
4326 if (AppUtils::GetInstance().IsLauncher(elementName.GetBundleName()) &&
4327 AppUtils::GetInstance().IsLauncherAbility(elementName.GetAbilityName())) {
4328 TAG_LOGI(AAFwkTag::ABILITYMGR, "cannot terminate launcher ability");
4329 return ERR_OK;
4330 }
4331 return TerminateAbilityWithFlag(token, resultCode, resultWant, true);
4332 }
4333
TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> & token)4334 int32_t AbilityManagerService::TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> &token)
4335 {
4336 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4337 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4338 if (!VerificationAllToken(token)) {
4339 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
4340 return ERR_INVALID_VALUE;
4341 }
4342
4343 if (!IsCallerSceneBoard()) {
4344 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
4345 return ERR_WRONG_INTERFACE_CALL;
4346 }
4347
4348 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4349 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4350
4351 auto type = abilityRecord->GetAbilityInfo().type;
4352 auto extensionAbilityType = abilityRecord->GetAbilityInfo().extensionAbilityType;
4353
4354 if (type != AppExecFwk::AbilityType::EXTENSION ||
4355 extensionAbilityType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
4356 return ERR_INVALID_VALUE;
4357 }
4358
4359 auto userId = GetValidUserId(DEFAULT_INVAL_VALUE);
4360 auto connectManager = GetConnectManagerByUserId(userId);
4361 if (!connectManager) {
4362 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
4363 return ERR_INVALID_VALUE;
4364 }
4365 return connectManager->TerminateAbility(token);
4366 }
4367
BackToCallerAbilityWithResult(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,int64_t callerRequestCode)4368 int AbilityManagerService::BackToCallerAbilityWithResult(const sptr<IRemoteObject> &token, int resultCode,
4369 const Want *resultWant, int64_t callerRequestCode)
4370 {
4371 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4372 if (!abilityRecord) {
4373 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
4374 return ERR_INVALID_VALUE;
4375 }
4376 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
4377 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4378 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
4379 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4380 return uiAbilityManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant,
4381 callerRequestCode);
4382 }
4383 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
4384 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
4385 return missionListManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant, callerRequestCode);
4386 }
4387
CloseAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)4388 int AbilityManagerService::CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
4389 {
4390 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4391 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4392 EventInfo eventInfo = BuildEventInfoByAbilityRecord(abilityRecord);
4393 SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
4394 return TerminateAbilityWithFlag(token, resultCode, resultWant, false);
4395 }
4396
TerminateAbilityWithFlag(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,bool flag)4397 int AbilityManagerService::TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode,
4398 const Want *resultWant, bool flag)
4399 {
4400 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4401 TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ability begin, flag:%{public}d.", flag);
4402 if (!VerificationAllToken(token)) {
4403 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
4404 return ERR_INVALID_VALUE;
4405 }
4406
4407 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4408 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4409 if (!JudgeSelfCalled(abilityRecord)) {
4410 return CHECK_PERMISSION_FAILED;
4411 }
4412
4413 if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) {
4414 TAG_LOGE(AAFwkTag::ABILITYMGR, "system ui not allow terminate");
4415 return ERR_INVALID_VALUE;
4416 }
4417
4418 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4419 auto type = abilityRecord->GetAbilityInfo().type;
4420 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
4421 auto connectManager = GetConnectManagerByUserId(userId);
4422 if (!connectManager) {
4423 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
4424 return ERR_INVALID_VALUE;
4425 }
4426 return connectManager->TerminateAbility(token);
4427 }
4428
4429 if (type == AppExecFwk::AbilityType::DATA) {
4430 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot terminate, use 'ReleaseDataAbility()'");
4431 return ERR_WRONG_INTERFACE_CALL;
4432 }
4433
4434 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4435 return ERR_WOULD_BLOCK;
4436 }
4437
4438 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
4439 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
4440 if (missionListManager) {
4441 return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag);
4442 }
4443 TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListManager null ownerUserId=%{public}d", ownerUserId);
4444 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4445 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
4446 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4447 return uiAbilityManager->CloseUIAbility(abilityRecord, resultCode, resultWant, false, false);
4448 }
4449 return ERR_INVALID_VALUE;
4450 }
4451
TerminateUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int resultCode,const Want * resultWant)4452 int AbilityManagerService::TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode,
4453 const Want *resultWant)
4454 {
4455 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4456 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4457 TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ui extension ability begin.");
4458 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
4459 auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
4460 std::shared_ptr<AbilityConnectManager> connectManager;
4461 std::shared_ptr<AbilityRecord> targetRecord;
4462 GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord, true);
4463 CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
4464 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
4465 EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, extensionSessionInfo->userId);
4466 eventInfo.lifeCycle = LIFE_CYCLE_TERMINATE;
4467 SendAbilityEvent(EventName::TERMINATE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
4468
4469 // self terminate or caller terminate is allowed.
4470 if (!(JudgeSelfCalled(targetRecord) || (abilityRecord != nullptr && JudgeSelfCalled(abilityRecord)))) {
4471 return CHECK_PERMISSION_FAILED;
4472 }
4473
4474 auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
4475 if (result != ERR_OK) {
4476 TAG_LOGE(AAFwkTag::ABILITYMGR, "judgeAbilityVisibleControl error");
4477 return result;
4478 }
4479
4480 if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
4481 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot terminate except ui extension ability");
4482 eventInfo.errReason = "cannot terminate except ui extension ability";
4483 SendExtensionReport(eventInfo, EXTENSION_TYPE_NOT_UI_EXTENSION);
4484 return ERR_WRONG_INTERFACE_CALL;
4485 }
4486
4487 TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension persistentId: %{public}d, element: %{public}s.",
4488 extensionSessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
4489 connectManager->TerminateAbilityWindowLocked(targetRecord, extensionSessionInfo);
4490 return ERR_OK;
4491 }
4492
CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)4493 int AbilityManagerService::CloseUIExtensionAbilityBySCB(const sptr<IRemoteObject> token)
4494 {
4495 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4496 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4497 TAG_LOGD(AAFwkTag::ABILITYMGR, "close uiextensionability by scb");
4498 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
4499
4500 if (!IsCallerSceneBoard()) {
4501 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
4502 return ERR_PERMISSION_DENIED;
4503 }
4504
4505 if (!VerificationAllToken(token)) {
4506 TAG_LOGE(AAFwkTag::ABILITYMGR, "verificationAllToken failed");
4507 return ERR_INVALID_VALUE;
4508 }
4509
4510 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4511 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4512 if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
4513 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability %{public}s not an uiextensionability",
4514 abilityRecord->GetURI().c_str());
4515 return ERR_INVALID_VALUE;
4516 }
4517
4518 auto sessionInfo = abilityRecord->GetSessionInfo();
4519 if (sessionInfo == nullptr) {
4520 TAG_LOGE(AAFwkTag::ABILITYMGR, "target session info is null, ability: %{public}s",
4521 abilityRecord->GetURI().c_str());
4522 return ERR_INVALID_VALUE;
4523 }
4524
4525 std::shared_ptr<AbilityConnectManager> connectManager;
4526 std::shared_ptr<AbilityRecord> targetRecord;
4527 GetConnectManagerAndUIExtensionBySessionInfo(sessionInfo, connectManager, targetRecord, true);
4528 if (connectManager == nullptr) {
4529 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null, ability: %{public}s", abilityRecord->GetURI().c_str());
4530 return ERR_INVALID_VALUE;
4531 }
4532
4533 sptr<Rosen::ISession> sessionProxy = iface_cast<Rosen::ISession>(sessionInfo->sessionToken);
4534 if (sessionProxy == nullptr) {
4535 TAG_LOGE(AAFwkTag::ABILITYMGR, "Get session proxy failed, ability: %{public}s",
4536 abilityRecord->GetURI().c_str());
4537 return ERR_INVALID_VALUE;
4538 }
4539
4540 // notify caller sync detach
4541 sessionProxy->NotifyExtensionDetachToDisplay();
4542 connectManager->TerminateAbilityWindowLocked(abilityRecord, sessionInfo);
4543 return ERR_OK;
4544 }
4545
CloseUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool isUserRequestedExit,uint32_t sceneFlag)4546 int AbilityManagerService::CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool isUserRequestedExit,
4547 uint32_t sceneFlag)
4548 {
4549 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4550 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4551 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
4552 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
4553 return ERR_INVALID_VALUE;
4554 }
4555
4556 if (!IsCallerSceneBoard()) {
4557 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
4558 return ERR_WRONG_INTERFACE_CALL;
4559 }
4560
4561 SetMinimizedDuringFreeInstall(sessionInfo);
4562
4563 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4564 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4565 TAG_LOGI(AAFwkTag::ABILITYMGR, "close session: %{public}d, resultCode: %{public}d, isClearSession: %{public}d",
4566 sessionInfo->persistentId, sessionInfo->resultCode, sessionInfo->isClearSession);
4567 if (sessionInfo->isClearSession) {
4568 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
4569 DeleteAbilityRecoverInfoBySessionId(sessionInfo->persistentId);
4570 }
4571 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
4572 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4573 abilityRecord->SetSceneFlag(sceneFlag);
4574 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4575 return ERR_WOULD_BLOCK;
4576 }
4577
4578 EventInfo eventInfo = BuildEventInfoByAbilityRecord(abilityRecord);
4579 SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
4580 if (isUserRequestedExit) {
4581 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
4582 AAFwk::ExitReason exitReason = { REASON_NORMAL, "User Request" };
4583 appExitReasonHelper_->RecordUIAbilityExitReason(abilityRecord->GetPid(), abilityRecord->GetAbilityInfo().name,
4584 exitReason);
4585 }
4586 eventInfo.errCode = uiAbilityManager->CloseUIAbility(abilityRecord, sessionInfo->resultCode,
4587 &(sessionInfo->want), sessionInfo->isClearSession, false);
4588 if (eventInfo.errCode != ERR_OK) {
4589 TAG_LOGE(AAFwkTag::ABILITYMGR, "close UIAbility by SCB failed: %{public}d", eventInfo.errCode);
4590 SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
4591 }
4592 return AbilityErrorUtil::ConvertToOriginErrorCode(eventInfo.errCode);
4593 }
4594
SendResultToAbility(int32_t requestCode,int32_t resultCode,Want & resultWant)4595 int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)
4596 {
4597 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
4598 if (!CheckCallerIsDmsProcess()) {
4599 TAG_LOGE(AAFwkTag::ABILITYMGR, "check processName failed");
4600 return ERR_INVALID_VALUE;
4601 }
4602 int missionId = resultWant.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
4603 resultWant.RemoveParam(DMS_MISSION_ID);
4604 if (missionId == DEFAULT_DMS_MISSION_ID) {
4605 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionId empty");
4606 return ERR_INVALID_VALUE;
4607 }
4608 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4609 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4610 auto uiAbilityManager = GetCurrentUIAbilityManager();
4611 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4612 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4613 } else {
4614 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4615 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4616 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4617 }
4618 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4619
4620 abilityRecord->SetResult(std::make_shared<AbilityResult>(requestCode, resultCode, resultWant));
4621 abilityRecord->SendResult(0, 0);
4622 return ERR_OK;
4623 }
4624
StartRemoteAbility(const Want & want,int requestCode,int32_t validUserId,const sptr<IRemoteObject> & callerToken)4625 int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId,
4626 const sptr<IRemoteObject> &callerToken)
4627 {
4628 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4629 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
4630 Want remoteWant = want;
4631 UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(remoteWant, callerToken);
4632 if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
4633 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
4634 return ERR_ADD_START_CONTROL_PARAM_FAILED;
4635 }
4636 if (AbilityUtil::IsStartFreeInstall(remoteWant)) {
4637 return freeInstallManager_ == nullptr ? ERR_NULL_FREE_INSTALL_MANAGER :
4638 freeInstallManager_->StartRemoteFreeInstall(remoteWant, requestCode, validUserId, callerToken);
4639 }
4640 if (remoteWant.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
4641 TAG_LOGI(AAFwkTag::ABILITYMGR, "try startAbilityForResult");
4642 int32_t missionId = -1;
4643 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4644 missionId = GetMissionIdByAbilityTokenInner(callerToken);
4645 if (!missionId) {
4646 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
4647 return ERR_GET_MISSION_ID_BY_ABILITY_TOKEN_FAILED;
4648 }
4649 } else {
4650 missionId = GetMissionIdByAbilityToken(callerToken);
4651 }
4652 if (missionId < 0) {
4653 return ERR_INVALID_MISSION_ID;
4654 }
4655 remoteWant.SetParam(DMS_MISSION_ID, missionId);
4656 }
4657
4658 int32_t callerUid = IPCSkeleton::GetCallingUid();
4659 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4660 #ifdef SUPPORT_UPMS
4661 UriUtils::GetInstance().CheckUriPermission(accessToken, remoteWant);
4662 #endif // SUPPORT_UPMS
4663 DistributedClient dmsClient;
4664 int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken);
4665 if (result != ERR_NONE) {
4666 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManagerService::startRemoteAbility failed, result=%{public}d", result);
4667 }
4668 return result;
4669 }
4670
CheckIsRemote(const std::string & deviceId)4671 bool AbilityManagerService::CheckIsRemote(const std::string& deviceId)
4672 {
4673 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4674 if (deviceId.empty()) {
4675 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkIsRemote:deviceId empty");
4676 return false;
4677 }
4678 std::string localDeviceId;
4679 if (!GetLocalDeviceId(localDeviceId)) {
4680 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkIsRemote:get local deviceId failed");
4681 return false;
4682 }
4683 if (localDeviceId == deviceId) {
4684 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkIsRemote:deviceId local");
4685 return false;
4686 }
4687 TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str());
4688 return true;
4689 }
4690
CheckIfOperateRemote(const Want & want)4691 bool AbilityManagerService::CheckIfOperateRemote(const Want &want)
4692 {
4693 std::string deviceId = want.GetElement().GetDeviceID();
4694 if (deviceId.empty() || want.GetElement().GetBundleName().empty() ||
4695 want.GetElement().GetAbilityName().empty()) {
4696 TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty");
4697 return false;
4698 }
4699 return CheckIsRemote(deviceId);
4700 }
4701
GetLocalDeviceId(std::string & localDeviceId)4702 bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId)
4703 {
4704 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4705 auto localNode = std::make_unique<NodeBasicInfo>();
4706 int32_t errCode = GetLocalNodeDeviceInfo(DM_PKG_NAME, localNode.get());
4707 if (errCode != ERR_OK) {
4708 TAG_LOGE(AAFwkTag::ABILITYMGR, "err=%{public}d", errCode);
4709 return false;
4710 }
4711 if (localNode != nullptr) {
4712 localDeviceId = localNode->networkId;
4713 TAG_LOGD(AAFwkTag::ABILITYMGR, "get local deviceId, deviceId = %{public}s",
4714 AnonymizeDeviceId(localDeviceId).c_str());
4715 return true;
4716 }
4717 TAG_LOGE(AAFwkTag::ABILITYMGR, "localDeviceId null");
4718 return false;
4719 }
4720
AnonymizeDeviceId(const std::string & deviceId)4721 std::string AbilityManagerService::AnonymizeDeviceId(const std::string& deviceId)
4722 {
4723 if (deviceId.length() < NON_ANONYMIZE_LENGTH) {
4724 return EMPTY_DEVICE_ID;
4725 }
4726 std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
4727 anonDeviceId.append("******");
4728 return anonDeviceId;
4729 }
4730
MinimizeAbility(const sptr<IRemoteObject> & token,bool fromUser)4731 int AbilityManagerService::MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)
4732 {
4733 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4734 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4735 TAG_LOGI(AAFwkTag::ABILITYMGR, "minimize ability, fromUser:%{public}d", fromUser);
4736 if (!VerificationAllToken(token)) {
4737 return ERR_INVALID_VALUE;
4738 }
4739
4740 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4741 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4742 if (!JudgeSelfCalled(abilityRecord)) {
4743 return CHECK_PERMISSION_FAILED;
4744 }
4745
4746 auto type = abilityRecord->GetAbilityInfo().type;
4747 if (type != AppExecFwk::AbilityType::PAGE) {
4748 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except page ability");
4749 return ERR_WRONG_INTERFACE_CALL;
4750 }
4751
4752 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4753 return ERR_WOULD_BLOCK;
4754 }
4755
4756 auto missionListManager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
4757 if (!missionListManager) {
4758 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null");
4759 return ERR_INVALID_VALUE;
4760 }
4761 return missionListManager->MinimizeAbility(token, fromUser);
4762 }
4763
MinimizeUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,bool fromUser)4764 int AbilityManagerService::MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo,
4765 bool fromUser)
4766 {
4767 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4768 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4769 TAG_LOGD(AAFwkTag::ABILITYMGR, "Minimize ui extension ability, fromUser:%{public}d.", fromUser);
4770 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
4771 auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
4772 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4773 EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, extensionSessionInfo->userId);
4774 eventInfo.lifeCycle = LIFE_CYCLE_MINIMIZE;
4775 SendAbilityEvent(EventName::ABILITY_ONBACKGROUND, HiSysEventType::BEHAVIOR, eventInfo);
4776 if (!JudgeSelfCalled(abilityRecord)) {
4777 return CHECK_PERMISSION_FAILED;
4778 }
4779
4780 std::shared_ptr<AbilityConnectManager> connectManager;
4781 std::shared_ptr<AbilityRecord> targetRecord;
4782 GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
4783 CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
4784 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
4785
4786 auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
4787 if (result != ERR_OK) {
4788 TAG_LOGE(AAFwkTag::ABILITYMGR, "judgeAbilityVisibleControl error");
4789 return result;
4790 }
4791
4792 if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
4793 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except ui extension ability");
4794 eventInfo.errReason = "cannot minimize except ui extension ability";
4795 SendExtensionReport(eventInfo, EXTENSION_TYPE_NOT_UI_EXTENSION);
4796 return ERR_WRONG_INTERFACE_CALL;
4797 }
4798 extensionSessionInfo->uiExtensionComponentId = (
4799 static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
4800 static_cast<uint64_t>(extensionSessionInfo->persistentId);
4801 TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
4802 extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
4803 connectManager->BackgroundAbilityWindowLocked(targetRecord, extensionSessionInfo);
4804 return ERR_OK;
4805 }
4806
SetMinimizedDuringFreeInstall(const sptr<SessionInfo> & sessionInfo)4807 void AbilityManagerService::SetMinimizedDuringFreeInstall(const sptr<SessionInfo> &sessionInfo)
4808 {
4809 if (sessionInfo == nullptr) {
4810 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
4811 return;
4812 }
4813
4814 if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
4815 return;
4816 }
4817
4818 std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
4819 if (sessionId.empty()) {
4820 return;
4821 }
4822
4823 if (freeInstallManager_ == nullptr) {
4824 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
4825 return;
4826 }
4827 FreeInstallInfo taskInfo;
4828 if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
4829 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task with sessionId=%{public}s does not exist",
4830 sessionId.c_str());
4831 return;
4832 }
4833
4834 if (taskInfo.isFreeInstallFinished) {
4835 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
4836 return;
4837 }
4838
4839 {
4840 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
4841 auto it = preStartSessionMap_.find(sessionId);
4842 if (it == preStartSessionMap_.end()) {
4843 TAG_LOGI(AAFwkTag::ABILITYMGR, "session info with sessionId=%{public}s does not exist",
4844 sessionId.c_str());
4845 return;
4846 }
4847 CHECK_POINTER(it->second);
4848 it->second->isMinimizedDuringFreeInstall = true;
4849 }
4850 }
4851
MinimizeUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool fromUser,uint32_t sceneFlag)4852 int AbilityManagerService::MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser,
4853 uint32_t sceneFlag)
4854 {
4855 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4856 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
4857 TAG_LOGI(AAFwkTag::ABILITYMGR, "called, sceneFlag:%{public}u", sceneFlag);
4858 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
4859 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
4860 return ERR_INVALID_VALUE;
4861 }
4862
4863 if (!IsCallerSceneBoard()) {
4864 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
4865 return ERR_WRONG_INTERFACE_CALL;
4866 }
4867
4868 SetMinimizedDuringFreeInstall(sessionInfo);
4869
4870 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4871 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4872 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
4873 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4874 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
4875 return ERR_WOULD_BLOCK;
4876 }
4877 return uiAbilityManager->MinimizeUIAbility(abilityRecord, fromUser, sceneFlag);
4878 }
4879
ConnectAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t userId)4880 int32_t AbilityManagerService::ConnectAbility(
4881 const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)
4882 {
4883 return ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::SERVICE, userId);
4884 }
4885
ConnectAbilityCommon(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,AppExecFwk::ExtensionAbilityType extensionType,int32_t userId,bool isQueryExtensionOnly)4886 int32_t AbilityManagerService::ConnectAbilityCommon(
4887 const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
4888 AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)
4889 {
4890 if (AppUtils::GetInstance().IsForbidStart()) {
4891 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
4892 return INNER_ERR;
4893 }
4894 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4895 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
4896 TAG_LOGI(AAFwkTag::SERVICE_EXT,
4897 "elementUri:%{public}s", want.GetElement().GetURI().c_str());
4898 CheckExtensionRateLimit();
4899 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4900 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4901 if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE && want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
4902 TAG_LOGE(AAFwkTag::SERVICE_EXT, "error to have UISERVICEHOSTPROXY_KEY");
4903 return ERR_WRONG_INTERFACE_CALL;
4904 }
4905 if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && IsCrossUserCall(userId)) {
4906 CHECK_CALLER_IS_SYSTEM_APP;
4907 }
4908 EventInfo eventInfo = BuildEventInfo(want, userId);
4909 eventInfo.lifeCycle = LIFE_CYCLE_CONNECT;
4910
4911 int result;
4912 #ifdef WITH_DLP
4913 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
4914 if (result != ERR_OK) {
4915 TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkDlpForExtension error");
4916 return result;
4917 }
4918 #endif // WITH_DLP
4919
4920 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
4921 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
4922 shouldBlockFunc);
4923 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4924 interceptorExecuter_->DoProcess(interceptorParam);
4925 if (result != ERR_OK) {
4926 TAG_LOGE(AAFwkTag::SERVICE_EXT, "interceptorExecuter_ null or doProcess error");
4927 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
4928 eventInfo.errReason = "interceptorExecuter_ null or doProcess error";
4929 SendExtensionReport(eventInfo, result, true);
4930 } else {
4931 eventInfo.errCode = result;
4932 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4933 }
4934 return result;
4935 }
4936
4937 int32_t validUserId = GetValidUserId(userId);
4938
4939 if (AbilityUtil::IsStartFreeInstall(want)) {
4940 CHECK_POINTER_AND_RETURN(freeInstallManager_, ERR_INVALID_VALUE);
4941 TAG_LOGD(AAFwkTag::SERVICE_EXT, "is start free install");
4942 std::string localDeviceId;
4943 if (!GetLocalDeviceId(localDeviceId)) {
4944 TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s:get Local deviceId failed", __func__);
4945 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
4946 eventInfo.errReason = "get Local deviceId failed";
4947 SendExtensionReport(eventInfo, GET_LOCAL_DEVICE_ID_FAILED, true);
4948 } else {
4949 eventInfo.errCode = ERR_INVALID_VALUE;
4950 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4951 }
4952 return ERR_INVALID_VALUE;
4953 }
4954 result = freeInstallManager_->ConnectFreeInstall(want, validUserId, callerToken, localDeviceId);
4955 if (result != ERR_OK) {
4956 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
4957 eventInfo.errReason = "ConnectFreeInstall error";
4958 SendExtensionReport(eventInfo, result, true);
4959 } else {
4960 eventInfo.errCode = result;
4961 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4962 }
4963 return result;
4964 }
4965 }
4966
4967 Want abilityWant = want;
4968 AbilityRequest abilityRequest;
4969 std::string uri = abilityWant.GetUri().ToString();
4970 bool isFileUri = (abilityWant.GetUri().GetScheme() == "file");
4971 if (!uri.empty() && !isFileUri) {
4972 // if the want include uri, it may only has uri information. it is probably a datashare extension.
4973 TAG_LOGD(AAFwkTag::SERVICE_EXT, "uri: %{public}s, userId: %{public}d", uri.c_str(), validUserId);
4974 AppExecFwk::ExtensionAbilityInfo extensionInfo;
4975 auto bms = AbilityUtil::GetBundleManagerHelper();
4976 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4977
4978 bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4979 if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4980 TAG_LOGE(AAFwkTag::SERVICE_EXT, "invalid extension ability info");
4981 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
4982 eventInfo.errReason = "invalid extension ability info";
4983 SendExtensionReport(eventInfo, EXTENSION_ABILITY_INFO_NOT_QUERY_BY_URI, true);
4984 } else {
4985 eventInfo.errCode = ERR_INVALID_VALUE;
4986 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4987 }
4988 return ERR_INVALID_VALUE;
4989 }
4990 abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4991 }
4992
4993 if (CheckIfOperateRemote(abilityWant)) {
4994 TAG_LOGD(AAFwkTag::SERVICE_EXT, "AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility");
4995 eventInfo.errCode = ConnectRemoteAbility(abilityWant, callerToken, connect->AsObject());
4996 if (eventInfo.errCode != ERR_OK) {
4997 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
4998 eventInfo.errReason = "ConnectRemoteAbility error";
4999 SendExtensionReport(eventInfo, eventInfo.errCode, true);
5000 } else {
5001 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
5002 }
5003 }
5004 return eventInfo.errCode;
5005 }
5006 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityWant, callerToken);
5007
5008 if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
5009 TAG_LOGD(AAFwkTag::SERVICE_EXT, "invalid Token.");
5010 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr, extensionType);
5011 if (eventInfo.errCode != ERR_OK) {
5012 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
5013 eventInfo.errReason = "ConnectLocalAbility error";
5014 SendExtensionReport(eventInfo, eventInfo.errCode, true);
5015 } else {
5016 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
5017 }
5018 }
5019 return eventInfo.errCode;
5020 }
5021 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken, extensionType, nullptr,
5022 isQueryExtensionOnly);
5023 if (eventInfo.errCode != ERR_OK) {
5024 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
5025 eventInfo.errReason = "ConnectLocalAbility error";
5026 SendExtensionReport(eventInfo, eventInfo.errCode, true);
5027 } else {
5028 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
5029 }
5030 }
5031 return eventInfo.errCode;
5032 }
5033
ConnectUIExtensionAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<SessionInfo> & sessionInfo,int32_t userId,sptr<UIExtensionAbilityConnectInfo> connectInfo)5034 int AbilityManagerService::ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect,
5035 const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)
5036 {
5037 if (AppUtils::GetInstance().IsForbidStart()) {
5038 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
5039 return INNER_ERR;
5040 }
5041 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5042 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
5043 TAG_LOGI(AAFwkTag::UI_EXT,
5044 "ConnectUIExtensionAbility bundlename: %{public}s, ability is %{public}s, userId is %{private}d",
5045 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
5046 CheckExtensionRateLimit();
5047 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
5048 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
5049 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
5050
5051 if (IsCrossUserCall(userId)) {
5052 CHECK_CALLER_IS_SYSTEM_APP;
5053 }
5054
5055 EventInfo eventInfo = BuildEventInfo(want, userId);
5056 eventInfo.lifeCycle = LIFE_CYCLE_CONNECT;
5057 sptr<IRemoteObject> callerToken = sessionInfo->callerToken;
5058
5059 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
5060 TAG_LOGE(AAFwkTag::UI_EXT, "connectUIExtensionAbility verificationAllToken failed");
5061 eventInfo.errReason = "not containsAbility or not find abilityRecord by callerToken";
5062 SendExtensionReport(eventInfo, INVALID_CALLER_TOKEN);
5063 return ERR_INVALID_CALLER;
5064 }
5065
5066 int result;
5067 #ifdef WITH_DLP
5068 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
5069 if (result != ERR_OK) {
5070 TAG_LOGE(AAFwkTag::UI_EXT, "checkDlpForExtension error");
5071 return result;
5072 }
5073 #endif // WITH_DLP
5074
5075 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
5076 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
5077 shouldBlockFunc);
5078 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
5079 interceptorExecuter_->DoProcess(interceptorParam);
5080 if (result != ERR_OK) {
5081 TAG_LOGE(AAFwkTag::UI_EXT, "interceptorExecuter_ null or doProcess error");
5082 eventInfo.errReason = "interceptorExecuter_ null or doProcess error";
5083 SendExtensionReport(eventInfo, result);
5084 return result;
5085 }
5086
5087 int32_t validUserId = GetValidUserId(userId);
5088
5089 Want abilityWant = want;
5090 AbilityRequest abilityRequest;
5091 std::string uri = abilityWant.GetUri().ToString();
5092 if (!uri.empty()) {
5093 // if the want include uri, it may only has uri information.
5094 TAG_LOGI(AAFwkTag::UI_EXT, "called. uri:%{public}s, userId %{public}d", uri.c_str(), validUserId);
5095 AppExecFwk::ExtensionAbilityInfo extensionInfo;
5096 auto bms = AbilityUtil::GetBundleManagerHelper();
5097 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
5098
5099 bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
5100 if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
5101 TAG_LOGE(AAFwkTag::UI_EXT, "invalid extension ability info");
5102 eventInfo.errReason = "invalid extension ability info";
5103 SendExtensionReport(eventInfo, EXTENSION_ABILITY_INFO_NOT_QUERY_BY_URI);
5104 return ERR_INVALID_VALUE;
5105 }
5106 abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
5107 }
5108
5109 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityWant, callerToken);
5110
5111 if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
5112 TAG_LOGI(AAFwkTag::UI_EXT, "invalid Token");
5113 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr,
5114 AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
5115 if (eventInfo.errCode != ERR_OK) {
5116 eventInfo.errReason = "ConnectLocalAbility error";
5117 SendExtensionReport(eventInfo, eventInfo.errCode);
5118 }
5119 return eventInfo.errCode;
5120 }
5121 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken,
5122 AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
5123 if (eventInfo.errCode != ERR_OK) {
5124 eventInfo.errReason = "ConnectLocalAbility error";
5125 SendExtensionReport(eventInfo, eventInfo.errCode);
5126 }
5127 return eventInfo.errCode;
5128 }
5129
BuildEventInfo(const Want & want,int32_t userId)5130 EventInfo AbilityManagerService::BuildEventInfo(const Want &want, int32_t userId)
5131 {
5132 EventInfo eventInfo;
5133 eventInfo.userId = userId;
5134 eventInfo.bundleName = want.GetElement().GetBundleName();
5135 eventInfo.moduleName = want.GetElement().GetModuleName();
5136 eventInfo.abilityName = want.GetElement().GetAbilityName();
5137 std::vector<AbilityRunningInfo> abilityRunningInfos;
5138 auto result = GetAbilityRunningInfos(abilityRunningInfos);
5139 if (result != ERR_OK) {
5140 return eventInfo;
5141 }
5142 for (const auto& info : abilityRunningInfos) {
5143 if (info.ability.GetBundleName() == eventInfo.bundleName &&
5144 info.ability.GetModuleName() == eventInfo.moduleName &&
5145 info.ability.GetAbilityName() == eventInfo.abilityName) {
5146 eventInfo.appIndex = info.appCloneIndex;
5147 }
5148 }
5149 return eventInfo;
5150 }
5151
BuildEventInfoByAbilityRecord(const std::shared_ptr<AbilityRecord> & abilityRecord)5152 EventInfo AbilityManagerService::BuildEventInfoByAbilityRecord(const std::shared_ptr<AbilityRecord> &abilityRecord)
5153 {
5154 EventInfo eventInfo;
5155 if (abilityRecord == nullptr) {
5156 TAG_LOGE(AAFwkTag::ABILITYMGR, "null abilityRecord");
5157 return eventInfo;
5158 }
5159 auto want = abilityRecord->GetWant();
5160 eventInfo.userId = abilityRecord->GetUid() / BASE_USER_RANGE;
5161 eventInfo.bundleName = want.GetElement().GetBundleName();
5162 eventInfo.moduleName = want.GetElement().GetModuleName();
5163 eventInfo.abilityName = want.GetElement().GetAbilityName();
5164 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
5165 eventInfo.bundleType = static_cast<int32_t>(abilityRecord->GetApplicationInfo().bundleType);
5166 eventInfo.appIndex = abilityRecord->GetAppIndex();
5167 return eventInfo;
5168 }
5169
DisconnectAbility(sptr<IAbilityConnection> connect)5170 int AbilityManagerService::DisconnectAbility(sptr<IAbilityConnection> connect)
5171 {
5172 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5173 TAG_LOGI(AAFwkTag::SERVICE_EXT, "Disconnect");
5174 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
5175 int err = DisconnectLocalAbility(connect);
5176 if (err == ERR_OK) {
5177 return ERR_OK;
5178 }
5179 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
5180 int remoteErr = DisconnectRemoteAbility(connect->AsObject());
5181 if (remoteErr == ERR_OK) {
5182 return ERR_OK;
5183 }
5184 if (remoteErr != INVALID_PARAMETERS_ERR &&
5185 remoteErr != CONNECTION_NOT_EXIST &&
5186 err == CONNECTION_NOT_EXIST) {
5187 err = remoteErr;
5188 }
5189 TAG_LOGE(AAFwkTag::SERVICE_EXT, "Disconnect error %{public}d", err);
5190 EventInfo eventInfo;
5191 eventInfo.errCode = err;
5192 EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
5193 return err;
5194 }
5195
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)5196 int32_t AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId,
5197 const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
5198 AppExecFwk::ExtensionAbilityType extensionType, const sptr<SessionInfo> &sessionInfo,
5199 bool isQueryExtensionOnly, sptr<UIExtensionAbilityConnectInfo> connectInfo)
5200 {
5201 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5202 TAG_LOGD(AAFwkTag::SERVICE_EXT, "called");
5203 StartAbilityInfoWrap threadLocalInfo;
5204 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
5205 if (!CheckCrossUser(userId, extensionType)) {
5206 TAG_LOGE(AAFwkTag::SERVICE_EXT, "multi-user non-concurrent unsatisfied");
5207 return ERR_CROSS_USER;
5208 }
5209
5210 AbilityRequest abilityRequest;
5211 ErrCode result = ERR_OK;
5212 TAG_LOGD(AAFwkTag::SERVICE_EXT, "start generate ability request, isQueryExtensionOnly: %{public}d, type: %{public}d",
5213 isQueryExtensionOnly, static_cast<int32_t>(extensionType));
5214 if (isQueryExtensionOnly ||
5215 AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
5216 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, userId);
5217 } else {
5218 result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId);
5219 }
5220 abilityRequest.sessionInfo = sessionInfo;
5221
5222 Want requestWant = want;
5223 CHECK_POINTER_AND_RETURN_LOG(connect, ERR_INVALID_VALUE, "connect is nullptr");
5224 TAG_LOGD(AAFwkTag::SERVICE_EXT, "requestWant SetParam success");
5225
5226 if (result != ERR_OK) {
5227 TAG_LOGE(AAFwkTag::SERVICE_EXT, "generate request error");
5228 return result;
5229 }
5230 result = CheckPermissionForUIService(extensionType, want, abilityRequest);
5231 if (result != ERR_OK) {
5232 return result;
5233 }
5234
5235 auto abilityInfo = abilityRequest.abilityInfo;
5236 threadLocalInfo.SetStartAbilityInfo(abilityInfo);
5237 if (abilityInfo.isStageBasedModel) {
5238 bool isService = (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE);
5239 if (isService && extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
5240 TAG_LOGE(AAFwkTag::SERVICE_EXT, "Service extension type, please use ConnectAbility");
5241 return ERR_WRONG_INTERFACE_CALL;
5242 }
5243 // not allow app to connect other extension by using connectServiceExtensionAbility
5244 bool isVpn = abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::VPN;
5245 if (callerToken && extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && !isService && !isVpn) {
5246 TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability, type not service");
5247 return TARGET_ABILITY_NOT_SERVICE;
5248 }
5249 }
5250 int32_t validUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
5251 TAG_LOGD(AAFwkTag::SERVICE_EXT, "validUserId : %{public}d, singleton is : %{public}d",
5252 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
5253
5254 result = CheckStaticCfgPermission(abilityRequest, false, -1);
5255 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
5256 TAG_LOGE(AAFwkTag::SERVICE_EXT, "checkStaticCfgPermission error, result=%{public}d", result);
5257 return ERR_STATIC_CFG_PERMISSION;
5258 }
5259
5260 AppExecFwk::ExtensionAbilityType targetExtensionType = abilityInfo.extensionAbilityType;
5261 TAG_LOGD(AAFwkTag::SERVICE_EXT, "extension type %{public}d.", targetExtensionType);
5262 if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
5263 if (!AAFwk::UIExtensionUtils::IsUIExtension(targetExtensionType)
5264 && targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW) {
5265 TAG_LOGE(AAFwkTag::SERVICE_EXT, "UI extension, target ability not UI extension");
5266 return ERR_WRONG_INTERFACE_CALL;
5267 }
5268
5269 // Cause window has used this api, don't check it when type is window.
5270 if (targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW &&
5271 !PermissionVerification::GetInstance()->VerifyCallingPermission(
5272 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY)) {
5273 TAG_LOGE(AAFwkTag::SERVICE_EXT, "permission %{public}s verification failed",
5274 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY);
5275 return ERR_PERMISSION_DENIED;
5276 }
5277 }
5278
5279 auto type = abilityInfo.type;
5280 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
5281 TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability failed, target ability not service");
5282 return TARGET_ABILITY_NOT_SERVICE;
5283 }
5284
5285 if (!HandleExecuteSAInterceptor(want, callerToken, abilityRequest, result)) {
5286 return result;
5287 }
5288
5289 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
5290 false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
5291 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
5292 afterCheckExecuter_->DoProcess(afterCheckParam);
5293 if (result != ERR_OK) {
5294 TAG_LOGE(AAFwkTag::SERVICE_EXT, "afterCheckExecuter_ null or doProcess error");
5295 return result;
5296 }
5297
5298 auto connectManager = GetConnectManagerByUserId(validUserId);
5299 if (connectManager == nullptr) {
5300 TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", validUserId);
5301 return ERR_INVALID_VALUE;
5302 }
5303
5304 if (extensionType == AppExecFwk::ExtensionAbilityType::APP_SERVICE) {
5305 auto targetService = connectManager->GetServiceRecordByAbilityRequest(abilityRequest);
5306 result = CheckCallAppServiceExtensionPermission(abilityRequest, targetService, true);
5307 TAG_LOGD(AAFwkTag::SERVICE_EXT, "CheckCallAppServiceExtensionPermission result: %{public}d", result);
5308 } else {
5309 result = CheckCallServicePermission(abilityRequest);
5310 }
5311 if (result != ERR_OK) {
5312 TAG_LOGE(AAFwkTag::SERVICE_EXT, "%{public}s checkCallServicePermission error", __func__);
5313 return result;
5314 }
5315
5316 ReportAppConnectOtherExtensionEvent(abilityInfo, want);
5317
5318 if (!ExtensionPermissionsUtil::CheckSAPermission(targetExtensionType)) {
5319 TAG_LOGE(AAFwkTag::SERVICE_EXT, "SA doesn't have target extension permission");
5320 return CHECK_PERMISSION_FAILED;
5321 }
5322
5323 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
5324 if (result != ERR_OK) {
5325 TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectAbility: app data ability preloading failed, '%{public}s', %{public}d",
5326 abilityInfo.bundleName.c_str(),
5327 result);
5328 return result;
5329 }
5330
5331 SetAbilityRequestSessionInfo(abilityRequest, targetExtensionType);
5332 return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo);
5333 }
5334
ConnectRemoteAbility(Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)5335 int AbilityManagerService::ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken,
5336 const sptr<IRemoteObject> &connect)
5337 {
5338 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
5339 UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(want, callerToken);
5340 if (AddStartControlParam(want, callerToken) != ERR_OK) {
5341 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
5342 return ERR_INVALID_VALUE;
5343 }
5344 TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, abilityName: %{public}s",
5345 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str());
5346 DistributedClient dmsClient;
5347 return dmsClient.ConnectRemoteAbility(want, connect);
5348 }
5349
DisconnectLocalAbility(const sptr<IAbilityConnection> & connect)5350 int AbilityManagerService::DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)
5351 {
5352 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5353 auto currentConnectManager = GetCurrentConnectManager();
5354 CHECK_POINTER_AND_RETURN(currentConnectManager, ERR_NO_INIT);
5355 if (currentConnectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
5356 return ERR_OK;
5357 }
5358 // If current connectManager does not exist connect, then try connectManagerU0
5359 auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
5360 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
5361 if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
5362 return ERR_OK;
5363 }
5364 connectManager = GetConnectManagerByUserId(U1_USER_ID);
5365 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
5366 if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
5367 return ERR_OK;
5368 }
5369
5370 auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
5371 if (userId == U0_USER_ID || userId == U1_USER_ID) {
5372 auto connectManagers = GetConnectManagers();
5373 for (auto& item : connectManagers) {
5374 if (item.second && item.second->DisconnectAbilityLocked(connect) == ERR_OK) {
5375 return ERR_OK;
5376 }
5377 }
5378 }
5379
5380 // EnterpriseAdminExtensionAbility Scene
5381 connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT);
5382 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
5383 return connectManager->DisconnectAbilityLocked(connect);
5384 }
5385
DisconnectRemoteAbility(const sptr<IRemoteObject> & connect)5386 int AbilityManagerService::DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)
5387 {
5388 TAG_LOGD(AAFwkTag::SERVICE_EXT, "call");
5389 int32_t callerUid = IPCSkeleton::GetCallingUid();
5390 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
5391 DistributedClient dmsClient;
5392 return dmsClient.DisconnectRemoteAbility(connect, callerUid, accessToken);
5393 }
5394
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callBack,AAFwk::WantParams & wantParams)5395 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
5396 int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
5397 {
5398 CHECK_CALLER_IS_SYSTEM_APP;
5399 TAG_LOGI(AAFwkTag::ABILITYMGR, "missionId: %{public}d", missionId);
5400 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5401 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5402 return CHECK_PERMISSION_FAILED;
5403 }
5404
5405 DistributedClient dmsClient;
5406 int32_t callingUid = IPCSkeleton::GetCallingUid();
5407 wantParams.SetParam(DMS_CALLING_UID, AAFwk::Integer::Box(callingUid));
5408 return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams);
5409 }
5410
ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,const sptr<IRemoteObject> & callback)5411 int AbilityManagerService::ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,
5412 const sptr<IRemoteObject> &callback)
5413 {
5414 CHECK_CALLER_IS_SYSTEM_APP;
5415 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5416 AAFWK::ContinueRadar::GetInstance().ClickIconContinue("ContinueMission");
5417 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5418 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5419 return CHECK_PERMISSION_FAILED;
5420 }
5421
5422 DistributedClient dmsClient;
5423 int32_t callingUid = IPCSkeleton::GetCallingUid();
5424 continueMissionInfo.wantParams.SetParam(DMS_CALLING_UID, AAFwk::Integer::Box(callingUid));
5425 return dmsClient.ContinueMission(continueMissionInfo, callback);
5426 }
5427
ContinueAbility(const std::string & deviceId,int32_t missionId,uint32_t versionCode)5428 int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)
5429 {
5430 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
5431 TAG_LOGI(AAFwkTag::ABILITYMGR,
5432 "ContinueAbility missionId = %{public}d, version = %{public}u.", missionId, versionCode);
5433 if (!CheckCallerIsDmsProcess()) {
5434 TAG_LOGE(AAFwkTag::ABILITYMGR, "check processName failed");
5435 return ERR_INVALID_VALUE;
5436 }
5437
5438 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
5439 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5440 auto uiAbilityManager = GetCurrentUIAbilityManager();
5441 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5442 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
5443 } else {
5444 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
5445 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
5446 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
5447 }
5448 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5449
5450 abilityRecord->ContinueAbility(deviceId, versionCode);
5451 return ERR_OK;
5452 }
5453
StartContinuation(const Want & want,const sptr<IRemoteObject> & abilityToken,int32_t status)5454 int AbilityManagerService::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)
5455 {
5456 TAG_LOGI(AAFwkTag::ABILITYMGR, "start continuation");
5457 if (!CheckIfOperateRemote(want)) {
5458 TAG_LOGE(AAFwkTag::ABILITYMGR, "deviceId or bundleName or abilityName empty");
5459 return ERR_INVALID_VALUE;
5460 }
5461 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
5462
5463 int32_t appUid = IPCSkeleton::GetCallingUid();
5464 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
5465 TAG_LOGI(AAFwkTag::ABILITYMGR, "try startContinuation");
5466 int32_t missionId = -1;
5467 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5468 missionId = GetMissionIdByAbilityTokenInner(abilityToken);
5469 if (!missionId) {
5470 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
5471 return ERR_INVALID_VALUE;
5472 }
5473 } else {
5474 missionId = GetMissionIdByAbilityToken(abilityToken);
5475 }
5476 if (missionId < 0) {
5477 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get missionId");
5478 return ERR_INVALID_VALUE;
5479 }
5480 AAFWK::ContinueRadar::GetInstance().SaveDataRemoteWant("StartContinuation");
5481 TAG_LOGD(AAFwkTag::ABILITYMGR,
5482 "bundleName: %{public}s, abilityName: %{public}s, missionId: %{public}d, status: %{public}d",
5483 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), missionId, status);
5484 DistributedClient dmsClient;
5485 auto result = dmsClient.StartContinuation(want, missionId, appUid, status, accessToken);
5486 if (result != ERR_OK) {
5487 TAG_LOGE(AAFwkTag::ABILITYMGR, "startContinuation failed, result=%{public}d, notify caller", result);
5488 NotifyContinuationResult(missionId, result);
5489 }
5490 return result;
5491 }
5492
NotifyCompleteContinuation(const std::string & deviceId,int32_t sessionId,bool isSuccess)5493 void AbilityManagerService::NotifyCompleteContinuation(const std::string &deviceId,
5494 int32_t sessionId, bool isSuccess)
5495 {
5496 TAG_LOGI(AAFwkTag::ABILITYMGR, "NotifyCompleteContinuation");
5497 AAFWK::ContinueRadar::GetInstance().ClickIconRecvOver("NotifyCompleteContinuation");
5498 sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
5499 if (samgrProxy == nullptr) {
5500 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get samgrProxy");
5501 return;
5502 }
5503 sptr<IRemoteObject> bmsProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
5504 if (bmsProxy == nullptr) {
5505 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bms from samgr");
5506 return;
5507 }
5508 auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bmsProxy);
5509 if (bundleMgr == nullptr) {
5510 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bms");
5511 return;
5512 }
5513 int32_t callerUid = IPCSkeleton::GetCallingUid();
5514 std::string callerBundleName;
5515 // reset ipc identity
5516 auto identity = IPCSkeleton::ResetCallingIdentity();
5517 bool result = bundleMgr->GetBundleNameForUid(callerUid, callerBundleName);
5518 // set ipc identity to raw
5519 IPCSkeleton::SetCallingIdentity(identity);
5520 TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName: %{public}s", callerBundleName.c_str());
5521 DistributedClient dmsClient;
5522 dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess, callerBundleName);
5523 }
5524
NotifyContinuationResult(int32_t missionId,int32_t result)5525 int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result)
5526 {
5527 TAG_LOGI(AAFwkTag::ABILITYMGR, "result : %{public}d", result);
5528
5529 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
5530 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5531 auto uiAbilityManager = GetCurrentUIAbilityManager();
5532 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5533 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
5534 } else {
5535 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
5536 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
5537 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
5538 }
5539 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5540
5541 if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
5542 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
5543 return ERR_INVALID_VALUE;
5544 }
5545 abilityRecord->NotifyContinuationResult(result);
5546 return ERR_OK;
5547 }
5548
StartSyncRemoteMissions(const std::string & devId,bool fixConflict,int64_t tag)5549 int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
5550 {
5551 CHECK_CALLER_IS_SYSTEM_APP;
5552 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5553 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5554 return CHECK_PERMISSION_FAILED;
5555 }
5556 DistributedClient dmsClient;
5557 int32_t callingUid = IPCSkeleton::GetCallingUid();
5558 uint32_t callingTokenId = IPCSkeleton::GetCallingTokenID();
5559 TAG_LOGD(AAFwkTag::ABILITYMGR, "fixConflict: %{public}d, tag: %{public}" PRId64, fixConflict, tag);
5560 return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag, callingUid, callingTokenId);
5561 }
5562
StopSyncRemoteMissions(const std::string & devId)5563 int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId)
5564 {
5565 CHECK_CALLER_IS_SYSTEM_APP;
5566 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5567 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5568 return CHECK_PERMISSION_FAILED;
5569 }
5570 DistributedClient dmsClient;
5571 int32_t callingUid = IPCSkeleton::GetCallingUid();
5572 return dmsClient.StopSyncRemoteMissions(devId, callingUid);
5573 }
5574
RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)5575 int AbilityManagerService::RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
5576 {
5577 if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
5578 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
5579 return CHECK_PERMISSION_FAILED;
5580 }
5581 return DelayedSingleton<ConnectionStateManager>::GetInstance()->RegisterObserver(observer);
5582 }
5583
UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)5584 int AbilityManagerService::UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
5585 {
5586 if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
5587 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
5588 return CHECK_PERMISSION_FAILED;
5589 }
5590 return DelayedSingleton<ConnectionStateManager>::GetInstance()->UnregisterObserver(observer);
5591 }
5592
5593 #ifdef WITH_DLP
GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> & infos)5594 int AbilityManagerService::GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)
5595 {
5596 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
5597 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't get dlp connection infos if caller not sa");
5598 return CHECK_PERMISSION_FAILED;
5599 }
5600 DelayedSingleton<ConnectionStateManager>::GetInstance()->GetDlpConnectionInfos(infos);
5601
5602 return ERR_OK;
5603 }
5604 #endif // WITH_DLP
5605
GetConnectionData(std::vector<AbilityRuntime::ConnectionData> & connectionData)5606 int AbilityManagerService::GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)
5607 {
5608 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
5609 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller no sa no connection data");
5610 return CHECK_PERMISSION_FAILED;
5611 }
5612 DelayedSingleton<ConnectionStateManager>::GetInstance()->GetConnectionData(connectionData);
5613
5614 return ERR_OK;
5615 }
5616
RegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)5617 int AbilityManagerService::RegisterMissionListener(const std::string &deviceId,
5618 const sptr<IRemoteMissionListener> &listener)
5619 {
5620 CHECK_CALLER_IS_SYSTEM_APP;
5621 std::string localDeviceId;
5622 if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
5623 TAG_LOGE(AAFwkTag::ABILITYMGR, "registerMissionListener:check deviceId failed");
5624 return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
5625 }
5626 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
5627 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5628 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5629 return CHECK_PERMISSION_FAILED;
5630 }
5631 DistributedClient dmsClient;
5632 int32_t callingUid = IPCSkeleton::GetCallingUid();
5633 return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject(), callingUid);
5634 }
5635
RegisterOnListener(const std::string & type,const sptr<IRemoteOnListener> & listener)5636 int AbilityManagerService::RegisterOnListener(const std::string &type,
5637 const sptr<IRemoteOnListener> &listener)
5638 {
5639 CHECK_CALLER_IS_SYSTEM_APP;
5640 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
5641 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5642 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5643 return CHECK_PERMISSION_FAILED;
5644 }
5645 DistributedClient dmsClient;
5646 int32_t callingUid = IPCSkeleton::GetCallingUid();
5647 return dmsClient.RegisterOnListener(type, listener->AsObject(), callingUid);
5648 }
5649
RegisterOffListener(const std::string & type,const sptr<IRemoteOnListener> & listener)5650 int AbilityManagerService::RegisterOffListener(const std::string &type,
5651 const sptr<IRemoteOnListener> &listener)
5652 {
5653 CHECK_CALLER_IS_SYSTEM_APP;
5654 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
5655 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5656 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5657 return CHECK_PERMISSION_FAILED;
5658 }
5659 DistributedClient dmsClient;
5660 int32_t callingUid = IPCSkeleton::GetCallingUid();
5661 return dmsClient.RegisterOffListener(type, listener->AsObject(), callingUid);
5662 }
5663
UnRegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)5664 int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId,
5665 const sptr<IRemoteMissionListener> &listener)
5666 {
5667 CHECK_CALLER_IS_SYSTEM_APP;
5668 std::string localDeviceId;
5669 if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
5670 TAG_LOGE(AAFwkTag::ABILITYMGR, "check deviceId failed");
5671 return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
5672 }
5673 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
5674 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5675 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5676 return CHECK_PERMISSION_FAILED;
5677 }
5678 DistributedClient dmsClient;
5679 return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
5680 }
5681
GetWantSender(const WantSenderInfo & wantSenderInfo,const sptr<IRemoteObject> & callerToken,int32_t uid)5682 sptr<IWantSender> AbilityManagerService::GetWantSender(
5683 const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken,
5684 int32_t uid)
5685 {
5686 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5687 auto pendingWantManager = GetCurrentPendingWantManager();
5688 CHECK_POINTER_AND_RETURN(pendingWantManager, nullptr);
5689
5690 auto bms = AbilityUtil::GetBundleManagerHelper();
5691 CHECK_POINTER_AND_RETURN(bms, nullptr);
5692
5693 int32_t callerUid = IPCSkeleton::GetCallingUid();
5694 int32_t userId = wantSenderInfo.userId;
5695 int32_t bundleMgrResult = 0;
5696
5697 if (userId < 0) {
5698 if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
5699 GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
5700 TAG_LOGE(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid failed uid=%{public}d", callerUid);
5701 return nullptr;
5702 }
5703 }
5704 TAG_LOGD(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid userId: %{public}d", userId);
5705 //sa caller and has uid,no need find from bms.
5706 bool isSpecifyUidBySa = (uid != -1) && (AAFwk::PermissionVerification::GetInstance()->IsSACall());
5707
5708 int32_t appUid = -1;
5709 int32_t appIndex = 0;
5710 std::string bundleName = "";
5711 if (!wantSenderInfo.allWants.empty()) {
5712 bundleName = wantSenderInfo.allWants.back().want.GetElement().GetBundleName();
5713 }
5714 if (!bundleName.empty()) {
5715 if (!isSpecifyUidBySa) {
5716 AppExecFwk::BundleInfo bundleInfo;
5717 MultiAppUtils::GetRunningMultiAppIndex(bundleName, callerUid, appIndex);
5718 bundleMgrResult = IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName,
5719 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
5720 appIndex, bundleInfo, userId));
5721 if (bundleMgrResult == ERR_OK) {
5722 appUid = bundleInfo.uid;
5723 }
5724 } else {
5725 appUid = uid;
5726 }
5727 TAG_LOGD(AAFwkTag::ABILITYMGR,
5728 "bundleName: %{public}s, uid: %{public}d, userId: %{public}d, appIndex: %{public}d", bundleName.c_str(),
5729 appUid, userId, appIndex);
5730 }
5731 if (!CheckSenderWantInfo(callerUid, wantSenderInfo)) {
5732 TAG_LOGE(AAFwkTag::ABILITYMGR, "check bundleName failed");
5733 return nullptr;
5734 }
5735
5736 bool isSystemApp = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
5737
5738 TAG_LOGI(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, appIndex: %{public}d, isSystemApp: %{public}d, "
5739 "userId: %{public}d", wantSenderInfo.bundleName.c_str(), appIndex, isSystemApp, userId);
5740 return pendingWantManager->GetWantSender(callerUid, appUid, isSystemApp, wantSenderInfo, callerToken, appIndex);
5741 }
5742
SendWantSender(sptr<IWantSender> target,SenderInfo & senderInfo)5743 int AbilityManagerService::SendWantSender(sptr<IWantSender> target, SenderInfo &senderInfo)
5744 {
5745 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5746 auto pendingWantManager = GetCurrentPendingWantManager();
5747 CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
5748 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
5749 return pendingWantManager->SendWantSender(target, senderInfo);
5750 }
5751
SendLocalWantSender(const SenderInfo & senderInfo)5752 int AbilityManagerService::SendLocalWantSender(const SenderInfo &senderInfo)
5753 {
5754 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5755 auto pendingWantManager = GetCurrentPendingWantManager();
5756 CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
5757 if (!PermissionVerification::GetInstance()->VerifyPermissionByTokenId(senderInfo.tokenId,
5758 PermissionConstants::PERMISSION_TRIGGER_LOCAL_WANTAGENT)) {
5759 TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to trigger local wantagent");
5760 return CHECK_PERMISSION_FAILED;
5761 }
5762 return pendingWantManager->SendLocalWantSender(senderInfo);
5763 }
5764
CancelWantSender(const sptr<IWantSender> & sender)5765 void AbilityManagerService::CancelWantSender(const sptr<IWantSender> &sender)
5766 {
5767 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5768 auto pendingWantManager = GetCurrentPendingWantManager();
5769 CHECK_POINTER(pendingWantManager);
5770 CHECK_POINTER(sender);
5771
5772 sptr<IRemoteObject> obj = sender->AsObject();
5773 if (!obj || obj->IsProxyObject()) {
5774 TAG_LOGE(AAFwkTag::ABILITYMGR, "obj null or proxy obj");
5775 return;
5776 }
5777
5778 auto bms = AbilityUtil::GetBundleManagerHelper();
5779 CHECK_POINTER(bms);
5780
5781 int32_t callerUid = IPCSkeleton::GetCallingUid();
5782 sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
5783
5784 int userId = -1;
5785 if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
5786 GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
5787 TAG_LOGE(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid failed uid=%{public}d", callerUid);
5788 return;
5789 }
5790 TAG_LOGD(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid userId: %{public}d", userId);
5791 bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
5792
5793 pendingWantManager->CancelWantSender(isSystemAppCall, sender);
5794 }
5795
CancelWantSenderByFlags(const sptr<IWantSender> & sender,uint32_t flags)5796 void AbilityManagerService::CancelWantSenderByFlags(const sptr<IWantSender> &sender, uint32_t flags)
5797 {
5798 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5799 auto pendingWantManager = GetCurrentPendingWantManager();
5800 CHECK_POINTER(pendingWantManager);
5801 CHECK_POINTER(sender);
5802
5803 sptr<IRemoteObject> obj = sender->AsObject();
5804 if (!obj || obj->IsProxyObject()) {
5805 TAG_LOGE(AAFwkTag::ABILITYMGR, "obj null or proxy obj");
5806 return;
5807 }
5808
5809 auto bms = AbilityUtil::GetBundleManagerHelper();
5810 CHECK_POINTER(bms);
5811
5812 sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
5813 CHECK_POINTER(record);
5814
5815 if (flags != 0 && record->GetKey() != nullptr &&
5816 (static_cast<uint32_t>(record->GetKey()->GetFlags()) & flags) == 0) {
5817 TAG_LOGI(AAFwkTag::ABILITYMGR, "flags=%{public}u not match wantAgent flags=%{public}d",
5818 flags, record->GetKey()->GetFlags());
5819 return;
5820 }
5821
5822 TAG_LOGI(AAFwkTag::ABILITYMGR, "code=%{public}d cancel by flags=%{public}u",
5823 record->GetKey() != nullptr ? record->GetKey()->GetCode() : -1, flags);
5824 bool isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
5825 pendingWantManager->CancelWantSender(isSystemAppCall, sender);
5826 }
5827
GetPendingWantUid(const sptr<IWantSender> & target)5828 int AbilityManagerService::GetPendingWantUid(const sptr<IWantSender> &target)
5829 {
5830 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
5831 auto pendingWantManager = GetCurrentPendingWantManager();
5832 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5833 if (target == nullptr) {
5834 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5835 return -1;
5836 }
5837 return pendingWantManager->GetPendingWantUid(target);
5838 }
5839
GetPendingWantUserId(const sptr<IWantSender> & target)5840 int AbilityManagerService::GetPendingWantUserId(const sptr<IWantSender> &target)
5841 {
5842 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
5843 auto pendingWantManager = GetCurrentPendingWantManager();
5844 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5845 if (target == nullptr) {
5846 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5847 return -1;
5848 }
5849 return pendingWantManager->GetPendingWantUserId(target);
5850 }
5851
GetPendingWantBundleName(const sptr<IWantSender> & target)5852 std::string AbilityManagerService::GetPendingWantBundleName(const sptr<IWantSender> &target)
5853 {
5854 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
5855 XCOLLIE_TIMER_DEFAULT(__PRETTY_FUNCTION__);
5856 auto pendingWantManager = GetCurrentPendingWantManager();
5857 CHECK_POINTER_AND_RETURN(pendingWantManager, "");
5858 CHECK_POINTER_AND_RETURN(target, "");
5859 return pendingWantManager->GetPendingWantBundleName(target);
5860 }
5861
GetPendingWantCode(const sptr<IWantSender> & target)5862 int AbilityManagerService::GetPendingWantCode(const sptr<IWantSender> &target)
5863 {
5864 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
5865 auto pendingWantManager = GetCurrentPendingWantManager();
5866 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5867 if (target == nullptr) {
5868 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5869 return -1;
5870 }
5871 return pendingWantManager->GetPendingWantCode(target);
5872 }
5873
GetPendingWantType(const sptr<IWantSender> & target)5874 int AbilityManagerService::GetPendingWantType(const sptr<IWantSender> &target)
5875 {
5876 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
5877 XCOLLIE_TIMER_DEFAULT(__PRETTY_FUNCTION__);
5878 auto pendingWantManager = GetCurrentPendingWantManager();
5879 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
5880 if (target == nullptr) {
5881 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
5882 return -1;
5883 }
5884 return pendingWantManager->GetPendingWantType(target);
5885 }
5886
RegisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)5887 void AbilityManagerService::RegisterCancelListener(const sptr<IWantSender> &sender,
5888 const sptr<IWantReceiver> &receiver)
5889 {
5890 TAG_LOGI(AAFwkTag::ABILITYMGR, "register cancel listener");
5891 auto pendingWantManager = GetCurrentPendingWantManager();
5892 CHECK_POINTER(pendingWantManager);
5893 CHECK_POINTER(sender);
5894 CHECK_POINTER(receiver);
5895 pendingWantManager->RegisterCancelListener(sender, receiver);
5896 }
5897
UnregisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)5898 void AbilityManagerService::UnregisterCancelListener(
5899 const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)
5900 {
5901 TAG_LOGI(AAFwkTag::ABILITYMGR, "unregister cancel listener");
5902 auto pendingWantManager = GetCurrentPendingWantManager();
5903 CHECK_POINTER(pendingWantManager);
5904 CHECK_POINTER(sender);
5905 CHECK_POINTER(receiver);
5906 pendingWantManager->UnregisterCancelListener(sender, receiver);
5907 }
5908
GetPendingRequestWant(const sptr<IWantSender> & target,std::shared_ptr<Want> & want)5909 int AbilityManagerService::GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)
5910 {
5911 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5912 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get pending request want.");
5913 XCOLLIE_TIMER_DEFAULT(__PRETTY_FUNCTION__);
5914 auto pendingWantManager = GetCurrentPendingWantManager();
5915 CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
5916 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
5917 CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE);
5918 CHECK_CALLER_IS_SYSTEM_APP;
5919 return pendingWantManager->GetPendingRequestWant(target, want);
5920 }
5921
LockMissionForCleanup(int32_t missionId)5922 int AbilityManagerService::LockMissionForCleanup(int32_t missionId)
5923 {
5924 TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock for clean all, id=%{public}d", missionId);
5925 auto missionListManager = GetCurrentMissionListManager();
5926 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5927 CHECK_CALLER_IS_SYSTEM_APP;
5928
5929 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5930 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5931 return CHECK_PERMISSION_FAILED;
5932 }
5933 return missionListManager->SetMissionLockedState(missionId, true);
5934 }
5935
UnlockMissionForCleanup(int32_t missionId)5936 int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId)
5937 {
5938 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5939 TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock for clean all, id=%{public}d", missionId);
5940 auto missionListManager = GetCurrentMissionListManager();
5941 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5942 CHECK_CALLER_IS_SYSTEM_APP;
5943
5944 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5945 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5946 return CHECK_PERMISSION_FAILED;
5947 }
5948 return missionListManager->SetMissionLockedState(missionId, false);
5949 }
5950
SetLockedState(int32_t sessionId,bool lockedState)5951 void AbilityManagerService::SetLockedState(int32_t sessionId, bool lockedState)
5952 {
5953 TAG_LOGI(AAFwkTag::ABILITYMGR, "request lock abilityRecord, sessionId :%{public}d", sessionId);
5954 if (!IsCallerSceneBoard()) {
5955 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
5956 return;
5957 }
5958 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5959 CHECK_POINTER(uiAbilityManager);
5960 auto abilityRecord = uiAbilityManager->GetAbilityRecordsById(sessionId);
5961 if (!abilityRecord) {
5962 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
5963 return;
5964 }
5965 abilityRecord->SetLockedState(lockedState);
5966 }
5967
RegisterMissionListener(const sptr<IMissionListener> & listener)5968 int AbilityManagerService::RegisterMissionListener(const sptr<IMissionListener> &listener)
5969 {
5970 TAG_LOGI(AAFwkTag::ABILITYMGR, "request registerMissionListener");
5971 auto missionListManager = GetCurrentMissionListManager();
5972 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5973 CHECK_CALLER_IS_SYSTEM_APP;
5974
5975 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5976 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5977 return CHECK_PERMISSION_FAILED;
5978 }
5979 return missionListManager->RegisterMissionListener(listener);
5980 }
5981
UnRegisterMissionListener(const sptr<IMissionListener> & listener)5982 int AbilityManagerService::UnRegisterMissionListener(const sptr<IMissionListener> &listener)
5983 {
5984 TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
5985 auto missionListManager = GetCurrentMissionListManager();
5986 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5987 CHECK_CALLER_IS_SYSTEM_APP;
5988
5989 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5990 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5991 return CHECK_PERMISSION_FAILED;
5992 }
5993 return missionListManager->UnRegisterMissionListener(listener);
5994 }
5995
GetMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)5996 int AbilityManagerService::GetMissionInfos(const std::string& deviceId, int32_t numMax,
5997 std::vector<MissionInfo> &missionInfos)
5998 {
5999 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6000 TAG_LOGI(AAFwkTag::ABILITYMGR, "request getMissionInfos");
6001 auto missionListManager = GetCurrentMissionListManager();
6002 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
6003 CHECK_CALLER_IS_SYSTEM_APP;
6004
6005 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6006 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6007 return CHECK_PERMISSION_FAILED;
6008 }
6009
6010 if (CheckIsRemote(deviceId)) {
6011 return GetRemoteMissionInfos(deviceId, numMax, missionInfos);
6012 }
6013
6014 return missionListManager->GetMissionInfos(numMax, missionInfos);
6015 }
6016
GetRemoteMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)6017 int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax,
6018 std::vector<MissionInfo> &missionInfos)
6019 {
6020 TAG_LOGI(AAFwkTag::ABILITYMGR, "getRemoteMissionInfos");
6021 DistributedClient dmsClient;
6022 int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos);
6023 if (result != ERR_OK) {
6024 TAG_LOGE(AAFwkTag::ABILITYMGR, "getRemoteMissionInfos failed, result=%{public}d", result);
6025 return result;
6026 }
6027 return ERR_OK;
6028 }
6029
GetMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)6030 int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId,
6031 MissionInfo &missionInfo)
6032 {
6033 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6034 TAG_LOGI(AAFwkTag::ABILITYMGR, "request getMissionInfo, missionId:%{public}d", missionId);
6035 auto missionListManager = GetCurrentMissionListManager();
6036 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
6037 CHECK_CALLER_IS_SYSTEM_APP;
6038
6039 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6040 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6041 return CHECK_PERMISSION_FAILED;
6042 }
6043
6044 if (CheckIsRemote(deviceId)) {
6045 return GetRemoteMissionInfo(deviceId, missionId, missionInfo);
6046 }
6047
6048 return missionListManager->GetMissionInfo(missionId, missionInfo);
6049 }
6050
GetRemoteMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)6051 int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId,
6052 MissionInfo &missionInfo)
6053 {
6054 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6055 TAG_LOGI(AAFwkTag::ABILITYMGR, "getMissionInfoFromDms");
6056 std::vector<MissionInfo> missionVector;
6057 int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector);
6058 if (result != ERR_OK) {
6059 return result;
6060 }
6061 for (auto iter = missionVector.begin(); iter != missionVector.end(); iter++) {
6062 if (iter->id == missionId) {
6063 missionInfo = *iter;
6064 return ERR_OK;
6065 }
6066 }
6067 TAG_LOGW(AAFwkTag::ABILITYMGR, "missionId not found");
6068 return ERR_INVALID_VALUE;
6069 }
6070
CleanMission(int32_t missionId)6071 int AbilityManagerService::CleanMission(int32_t missionId)
6072 {
6073 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6074 TAG_LOGI(AAFwkTag::ABILITYMGR, "request cleanMission, missionId:%{public}d", missionId);
6075 auto missionListManager = GetCurrentMissionListManager();
6076 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
6077 CHECK_CALLER_IS_SYSTEM_APP;
6078
6079 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6080 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6081 return CHECK_PERMISSION_FAILED;
6082 }
6083
6084 return missionListManager->ClearMission(missionId);
6085 }
6086
CleanAllMissions()6087 int AbilityManagerService::CleanAllMissions()
6088 {
6089 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6090 TAG_LOGI(AAFwkTag::ABILITYMGR, "request cleanAllMissions");
6091 auto missionListManager = GetCurrentMissionListManager();
6092 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
6093 CHECK_CALLER_IS_SYSTEM_APP;
6094
6095 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6096 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6097 return CHECK_PERMISSION_FAILED;
6098 }
6099
6100 Want want;
6101 want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME);
6102 if (!IsAbilityControllerStart(want, AbilityConfig::LAUNCHER_BUNDLE_NAME)) {
6103 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", want.GetBundle().c_str());
6104 return ERR_WOULD_BLOCK;
6105 }
6106
6107 return missionListManager->ClearAllMissions();
6108 }
6109
MoveMissionToFront(int32_t missionId)6110 int AbilityManagerService::MoveMissionToFront(int32_t missionId)
6111 {
6112 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6113 TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
6114 CHECK_CALLER_IS_SYSTEM_APP;
6115 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6116 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6117 return CHECK_PERMISSION_FAILED;
6118 }
6119
6120 if (!IsAbilityControllerStartById(missionId)) {
6121 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart false");
6122 return ERR_WOULD_BLOCK;
6123 }
6124
6125 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6126 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
6127 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
6128 return uiAbilityManager->MoveMissionToFront(missionId);
6129 }
6130
6131 auto missionListManager = GetCurrentMissionListManager();
6132 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
6133 return missionListManager->MoveMissionToFront(missionId);
6134 }
6135
MoveMissionToFront(int32_t missionId,const StartOptions & startOptions)6136 int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)
6137 {
6138 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6139 TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
6140 CHECK_CALLER_IS_SYSTEM_APP;
6141 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6142 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6143 return CHECK_PERMISSION_FAILED;
6144 }
6145
6146 if (!IsAbilityControllerStartById(missionId)) {
6147 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart false");
6148 return ERR_WOULD_BLOCK;
6149 }
6150
6151 auto options = std::make_shared<StartOptions>(startOptions);
6152 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6153 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
6154 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
6155 return uiAbilityManager->MoveMissionToFront(missionId, options);
6156 }
6157
6158 auto missionListManager = GetCurrentMissionListManager();
6159 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
6160 return missionListManager->MoveMissionToFront(missionId, options);
6161 }
6162
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)6163 int AbilityManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
6164 {
6165 CHECK_CALLER_IS_SYSTEM_APP;
6166 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6167 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6168 return CHECK_PERMISSION_FAILED;
6169 }
6170 #ifdef SUPPORT_SCREEN
6171 if (wmsHandler_) {
6172 auto ret = wmsHandler_->MoveMissionsToForeground(missionIds, topMissionId);
6173 if (ret) {
6174 TAG_LOGE(AAFwkTag::ABILITYMGR, "moveMissionsToForeground failed, missiondIds may invalid");
6175 return ERR_INVALID_VALUE;
6176 } else {
6177 return NO_ERROR;
6178 }
6179 }
6180 #endif // SUPPORT_SCREEN
6181 return ERR_NO_INIT;
6182 }
6183
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)6184 int AbilityManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
6185 std::vector<int32_t>& result)
6186 {
6187 CHECK_CALLER_IS_SYSTEM_APP;
6188 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6189 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
6190 return CHECK_PERMISSION_FAILED;
6191 }
6192 #ifdef SUPPORT_SCREEN
6193 if (wmsHandler_) {
6194 auto ret = wmsHandler_->MoveMissionsToBackground(missionIds, result);
6195 if (ret) {
6196 TAG_LOGE(AAFwkTag::ABILITYMGR, "moveMissionsToBackground failed, missiondIds may invalid");
6197 return ERR_INVALID_VALUE;
6198 } else {
6199 return NO_ERROR;
6200 }
6201 }
6202 #endif // SUPPORT_SCREEN
6203 return ERR_NO_INIT;
6204 }
6205
GetMissionIdByToken(const sptr<IRemoteObject> & token)6206 int32_t AbilityManagerService::GetMissionIdByToken(const sptr<IRemoteObject> &token)
6207 {
6208 TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken.");
6209 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6210 if (!abilityRecord) {
6211 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
6212 return ERR_INVALID_VALUE;
6213 }
6214 if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
6215 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
6216 return ERR_INVALID_VALUE;
6217 }
6218 return GetMissionIdByAbilityTokenInner(token);
6219 }
6220
IsAbilityControllerStartById(int32_t missionId)6221 bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId)
6222 {
6223 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6224 auto missionListWrap = GetMissionListWrap();
6225 if (missionListWrap == nullptr) {
6226 TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null");
6227 return true;
6228 }
6229 InnerMissionInfo innerMissionInfo;
6230 int getMission = missionListWrap->GetInnerMissionInfoById(missionId, innerMissionInfo);
6231 if (getMission != ERR_OK) {
6232 TAG_LOGE(AAFwkTag::ABILITYMGR,
6233 "cannot find mission info:%{public}d", missionId);
6234 return true;
6235 }
6236 if (!IsAbilityControllerStart(innerMissionInfo.missionInfo.want, innerMissionInfo.missionInfo.want.GetBundle())) {
6237 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s",
6238 innerMissionInfo.missionInfo.want.GetBundle().c_str());
6239 return false;
6240 }
6241 return true;
6242 }
6243
GetConnectRecordListByCallback(sptr<IAbilityConnection> callback)6244 std::list<std::shared_ptr<ConnectionRecord>> AbilityManagerService::GetConnectRecordListByCallback(
6245 sptr<IAbilityConnection> callback)
6246 {
6247 auto connectManager = GetCurrentConnectManager();
6248 CHECK_POINTER_AND_RETURN(connectManager, std::list<std::shared_ptr<ConnectionRecord>>());
6249 return connectManager->GetConnectRecordListByCallback(callback);
6250 }
6251
GenerateDataAbilityRequestByUri(const std::string & dataAbilityUri,AbilityRequest & abilityRequest,sptr<IRemoteObject> callerToken,int32_t userId)6252 bool AbilityManagerService::GenerateDataAbilityRequestByUri(const std::string& dataAbilityUri,
6253 AbilityRequest &abilityRequest, sptr<IRemoteObject> callerToken, int32_t userId)
6254 {
6255 auto bms = AbilityUtil::GetBundleManagerHelper();
6256 CHECK_POINTER_AND_RETURN(bms, false);
6257 TAG_LOGI(AAFwkTag::ABILITYMGR, "dataAbilityUri: %{public}s, userId: %{public}d", dataAbilityUri.c_str(), userId);
6258 bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo));
6259 if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) {
6260 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid ability info acquiring");
6261 return false;
6262 }
6263 abilityRequest.callerToken = callerToken;
6264 return true;
6265 }
6266
AcquireDataAbility(const Uri & uri,bool tryBind,const sptr<IRemoteObject> & callerToken)6267 sptr<IAbilityScheduler> AbilityManagerService::AcquireDataAbility(
6268 const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
6269 {
6270 auto localUri(uri);
6271 if (localUri.GetScheme() != AbilityConfig::SCHEME_DATA_ABILITY) {
6272 TAG_LOGE(AAFwkTag::ABILITYMGR, "acquire data ability invalid uri scheme");
6273 return nullptr;
6274 }
6275 std::vector<std::string> pathSegments;
6276 localUri.GetPathSegments(pathSegments);
6277 if (pathSegments.empty()) {
6278 TAG_LOGE(AAFwkTag::ABILITYMGR, "acquire data ability invalid uri path");
6279 return nullptr;
6280 }
6281
6282 auto userId = GetValidUserId(INVALID_USER_ID);
6283 AbilityRequest abilityRequest;
6284 if (!GenerateDataAbilityRequestByUri(localUri.ToString(), abilityRequest, callerToken, userId)) {
6285 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate data ability request failed");
6286 return nullptr;
6287 }
6288
6289 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6290 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6291 if (!isSaCall && CheckCallDataAbilityPermission(abilityRequest, isShellCall, isSaCall) != ERR_OK) {
6292 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid ability request info acquiring");
6293 return nullptr;
6294 }
6295
6296 TAG_LOGD(AAFwkTag::ABILITYMGR, "Query data ability info: %{public}s|%{public}s|%{public}s",
6297 abilityRequest.appInfo.name.c_str(), abilityRequest.appInfo.bundleName.c_str(),
6298 abilityRequest.abilityInfo.name.c_str());
6299
6300 if (CheckStaticCfgPermission(abilityRequest, false, -1, true, isSaCall) !=
6301 AppExecFwk::Constants::PERMISSION_GRANTED) {
6302 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission fail");
6303 return nullptr;
6304 }
6305
6306 if (!VerificationAllToken(callerToken)) {
6307 TAG_LOGI(AAFwkTag::ABILITYMGR, "verificationAllToken fail");
6308 return nullptr;
6309 }
6310
6311 if (abilityRequest.abilityInfo.applicationInfo.singleton) {
6312 userId = U0_USER_ID;
6313 }
6314
6315 std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6316 CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr);
6317 ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
6318 bool isNotHap = isSaCall || isShellCall;
6319 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
6320 return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap);
6321 }
6322
ReleaseDataAbility(sptr<IAbilityScheduler> dataAbilityScheduler,const sptr<IRemoteObject> & callerToken)6323 int AbilityManagerService::ReleaseDataAbility(
6324 sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
6325 {
6326 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
6327 if (!dataAbilityScheduler || !callerToken) {
6328 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilitySchedule or callerToken null");
6329 return ERR_INVALID_VALUE;
6330 }
6331
6332 std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler);
6333 if (!dataAbilityManager) {
6334 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityScheduler absent");
6335 return ERR_INVALID_VALUE;
6336 }
6337
6338 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6339 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6340 bool isNotHap = isSaCall || isShellCall;
6341 return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isNotHap);
6342 }
6343
AttachAbilityThread(const sptr<IAbilityScheduler> & scheduler,const sptr<IRemoteObject> & token)6344 int AbilityManagerService::AttachAbilityThread(
6345 const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
6346 {
6347 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6348 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
6349 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
6350 CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE);
6351 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
6352 return ERR_INVALID_VALUE;
6353 }
6354 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6355 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6356 if (!JudgeSelfCalled(abilityRecord)) {
6357 return CHECK_PERMISSION_FAILED;
6358 }
6359
6360 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6361 auto abilityInfo = abilityRecord->GetAbilityInfo();
6362 auto type = abilityInfo.type;
6363 // force timeout ability for test
6364 if (IsNeedTimeoutForTest(abilityInfo.name, AbilityRecord::ConvertAbilityState(AbilityState::INITIAL))) {
6365 TAG_LOGW(AAFwkTag::ABILITYMGR,
6366 "force timeout ability, state:INITIAL, ability:%{public}s", abilityInfo.name.c_str());
6367 return ERR_OK;
6368 }
6369 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
6370 auto connectManager = GetConnectManagerByUserId(userId);
6371 if (!connectManager) {
6372 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6373 return ERR_INVALID_VALUE;
6374 }
6375 return connectManager->AttachAbilityThreadLocked(scheduler, token);
6376 } else if (type == AppExecFwk::AbilityType::DATA) {
6377 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6378 if (!dataAbilityManager) {
6379 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
6380 return ERR_INVALID_VALUE;
6381 }
6382 return dataAbilityManager->AttachAbilityThread(scheduler, token);
6383 } else {
6384 std::string entry = "AbilityManagerService::AttachAbilityThread; the end of load lifecycle.";
6385 FreezeUtil::GetInstance().AddLifecycleEvent(token, entry);
6386 int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
6387 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6388 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
6389 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
6390 return uiAbilityManager->AttachAbilityThread(scheduler, token);
6391 }
6392 auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
6393 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
6394 return missionListManager->AttachAbilityThread(scheduler, token);
6395 }
6396 }
6397
DumpSysInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6398 void AbilityManagerService::DumpSysInner(
6399 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
6400 {
6401 std::vector<std::string> argList;
6402 SplitStr(args, " ", argList);
6403 if (argList.empty()) {
6404 return;
6405 }
6406
6407 DumpSysMissionListInner(args, info, isClient, isUserID, userId);
6408 DumpSysStateInner(args, info, isClient, isUserID, userId);
6409 DumpSysPendingInner(args, info, isClient, isUserID, userId);
6410 DumpSysProcess(args, info, isClient, isUserID, userId);
6411 }
6412
DumpSysMissionListInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6413 void AbilityManagerService::DumpSysMissionListInner(
6414 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
6415 {
6416 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6417 DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId);
6418 return;
6419 }
6420 std::shared_ptr<MissionListManagerInterface> targetManager;
6421 if (isUserID) {
6422 auto missionListManager = GetMissionListManagerByUserId(userId);
6423 if (missionListManager == nullptr) {
6424 info.push_back("error: No user found.");
6425 return;
6426 }
6427 targetManager = missionListManager;
6428 } else {
6429 targetManager = GetCurrentMissionListManager();
6430 }
6431
6432 CHECK_POINTER(targetManager);
6433
6434 std::vector<std::string> argList;
6435 SplitStr(args, " ", argList);
6436 if (argList.empty()) {
6437 return;
6438 }
6439
6440 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6441 targetManager->DumpMissionList(info, isClient, argList[1]);
6442 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6443 targetManager->DumpMissionList(info, isClient);
6444 } else {
6445 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6446 }
6447 }
6448
DumpSysMissionListInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6449 void AbilityManagerService::DumpSysMissionListInnerBySCB(
6450 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
6451 {
6452 if (!isUserID) {
6453 userId = GetUserId();
6454 }
6455
6456 std::vector<std::string> argList;
6457 SplitStr(args, " ", argList);
6458 if (argList.empty()) {
6459 return;
6460 }
6461
6462 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
6463 CHECK_POINTER(uiAbilityManager);
6464 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6465 uiAbilityManager->DumpMissionList(info, isClient, argList[1]);
6466 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6467 uiAbilityManager->DumpMissionList(info, isClient);
6468 } else {
6469 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6470 }
6471 }
6472
DumpSysAbilityInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6473 void AbilityManagerService::DumpSysAbilityInner(
6474 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
6475 {
6476 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6477 DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId);
6478 return;
6479 }
6480 std::shared_ptr<MissionListManagerInterface> targetManager;
6481 if (isUserID) {
6482 auto missionListManager = GetMissionListManagerByUserId(userId);
6483 if (missionListManager == nullptr) {
6484 info.push_back("error: No user found.");
6485 return;
6486 }
6487 targetManager = missionListManager;
6488 } else {
6489 targetManager = GetCurrentMissionListManager();
6490 }
6491
6492 CHECK_POINTER(targetManager);
6493
6494 std::vector<std::string> argList;
6495 SplitStr(args, " ", argList);
6496 if (argList.empty()) {
6497 return;
6498 }
6499 if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
6500 TAG_LOGI(AAFwkTag::ABILITYMGR, "argList=%{public}s", argList[1].c_str());
6501 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
6502 try {
6503 auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
6504 targetManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
6505 } catch (...) {
6506 TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
6507 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6508 }
6509 } else {
6510 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6511 }
6512 }
6513
DumpSysAbilityInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6514 void AbilityManagerService::DumpSysAbilityInnerBySCB(
6515 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
6516 {
6517 if (!isUserID) {
6518 userId = GetUserId();
6519 }
6520
6521 std::vector<std::string> argList;
6522 SplitStr(args, " ", argList);
6523 if (argList.empty()) {
6524 return;
6525 }
6526 if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
6527 TAG_LOGI(AAFwkTag::ABILITYMGR, "argList=%{public}s", argList[1].c_str());
6528 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
6529 try {
6530 auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
6531 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
6532 CHECK_POINTER(uiAbilityManager);
6533 uiAbilityManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
6534 } catch (...) {
6535 TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
6536 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6537 }
6538 } else {
6539 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6540 }
6541 }
6542
DumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6543 void AbilityManagerService::DumpSysStateInner(
6544 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
6545 {
6546 TAG_LOGI(AAFwkTag::ABILITYMGR, "dumpSysStateInner begin:%{public}s", args.c_str());
6547 std::shared_ptr<AbilityConnectManager> targetManager;
6548
6549 if (isUserID) {
6550 auto connectManager = GetConnectManagerByUserId(userId);
6551 if (connectManager == nullptr) {
6552 info.push_back("error: No user found.");
6553 return;
6554 }
6555 targetManager = connectManager;
6556 } else {
6557 targetManager = GetCurrentConnectManager();
6558 }
6559
6560 CHECK_POINTER(targetManager);
6561
6562 std::vector<std::string> argList;
6563 SplitStr(args, " ", argList);
6564 if (argList.empty()) {
6565 return;
6566 }
6567
6568 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6569 targetManager->DumpState(info, isClient, argList[1]);
6570 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6571 targetManager->DumpState(info, isClient);
6572 } else {
6573 TAG_LOGI(AAFwkTag::ABILITYMGR, "uri=%{public}s", argList[1].c_str());
6574 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
6575 targetManager->DumpStateByUri(info, isClient, argList[1], params);
6576 }
6577 }
6578
DumpSysPendingInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6579 void AbilityManagerService::DumpSysPendingInner(
6580 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
6581 {
6582 std::shared_ptr<PendingWantManager> targetManager;
6583 if (isUserID) {
6584 auto pendingWantManager = GetPendingWantManagerByUserId(userId);
6585 if (pendingWantManager == nullptr) {
6586 info.push_back("error: No user found.");
6587 return;
6588 }
6589 targetManager = pendingWantManager;
6590 } else {
6591 targetManager = GetCurrentPendingWantManager();
6592 }
6593
6594 CHECK_POINTER(targetManager);
6595
6596 std::vector<std::string> argList;
6597 SplitStr(args, " ", argList);
6598 if (argList.empty()) {
6599 return;
6600 }
6601
6602 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6603 targetManager->DumpByRecordId(info, argList[1]);
6604 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6605 targetManager->Dump(info);
6606 } else {
6607 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6608 }
6609 }
6610
DumpSysProcess(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6611 void AbilityManagerService::DumpSysProcess(
6612 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
6613 {
6614 std::vector<std::string> argList;
6615 SplitStr(args, " ", argList);
6616 if (argList.empty()) {
6617 return;
6618 }
6619 std::vector<AppExecFwk::RunningProcessInfo> processInfos;
6620 int ret = 0;
6621 if (isUserID) {
6622 ret = GetProcessRunningInfosByUserId(processInfos, userId);
6623 } else {
6624 ret = GetProcessRunningInfos(processInfos);
6625 }
6626
6627 if (ret != ERR_OK || processInfos.size() == 0) {
6628 return;
6629 }
6630
6631 std::string dumpInfo = " AppRunningRecords:";
6632 info.push_back(dumpInfo);
6633 auto processInfoID = 0;
6634 auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false);
6635 for (const auto& processInfo : processInfos) {
6636 if (hasProcessName && argList[1] != processInfo.processName_) {
6637 continue;
6638 }
6639
6640 dumpInfo = " AppRunningRecord ID #" + std::to_string(processInfoID);
6641 processInfoID++;
6642 info.push_back(dumpInfo);
6643 dumpInfo = " process name [" + processInfo.processName_ + "]";
6644 info.push_back(dumpInfo);
6645 dumpInfo = " pid #" + std::to_string(processInfo.pid_) +
6646 " uid #" + std::to_string(processInfo.uid_);
6647 info.push_back(dumpInfo);
6648 auto appState = static_cast<AppState>(processInfo.state_);
6649 dumpInfo = " state #" + DelayedSingleton<AppScheduler>::GetInstance()->ConvertAppState(appState);
6650 info.push_back(dumpInfo);
6651 DumpUIExtensionRootHostRunningInfos(processInfo.pid_, info);
6652 DumpUIExtensionProviderRunningInfos(processInfo.pid_, info);
6653 }
6654 }
6655
DumpUIExtensionRootHostRunningInfos(pid_t pid,std::vector<std::string> & info)6656 void AbilityManagerService::DumpUIExtensionRootHostRunningInfos(pid_t pid, std::vector<std::string> &info)
6657 {
6658 auto appMgr = AppMgrUtil::GetAppMgr();
6659 if (appMgr == nullptr) {
6660 TAG_LOGW(AAFwkTag::ABILITYMGR, "get appMgr failed");
6661 return;
6662 }
6663
6664 std::vector<pid_t> hostPids;
6665 auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionRootHostPid(pid, hostPids));
6666 if (ret != ERR_OK) {
6667 TAG_LOGE(AAFwkTag::ABILITYMGR, "get root host process info faild");
6668 return;
6669 }
6670
6671 if (hostPids.size() == 0) {
6672 TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extenson root host of pid %{public}d.", pid);
6673 return;
6674 }
6675
6676 std::string temp;
6677 for (size_t i = 0; i < hostPids.size(); i++) {
6678 temp = " root caller #" + std::to_string(i);
6679 info.push_back(temp);
6680 temp = " pid #" + std::to_string(hostPids[i]);
6681 info.push_back(temp);
6682 }
6683 }
6684
DumpUIExtensionProviderRunningInfos(pid_t hostPid,std::vector<std::string> & info)6685 void AbilityManagerService::DumpUIExtensionProviderRunningInfos(pid_t hostPid, std::vector<std::string> &info)
6686 {
6687 auto appMgr = AppMgrUtil::GetAppMgr();
6688 if (appMgr == nullptr) {
6689 TAG_LOGW(AAFwkTag::ABILITYMGR, "get appMgr failed");
6690 return;
6691 }
6692
6693 std::vector<pid_t> providerPids;
6694 auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionProviderPid(hostPid, providerPids));
6695 if (ret != ERR_OK) {
6696 TAG_LOGE(AAFwkTag::ABILITYMGR, "get process info failed");
6697 return;
6698 }
6699
6700 if (providerPids.size() == 0) {
6701 TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extension provider of pid %{public}d.", hostPid);
6702 return;
6703 }
6704
6705 std::string temp;
6706 for (size_t i = 0; i < providerPids.size(); i++) {
6707 temp = " uiextension provider #" + std::to_string(i);
6708 info.push_back(temp);
6709 temp = " pid #" + std::to_string(providerPids[i]);
6710 info.push_back(temp);
6711 }
6712 }
6713
DataDumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6714 void AbilityManagerService::DataDumpSysStateInner(
6715 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
6716 {
6717 std::shared_ptr<DataAbilityManager> targetManager;
6718 if (isUserID) {
6719 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6720 if (dataAbilityManager == nullptr) {
6721 info.push_back("error: No user found.");
6722 return;
6723 }
6724 targetManager = dataAbilityManager;
6725 } else {
6726 targetManager = GetCurrentDataAbilityManager();
6727 }
6728
6729 CHECK_POINTER(targetManager);
6730
6731 std::vector<std::string> argList;
6732 SplitStr(args, " ", argList);
6733 if (argList.empty()) {
6734 return;
6735 }
6736 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6737 targetManager->DumpSysState(info, isClient, argList[1]);
6738 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6739 targetManager->DumpSysState(info, isClient);
6740 } else {
6741 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
6742 }
6743 }
6744
DumpInner(const std::string & args,std::vector<std::string> & info)6745 void AbilityManagerService::DumpInner(const std::string &args, std::vector<std::string> &info)
6746 {
6747 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6748 auto uiAbilityManager = GetCurrentUIAbilityManager();
6749 CHECK_POINTER(uiAbilityManager);
6750 uiAbilityManager->Dump(info);
6751 return;
6752 }
6753
6754 auto missionListManager = GetCurrentMissionListManager();
6755 if (missionListManager) {
6756 missionListManager->Dump(info);
6757 }
6758 }
6759
DumpMissionListInner(const std::string & args,std::vector<std::string> & info)6760 void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector<std::string> &info)
6761 {
6762 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6763 auto uiAbilityManager = GetCurrentUIAbilityManager();
6764 CHECK_POINTER(uiAbilityManager);
6765 uiAbilityManager->DumpMissionList(info, false, " ");
6766 return;
6767 }
6768 auto missionListManager = GetCurrentMissionListManager();
6769 if (missionListManager) {
6770 missionListManager->DumpMissionList(info, false, "");
6771 }
6772 }
6773
DumpMissionInfosInner(const std::string & args,std::vector<std::string> & info)6774 void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)
6775 {
6776 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6777 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
6778 #ifdef SUPPORT_GRAPHICS
6779 Rosen::WindowManager::GetInstance().DumpSessionAll(info);
6780 #endif // SUPPORT_GRAPHICS
6781 return;
6782 }
6783 auto missionListManager = GetCurrentMissionListManager();
6784 if (missionListManager) {
6785 missionListManager->DumpMissionInfos(info);
6786 }
6787 }
6788
DumpMissionInner(const std::string & args,std::vector<std::string> & info)6789 void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector<std::string> &info)
6790 {
6791 std::vector<std::string> argList;
6792 SplitStr(args, " ", argList);
6793 if (argList.empty()) {
6794 return;
6795 }
6796 if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6797 info.push_back("error: invalid argument, please see 'ability dump -h'.");
6798 return;
6799 }
6800 int missionId = DEFAULT_INVAL_VALUE;
6801 (void)StrToInt(argList[1], missionId);
6802
6803 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6804 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
6805 #ifdef SUPPORT_GRAPHICS
6806 Rosen::WindowManager::GetInstance().DumpSessionWithId(missionId, info);
6807 #endif // SUPPORT_GRAPHICS
6808 return;
6809 }
6810
6811 auto missionListManager = GetCurrentMissionListManager();
6812 CHECK_POINTER_LOG(missionListManager, "Current mission manager not init.");
6813 missionListManager->DumpMission(missionId, info);
6814 }
6815
DumpStateInner(const std::string & args,std::vector<std::string> & info)6816 void AbilityManagerService::DumpStateInner(const std::string &args, std::vector<std::string> &info)
6817 {
6818 auto connectManager = GetCurrentConnectManager();
6819 CHECK_POINTER_LOG(connectManager, "Current mission manager not init.");
6820 std::vector<std::string> argList;
6821 SplitStr(args, " ", argList);
6822 if (argList.empty()) {
6823 return;
6824 }
6825 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6826 connectManager->DumpState(info, false, argList[1]);
6827 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6828 connectManager->DumpState(info, false);
6829 } else {
6830 info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
6831 }
6832 }
6833
DataDumpStateInner(const std::string & args,std::vector<std::string> & info)6834 void AbilityManagerService::DataDumpStateInner(const std::string &args, std::vector<std::string> &info)
6835 {
6836 auto dataAbilityManager = GetCurrentDataAbilityManager();
6837 CHECK_POINTER(dataAbilityManager);
6838 std::vector<std::string> argList;
6839 SplitStr(args, " ", argList);
6840 if (argList.empty()) {
6841 return;
6842 }
6843 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
6844 dataAbilityManager->DumpState(info, argList[1]);
6845 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
6846 dataAbilityManager->DumpState(info);
6847 } else {
6848 info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
6849 }
6850 }
6851
DumpState(const std::string & args,std::vector<std::string> & info)6852 void AbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
6853 {
6854 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6855 auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
6856 if (!isShellCall && !isHidumperServiceCall) {
6857 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
6858 return;
6859 }
6860 std::vector<std::string> argList;
6861 SplitStr(args, " ", argList);
6862 if (argList.empty()) {
6863 return;
6864 }
6865 auto key = DumpUtils::DumpMap(argList[0]);
6866 if (!key.first) {
6867 return;
6868 }
6869 switch (key.second) {
6870 case DumpUtils::KEY_DUMP_SERVICE:
6871 DumpStateInner(args, info);
6872 break;
6873 case DumpUtils::KEY_DUMP_DATA:
6874 DataDumpStateInner(args, info);
6875 break;
6876 case DumpUtils::KEY_DUMP_ALL:
6877 DumpInner(args, info);
6878 break;
6879 case DumpUtils::KEY_DUMP_MISSION:
6880 DumpMissionInner(args, info);
6881 break;
6882 case DumpUtils::KEY_DUMP_MISSION_LIST:
6883 DumpMissionListInner(args, info);
6884 break;
6885 case DumpUtils::KEY_DUMP_MISSION_INFOS:
6886 DumpMissionInfosInner(args, info);
6887 break;
6888 default:
6889 info.push_back("error: invalid argument, please see 'ability dump -h'.");
6890 break;
6891 }
6892 }
6893
DumpSysState(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)6894 void AbilityManagerService::DumpSysState(
6895 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
6896 {
6897 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
6898 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6899 auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
6900 if (!isShellCall && !isHidumperServiceCall) {
6901 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
6902 return;
6903 }
6904 std::vector<std::string> argList;
6905 SplitStr(args, " ", argList);
6906 if (argList.empty()) {
6907 return;
6908 }
6909 auto key = DumpUtils::DumpsysMap(argList[0]);
6910 if (!key.first) {
6911 return;
6912 }
6913 switch (key.second) {
6914 case DumpUtils::KEY_DUMP_SYS_ALL:
6915 DumpSysInner(args, info, isClient, isUserID, userId);
6916 break;
6917 case DumpUtils::KEY_DUMP_SYS_SERVICE:
6918 DumpSysStateInner(args, info, isClient, isUserID, userId);
6919 break;
6920 case DumpUtils::KEY_DUMP_SYS_PENDING:
6921 DumpSysPendingInner(args, info, isClient, isUserID, userId);
6922 break;
6923 case DumpUtils::KEY_DUMP_SYS_PROCESS:
6924 DumpSysProcess(args, info, isClient, isUserID, userId);
6925 break;
6926 case DumpUtils::KEY_DUMP_SYS_DATA:
6927 DataDumpSysStateInner(args, info, isClient, isUserID, userId);
6928 break;
6929 case DumpUtils::KEY_DUMP_SYS_MISSION_LIST:
6930 DumpSysMissionListInner(args, info, isClient, isUserID, userId);
6931 break;
6932 case DumpUtils::KEY_DUMP_SYS_ABILITY:
6933 DumpSysAbilityInner(args, info, isClient, isUserID, userId);
6934 break;
6935 default:
6936 info.push_back("error: invalid argument, please see 'ability dump -h'.");
6937 break;
6938 }
6939 }
6940
AbilityTransitionDone(const sptr<IRemoteObject> & token,int state,const PacMap & saveData)6941 int AbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
6942 {
6943 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6944 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
6945 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
6946 return ERR_INVALID_VALUE;
6947 }
6948 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6949 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
6950 auto callerPid = IPCSkeleton::GetCallingPid();
6951 TAG_LOGI(AAFwkTag::ABILITYMGR, "AbilityTransitionDone, ability:%{public}s, state:%{public}d, callerPid:%{public}d",
6952 abilityRecord->GetURI().c_str(), state, callerPid);
6953 if (!JudgeSelfCalled(abilityRecord)) {
6954 return CHECK_PERMISSION_FAILED;
6955 }
6956
6957 auto abilityInfo = abilityRecord->GetAbilityInfo();
6958 auto type = abilityInfo.type;
6959 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6960 // force timeout ability for test
6961 int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast<AbilityLifeCycleState>(state));
6962 bool isTerminate = abilityRecord->IsAbilityState(AbilityState::TERMINATING) && targetState == AbilityState::INITIAL;
6963 std::string tempState = isTerminate ? AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) :
6964 AbilityRecord::ConvertAbilityState(static_cast<AbilityState>(targetState));
6965 if (IsNeedTimeoutForTest(abilityInfo.name, tempState)) {
6966 TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability, state:%{public}s, ability:%{public}s",
6967 tempState.c_str(),
6968 abilityInfo.name.c_str());
6969 return ERR_OK;
6970 }
6971 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
6972 auto connectManager = GetConnectManagerByUserId(userId);
6973 if (!connectManager) {
6974 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6975 return ERR_INVALID_VALUE;
6976 }
6977 return connectManager->AbilityTransitionDone(token, state);
6978 }
6979 if (type == AppExecFwk::AbilityType::DATA) {
6980 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6981 if (!dataAbilityManager) {
6982 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
6983 return ERR_INVALID_VALUE;
6984 }
6985 return dataAbilityManager->AbilityTransitionDone(token, state);
6986 }
6987
6988 if (targetState == AbilityState::BACKGROUND) {
6989 std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of background lifecycle.";
6990 FreezeUtil::GetInstance().AddLifecycleEvent(token, entry);
6991 } else if (targetState != AbilityState::INITIAL) {
6992 std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of foreground lifecycle.";
6993 FreezeUtil::GetInstance().AddLifecycleEvent(token, entry);
6994 }
6995
6996 int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
6997 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6998 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
6999 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7000 return uiAbilityManager->AbilityTransactionDone(token, state, saveData);
7001 } else {
7002 auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
7003 if (!missionListManager) {
7004 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", ownerMissionUserId);
7005 return ERR_INVALID_VALUE;
7006 }
7007 return missionListManager->AbilityTransactionDone(token, state, saveData);
7008 }
7009 }
7010
AbilityWindowConfigTransitionDone(const sptr<IRemoteObject> & token,const WindowConfig & windowConfig)7011 int AbilityManagerService::AbilityWindowConfigTransitionDone(
7012 const sptr<IRemoteObject> &token, const WindowConfig &windowConfig)
7013 {
7014 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7015 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
7016 return ERR_INVALID_VALUE;
7017 }
7018 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7019 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record null.");
7020 if (!JudgeSelfCalled(abilityRecord)) {
7021 return CHECK_PERMISSION_FAILED;
7022 }
7023
7024 TAG_LOGI(AAFwkTag::ABILITYMGR, "ability:%{public}s", abilityRecord->GetURI().c_str());
7025 auto abilityInfo = abilityRecord->GetAbilityInfo();
7026 auto type = abilityInfo.extensionAbilityType;
7027 if (type != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
7028 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid type");
7029 return ERR_INVALID_VALUE;
7030 }
7031 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
7032 auto connectManager = GetConnectManagerByUserId(userId);
7033 if(!connectManager) {
7034 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
7035 return ERR_INVALID_VALUE;
7036 }
7037 return connectManager->AbilityWindowConfigTransactionDone(token, windowConfig);
7038 }
7039
ScheduleConnectAbilityDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & remoteObject)7040 int AbilityManagerService::ScheduleConnectAbilityDone(
7041 const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
7042 {
7043 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7044 TAG_LOGD(AAFwkTag::SERVICE_EXT, "called");
7045 if (!VerificationAllToken(token)) {
7046 return ERR_INVALID_VALUE;
7047 }
7048
7049 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7050 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7051 if (!JudgeSelfCalled(abilityRecord)) {
7052 return CHECK_PERMISSION_FAILED;
7053 }
7054
7055 auto type = abilityRecord->GetAbilityInfo().type;
7056 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
7057 TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability failed, target ability not service");
7058 return TARGET_ABILITY_NOT_SERVICE;
7059 }
7060 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
7061 auto connectManager = GetConnectManagerByUserId(userId);
7062 if (!connectManager) {
7063 TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", userId);
7064 return ERR_INVALID_VALUE;
7065 }
7066 return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject);
7067 }
7068
ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> & token)7069 int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
7070 {
7071 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7072 TAG_LOGD(AAFwkTag::SERVICE_EXT, "call");
7073 if (!VerificationAllToken(token)) {
7074 return ERR_INVALID_VALUE;
7075 }
7076
7077 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7078 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7079 if (!JudgeSelfCalled(abilityRecord)) {
7080 return CHECK_PERMISSION_FAILED;
7081 }
7082
7083 auto type = abilityRecord->GetAbilityInfo().type;
7084 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
7085 TAG_LOGE(AAFwkTag::SERVICE_EXT, "ability failed, target ability not service");
7086 return TARGET_ABILITY_NOT_SERVICE;
7087 }
7088 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
7089 auto connectManager = GetConnectManagerByUserId(userId);
7090 if (!connectManager) {
7091 TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId=%{public}d", userId);
7092 return ERR_INVALID_VALUE;
7093 }
7094 return connectManager->ScheduleDisconnectAbilityDoneLocked(token);
7095 }
7096
ScheduleCommandAbilityDone(const sptr<IRemoteObject> & token)7097 int AbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
7098 {
7099 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7100 TAG_LOGD(AAFwkTag::SERVICE_EXT, "Schedule command ability done.");
7101 if (!VerificationAllToken(token)) {
7102 return ERR_INVALID_VALUE;
7103 }
7104
7105 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7106 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7107 if (!JudgeSelfCalled(abilityRecord)) {
7108 return CHECK_PERMISSION_FAILED;
7109 }
7110 // force timeout ability for test
7111 if (IsNeedTimeoutForTest(abilityRecord->GetAbilityInfo().name, std::string("COMMAND"))) {
7112 TAG_LOGW(AAFwkTag::SERVICE_EXT, "force timeout ability, state:COMMAND, ability: %{public}s",
7113 abilityRecord->GetAbilityInfo().name.c_str());
7114 return ERR_OK;
7115 }
7116 auto type = abilityRecord->GetAbilityInfo().type;
7117 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
7118 TAG_LOGE(AAFwkTag::SERVICE_EXT, "failed, target ability not service");
7119 return TARGET_ABILITY_NOT_SERVICE;
7120 }
7121 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
7122 auto connectManager = GetConnectManagerByUserId(userId);
7123 if (!connectManager) {
7124 TAG_LOGE(AAFwkTag::SERVICE_EXT, "connectManager null userId = %{public}d", userId);
7125 return ERR_INVALID_VALUE;
7126 }
7127 return connectManager->ScheduleCommandAbilityDoneLocked(token);
7128 }
7129
ScheduleCommandAbilityWindowDone(const sptr<IRemoteObject> & token,const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd,AbilityCommand abilityCmd)7130 int AbilityManagerService::ScheduleCommandAbilityWindowDone(
7131 const sptr<IRemoteObject> &token,
7132 const sptr<SessionInfo> &sessionInfo,
7133 WindowCommand winCmd,
7134 AbilityCommand abilityCmd)
7135 {
7136 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7137 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter.");
7138 if (!VerificationAllToken(token)) {
7139 return ERR_INVALID_VALUE;
7140 }
7141
7142 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7143 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7144 if (!JudgeSelfCalled(abilityRecord)) {
7145 return CHECK_PERMISSION_FAILED;
7146 }
7147
7148 if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)
7149 && !UIExtensionUtils::IsWindowExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
7150 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not ui or window extension");
7151 return ERR_INVALID_VALUE;
7152 }
7153 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
7154 auto connectManager = GetConnectManagerByUserId(userId);
7155 if (!connectManager) {
7156 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
7157 return ERR_INVALID_VALUE;
7158 }
7159 return connectManager->ScheduleCommandAbilityWindowDone(token, sessionInfo, winCmd, abilityCmd);
7160 }
7161
OnAbilityRequestDone(const sptr<IRemoteObject> & token,const int32_t state)7162 void AbilityManagerService::OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)
7163 {
7164 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7165 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7166 CHECK_POINTER(abilityRecord);
7167 TAG_LOGI(AAFwkTag::ABILITYMGR, "OnAbilityRequestDone, bundleName: %{public}s, abilityName: %{public}s",
7168 abilityRecord->GetAbilityInfo().bundleName.c_str(), abilityRecord->GetAbilityInfo().name.c_str());
7169 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
7170
7171 auto type = abilityRecord->GetAbilityInfo().type;
7172 switch (type) {
7173 case AppExecFwk::AbilityType::DATA: {
7174 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
7175 if (!dataAbilityManager) {
7176 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
7177 return;
7178 }
7179 dataAbilityManager->OnAbilityRequestDone(token, state);
7180 break;
7181 }
7182 case AppExecFwk::AbilityType::SERVICE:
7183 case AppExecFwk::AbilityType::EXTENSION: {
7184 auto connectManager = GetConnectManagerByUserId(userId);
7185 if (!connectManager) {
7186 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
7187 return;
7188 }
7189 connectManager->OnAbilityRequestDone(token, state);
7190 break;
7191 }
7192 default: {
7193 int32_t ownerUserId = abilityRecord->GetOwnerMissionUserId();
7194 if (type == AppExecFwk::AbilityType::PAGE) {
7195 auto eventInfo = BuildEventInfoByAbilityRecord(abilityRecord);
7196 SendUIAbilityEvent(eventInfo, state);
7197 }
7198 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7199 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
7200 CHECK_POINTER(uiAbilityManager);
7201 uiAbilityManager->OnAbilityRequestDone(token, state);
7202 } else {
7203 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
7204 if (!missionListManager) {
7205 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", ownerUserId);
7206 return;
7207 }
7208 missionListManager->OnAbilityRequestDone(token, state);
7209 }
7210 break;
7211 }
7212 }
7213 }
7214
OnAppStateChanged(const AppInfo & info)7215 void AbilityManagerService::OnAppStateChanged(const AppInfo &info)
7216 {
7217 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7218 auto connectManager = GetCurrentConnectManager();
7219 CHECK_POINTER_LOG(connectManager, "Connect manager not init.");
7220 connectManager->OnAppStateChanged(info);
7221 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7222 auto uiAbilityManager = GetCurrentUIAbilityManager();
7223 CHECK_POINTER(uiAbilityManager);
7224 uiAbilityManager->OnAppStateChanged(info);
7225 } else {
7226 auto missionListManager = GetCurrentMissionListManager();
7227 CHECK_POINTER_LOG(missionListManager, "Current mission list manager not init.");
7228 missionListManager->OnAppStateChanged(info);
7229 }
7230 auto dataAbilityManager = GetCurrentDataAbilityManager();
7231 CHECK_POINTER(dataAbilityManager);
7232 dataAbilityManager->OnAppStateChanged(info);
7233
7234 auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
7235 CHECK_POINTER(residentProcessMgr);
7236 residentProcessMgr->OnAppStateChanged(info);
7237
7238 if (system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
7239 KeepAliveProcessManager::GetInstance().OnAppStateChanged(info);
7240 }
7241 KioskManager::GetInstance().OnAppStop(info);
7242 }
7243
GetEventHandler()7244 std::shared_ptr<AbilityEventHandler> AbilityManagerService::GetEventHandler()
7245 {
7246 return eventHandler_;
7247 }
7248
7249 // multi user scene
GetUserId() const7250 int32_t AbilityManagerService::GetUserId() const
7251 {
7252 if (userController_) {
7253 auto userId = userController_->GetCurrentUserId();
7254 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is %{public}d", userId);
7255 return userId;
7256 }
7257 return U0_USER_ID;
7258 }
7259 #ifndef DISABLE_LAUNCHER
StartHighestPriorityAbility(int32_t userId,bool isBoot,bool isAppRecovery)7260 int AbilityManagerService::StartHighestPriorityAbility(int32_t userId, bool isBoot, bool isAppRecovery)
7261 {
7262 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7263 auto bms = AbilityUtil::GetBundleManagerHelper();
7264 CHECK_POINTER_AND_RETURN(bms, BMS_NOT_CONNECTED);
7265
7266 /* Query the highest priority ability or extension ability, and start it. usually, it is OOBE or launcher */
7267 Want want;
7268 want.AddEntity(HIGHEST_PRIORITY_ABILITY_ENTITY);
7269 AppExecFwk::AbilityInfo abilityInfo;
7270 AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
7271 int attemptNums = 0;
7272 int64_t startTime = AbilityRuntime::TimeUtil::CurrentTimeMillis();
7273 int64_t bmsCntTime = 0;
7274 int64_t queryTime = 0;
7275 while (true) {
7276 bms->PreConnect();
7277 bmsCntTime = AbilityRuntime::TimeUtil::CurrentTimeMillis();
7278 if (IN_PROCESS_CALL(bms->ImplicitQueryInfoByPriority(want,
7279 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId,
7280 abilityInfo, extensionAbilityInfo))) {
7281 break;
7282 }
7283 TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting query highest priority ability info completed");
7284 ++attemptNums;
7285 if (!isBoot && attemptNums > SWITCH_ACCOUNT_TRY) {
7286 TAG_LOGE(AAFwkTag::ABILITYMGR, "query highest priority ability failed");
7287 return RESOLVE_ABILITY_ERR;
7288 }
7289 AbilityRequest abilityRequest;
7290 usleep(REPOLL_TIME_MICRO_SECONDS);
7291 }
7292 queryTime = AbilityRuntime::TimeUtil::CurrentTimeMillis();
7293
7294 if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
7295 TAG_LOGE(AAFwkTag::ABILITYMGR, "query highest priority ability failed");
7296 return RESOLVE_ABILITY_ERR;
7297 }
7298
7299 Want abilityWant; // donot use 'want' here, because the entity of 'want' is not empty
7300 if (!abilityInfo.name.empty()) {
7301 /* highest priority ability */
7302 TAG_LOGI(AAFwkTag::ABILITYMGR, "start highest priority ability bundleName:%{public}s, ability:%{public}s",
7303 abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
7304 abilityWant.SetElementName(abilityInfo.bundleName, abilityInfo.name);
7305 } else {
7306 /* highest priority extension ability */
7307 TAG_LOGI(AAFwkTag::ABILITYMGR,
7308 "start highest priority extension ability bundleName:%{public}s, ability:%{public}s,"
7309 "BMScntTime:%{public}" PRId64 " ms, queryTime:%{public}" PRId64 " ms",
7310 extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str(),
7311 bmsCntTime - startTime, queryTime - bmsCntTime);
7312 abilityWant.SetElementName(extensionAbilityInfo.bundleName, extensionAbilityInfo.name);
7313 }
7314
7315 #ifdef SUPPORT_GRAPHICS
7316 abilityWant.SetParam(NEED_STARTINGWINDOW, false);
7317 // wait BOOT_ANIMATION_STARTED to start LAUNCHER
7318 WaitBootAnimationStart();
7319 #endif
7320 if (isAppRecovery) {
7321 abilityWant.SetParam("ohos.app.logout_recovery", true);
7322 }
7323 /* note: OOBE APP need disable itself, otherwise, it will be started when restart system everytime */
7324 return StartAbility(abilityWant, userId, DEFAULT_INVAL_VALUE);
7325 }
7326 #endif
GenerateAbilityRequest(const Want & want,int requestCode,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)7327 int AbilityManagerService::GenerateAbilityRequest(const Want &want, int requestCode, AbilityRequest &request,
7328 const sptr<IRemoteObject> &callerToken, int32_t userId)
7329 {
7330 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7331 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7332 if (abilityRecord != nullptr) {
7333 request.callerTokenRecordId = abilityRecord->GetRecordId();
7334 }
7335 if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
7336 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
7337 (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
7338 (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
7339 }
7340
7341 int32_t appIndex = 0;
7342 (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
7343 if (abilityRecord != nullptr &&
7344 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName() &&
7345 abilityRecord->GetAppIndex() == appIndex) {
7346 (const_cast<Want &>(want)).SetParam(DEBUG_APP, abilityRecord->IsDebugApp());
7347 }
7348
7349 request.want = want;
7350 request.requestCode = requestCode;
7351 request.callerToken = callerToken;
7352 auto setting = AbilityStartSetting::GetEmptySetting();
7353 if (setting != nullptr) {
7354 setting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "false"); // default is false
7355 request.startSetting = std::make_shared<AbilityStartSetting>(*(setting.get()));
7356 }
7357
7358 auto abilityInfo = StartAbilityUtils::startAbilityInfo;
7359 if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
7360 int32_t appIndex = 0;
7361 if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
7362 return ERR_APP_CLONE_INDEX_INVALID;
7363 }
7364 Want localWant = want;
7365 if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
7366 localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
7367 localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
7368 localWant.RemoveParam(PARAM_RESV_ANCO_IS_NEED_UPDATE_NAME);
7369 localWant.SetParam(Want::PARAM_RESV_CALLER_TOKEN, static_cast<int32_t>(IPCSkeleton::GetCallingTokenID()));
7370 localWant.SetParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid());
7371 }
7372 abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(localWant, userId, appIndex, callerToken);
7373 }
7374 CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
7375 if (abilityInfo->status != ERR_OK) {
7376 return abilityInfo->status;
7377 }
7378 request.abilityInfo = abilityInfo->abilityInfo;
7379 request.extensionProcessMode = abilityInfo->extensionProcessMode;
7380 request.customProcess = abilityInfo->customProcess;
7381 request.collaboratorType = GetCollaboratorType(request.abilityInfo.applicationInfo.codePath);
7382
7383 if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) {
7384 TAG_LOGI(AAFwkTag::ABILITYMGR, "stage mode, abilityInfo SERVICE type reset EXTENSION");
7385 request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
7386 }
7387
7388 if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
7389 TAG_LOGE(AAFwkTag::ABILITYMGR, "get app info failed");
7390 return RESOLVE_APP_ERR;
7391 }
7392 if (want.GetIntParam(AAFwk::SCREEN_MODE_KEY, ScreenMode::IDLE_SCREEN_MODE) == ScreenMode::JUMP_SCREEN_MODE &&
7393 (request.abilityInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE ||
7394 request.abilityInfo.launchMode != AppExecFwk::LaunchMode::SINGLETON)) {
7395 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface of starting atomicService start only atomicService");
7396 return TARGET_ABILITY_NOT_SERVICE;
7397 }
7398 request.appInfo = request.abilityInfo.applicationInfo;
7399 request.uid = request.appInfo.uid;
7400 TAG_LOGD(AAFwkTag::ABILITYMGR,
7401 "GenerateAbilityRequest end, app name: %{public}s, moduleName name: %{public}s, uid: %{public}d.",
7402 request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid);
7403
7404 request.want.SetModuleName(request.abilityInfo.moduleName);
7405
7406 int32_t startRecent = AbilityPermissionUtil::GetInstance().CheckStartRecentAbility(want, request);
7407 if (startRecent != ERR_OK) {
7408 return startRecent;
7409 }
7410
7411 if (ModalSystemDialogUtil::CheckDebugAppNotInDeveloperMode(request.abilityInfo.applicationInfo)) {
7412 // local debug do not show dialog.
7413 if (AAFwk::PermissionVerification::GetInstance()->VerifyStartLocalDebug(IPCSkeleton::GetCallingTokenID())) {
7414 TAG_LOGD(AAFwkTag::ABILITYMGR, "local debug");
7415 return ERR_OK;
7416 }
7417 if (AAFwk::PermissionVerification::GetInstance()->VerifyStartLocalDebug(
7418 request.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0))) {
7419 TAG_LOGD(AAFwkTag::ABILITYMGR, "real call is local debug");
7420 return ERR_OK;
7421 }
7422 if (abilityRecord != nullptr) {
7423 std::string targetBundleName = request.want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
7424 std::string callerBundleName = abilityRecord->GetApplicationInfo().bundleName;
7425 if (targetBundleName.compare(callerBundleName) ==0) {
7426 TAG_LOGD(AAFwkTag::ABILITYMGR, "same bundle");
7427 return ERR_OK;
7428 }
7429 }
7430 // service and extension do not show dialog.
7431 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
7432 !(request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
7433 request.abilityInfo.type == AppExecFwk::AbilityType::EXTENSION)) {
7434 ModalSystemDialogUtil::ShowDeveloperModeDialog(
7435 request.abilityInfo.bundleName, request.abilityInfo.moduleName, request.abilityInfo.labelId, userId);
7436 }
7437 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer mode");
7438 return ERR_NOT_DEVELOPER_MODE;
7439 }
7440
7441 return ERR_OK;
7442 }
7443
GenerateExtensionAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)7444 int AbilityManagerService::GenerateExtensionAbilityRequest(
7445 const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
7446 {
7447 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7448 if (abilityRecord != nullptr) {
7449 request.callerTokenRecordId = abilityRecord->GetRecordId();
7450 }
7451 if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
7452 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
7453 (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
7454 (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
7455 }
7456 request.want = want;
7457 request.callerToken = callerToken;
7458 request.startSetting = nullptr;
7459
7460 auto abilityInfo = StartAbilityUtils::startAbilityInfo;
7461 if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
7462 int32_t appIndex = 0;
7463 if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
7464 return ERR_APP_CLONE_INDEX_INVALID;
7465 }
7466 abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, appIndex);
7467 }
7468 CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
7469 if (abilityInfo->status != ERR_OK) {
7470 return abilityInfo->status;
7471 }
7472 if (ModalSystemDialogUtil::CheckDebugAppNotInDeveloperMode(abilityInfo->abilityInfo.applicationInfo)) {
7473 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer mode");
7474 return ERR_NOT_DEVELOPER_MODE;
7475 }
7476 auto result = InitialAbilityRequest(request, *abilityInfo);
7477 return result;
7478 }
7479
InitialAbilityRequest(AbilityRequest & request,const StartAbilityInfo & abilityInfo) const7480 int32_t AbilityManagerService::InitialAbilityRequest(AbilityRequest &request,
7481 const StartAbilityInfo &abilityInfo) const
7482 {
7483 request.abilityInfo = abilityInfo.abilityInfo;
7484 request.extensionProcessMode = abilityInfo.extensionProcessMode;
7485 request.customProcess = abilityInfo.customProcess;
7486 if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
7487 TAG_LOGE(AAFwkTag::ABILITYMGR, "get app info failed");
7488 return RESOLVE_APP_ERR;
7489 }
7490 request.appInfo = request.abilityInfo.applicationInfo;
7491 request.uid = request.appInfo.uid;
7492 TAG_LOGD(AAFwkTag::ABILITYMGR,
7493 "GenerateExtensionAbilityRequest end, app name:%{public}s, bundle name:%{public}s, uid:%{public}d, moduleName:%{public}s",
7494 request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid, request.abilityInfo.moduleName.c_str());
7495
7496 request.want.SetModuleName(request.abilityInfo.moduleName);
7497
7498 return ERR_OK;
7499 }
7500
StopServiceAbility(const Want & want,int32_t userId,const sptr<IRemoteObject> & token)7501 int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)
7502 {
7503 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7504 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
7505 TAG_LOGD(AAFwkTag::ABILITYMGR, "call.");
7506
7507 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7508 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
7509 if (!isSaCall && !isShellCall) {
7510 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7511 if (abilityRecord == nullptr) {
7512 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord null");
7513 return ERR_INVALID_VALUE;
7514 }
7515 }
7516
7517 int32_t validUserId = GetValidUserId(userId);
7518 if (!JudgeMultiUserConcurrency(validUserId)) {
7519 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
7520 return ERR_CROSS_USER;
7521 }
7522
7523 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
7524 AbilityRequest abilityRequest;
7525 auto result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId);
7526 if (result != ERR_OK) {
7527 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
7528 return result;
7529 }
7530
7531 auto abilityInfo = abilityRequest.abilityInfo;
7532 validUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
7533 TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
7534 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
7535
7536 auto type = abilityInfo.type;
7537 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
7538 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not service type");
7539 return TARGET_ABILITY_NOT_SERVICE;
7540 }
7541
7542 auto res = JudgeAbilityVisibleControl(abilityInfo);
7543 if (res != ERR_OK) {
7544 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability invisible");
7545 return res;
7546 }
7547
7548 auto connectManager = GetConnectManagerByUserId(validUserId);
7549 if (connectManager == nullptr) {
7550 return ERR_INVALID_VALUE;
7551 }
7552
7553 return connectManager->StopServiceAbility(abilityRequest);
7554 }
7555
OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)7556 void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)
7557 {
7558 CHECK_POINTER(abilityRecord);
7559 TAG_LOGI(AAFwkTag::ABILITYMGR, "On ability died: %{public}s, %{public}d, %{public}" PRId64,
7560 abilityRecord->GetURI().c_str(), abilityRecord->GetRecordId(),
7561 abilityRecord->GetAbilityRecordId());
7562 if (abilityRecord->GetToken()) {
7563 FreezeUtil::GetInstance().DeleteLifecycleEvent(abilityRecord->GetToken()->AsObject());
7564 if (KioskManager::GetInstance().IsInKioskMode() &&
7565 KioskManager::GetInstance().IsInWhiteList(abilityRecord->GetAbilityInfo().bundleName)) {
7566 KioskManager::GetInstance().ExitKioskMode(abilityRecord->GetToken()->AsObject());
7567 }
7568 }
7569 FreezeUtil::GetInstance().DeleteAppLifecycleEvent(abilityRecord->GetPid());
7570 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7571 if (abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
7572 auto uiAbilityManager = GetUIAbilityManagerByUserId(abilityRecord->GetOwnerMissionUserId());
7573 CHECK_POINTER(uiAbilityManager);
7574 uiAbilityManager->OnAbilityDied(abilityRecord);
7575 return;
7576 }
7577 } else {
7578 auto manager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
7579 if (manager && abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
7580 ReleaseAbilityTokenMap(abilityRecord->GetToken());
7581 manager->OnAbilityDied(abilityRecord, GetUserId());
7582 return;
7583 }
7584 }
7585
7586 auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
7587 if (connectManager) {
7588 connectManager->OnAbilityDied(abilityRecord, GetUserId());
7589 return;
7590 } else {
7591 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager not found");
7592 }
7593
7594 auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken());
7595 if (dataAbilityManager) {
7596 dataAbilityManager->OnAbilityDied(abilityRecord);
7597 }
7598 }
7599
OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)7600 void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
7601 {
7602 CHECK_POINTER(callRecord);
7603 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7604 auto uiAbilityManager = GetCurrentUIAbilityManager();
7605 CHECK_POINTER(uiAbilityManager);
7606 uiAbilityManager->OnCallConnectDied(callRecord);
7607 return;
7608 }
7609 auto missionListManager = GetCurrentMissionListManager();
7610 if (missionListManager) {
7611 missionListManager->OnCallConnectDied(callRecord);
7612 }
7613 }
7614
ReleaseAbilityTokenMap(const sptr<IRemoteObject> & token)7615 void AbilityManagerService::ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)
7616 {
7617 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
7618 for (auto iter = callStubTokenMap_.begin(); iter != callStubTokenMap_.end(); iter++) {
7619 if (iter->second == token) {
7620 callStubTokenMap_.erase(iter);
7621 break;
7622 }
7623 }
7624 }
7625
CheckPermissionForKillCollaborator()7626 bool AbilityManagerService::CheckPermissionForKillCollaborator()
7627 {
7628 // check permission first
7629 auto isSaCall = PermissionVerification::GetInstance()->IsSACall();
7630 auto isShellCall = PermissionVerification::GetInstance()->IsShellCall();
7631 auto isCallingPerm = PermissionVerification::GetInstance()->VerifyCallingPermission(
7632 PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
7633 if (!isSaCall && !isShellCall && !isCallingPerm) {
7634 return false;
7635 }
7636 return true;
7637 }
7638
KillProcess(const std::string & bundleName,bool clearPageStack,int32_t appIndex)7639 int AbilityManagerService::KillProcess(const std::string &bundleName, bool clearPageStack, int32_t appIndex)
7640 {
7641 TAG_LOGI(AAFwkTag::ABILITYMGR, "Kill process, bundleName: %{public}s, clearPageStack: %{public}d",
7642 bundleName.c_str(), clearPageStack);
7643 // check permission first
7644 auto isAllowKillProcessForCollaborator = CheckPermissionForKillCollaborator();
7645 if (!isAllowKillProcessForCollaborator &&
7646 DelayedSingleton<AppScheduler>::GetInstance()->VerifyKillProcessPermission(bundleName) != ERR_OK) {
7647 TAG_LOGE(AAFwkTag::ABILITYMGR, "KillProcess permission verification fail");
7648 return ERR_PERMISSION_DENIED;
7649 }
7650
7651 auto bms = AbilityUtil::GetBundleManagerHelper();
7652 CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED);
7653 int32_t userId = GetUserId();
7654 AppExecFwk::BundleInfo bundleInfo;
7655 if (IN_PROCESS_CALL(bms->GetCloneBundleInfoExt(bundleName,
7656 static_cast<uint32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
7657 appIndex, userId, bundleInfo)) != ERR_OK) {
7658 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle info when kill process failed");
7659 return GET_BUNDLE_INFO_FAILED;
7660 }
7661
7662 int32_t collaboratorType = GetCollaboratorType(bundleInfo.applicationInfo.codePath);
7663 if (CheckCollaboratorType(collaboratorType)) {
7664 if (!isAllowKillProcessForCollaborator) {
7665 TAG_LOGE(AAFwkTag::APPMGR, "KillProcess permission verification fail");
7666 return ERR_PERMISSION_DENIED;
7667 }
7668 return KillProcessForCollaborator(collaboratorType, bundleName, userId);
7669 }
7670
7671 KeepAliveType type;
7672 if (KeepAliveUtils::IsKeepAliveBundle(bundleInfo, userId, type)
7673 && DelayedSingleton<AppScheduler>::GetInstance()->IsMemorySizeSufficent()) {
7674 TAG_LOGE(AAFwkTag::ABILITYMGR, "no kill alive process");
7675 return KILL_PROCESS_KEEP_ALIVE;
7676 }
7677
7678 int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName, clearPageStack, appIndex);
7679 return ret == ERR_OK ? ERR_OK : KILL_PROCESS_FAILED;
7680 }
7681
KillProcessForCollaborator(int32_t collaboratorType,const std::string & bundleName,int32_t userId)7682 int32_t AbilityManagerService::KillProcessForCollaborator(int32_t collaboratorType,
7683 const std::string &bundleName, int32_t userId)
7684 {
7685 TAG_LOGI(AAFwkTag::ABILITYMGR, "Collaborator kill");
7686 auto collaborator = GetCollaborator(collaboratorType);
7687 if (collaborator == nullptr) {
7688 TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator null");
7689 return KILL_PROCESS_FAILED;
7690 }
7691 if (collaborator->NotifyKillProcesses(bundleName, userId) != ERR_OK) {
7692 return KILL_PROCESS_FAILED;
7693 }
7694 return ERR_OK;
7695 }
7696
UninstallApp(const std::string & bundleName,int32_t uid)7697 int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid)
7698 {
7699 return UninstallApp(bundleName, uid, 0);
7700 }
7701
UninstallApp(const std::string & bundleName,int32_t uid,int32_t appIndex)7702 int32_t AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex)
7703 {
7704 TAG_LOGI(AAFwkTag::ABILITYMGR, "uninstall app, bundleName:%{public}s, uid=%{public}d, appIndex:%{public}d",
7705 bundleName.c_str(), uid, appIndex);
7706 return UninstallAppInner(bundleName, uid, appIndex, false, "");
7707 }
7708
UpgradeApp(const std::string & bundleName,const int32_t uid,const std::string & exitMsg,int32_t appIndex)7709 int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg,
7710 int32_t appIndex)
7711 {
7712 TAG_LOGI(AAFwkTag::ABILITYMGR,
7713 "upgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg:%{public}s, appIndex:%{public}d",
7714 bundleName.c_str(), uid, exitMsg.c_str(), appIndex);
7715 return UninstallAppInner(bundleName, uid, appIndex, true, exitMsg);
7716 }
7717
UninstallAppInner(const std::string & bundleName,const int32_t uid,int32_t appIndex,const bool isUpgrade,const std::string & exitMsg)7718 int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex,
7719 const bool isUpgrade, const std::string &exitMsg)
7720 {
7721 pid_t callingPid = IPCSkeleton::GetCallingPid();
7722 pid_t pid = getprocpid();
7723 if (callingPid != pid) {
7724 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: not bundleMgr", __func__);
7725 return CHECK_PERMISSION_FAILED;
7726 }
7727
7728 auto userId = uid / BASE_USER_RANGE;
7729 if (isUpgrade) {
7730 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
7731 AAFwk::ExitReason exitReason = { REASON_UPGRADE, exitMsg };
7732 appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
7733 IN_PROCESS_CALL_WITHOUT_RET(
7734 KeepAliveProcessManager::GetInstance().SaveAppSeriviceRestartAfterUpgrade(bundleName, uid));
7735 } else {
7736 IN_PROCESS_CALL_WITHOUT_RET(
7737 KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(bundleName, userId, false, true, false));
7738 if (userId == U1_USER_ID) {
7739 IN_PROCESS_CALL_WITHOUT_RET(KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(
7740 bundleName, false, true, false));
7741 }
7742 }
7743 IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppExecFwk::AppMgrClient>::
7744 GetInstance()->SetKeepAliveEnableState(bundleName, false, uid));
7745 auto connectManager = GetConnectManagerByUserId(userId);
7746 if (connectManager) {
7747 connectManager->UninstallApp(bundleName, uid);
7748 }
7749
7750 CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT);
7751 subManagersHelper_->UninstallApp(bundleName, uid);
7752 int ret = IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->NotifyUninstallOrUpgradeApp(bundleName,
7753 uid, isUpgrade));
7754 if (ret != ERR_OK) {
7755 return UNINSTALL_APP_FAILED;
7756 }
7757 if (!isUpgrade) {
7758 DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->DeleteAppExitReason(bundleName, uid,
7759 appIndex);
7760 }
7761 return ERR_OK;
7762 }
7763
PreLoadAppDataAbilities(const std::string & bundleName,const int32_t userId)7764 int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)
7765 {
7766 if (bundleName.empty()) {
7767 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name preloading");
7768 return ERR_INVALID_VALUE;
7769 }
7770
7771 ffrt::submit([weak = weak_from_this(), bundleName, userId]() {
7772 auto pthis = weak.lock();
7773 if (pthis == nullptr) {
7774 TAG_LOGE(AAFwkTag::ABILITYMGR, "pthis null");
7775 return;
7776 }
7777 pthis->PreLoadAppDataAbilitiesTask(bundleName, userId);
7778 }, ffrt::task_attr().timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
7779
7780 return ERR_OK;
7781 }
7782
PreLoadAppDataAbilitiesTask(const std::string & bundleName,const int32_t userId)7783 void AbilityManagerService::PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId)
7784 {
7785 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7786 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
7787 if (dataAbilityManager == nullptr) {
7788 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid data ability manager preloading");
7789 return;
7790 }
7791
7792 auto bms = AbilityUtil::GetBundleManagerHelper();
7793 CHECK_POINTER(bms);
7794
7795 AppExecFwk::BundleInfo bundleInfo;
7796 bool ret = IN_PROCESS_CALL(
7797 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
7798 if (!ret) {
7799 TAG_LOGE(AAFwkTag::ABILITYMGR,
7800 "get bundleInfo preloading failed, userId:%{public}d", userId);
7801 return;
7802 }
7803
7804 auto begin = system_clock::now();
7805 AbilityRequest dataAbilityRequest;
7806 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(dataAbilityRequest.want, nullptr);
7807 dataAbilityRequest.appInfo = bundleInfo.applicationInfo;
7808 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
7809 if (it->type != AppExecFwk::AbilityType::DATA) {
7810 continue;
7811 }
7812 if ((system_clock::now() - begin) >= DATA_ABILITY_START_TIMEOUT) {
7813 TAG_LOGE(AAFwkTag::ABILITYMGR, "app data ability preloading '%{public}s' timeout", bundleName.c_str());
7814 return;
7815 }
7816 dataAbilityRequest.abilityInfo = *it;
7817 dataAbilityRequest.uid = bundleInfo.uid;
7818 TAG_LOGD(AAFwkTag::ABILITYMGR, "App data ability preloading: '%{public}s.%{public}s'...",
7819 it->bundleName.c_str(), it->name.c_str());
7820
7821 auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false);
7822 if (dataAbility == nullptr) {
7823 TAG_LOGE(AAFwkTag::ABILITYMGR,
7824 "preload data ability failed '%{public}s.%{public}s'", it->bundleName.c_str(), it->name.c_str());
7825 return;
7826 }
7827 }
7828 }
7829
IsSystemUiApp(const AppExecFwk::AbilityInfo & info) const7830 bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const
7831 {
7832 if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) {
7833 return false;
7834 }
7835 return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR ||
7836 info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR ||
7837 info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME);
7838 }
7839
IsSystemUI(const std::string & bundleName) const7840 bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const
7841 {
7842 return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME;
7843 }
7844
HandleLoadTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)7845 void AbilityManagerService::HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
7846 {
7847 TAG_LOGD(AAFwkTag::ABILITYMGR, "load timeout %{public}" PRId64, abilityRecordId);
7848 if (isExtension) {
7849 auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
7850 if (connectManager != nullptr) {
7851 connectManager->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
7852 }
7853 return;
7854 }
7855
7856 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7857 auto uiAbilityManagers = GetUIAbilityManagers();
7858 for (auto& item : uiAbilityManagers) {
7859 if (item.second) {
7860 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
7861 }
7862 }
7863 return;
7864 }
7865 auto missionListManagers = GetMissionListManagers();
7866 for (auto& item : missionListManagers) {
7867 if (item.second) {
7868 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
7869 }
7870 }
7871 }
7872
HandleActiveTimeOut(int64_t abilityRecordId)7873 void AbilityManagerService::HandleActiveTimeOut(int64_t abilityRecordId)
7874 {
7875 TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle active timeout.");
7876 auto missionListManagers = GetMissionListManagers();
7877 for (auto& item : missionListManagers) {
7878 if (item.second) {
7879 item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecordId);
7880 }
7881 }
7882 }
7883
HandleInactiveTimeOut(int64_t abilityRecordId)7884 void AbilityManagerService::HandleInactiveTimeOut(int64_t abilityRecordId)
7885 {
7886 TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle inactive timeout.");
7887 auto missionListManagers = GetMissionListManagers();
7888 for (auto& item : missionListManagers) {
7889 if (item.second) {
7890 item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
7891 }
7892 }
7893 auto connectManagers = GetConnectManagers();
7894 for (auto& item : connectManagers) {
7895 if (item.second) {
7896 item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
7897 }
7898 }
7899 }
7900
HandleConnectTimeOut(int64_t abilityRecordId,bool isHalf)7901 void AbilityManagerService::HandleConnectTimeOut(int64_t abilityRecordId, bool isHalf)
7902 {
7903 TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle connect timeout.");
7904 auto connectManagers = GetConnectManagers();
7905 for (auto& item : connectManagers) {
7906 if (item.second) {
7907 item.second->OnTimeOut(AbilityManagerService::CONNECT_TIMEOUT_MSG, abilityRecordId, isHalf);
7908 }
7909 }
7910 }
7911
HandleForegroundTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)7912 void AbilityManagerService::HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
7913 {
7914 TAG_LOGD(AAFwkTag::ABILITYMGR, "foreground timeout %{public}" PRId64, abilityRecordId);
7915 if (isExtension) {
7916 auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
7917 if (connectManager != nullptr) {
7918 connectManager->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
7919 }
7920 return;
7921 }
7922
7923 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7924 auto uiAbilityManagers = GetUIAbilityManagers();
7925 for (auto& item : uiAbilityManagers) {
7926 if (item.second) {
7927 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
7928 }
7929 }
7930 return;
7931 }
7932 auto missionListManagers = GetMissionListManagers();
7933 for (auto& item : missionListManagers) {
7934 if (item.second) {
7935 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
7936 }
7937 }
7938 }
7939
HandleShareDataTimeOut(int64_t uniqueId)7940 void AbilityManagerService::HandleShareDataTimeOut(int64_t uniqueId)
7941 {
7942 WantParams wantParam;
7943 int32_t ret = GetShareDataPairAndReturnData(nullptr, ERR_TIMED_OUT, uniqueId, wantParam);
7944 if (ret) {
7945 TAG_LOGE(AAFwkTag::ABILITYMGR, "acqurieShareData failed");
7946 }
7947 }
7948
GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)7949 int32_t AbilityManagerService::GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,
7950 const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
7951 {
7952 TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d, wantParam size:%{public}d",
7953 resultCode, uniqueId, wantParam.Size());
7954 {
7955 std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
7956 auto it = iAcquireShareDataMap_.find(uniqueId);
7957 if (it != iAcquireShareDataMap_.end()) {
7958 auto shareDataPair = it->second;
7959 if (abilityRecord && shareDataPair.first != abilityRecord->GetAbilityRecordId()) {
7960 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is not the abilityRecord from request");
7961 return ERR_INVALID_VALUE;
7962 }
7963 auto callback = shareDataPair.second;
7964 if (!callback) {
7965 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback object null");
7966 return ERR_INVALID_VALUE;
7967 }
7968 auto ret = callback->AcquireShareDataDone(resultCode, wantParam);
7969 iAcquireShareDataMap_.erase(it);
7970 return ret;
7971 }
7972 }
7973 TAG_LOGE(AAFwkTag::ABILITYMGR, "iAcquireShareData null");
7974 return ERR_INVALID_VALUE;
7975 }
7976
VerificationToken(const sptr<IRemoteObject> & token)7977 bool AbilityManagerService::VerificationToken(const sptr<IRemoteObject> &token)
7978 {
7979 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token");
7980 auto dataAbilityManager = GetCurrentDataAbilityManager();
7981 CHECK_POINTER_RETURN_BOOL(dataAbilityManager);
7982 auto connectManager = GetCurrentConnectManager();
7983 CHECK_POINTER_RETURN_BOOL(connectManager);
7984 auto missionListManager = GetCurrentMissionListManager();
7985 CHECK_POINTER_RETURN_BOOL(missionListManager);
7986
7987 if (missionListManager->GetAbilityRecordByToken(token)) {
7988 return true;
7989 }
7990 if (missionListManager->GetAbilityFromTerminateList(token)) {
7991 return true;
7992 }
7993
7994 if (dataAbilityManager->GetAbilityRecordByToken(token)) {
7995 return true;
7996 }
7997
7998 if (connectManager->GetExtensionByTokenFromServiceMap(token)) {
7999 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
8000 return true;
8001 }
8002
8003 if (AbilityCacheManager::GetInstance().FindRecordByToken(token)) {
8004 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
8005 return true;
8006 }
8007
8008 if (connectManager->GetExtensionByTokenFromTerminatingMap(token)) {
8009 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
8010 return true;
8011 }
8012
8013 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify token failed");
8014 return false;
8015 }
8016
VerificationAllToken(const sptr<IRemoteObject> & token)8017 bool AbilityManagerService::VerificationAllToken(const sptr<IRemoteObject> &token)
8018 {
8019 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8020 CHECK_POINTER_AND_RETURN(subManagersHelper_, false);
8021 return subManagersHelper_->VerificationAllToken(token);
8022 }
8023
GetCurrentDataAbilityManager()8024 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetCurrentDataAbilityManager()
8025 {
8026 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8027 return subManagersHelper_->GetCurrentDataAbilityManager();
8028 }
8029
GetDataAbilityManager(const sptr<IAbilityScheduler> & scheduler)8030 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManager(
8031 const sptr<IAbilityScheduler> &scheduler)
8032 {
8033 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8034 return subManagersHelper_->GetDataAbilityManager(scheduler);
8035 }
8036
GetDataAbilityManagerByUserId(int32_t userId)8037 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId)
8038 {
8039 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8040 return subManagersHelper_->GetDataAbilityManagerByUserId(userId);
8041 }
8042
GetDataAbilityManagerByToken(const sptr<IRemoteObject> & token)8043 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByToken(
8044 const sptr<IRemoteObject> &token)
8045 {
8046 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8047 return subManagersHelper_->GetDataAbilityManagerByToken(token);
8048 }
8049
GetConnectManagers()8050 std::unordered_map<int, std::shared_ptr<AbilityConnectManager>> AbilityManagerService::GetConnectManagers()
8051 {
8052 if (subManagersHelper_ == nullptr) {
8053 TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
8054 return std::unordered_map<int, std::shared_ptr<AbilityConnectManager>>();
8055 }
8056 return subManagersHelper_->GetConnectManagers();
8057 }
8058
GetCurrentConnectManager()8059 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetCurrentConnectManager()
8060 {
8061 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8062 return subManagersHelper_->GetCurrentConnectManager();
8063 }
8064
GetConnectManagerByUserId(int32_t userId)8065 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByUserId(int32_t userId)
8066 {
8067 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8068 return subManagersHelper_->GetConnectManagerByUserId(userId);
8069 }
8070
GetConnectManagerByToken(const sptr<IRemoteObject> & token)8071 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByToken(
8072 const sptr<IRemoteObject> &token)
8073 {
8074 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8075 return subManagersHelper_->GetConnectManagerByToken(token);
8076 }
8077
GetConnectManagerByAbilityRecordId(const int64_t & abilityRecordId)8078 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByAbilityRecordId(
8079 const int64_t &abilityRecordId)
8080 {
8081 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8082 return subManagersHelper_->GetConnectManagerByAbilityRecordId(abilityRecordId);
8083 }
8084
GetCurrentPendingWantManager()8085 std::shared_ptr<PendingWantManager> AbilityManagerService::GetCurrentPendingWantManager()
8086 {
8087 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8088 return subManagersHelper_->GetCurrentPendingWantManager();
8089 }
8090
GetPendingWantManagerByUserId(int32_t userId)8091 std::shared_ptr<PendingWantManager> AbilityManagerService::GetPendingWantManagerByUserId(int32_t userId)
8092 {
8093 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8094 return subManagersHelper_->GetPendingWantManagerByUserId(userId);
8095 }
8096
GetMissionListManagers()8097 std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>> AbilityManagerService::GetMissionListManagers()
8098 {
8099 if (subManagersHelper_ == nullptr) {
8100 TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
8101 return std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>>();
8102 }
8103 return subManagersHelper_->GetMissionListManagers();
8104 }
8105
GetCurrentMissionListManager()8106 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetCurrentMissionListManager()
8107 {
8108 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8109 return subManagersHelper_->GetCurrentMissionListManager();
8110 }
8111
GetMissionListManagerByUserId(int32_t userId)8112 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetMissionListManagerByUserId(int32_t userId)
8113 {
8114 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8115 return subManagersHelper_->GetMissionListManagerByUserId(userId);
8116 }
8117
GetMissionListWrap()8118 std::shared_ptr<MissionListWrap> AbilityManagerService::GetMissionListWrap()
8119 {
8120 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8121 return subManagersHelper_->GetMissionListWrap();
8122 }
8123
GetUIAbilityManagers()8124 std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>> AbilityManagerService::GetUIAbilityManagers()
8125 {
8126 if (subManagersHelper_ == nullptr) {
8127 TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
8128 return std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>>();
8129 }
8130 return subManagersHelper_->GetUIAbilityManagers();
8131 }
8132
GetCurrentUIAbilityManager()8133 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetCurrentUIAbilityManager()
8134 {
8135 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8136 return subManagersHelper_->GetCurrentUIAbilityManager();
8137 }
8138
GetUIAbilityManagerByUserId(int32_t userId) const8139 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUserId(int32_t userId) const
8140 {
8141 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8142 return subManagersHelper_->GetUIAbilityManagerByUserId(userId);
8143 }
8144
GetUIAbilityManagerByUid(int32_t uid)8145 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUid(int32_t uid)
8146 {
8147 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
8148 return subManagersHelper_->GetUIAbilityManagerByUid(uid);
8149 }
8150
StartResidentApps(int32_t userId)8151 void AbilityManagerService::StartResidentApps(int32_t userId)
8152 {
8153 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps %{public}d", userId);
8154 ConnectServices();
8155 auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
8156 CHECK_POINTER(residentProcessManager);
8157 std::vector<AppExecFwk::BundleInfo> bundleInfos;
8158 if (!residentProcessManager->GetResidentBundleInfosForUser(bundleInfos, userId)) {
8159 TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident bundleinfos failed");
8160 return;
8161 }
8162 residentProcessManager->Init();
8163 TAG_LOGI(AAFwkTag::ABILITYMGR, "startResidentApps getBundleInfos size:%{public}zu", bundleInfos.size());
8164
8165 residentProcessManager->StartResidentProcessWithMainElement(bundleInfos, userId);
8166 if (!bundleInfos.empty()) {
8167 #ifdef SUPPORT_GRAPHICS
8168 if (userId == U0_USER_ID) {
8169 WaitBootAnimationStart();
8170 }
8171 #endif
8172 residentProcessManager->StartResidentProcess(bundleInfos);
8173 }
8174 }
8175
StartKeepAliveApps(int32_t userId)8176 void AbilityManagerService::StartKeepAliveApps(int32_t userId)
8177 {
8178 if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
8179 return;
8180 }
8181 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps %{public}d", userId);
8182 ConnectServices();
8183 std::vector<AppExecFwk::BundleInfo> bundleInfos;
8184 if (!KeepAliveProcessManager::GetInstance().GetKeepAliveBundleInfosForUser(
8185 bundleInfos, userId)) {
8186 TAG_LOGE(AAFwkTag::ABILITYMGR, "get keep-alive bundle info failed");
8187 return;
8188 }
8189 KeepAliveProcessManager::GetInstance().FilterNeedRestartKeepAliveBundleInfos(bundleInfos);
8190 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps getBundleInfos size:%{public}zu", bundleInfos.size());
8191
8192 KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfos, userId);
8193 }
8194
StartAutoStartupApps()8195 void AbilityManagerService::StartAutoStartupApps()
8196 {
8197 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
8198 if (abilityAutoStartupService_ == nullptr) {
8199 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
8200 return;
8201 }
8202 std::vector<AutoStartupInfo> infoList;
8203 int32_t result = abilityAutoStartupService_->QueryAllAutoStartupApplicationsWithoutPermission(infoList,
8204 GetUserId());
8205 if (result != ERR_OK) {
8206 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed query data");
8207 return;
8208 }
8209
8210 if (taskHandler_ == nullptr) {
8211 TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler null");
8212 return;
8213 }
8214 std::queue<AutoStartupInfo> infoQueue;
8215 for (auto &info : infoList) {
8216 info.retryCount = START_AUTO_START_APP_RETRY_MAX_TIMES;
8217 infoQueue.push(info);
8218 }
8219 StartAutoStartupApps(infoQueue);
8220 }
8221
StartAutoStartupApps(std::queue<AutoStartupInfo> infoQueue)8222 void AbilityManagerService::StartAutoStartupApps(std::queue<AutoStartupInfo> infoQueue)
8223 {
8224 if (infoQueue.empty()) {
8225 return;
8226 }
8227 if (taskHandler_ == nullptr) {
8228 TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler null");
8229 return;
8230 }
8231 auto info = infoQueue.front();
8232 infoQueue.pop();
8233 AppExecFwk::ElementName element;
8234 element.SetBundleName(info.bundleName);
8235 element.SetAbilityName(info.abilityName);
8236 element.SetModuleName(info.moduleName);
8237 Want want;
8238 want.SetElement(element);
8239 want.SetParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, true);
8240 if (info.appCloneIndex >= 0 && info.appCloneIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
8241 want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, info.appCloneIndex);
8242 }
8243 int32_t result = ERR_OK;
8244 if (info.abilityTypeName == AbilityRuntime::EXTENSION_TYPE_APP_SERVICE) {
8245 result = StartExtensionAbility(
8246 want, nullptr, DEFAULT_INVAL_VALUE, AppExecFwk::ExtensionAbilityType::APP_SERVICE);
8247 } else {
8248 result = StartAbility(want);
8249 }
8250 if ((result != ERR_OK) && (info.retryCount > 0)) {
8251 info.retryCount--;
8252 infoQueue.push(info);
8253 }
8254 auto nextStartAutoStartupAppsTask = [aams = weak_from_this(), infoQueue]() {
8255 auto obj = aams.lock();
8256 if (obj == nullptr) {
8257 TAG_LOGE(AAFwkTag::ABILITYMGR, "start auto startup app error, obj null");
8258 return;
8259 }
8260 obj->StartAutoStartupApps(infoQueue);
8261 };
8262 taskHandler_->SubmitTask(nextStartAutoStartupAppsTask, "StartAutoStartupApps", START_AUTO_START_APP_DELAY_TIME);
8263 }
8264
SubscribeScreenUnlockedEvent()8265 void AbilityManagerService::SubscribeScreenUnlockedEvent()
8266 {
8267 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
8268 // add listen screen unlocked.
8269 EventFwk::MatchingSkills matchingSkills;
8270 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
8271 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
8272 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
8273 subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
8274 screenSubscriber_ = std::make_shared<AbilityRuntime::AbilityManagerEventSubscriber>(subscribeInfo,
8275 GetScreenUnlockCallback(), GetUserScreenUnlockCallback());
8276 bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber_);
8277 if (!subResult) {
8278 RetrySubscribeScreenUnlockedEvent(RETRY_COUNT);
8279 }
8280 }
8281
GetScreenUnlockCallback()8282 std::function<void()> AbilityManagerService::GetScreenUnlockCallback()
8283 {
8284 auto screenUnlockCallback = [abilityManager = weak_from_this()]() {
8285 TAG_LOGI(AAFwkTag::ABILITYMGR, "on screen unlocked");
8286 auto abilityMgr = abilityManager.lock();
8287 if (abilityMgr == nullptr) {
8288 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
8289 return;
8290 }
8291 auto taskHandler = abilityMgr->GetTaskHandler();
8292 if (taskHandler == nullptr) {
8293 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid taskHandler pointer");
8294 return;
8295 }
8296 auto screenUnlockTask = [abilityManager]() {
8297 auto abilityMgr = abilityManager.lock();
8298 if (abilityMgr == nullptr) {
8299 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
8300 return;
8301 }
8302 abilityMgr->RemoveScreenUnlockInterceptor();
8303 abilityMgr->UnSubscribeScreenUnlockedEvent();
8304 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartFailedResidentAbilities();
8305 };
8306 taskHandler->SubmitTask(screenUnlockTask, "ScreenUnlockTask");
8307 auto delayStartAutoStartupAppTask = [abilityManager]() {
8308 auto abilityMgr = abilityManager.lock();
8309 if (abilityMgr == nullptr) {
8310 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
8311 return;
8312 }
8313 abilityMgr->StartAutoStartupApps();
8314 };
8315 taskHandler->SubmitTask(delayStartAutoStartupAppTask, "DelayStartAutoStartupApps",
8316 START_AUTO_START_APP_DELAY_TIME);
8317 };
8318 return screenUnlockCallback;
8319 }
8320
GetUserScreenUnlockCallback()8321 std::function<void()> AbilityManagerService::GetUserScreenUnlockCallback()
8322 {
8323 auto userScreenUnlockCallback = [abilityManager = weak_from_this()]() {
8324 TAG_LOGD(AAFwkTag::ABILITYMGR, "On user screen unlocked.");
8325 auto abilityMgr = abilityManager.lock();
8326 if (abilityMgr == nullptr) {
8327 TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
8328 return;
8329 }
8330 abilityMgr->RemoveScreenUnlockInterceptor();
8331 };
8332 return userScreenUnlockCallback;
8333 }
8334
UnSubscribeScreenUnlockedEvent()8335 void AbilityManagerService::UnSubscribeScreenUnlockedEvent()
8336 {
8337 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
8338 bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_);
8339 TAG_LOGD(AAFwkTag::ABILITYMGR, "Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult);
8340 }
8341
RetrySubscribeScreenUnlockedEvent(int32_t retryCount)8342 void AbilityManagerService::RetrySubscribeScreenUnlockedEvent(int32_t retryCount)
8343 {
8344 TAG_LOGD(AAFwkTag::ABILITYMGR, "RetryCount: %{public}d.", retryCount);
8345 auto retrySubscribeScreenUnlockedEventTask = [aams = weak_from_this(), screenSubscriber = screenSubscriber_,
8346 retryCount]() {
8347 bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber);
8348 auto obj = aams.lock();
8349 if (obj == nullptr) {
8350 TAG_LOGE(AAFwkTag::ABILITYMGR, "retry subscribe screen unlocked event, obj null");
8351 return;
8352 }
8353 if (!subResult && retryCount > 0) {
8354 obj->RetrySubscribeScreenUnlockedEvent(retryCount - 1);
8355 }
8356 };
8357 constexpr int32_t delaytime = 200 * 1000; // us
8358 ffrt::submit(std::move(retrySubscribeScreenUnlockedEventTask),
8359 ffrt::task_attr().delay(delaytime).name("RetrySubscribeScreenUnlockedEvent")
8360 .timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
8361 }
8362
RemoveScreenUnlockInterceptor()8363 void AbilityManagerService::RemoveScreenUnlockInterceptor()
8364 {
8365 if (interceptorExecuter_ != nullptr) {
8366 interceptorExecuter_->RemoveInterceptor("ScreenUnlock");
8367 }
8368 }
8369
RemoveUnauthorizedLaunchReasonMessage(const Want & want,AbilityRequest & abilityRequest,uint32_t callerTokenId)8370 void AbilityManagerService::RemoveUnauthorizedLaunchReasonMessage(const Want &want, AbilityRequest &abilityRequest,
8371 uint32_t callerTokenId)
8372 {
8373 std::string value = want.GetStringParam(Want::PARM_LAUNCH_REASON_MESSAGE);
8374 TAG_LOGD(AAFwkTag::ABILITYMGR, "launchReasonMessage:%{public}s", value.c_str());
8375 if (!AppUtils::GetInstance().IsSystemReasonMessage(value)) {
8376 TAG_LOGW(AAFwkTag::ABILITYMGR, "not allow, remove");
8377 (const_cast<Want &>(want)).RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
8378 abilityRequest.want.RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
8379 return;
8380 }
8381 if (!PermissionVerification::GetInstance()->VerifyPermissionByTokenId(callerTokenId,
8382 PermissionConstants::PERMISSION_SET_LAUNCH_REASON_MESSAGE) ||
8383 (!PermissionVerification::GetInstance()->IsSystemAppCall() &&
8384 !PermissionVerification::GetInstance()->IsSACall())) {
8385 TAG_LOGD(AAFwkTag::ABILITYMGR, "verifyPermission failed, remove launch reason message.");
8386 (const_cast<Want &>(want)).RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
8387 abilityRequest.want.RemoveParam(Want::PARM_LAUNCH_REASON_MESSAGE);
8388 }
8389 }
8390
ConnectServices()8391 void AbilityManagerService::ConnectServices()
8392 {
8393 TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting appMgr service run completed");
8394 while (!DelayedSingleton<AppScheduler>::GetInstance()->Init(shared_from_this())) {
8395 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed init appScheduler");
8396 usleep(REPOLL_TIME_MICRO_SECONDS);
8397 }
8398
8399 TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting bundleMgr service run completed");
8400 while (AbilityUtil::GetBundleManagerHelper() == nullptr) {
8401 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle manager helper failed");
8402 usleep(REPOLL_TIME_MICRO_SECONDS);
8403 }
8404 AbilityUtil::GetBundleManagerHelper()->ConnectTillSuccess();
8405 TAG_LOGI(AAFwkTag::ABILITYMGR, "bms success");
8406 }
8407
GetWantSenderInfo(const sptr<IWantSender> & target,std::shared_ptr<WantSenderInfo> & info)8408 int AbilityManagerService::GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)
8409 {
8410 TAG_LOGI(AAFwkTag::ABILITYMGR, "get pending request info");
8411 auto pendingWantManager = GetCurrentPendingWantManager();
8412 CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
8413 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
8414 CHECK_POINTER_AND_RETURN(info, ERR_INVALID_VALUE);
8415 return pendingWantManager->GetWantSenderInfo(target, info);
8416 }
8417
GetAppMemorySize()8418 int AbilityManagerService::GetAppMemorySize()
8419 {
8420 TAG_LOGI(AAFwkTag::ABILITYMGR, "service getAppMemorySize start");
8421 const char *key = "const.product.arkheaplimit";
8422 const char *def = "512m";
8423 char *valueGet = nullptr;
8424 unsigned int len = 128;
8425 int ret = GetParameter(key, def, valueGet, len);
8426 int resultInt = 0;
8427 if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
8428 if (valueGet == nullptr) {
8429 TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, valueGet null", __func__);
8430 return APP_MEMORY_SIZE;
8431 }
8432 int len = strlen(valueGet);
8433 for (int i = 0; i < len; i++) {
8434 if (valueGet[i] >= '0' && valueGet[i] <= '9') {
8435 resultInt *= SIZE_10;
8436 resultInt += valueGet[i] - '0';
8437 }
8438 }
8439 if (resultInt == 0) {
8440 return APP_MEMORY_SIZE;
8441 }
8442 return resultInt;
8443 }
8444 return APP_MEMORY_SIZE;
8445 }
8446
IsRamConstrainedDevice()8447 bool AbilityManagerService::IsRamConstrainedDevice()
8448 {
8449 TAG_LOGI(AAFwkTag::ABILITYMGR, "service IsRamConstrainedDevice start");
8450 const char *key = "const.product.islowram";
8451 const char *def = "0";
8452 char *valueGet = nullptr;
8453 unsigned int len = 128;
8454 int ret = GetParameter(key, def, valueGet, len);
8455 if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
8456 int value = atoi(valueGet);
8457 if (value) {
8458 return true;
8459 }
8460 return false;
8461 }
8462 return false;
8463 }
8464
GetMissionIdByAbilityToken(const sptr<IRemoteObject> & token)8465 int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)
8466 {
8467 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8468 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8469 if (!abilityRecord) {
8470 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
8471 return -1;
8472 }
8473 if (!JudgeSelfCalled(abilityRecord)) {
8474 return -1;
8475 }
8476 return GetMissionIdByAbilityTokenInner(token);
8477 }
8478
GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> & token)8479 int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)
8480 {
8481 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8482 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8483 if (!abilityRecord) {
8484 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
8485 return -1;
8486 }
8487 auto userId = abilityRecord->GetOwnerMissionUserId();
8488 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8489 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
8490 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
8491 return uiAbilityManager->GetSessionIdByAbilityToken(token);
8492 }
8493 auto missionListManager = GetMissionListManagerByUserId(userId);
8494 if (!missionListManager) {
8495 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null mission userId=%{public}d", userId);
8496 return -1;
8497 }
8498 return missionListManager->GetMissionIdByAbilityToken(token);
8499 }
8500
GetAbilityTokenByMissionId(int32_t missionId)8501 sptr<IRemoteObject> AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId)
8502 {
8503 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8504 auto missionListManager = GetCurrentMissionListManager();
8505 if (!missionListManager) {
8506 return nullptr;
8507 }
8508 return missionListManager->GetAbilityTokenByMissionId(missionId);
8509 }
8510
StartRemoteAbilityByCall(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)8511 int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken,
8512 const sptr<IRemoteObject> &connect)
8513 {
8514 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin startRemoteAbilityByCall", __func__);
8515 Want remoteWant = want;
8516 UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(remoteWant, callerToken);
8517 if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
8518 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
8519 return ERR_INVALID_VALUE;
8520 }
8521 int32_t missionId = -1;
8522 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8523 missionId = GetMissionIdByAbilityTokenInner(callerToken);
8524 if (!missionId) {
8525 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
8526 return ERR_INVALID_VALUE;
8527 }
8528 } else {
8529 missionId = GetMissionIdByAbilityToken(callerToken);
8530 }
8531 if (missionId < 0) {
8532 return ERR_INVALID_VALUE;
8533 }
8534 remoteWant.SetParam(DMS_MISSION_ID, missionId);
8535 DistributedClient dmsClient;
8536 return dmsClient.StartRemoteAbilityByCall(remoteWant, connect);
8537 }
8538
ReleaseRemoteAbility(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element)8539 int AbilityManagerService::ReleaseRemoteAbility(const sptr<IRemoteObject> &connect,
8540 const AppExecFwk::ElementName &element)
8541 {
8542 DistributedClient dmsClient;
8543 return dmsClient.ReleaseRemoteAbility(connect, element);
8544 }
8545
StartAbilityByCall(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId,bool isSilent)8546 int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect,
8547 const sptr<IRemoteObject> &callerToken, int32_t accountId, bool isSilent)
8548 {
8549 std::string errMsg;
8550 return StartAbilityByCallWithErrMsg(want, connect, callerToken, accountId, errMsg, isSilent);
8551 }
8552
StartAbilityByCallWithErrMsg(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId,std::string & errMsg,bool isSilent)8553 int AbilityManagerService::StartAbilityByCallWithErrMsg(const Want &want, const sptr<IAbilityConnection> &connect,
8554 const sptr<IRemoteObject> &callerToken, int32_t accountId, std::string &errMsg, bool isSilent)
8555 {
8556 if (AppUtils::GetInstance().IsForbidStart()) {
8557 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
8558 return INNER_ERR;
8559 }
8560 XCOLLIE_TIMER_LESS_IGNORE(__PRETTY_FUNCTION__, !want.GetElement().GetDeviceID().empty());
8561 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
8562 int paramCheckResult = AbilityStartByCallHelper::CheckParam(connect, errMsg);
8563 if (paramCheckResult != ERR_OK) {
8564 return paramCheckResult;
8565 }
8566
8567 if (IsCrossUserCall(accountId)) {
8568 CHECK_CALLER_IS_SYSTEM_APP;
8569 }
8570
8571 if (VerifyAccountPermission(accountId) == CHECK_PERMISSION_FAILED) {
8572 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
8573 errMsg = "verify account permission failed";
8574 return CHECK_PERMISSION_FAILED;
8575 }
8576
8577 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8578 if (abilityRecord && !JudgeSelfCalled(abilityRecord)) {
8579 errMsg = "verify account permission failed";
8580 return CHECK_PERMISSION_FAILED;
8581 }
8582
8583 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
8584 int32_t appIndex = 0;
8585 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
8586 errMsg = "app index is error";
8587 return ERR_APP_CLONE_INDEX_INVALID;
8588 }
8589 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
8590 GetUserId(), appIndex, callerToken, false);
8591 if (checkRet != ERR_OK) {
8592 return checkRet;
8593 }
8594
8595 #ifdef SUPPORT_SCREEN
8596 DmsUtil::GetInstance().UpdateFlagForCollaboration(want);
8597 #endif
8598
8599 StartAbilityInfoWrap threadLocalInfo(want, GetUserId(), appIndex, callerToken);
8600 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
8601 isSilent = want.GetBoolParam(Want::PARAM_RESV_CALL_TO_FOREGROUND, false) ? true : !isSilent;
8602 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), isSilent, nullptr,
8603 shouldBlockFunc);
8604 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
8605 interceptorExecuter_->DoProcess(interceptorParam);
8606 if (result != ERR_OK) {
8607 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
8608 return result;
8609 }
8610
8611 if (CheckIfOperateRemote(want)) {
8612 TAG_LOGI(AAFwkTag::ABILITYMGR, "start remote ability by call");
8613 return StartRemoteAbilityByCall(want, callerToken, connect->AsObject());
8614 }
8615
8616 if (accountId == U0_USER_ID) {
8617 accountId = DEFAULT_INVAL_VALUE;
8618 }
8619 int32_t oriValidUserId = GetValidUserId(accountId);
8620 if (!JudgeMultiUserConcurrency(oriValidUserId)) {
8621 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
8622 return ERR_CROSS_USER;
8623 }
8624
8625 AbilityRequest abilityRequest;
8626 abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
8627 abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
8628 abilityRequest.callerToken = callerToken;
8629 abilityRequest.want = want;
8630 abilityRequest.connect = connect;
8631 result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
8632 if (result != ERR_OK) {
8633 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request error");
8634 return result;
8635 }
8636
8637 if (!HandleExecuteSAInterceptor(want, callerToken, abilityRequest, result)) {
8638 return result;
8639 }
8640
8641 if (!abilityRequest.abilityInfo.isStageBasedModel) {
8642 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not stage base model");
8643 return RESOLVE_CALL_ABILITY_VERSION_ERR;
8644 }
8645
8646 result = CheckStartByCallPermission(abilityRequest);
8647 if (result != ERR_OK) {
8648 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStartByCallPermission fail, result:%{public}d", result);
8649 return result;
8650 }
8651
8652 TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityInfo.applicationInfo.singleton is %{public}s",
8653 abilityRequest.abilityInfo.applicationInfo.singleton ? "true" : "false");
8654 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
8655 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
8656 false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityRequest.abilityInfo), false, appIndex);
8657 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
8658 afterCheckExecuter_->DoProcess(afterCheckParam);
8659 if (result != ERR_OK) {
8660 errMsg = "afterCheckParam is nullptr";
8661 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
8662 return result;
8663 }
8664 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
8665 RemoveUnauthorizedLaunchReasonMessage(want, abilityRequest, callerTokenId);
8666 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8667 abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
8668 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
8669 if (uiAbilityManager == nullptr) {
8670 TAG_LOGE(AAFwkTag::ABILITYMGR, "uiAbilityManager null, userId is invalid:%{public}d", oriValidUserId);
8671 errMsg = "uiAbilityManager null, userId is invalid";
8672 return ERR_INVALID_VALUE;
8673 }
8674 return uiAbilityManager->ResolveLocked(abilityRequest, errMsg);
8675 }
8676
8677 auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
8678 if (missionListMgr == nullptr) {
8679 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null designated user id=%{public}d", oriValidUserId);
8680 errMsg = "userId is not invalid";
8681 return ERR_INVALID_VALUE;
8682 }
8683 ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
8684
8685 return missionListMgr->ResolveLocked(abilityRequest);
8686 }
8687
StartAbilityJust(AbilityRequest & abilityRequest,int32_t validUserId)8688 int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)
8689 {
8690 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8691 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
8692 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
8693 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8694 auto uiAbilityManager = GetUIAbilityManagerByUserId(validUserId);
8695 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
8696 std::string errMsg;
8697 return uiAbilityManager->ResolveLocked(abilityRequest, errMsg);
8698 }
8699
8700 auto missionListMgr = GetMissionListManagerByUserId(validUserId);
8701 if (missionListMgr == nullptr) {
8702 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null designated userId=%{public}d", validUserId);
8703 return ERR_INVALID_VALUE;
8704 }
8705 ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
8706
8707 return missionListMgr->ResolveLocked(abilityRequest);
8708 }
8709
ReleaseCall(const sptr<IAbilityConnection> & connect,const AppExecFwk::ElementName & element)8710 int AbilityManagerService::ReleaseCall(
8711 const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
8712 {
8713 TAG_LOGD(AAFwkTag::ABILITYMGR, "Release called ability.");
8714
8715 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
8716 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
8717
8718 std::string elementName = element.GetURI();
8719 TAG_LOGD(AAFwkTag::ABILITYMGR, "try to release called ability, name: %{public}s.", elementName.c_str());
8720
8721 if (CheckIsRemote(element.GetDeviceID())) {
8722 TAG_LOGI(AAFwkTag::ABILITYMGR, "release remote ability");
8723 return ReleaseRemoteAbility(connect->AsObject(), element);
8724 }
8725
8726 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8727 auto uiAbilityManager = GetCurrentUIAbilityManager();
8728 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
8729 return uiAbilityManager->ReleaseCallLocked(connect, element);
8730 }
8731 auto missionListManager = GetCurrentMissionListManager();
8732 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8733 return missionListManager->ReleaseCallLocked(connect, element);
8734 }
8735
JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo & abilityInfo)8736 int AbilityManagerService::JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)
8737 {
8738 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
8739 if (abilityInfo.visible) {
8740 return ERR_OK;
8741 }
8742 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
8743 if (callerTokenId == abilityInfo.applicationInfo.accessTokenId ||
8744 callerTokenId == static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID())) { // foundation call is allowed
8745 return ERR_OK;
8746 }
8747 if (AccessTokenKit::VerifyAccessToken(callerTokenId,
8748 PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == AppExecFwk::Constants::PERMISSION_GRANTED) {
8749 return ERR_OK;
8750 }
8751 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken:%{private}u, targetToken:%{private}u, caller without permission",
8752 callerTokenId, abilityInfo.applicationInfo.accessTokenId);
8753 return ABILITY_VISIBLE_FALSE_DENY_REQUEST;
8754 }
8755
StartUser(int userId,sptr<IUserCallback> callback,bool isAppRecovery)8756 int AbilityManagerService::StartUser(int userId, sptr<IUserCallback> callback, bool isAppRecovery)
8757 {
8758 TAG_LOGI(AAFwkTag::ABILITYMGR, "startUser in service:%{public}d", userId);
8759 if (callback == nullptr) {
8760 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUser callback is nullptr");
8761 return INVALID_PARAMETERS_ERR;
8762 }
8763 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
8764 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUser permission verification failed, not account process");
8765 callback->OnStartUserDone(userId, CHECK_PERMISSION_FAILED);
8766 return CHECK_PERMISSION_FAILED;
8767 }
8768
8769 if (ShouldBlockAllAppStart() && callback != nullptr) {
8770 TAG_LOGI(AAFwkTag::ABILITYMGR, "low-mem mode, disallow");
8771 callback->OnStartUserDone(userId, ERR_ALL_APP_START_BLOCKED);
8772 return ERR_ALL_APP_START_BLOCKED;
8773 }
8774
8775 if (userController_) {
8776 return userController_->StartUser(userId, callback, isAppRecovery);
8777 }
8778 return 0;
8779 }
8780
StopUser(int userId,const sptr<IUserCallback> & callback)8781 int AbilityManagerService::StopUser(int userId, const sptr<IUserCallback> &callback)
8782 {
8783 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
8784 TAG_LOGI(AAFwkTag::ABILITYMGR, "stopUser in service:%{public}d", userId);
8785 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
8786 TAG_LOGE(AAFwkTag::ABILITYMGR, "stopUser permission verification failed, not account process");
8787 if (callback != nullptr) {
8788 callback->OnStopUserDone(userId, CHECK_PERMISSION_FAILED);
8789 }
8790 return CHECK_PERMISSION_FAILED;
8791 }
8792
8793 auto ret = -1;
8794 if (userController_) {
8795 ret = userController_->StopUser(userId);
8796 TAG_LOGD(AAFwkTag::ABILITYMGR, "ret = %{public}d", ret);
8797 }
8798 if (callback) {
8799 callback->OnStopUserDone(userId, ret);
8800 }
8801 if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
8802 return 0;
8803 }
8804 IN_PROCESS_CALL_WITHOUT_RET(KeepAliveProcessManager::GetInstance().ClearKeepAliveAppServiceExtension(userId));
8805 std::vector<AppExecFwk::BundleInfo> bundleInfos;
8806 if (!KeepAliveProcessManager::GetInstance().GetKeepAliveBundleInfosForUser(bundleInfos, userId)) {
8807 TAG_LOGE(AAFwkTag::ABILITYMGR, "get keep-alive bundle info failed");
8808 return 0;
8809 }
8810 for (const auto &bundleInfo : bundleInfos) {
8811 IN_PROCESS_CALL_WITHOUT_RET(KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(
8812 bundleInfo.name, userId, false, true, false));
8813 if (userId == U1_USER_ID) {
8814 IN_PROCESS_CALL_WITHOUT_RET(KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(
8815 bundleInfo.name, false, true, false));
8816 }
8817 }
8818 return 0;
8819 }
8820
LogoutUser(int32_t userId,sptr<IUserCallback> callback)8821 int AbilityManagerService::LogoutUser(int32_t userId, sptr<IUserCallback> callback)
8822 {
8823 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
8824 TAG_LOGI(AAFwkTag::ABILITYMGR, "LogoutUser in service:%{public}d", userId);
8825 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
8826 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed, not account process");
8827 if (callback != nullptr) {
8828 callback->OnLogoutUserDone(userId, CHECK_PERMISSION_FAILED);
8829 }
8830 return CHECK_PERMISSION_FAILED;
8831 }
8832
8833 // Lister screen unlock for auto startup apps.
8834 if (system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) {
8835 InitInterceptorForScreenUnlock();
8836 SubscribeScreenUnlockedEvent();
8837 }
8838
8839 if (userController_) {
8840 auto ret = userController_->LogoutUser(userId, callback);
8841 TAG_LOGD(AAFwkTag::ABILITYMGR, "logout user return = %{public}d", ret);
8842 return ret;
8843 }
8844 return ERR_OK;
8845 }
8846
OnAcceptWantResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)8847 void AbilityManagerService::OnAcceptWantResponse(
8848 const AAFwk::Want &want, const std::string &flag, int32_t requestId)
8849 {
8850 TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
8851 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8852 auto uiAbilityManager = GetCurrentUIAbilityManager();
8853 CHECK_POINTER(uiAbilityManager);
8854 uiAbilityManager->OnAcceptWantResponse(want, flag, requestId);
8855 return;
8856 }
8857 auto missionListManager = GetCurrentMissionListManager();
8858 if (!missionListManager) {
8859 return;
8860 }
8861 missionListManager->OnAcceptWantResponse(want, flag);
8862 }
8863
OnStartSpecifiedAbilityTimeoutResponse(int32_t requestId)8864 void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(int32_t requestId)
8865 {
8866 TAG_LOGI(AAFwkTag::ABILITYMGR, "OnStartSpecifiedAbilityTimeoutResponse %{public}d", requestId);
8867 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8868 auto uiAbilityManager = GetCurrentUIAbilityManager();
8869 CHECK_POINTER(uiAbilityManager);
8870 uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(requestId);
8871 return;
8872 }
8873 auto missionListManager = GetCurrentMissionListManager();
8874 if (!missionListManager) {
8875 return;
8876 }
8877 missionListManager->OnStartSpecifiedAbilityTimeoutResponse();
8878 }
8879
OnStartSpecifiedProcessResponse(const std::string & flag,int32_t requestId,const std::string & callerProcessName)8880 void AbilityManagerService::OnStartSpecifiedProcessResponse(const std::string &flag, int32_t requestId,
8881 const std::string &callerProcessName)
8882 {
8883 TAG_LOGD(AAFwkTag::ABILITYMGR, "flag = %{public}s", flag.c_str());
8884 auto connectManager = GetCurrentConnectManager();
8885 CHECK_POINTER(connectManager);
8886 if (connectManager->HasRequestIdInLoadAbilityQueue(requestId)) {
8887 TAG_LOGD(AAFwkTag::ABILITYMGR, "uiextension StartSpecifiedProcessResponse, requestId = %{public}d", requestId);
8888 connectManager->OnStartSpecifiedProcessResponse(flag, requestId);
8889 return;
8890 }
8891
8892 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8893 auto uiAbilityManager = GetCurrentUIAbilityManager();
8894 CHECK_POINTER(uiAbilityManager);
8895 uiAbilityManager->OnStartSpecifiedProcessResponse(flag, requestId, callerProcessName);
8896 return;
8897 }
8898 }
8899
OnStartSpecifiedProcessTimeoutResponse(int32_t requestId)8900 void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(int32_t requestId)
8901 {
8902 TAG_LOGI(AAFwkTag::ABILITYMGR, "OnStartSpecifiedProcessTimeoutResponse %{public}d", requestId);
8903 auto connectManager = GetCurrentConnectManager();
8904 CHECK_POINTER(connectManager);
8905 if (connectManager->HasRequestIdInLoadAbilityQueue(requestId)) {
8906 TAG_LOGD(AAFwkTag::ABILITYMGR, "uiextension StartSpecifiedProcessTimeoutResponse");
8907 connectManager->OnStartSpecifiedProcessTimeoutResponse(requestId);
8908 return;
8909 }
8910 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8911 auto uiAbilityManager = GetCurrentUIAbilityManager();
8912 CHECK_POINTER(uiAbilityManager);
8913 uiAbilityManager->OnStartSpecifiedProcessTimeoutResponse(requestId);
8914 return;
8915 }
8916 }
8917
OnStartSpecifiedFailed(int32_t requestId)8918 void AbilityManagerService::OnStartSpecifiedFailed(int32_t requestId)
8919 {
8920 TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
8921 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8922 auto uiAbilityManager = GetCurrentUIAbilityManager();
8923 CHECK_POINTER(uiAbilityManager);
8924 uiAbilityManager->OnStartSpecifiedFailed(requestId);
8925 return;
8926 }
8927 }
8928
GetAbilityRunningInfos(std::vector<AbilityRunningInfo> & info)8929 int AbilityManagerService::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
8930 {
8931 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8932 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get running ability infos.");
8933 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
8934 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8935 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
8936 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
8937 uiAbilityManager->GetAbilityRunningInfos(info, isPerm);
8938 } else {
8939 auto missionListManager = GetCurrentMissionListManager();
8940 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
8941 missionListManager->GetAbilityRunningInfos(info, isPerm);
8942 }
8943
8944 UpdateFocusState(info);
8945
8946 return ERR_OK;
8947 }
8948
UpdateFocusState(std::vector<AbilityRunningInfo> & info)8949 void AbilityManagerService::UpdateFocusState(std::vector<AbilityRunningInfo> &info)
8950 {
8951 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8952 if (info.empty()) {
8953 return;
8954 }
8955
8956 #ifdef SUPPORT_GRAPHICS
8957 sptr<IRemoteObject> token;
8958 int ret = IN_PROCESS_CALL(GetTopAbility(token));
8959 if (ret != ERR_OK || token == nullptr) {
8960 return;
8961 }
8962
8963 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8964 if (abilityRecord == nullptr) {
8965 TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
8966 return;
8967 }
8968
8969 for (auto &item : info) {
8970 if (item.uid == abilityRecord->GetUid() && item.pid == abilityRecord->GetPid() &&
8971 item.ability == abilityRecord->GetElementName()) {
8972 item.abilityState = static_cast<int>(AbilityState::ACTIVE);
8973 break;
8974 }
8975 }
8976 #endif
8977 }
8978
GetExtensionRunningInfos(int upperLimit,std::vector<ExtensionRunningInfo> & info)8979 int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)
8980 {
8981 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8982 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension infos, upperLimit : %{public}d", upperLimit);
8983 CHECK_CALLER_IS_SYSTEM_APP;
8984 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
8985 auto connectManager = GetCurrentConnectManager();
8986 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
8987 connectManager->GetExtensionRunningInfos(upperLimit, info, GetUserId(), isPerm);
8988 return ERR_OK;
8989 }
8990
GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> & info)8991 int AbilityManagerService::GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)
8992 {
8993 return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfos(info);
8994 }
8995
GetAllIntentExemptionInfo(std::vector<AppExecFwk::IntentExemptionInfo> & info)8996 int32_t AbilityManagerService::GetAllIntentExemptionInfo(std::vector<AppExecFwk::IntentExemptionInfo> &info)
8997 {
8998 const auto exemptionData =
8999 DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetAllIntentExemptionInfo();
9000 for (auto& data : exemptionData) {
9001 AppExecFwk::IntentExemptionInfo tmpInfo;
9002 tmpInfo.uid_ = data.first;
9003 tmpInfo.duration_ = INTENT_EXEMPTION_DURATION;
9004 info.push_back(tmpInfo);
9005 }
9006 return ERR_OK;
9007 }
9008
GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> & info,int32_t userId)9009 int AbilityManagerService::GetProcessRunningInfosByUserId(
9010 std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)
9011 {
9012 return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfosByUserId(info, userId);
9013 }
9014
ClearUserData(int32_t userId)9015 void AbilityManagerService::ClearUserData(int32_t userId)
9016 {
9017 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9018 // notify disconnect done to callers before clear connectManager's user data
9019 DisconnectBeforeCleanupByUserId(userId);
9020 CHECK_POINTER(subManagersHelper_);
9021 subManagersHelper_->ClearSubManagers(userId);
9022 }
9023
DisconnectBeforeCleanupByUserId(int32_t userId)9024 void AbilityManagerService::DisconnectBeforeCleanupByUserId(int32_t userId) {
9025 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9026 auto connectManager = GetConnectManagerByUserId(userId);
9027 CHECK_POINTER(connectManager);
9028 TAG_LOGI(AAFwkTag::ABILITYMGR, "handle all abilities die before clear data, userId:%{public}d", userId);
9029 connectManager->DisconnectBeforeCleanup();
9030 }
9031
RegisterSnapshotHandler(const sptr<ISnapshotHandler> & handler)9032 int AbilityManagerService::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
9033 {
9034 if (IPCSkeleton::GetCallingUid() != SAMGR_UID) {
9035 TAG_LOGE(AAFwkTag::ABILITYMGR, "register snapshot handler permission fail:%{public}d",
9036 IPCSkeleton::GetCallingUid());
9037 return CHECK_PERMISSION_FAILED;
9038 }
9039
9040 auto missionListManager = GetCurrentMissionListManager();
9041 CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
9042 missionListManager->RegisterSnapshotHandler(handler);
9043 TAG_LOGI(AAFwkTag::ABILITYMGR, "snapshot: abilityManagerService register snapshot handler success");
9044 return ERR_OK;
9045 }
9046
GetMissionSnapshot(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot,bool isLowResolution)9047 int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId,
9048 MissionSnapshot& missionSnapshot, bool isLowResolution)
9049 {
9050 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9051 CHECK_CALLER_IS_SYSTEM_APP;
9052 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
9053 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
9054 return CHECK_PERMISSION_FAILED;
9055 }
9056
9057 if (CheckIsRemote(deviceId)) {
9058 TAG_LOGI(AAFwkTag::ABILITYMGR, "get remote mission snapshot");
9059 return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot);
9060 }
9061 TAG_LOGI(AAFwkTag::ABILITYMGR, "get local mission snapshot");
9062 auto missionListManager = GetCurrentMissionListManager();
9063 CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
9064 auto token = GetAbilityTokenByMissionId(missionId);
9065 bool result = missionListManager->GetMissionSnapshot(missionId, token, missionSnapshot, isLowResolution);
9066 if (!result) {
9067 return INNER_ERR;
9068 }
9069 return ERR_OK;
9070 }
9071 #ifdef SUPPORT_SCREEN
UpdateMissionSnapShot(const sptr<IRemoteObject> & token,const std::shared_ptr<Media::PixelMap> & pixelMap)9072 void AbilityManagerService::UpdateMissionSnapShot(const sptr<IRemoteObject> &token,
9073 const std::shared_ptr<Media::PixelMap> &pixelMap)
9074 {
9075 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)) {
9076 return;
9077 }
9078 auto missionListManager = GetCurrentMissionListManager();
9079 if (missionListManager) {
9080 missionListManager->UpdateSnapShot(token, pixelMap);
9081 }
9082 }
9083 #endif // SUPPORT_SCREEN
EnableRecoverAbility(const sptr<IRemoteObject> & token)9084 void AbilityManagerService::EnableRecoverAbility(const sptr<IRemoteObject>& token)
9085 {
9086 TAG_LOGD(AAFwkTag::ABILITYMGR, "Enable recovery ability.");
9087 if (token == nullptr) {
9088 return;
9089 }
9090 auto record = Token::GetAbilityRecordByToken(token);
9091 if (record == nullptr) {
9092 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::failed find abilityRecord by token", __func__);
9093 return;
9094 }
9095 if (record->IsClearMissionFlag()) {
9096 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::not allow EnableRecoverAbility before clearMission",
9097 __func__);
9098 return;
9099 }
9100
9101 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9102 auto tokenID = record->GetApplicationInfo().accessTokenId;
9103 if (callingTokenId != tokenID) {
9104 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery scheduleRecoverAbility not self, not enabled");
9105 return;
9106 }
9107 {
9108 std::lock_guard<ffrt::mutex> guard(globalLock_);
9109 auto it = appRecoveryHistory_.find(record->GetUid());
9110 if (it == appRecoveryHistory_.end()) {
9111 appRecoveryHistory_.emplace(record->GetUid(), 0);
9112 }
9113 }
9114 auto userId = record->GetOwnerMissionUserId();
9115 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9116 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
9117 CHECK_POINTER(uiAbilityManager);
9118 const auto& abilityInfo = record->GetAbilityInfo();
9119 std::string abilityName = abilityInfo.name;
9120 auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
9121 if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
9122 abilityName += std::to_string(sessionId);
9123 }
9124 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->AddAbilityRecoverInfo(
9125 abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName, sessionId);
9126 } else {
9127 auto missionListMgr = GetMissionListManagerByUserId(userId);
9128 if (missionListMgr == nullptr) {
9129 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null");
9130 return;
9131 }
9132 missionListMgr->EnableRecoverAbility(record->GetMissionId());
9133 }
9134 }
9135
ScheduleClearRecoveryPageStack()9136 void AbilityManagerService::ScheduleClearRecoveryPageStack()
9137 {
9138 int32_t callerUid = IPCSkeleton::GetCallingUid();
9139 std::string bundleName;
9140 auto bms = AbilityUtil::GetBundleManagerHelper();
9141 CHECK_POINTER_IS_NULLPTR(bms);
9142
9143 if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
9144 TAG_LOGE(AAFwkTag::ABILITYMGR, "scheduleClearRecoveryPageStack get bundleName failed");
9145 return;
9146 }
9147
9148 auto tokenId = IPCSkeleton::GetCallingTokenID();
9149
9150 TAG_LOGI(AAFwkTag::ABILITYMGR,
9151 "ScheduleClearRecoveryPageStack bundleName = %{public}s, callerUid = %{public}d, tokenId = %{public}d",
9152 bundleName.c_str(), callerUid, tokenId);
9153 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
9154 DeleteAppExitReason(bundleName, tokenId);
9155 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
9156 DeleteAllRecoverInfoByTokenId(tokenId);
9157 }
9158
ReportAppRecoverResult(const int32_t appId,const AppExecFwk::ApplicationInfo & appInfo,const std::string & abilityName,const std::string & result)9159 void AbilityManagerService::ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo,
9160 const std::string& abilityName, const std::string& result)
9161 {
9162 HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
9163 "APP_UID", appId,
9164 "VERSION_CODE", std::to_string(appInfo.versionCode),
9165 "VERSION_NAME", appInfo.versionName,
9166 "BUNDLE_NAME", appInfo.bundleName,
9167 "ABILITY_NAME", abilityName,
9168 "RECOVERY_RESULT", result);
9169 }
9170
SubmitSaveRecoveryInfo(const sptr<IRemoteObject> & token)9171 void AbilityManagerService::SubmitSaveRecoveryInfo(const sptr<IRemoteObject>& token)
9172 {
9173 if (token == nullptr) {
9174 TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo token null");
9175 return;
9176 }
9177 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9178 if (abilityRecord == nullptr) {
9179 TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo abilityRecord null");
9180 return;
9181 }
9182 auto abilityInfo = abilityRecord->GetAbilityInfo();
9183 auto userId = abilityRecord->GetOwnerMissionUserId();
9184 auto tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
9185 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9186 if (callingTokenId != tokenId) {
9187 TAG_LOGE(AAFwkTag::ABILITYMGR, "SubmitSaveRecoveryInfo not self, not enabled");
9188 return;
9189 }
9190 std::string abilityName = abilityInfo.name;
9191 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9192 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
9193 CHECK_POINTER(uiAbilityManager);
9194 auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
9195 if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
9196 abilityName += std::to_string(sessionId);
9197 }
9198 } else {
9199 auto missionListMgr = GetMissionListManagerByUserId(userId);
9200 if (missionListMgr == nullptr) {
9201 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null");
9202 return;
9203 }
9204 abilityName += std::to_string(abilityRecord->GetMissionId());
9205 }
9206 TAG_LOGI(AAFwkTag::ABILITYMGR,
9207 "submitInfo bundleName = %{public}s, moduleName = %{public}s, abilityName = %{public}s, tokenId = %{public}d",
9208 abilityInfo.bundleName.c_str(), abilityInfo.moduleName.c_str(), abilityName.c_str(), tokenId);
9209 RecoveryInfo recoveryInfo;
9210 recoveryInfo.bundleName = abilityInfo.bundleName;
9211 recoveryInfo.moduleName = abilityInfo.moduleName;
9212 recoveryInfo.abilityName = abilityName;
9213 recoveryInfo.time = time(nullptr);
9214 OHOS::AAFwk::RecoveryInfoTimer::GetInstance().SubmitSaveRecoveryInfo(recoveryInfo);
9215 }
9216
AppRecoverKill(pid_t pid,int32_t reason)9217 void AbilityManagerService::AppRecoverKill(pid_t pid, int32_t reason)
9218 {
9219 AppExecFwk::AppFaultDataBySA faultDataSA;
9220 faultDataSA.errorObject.name = "appRecovery";
9221 switch (reason) {
9222 case AppExecFwk::StateReason::CPP_CRASH:
9223 faultDataSA.faultType = AppExecFwk::FaultDataType::CPP_CRASH;
9224 break;
9225 case AppExecFwk::StateReason::JS_ERROR:
9226 faultDataSA.faultType = AppExecFwk::FaultDataType::JS_ERROR;
9227 break;
9228 case AppExecFwk::StateReason::LIFECYCLE:
9229 case AppExecFwk::StateReason::APP_FREEZE:
9230 faultDataSA.faultType = AppExecFwk::FaultDataType::APP_FREEZE;
9231 break;
9232 default:
9233 faultDataSA.faultType = AppExecFwk::FaultDataType::UNKNOWN;
9234 }
9235 faultDataSA.pid = pid;
9236 IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFaultBySA(faultDataSA));
9237 }
9238
ScheduleRecoverAbility(const sptr<IRemoteObject> & token,int32_t reason,const Want * want)9239 void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)
9240 {
9241 if (token == nullptr) {
9242 return;
9243 }
9244 auto record = Token::GetAbilityRecordByToken(token);
9245 if (record == nullptr) {
9246 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::failed find abilityRecord by token", __func__);
9247 return;
9248 }
9249 if (!record->IsForeground() && !record->GetAbilityForegroundingFlag()) {
9250 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::recoveryAbility failed"
9251 "due background", __func__);
9252 return;
9253 }
9254
9255 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9256 auto tokenID = record->GetApplicationInfo().accessTokenId;
9257 if (callingTokenId != tokenID) {
9258 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery scheduleRecoverAbility no self, no enabled");
9259 return;
9260 }
9261
9262 AAFwk::Want curWant;
9263 {
9264 std::lock_guard<ffrt::mutex> guard(globalLock_);
9265 auto type = record->GetAbilityInfo().type;
9266 if (type != AppExecFwk::AbilityType::PAGE) {
9267 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::only recover for page ability", __func__);
9268 return;
9269 }
9270
9271 constexpr int64_t MIN_RECOVERY_TIME = 60;
9272 int64_t now = time(nullptr);
9273 auto it = appRecoveryHistory_.find(record->GetUid());
9274 auto appInfo = record->GetApplicationInfo();
9275 auto abilityInfo = record->GetAbilityInfo();
9276
9277 if ((it != appRecoveryHistory_.end()) &&
9278 (it->second + MIN_RECOVERY_TIME > now)) {
9279 TAG_LOGE(AAFwkTag::ABILITYMGR,
9280 "%{public}s appRecovery recover more once in one minute, kill app(%{public}d)",
9281 __func__, record->GetPid());
9282 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_WITHIN_ONE_MINUTE");
9283 AppRecoverKill(record->GetPid(), reason);
9284 return;
9285 }
9286
9287 if (want != nullptr) {
9288 TAG_LOGD(AAFwkTag::ABILITYMGR, "BundleName:%{public}s targetBundleName:%{public}s.",
9289 appInfo.bundleName.c_str(), want->GetElement().GetBundleName().c_str());
9290 if (want->GetElement().GetBundleName().empty() ||
9291 (appInfo.bundleName.compare(want->GetElement().GetBundleName()) != 0)) {
9292 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery bundleName not match, not recovery ability");
9293 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_BUNDLE_NAME_NOT_MATCH");
9294 return;
9295 }
9296 if (want->GetElement().GetAbilityName().empty()) {
9297 TAG_LOGD(AAFwkTag::ABILITYMGR, "AppRecovery recovery target ability is empty");
9298 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_TARGET_ABILITY_EMPTY");
9299 return;
9300 }
9301 auto bms = AbilityUtil::GetBundleManagerHelper();
9302 CHECK_POINTER_IS_NULLPTR(bms);
9303 AppExecFwk::BundleInfo bundleInfo;
9304 auto bundleName = want->GetElement().GetBundleName();
9305 int32_t userId = GetUserId();
9306 bool ret = IN_PROCESS_CALL(
9307 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo,
9308 userId));
9309 if (!ret) {
9310 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery get bundleInfo fail, not recovery");
9311 return;
9312 }
9313 bool isRestartPage = false;
9314 auto abilityName = want->GetElement().GetAbilityName();
9315 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
9316 if ((abilityName.compare(it->name) == 0) && it->type == AppExecFwk::AbilityType::PAGE) {
9317 isRestartPage = true;
9318 break;
9319 }
9320 }
9321 if (!isRestartPage) {
9322 TAG_LOGI(AAFwkTag::ABILITYMGR, "appRecovery target ability type not PAGE");
9323 ReportAppRecoverResult(record->GetUid(), appInfo, abilityName, "FAIL_TARGET_ABILITY_NOT_PAGE");
9324 return;
9325 }
9326 }
9327
9328 appRecoveryHistory_[record->GetUid()] = now;
9329 curWant = (want == nullptr) ? record->GetWant() : *want;
9330 if (curWant.GetBoolParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true)) {
9331 curWant.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
9332 }
9333
9334 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "SUCCESS");
9335 }
9336 RestartApp(curWant, true);
9337 }
9338
GetRemoteMissionSnapshotInfo(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot)9339 int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId,
9340 MissionSnapshot& missionSnapshot)
9341 {
9342 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9343 TAG_LOGI(AAFwkTag::ABILITYMGR, "getRemoteMissionSnapshotInfo");
9344 std::unique_ptr<MissionSnapshot> missionSnapshotPtr = std::make_unique<MissionSnapshot>();
9345 DistributedClient dmsClient;
9346 int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr);
9347 if (result != ERR_OK) {
9348 TAG_LOGE(AAFwkTag::ABILITYMGR, "getRemoteMissionSnapshotInfo failed, result=%{public}d", result);
9349 return result;
9350 }
9351 missionSnapshot = *missionSnapshotPtr;
9352 return ERR_OK;
9353 }
9354
StartSwitchUserDialog()9355 void AbilityManagerService::StartSwitchUserDialog()
9356 {
9357 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog extension ability come");
9358 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9359 TAG_LOGE(AAFwkTag::ABILITYMGR, "scene board enabled, dialog not show");
9360 return;
9361 }
9362
9363 if (userController_ == nullptr) {
9364 TAG_LOGE(AAFwkTag::ABILITYMGR, "user Controller instance null");
9365 return;
9366 }
9367 #ifdef SUPPORT_GRAPHICS
9368 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
9369 if (sysDialog == nullptr) {
9370 TAG_LOGE(AAFwkTag::ABILITYMGR, "system dialog scheduler instance null");
9371 return;
9372 }
9373
9374 Want dialogWant = sysDialog->GetSwitchUserDialogWant();
9375 StartSwitchUserDialogInner(dialogWant, userController_->GetFreezingNewUserId());
9376 #endif // SUPPORT_GRAPHICS
9377 }
9378
9379
StartSwitchUserDialogInner(const Want & want,int32_t lastUserId)9380 void AbilityManagerService::StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)
9381 {
9382 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog inner come");
9383 EventInfo eventInfo = BuildEventInfo(want, lastUserId);
9384 eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
9385 AbilityRequest abilityRequest;
9386 auto result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
9387 if (result != ERR_OK) {
9388 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
9389 eventInfo.errCode = result;
9390 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
9391 return;
9392 }
9393
9394 auto abilityInfo = abilityRequest.abilityInfo;
9395 auto startUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
9396 result = CheckOptExtensionAbility(want, abilityRequest, startUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
9397 if (result != ERR_OK) {
9398 TAG_LOGE(AAFwkTag::ABILITYMGR, "check extensionAbility type error");
9399 eventInfo.errCode = result;
9400 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
9401 return;
9402 }
9403
9404 auto connectManager = GetConnectManagerByUserId(startUserId);
9405 if (connectManager == nullptr) {
9406 CHECK_POINTER(subManagersHelper_);
9407 subManagersHelper_->InitConnectManager(startUserId, false);
9408 connectManager = GetConnectManagerByUserId(startUserId);
9409 if (connectManager == nullptr) {
9410 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", startUserId);
9411 eventInfo.errCode = ERR_INVALID_VALUE;
9412 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
9413 return;
9414 }
9415 }
9416
9417 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
9418 if (eventInfo.errCode != ERR_OK) {
9419 TAG_LOGE(AAFwkTag::ABILITYMGR, "eventInfo errCode:%{public}d", eventInfo.errCode);
9420 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
9421 }
9422 }
9423
StartFreezingScreen()9424 void AbilityManagerService::StartFreezingScreen()
9425 {
9426 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9427 #ifdef SUPPORT_GRAPHICS
9428 StartSwitchUserDialog();
9429 std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
9430 IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Freeze(displayIds));
9431 #endif
9432 }
9433
StopFreezingScreen()9434 void AbilityManagerService::StopFreezingScreen()
9435 {
9436 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9437 #ifdef SUPPORT_GRAPHICS
9438 std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
9439 IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Unfreeze(displayIds));
9440 StopSwitchUserDialog();
9441 #endif
9442 }
9443
UserStarted(int32_t userId)9444 void AbilityManagerService::UserStarted(int32_t userId)
9445 {
9446 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9447 CHECK_POINTER(subManagersHelper_);
9448 subManagersHelper_->InitSubManagers(userId, false);
9449 }
9450
SwitchToUser(int32_t oldUserId,int32_t userId,sptr<IUserCallback> callback,bool isAppRecovery)9451 int AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId, sptr<IUserCallback> callback,
9452 bool isAppRecovery)
9453 {
9454 TAG_LOGI(AAFwkTag::ABILITYMGR,
9455 "%{public}s, oldUserId:%{public}d, newUserId:%{public}d, isAppRecovery:%{public}d", __func__,
9456 oldUserId, userId, isAppRecovery);
9457 SwitchManagers(userId);
9458 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9459 PauseOldUser(oldUserId);
9460 ConnectServices();
9461 StartUserApps();
9462 }
9463 #ifndef DISABLE_LAUNCHER
9464 bool isBoot = oldUserId == U0_USER_ID ? true : false;
9465 auto ret = StartHighestPriorityAbility(userId, isBoot, isAppRecovery);
9466 if (ret != ERR_OK) {
9467 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartHighestPriorityAbility failed: %{public}d", ret);
9468 }
9469 #else
9470 auto ret = ERR_OK;
9471 #endif
9472 if (callback) {
9473 callback->OnStartUserDone(userId, ret);
9474 }
9475 if (taskHandler_) {
9476 taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() {
9477 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps userId:%{public}d", userId);
9478 abilityMs->StartResidentApps(userId);
9479 });
9480 }
9481 StartKeepAliveAppsInner(userId);
9482 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
9483 AmsConfigurationParameter::GetInstance().MultiUserType() != 0) {
9484 TAG_LOGI(AAFwkTag::ABILITYMGR, "no need terminate old scb");
9485 return ret;
9486 }
9487 PauseOldConnectManager(oldUserId);
9488 return ret;
9489 }
9490
IsSceneBoardReady(int32_t userId)9491 bool AbilityManagerService::IsSceneBoardReady(int32_t userId)
9492 {
9493 if (userId < 0) {
9494 userId = GetUserId();
9495 }
9496 auto connectManager = GetConnectManagerByUserId(userId);
9497 if (connectManager == nullptr) {
9498 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr");
9499 return false;
9500 }
9501 if (connectManager->GetSceneBoardTokenId() == 0) {
9502 TAG_LOGI(AAFwkTag::ABILITYMGR, "SCB not ready");
9503 return false;
9504 }
9505 return true;
9506 }
9507
StartKeepAliveAppsInner(int32_t userId)9508 void AbilityManagerService::StartKeepAliveAppsInner(int32_t userId)
9509 {
9510 if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
9511 TAG_LOGE(AAFwkTag::ABILITYMGR, "not supported");
9512 return;
9513 }
9514 if (taskHandler_ == nullptr) {
9515 TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler nullptr");
9516 return;
9517 }
9518 taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId] {
9519 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartKeepAliveApps userId:%{public}d", userId);
9520 abilityMs->StartKeepAliveApps(userId);
9521 });
9522 }
9523
SwitchManagers(int32_t userId,bool switchUser)9524 void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser)
9525 {
9526 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId);
9527 CHECK_POINTER(subManagersHelper_);
9528 subManagersHelper_->InitSubManagers(userId, switchUser);
9529 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----end", __func__, userId);
9530 }
9531
PauseOldUser(int32_t userId)9532 void AbilityManagerService::PauseOldUser(int32_t userId)
9533 {
9534 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId);
9535 PauseOldMissionListManager(userId);
9536 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----end", __func__, userId);
9537 }
9538
PauseOldMissionListManager(int32_t userId)9539 void AbilityManagerService::PauseOldMissionListManager(int32_t userId)
9540 {
9541 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId);
9542 auto manager = GetMissionListManagerByUserId(userId);
9543 CHECK_POINTER(manager);
9544 manager->PauseManager();
9545 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId);
9546 }
9547
PauseOldConnectManager(int32_t userId)9548 void AbilityManagerService::PauseOldConnectManager(int32_t userId)
9549 {
9550 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----begin", __func__, userId);
9551 if (userId == U0_USER_ID || userId == U1_USER_ID) {
9552 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, u0 not stop, id:%{public}d-----null", __func__, userId);
9553 return;
9554 }
9555
9556 auto manager = GetConnectManagerByUserId(userId);
9557 CHECK_POINTER(manager);
9558 manager->PauseExtensions();
9559 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----end", __func__, userId);
9560 }
9561
StartUserApps()9562 void AbilityManagerService::StartUserApps()
9563 {
9564 auto missionListManager = GetCurrentMissionListManager();
9565 if (missionListManager && missionListManager->IsStarted()) {
9566 TAG_LOGI(AAFwkTag::ABILITYMGR, "missionListManager ResumeManager");
9567 missionListManager->ResumeManager();
9568 }
9569 }
9570
GetValidUserId(const int32_t userId)9571 int32_t AbilityManagerService::GetValidUserId(const int32_t userId)
9572 {
9573 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId = %{public}d.", userId);
9574 int32_t validUserId = userId;
9575
9576 if (DEFAULT_INVAL_VALUE == userId) {
9577 validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
9578 TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId = %{public}d, CallingUid = %{public}d.", validUserId,
9579 IPCSkeleton::GetCallingUid());
9580 if (validUserId == U0_USER_ID || validUserId == U1_USER_ID) {
9581 validUserId = GetUserId();
9582 }
9583 }
9584 return validUserId;
9585 }
9586
SetAbilityController(const sptr<IAbilityController> & abilityController,bool imAStabilityTest)9587 int AbilityManagerService::SetAbilityController(const sptr<IAbilityController> &abilityController,
9588 bool imAStabilityTest)
9589 {
9590 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest);
9591 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyControllerPerm();
9592 if (!isPerm) {
9593 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
9594 return CHECK_PERMISSION_FAILED;
9595 }
9596
9597 std::lock_guard<ffrt::mutex> guard(globalLock_);
9598 abilityController_ = abilityController;
9599 controllerIsAStabilityTest_ = imAStabilityTest;
9600 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, end", __func__);
9601 return ERR_OK;
9602 }
9603
IsRunningInStabilityTest()9604 bool AbilityManagerService::IsRunningInStabilityTest()
9605 {
9606 std::lock_guard<ffrt::mutex> guard(globalLock_);
9607 bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_;
9608 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret);
9609 return ret;
9610 }
9611
IsAbilityControllerStart(const Want & want,const std::string & bundleName)9612 bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName)
9613 {
9614 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9615 TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
9616 if (abilityController_ == nullptr) {
9617 TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
9618 return true;
9619 }
9620
9621 if (controllerIsAStabilityTest_) {
9622 bool isStart = abilityController_->AllowAbilityStart(want, bundleName);
9623 if (!isStart) {
9624 TAG_LOGI(AAFwkTag::ABILITYMGR,
9625 "controller starting can't start ability:%{public}s", bundleName.c_str());
9626 return false;
9627 }
9628 }
9629 return true;
9630 }
9631
IsAbilityControllerForeground(const std::string & bundleName)9632 bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName)
9633 {
9634 TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
9635 if (abilityController_ == nullptr) {
9636 TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
9637 return true;
9638 }
9639
9640 if (controllerIsAStabilityTest_) {
9641 bool isResume = abilityController_->AllowAbilityBackground(bundleName);
9642 if (!isResume) {
9643 TAG_LOGI(AAFwkTag::ABILITYMGR,
9644 "controller resuming can't terminate ability:%{public}s", bundleName.c_str());
9645 return false;
9646 }
9647 }
9648 return true;
9649 }
9650
StartUserTest(const Want & want,const sptr<IRemoteObject> & observer)9651 int AbilityManagerService::StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)
9652 {
9653 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
9654 if (observer == nullptr) {
9655 TAG_LOGE(AAFwkTag::ABILITYMGR, "observer null");
9656 return ERR_INVALID_VALUE;
9657 }
9658
9659 std::string bundleName = want.GetStringParam("-b");
9660 if (bundleName.empty()) {
9661 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name");
9662 return ERR_INVALID_VALUE;
9663 }
9664
9665 auto checkResult = AbilityUtil::CheckInstanceKey(want);
9666 if (checkResult != ERR_OK) {
9667 return checkResult;
9668 }
9669 int32_t appIndex = 0;
9670 if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex) || appIndex != 0) {
9671 TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support app clone");
9672 return ERR_NOT_SUPPORT_APP_CLONE;
9673 }
9674
9675 auto bms = AbilityUtil::GetBundleManagerHelper();
9676 CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL);
9677 AppExecFwk::BundleInfo bundleInfo;
9678 if (!IN_PROCESS_CALL(
9679 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID))) {
9680 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundleInfo by U0_USER_ID %{public}d", U0_USER_ID);
9681 int32_t userId = GetUserId();
9682 TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, userId: %{public}d", bundleName.c_str(), userId);
9683 if (!IN_PROCESS_CALL(
9684 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
9685 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundleInfo by userId %{public}d", userId);
9686 return GET_BUNDLE_INFO_FAILED;
9687 }
9688 }
9689
9690 bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
9691 if (isDebugApp && bundleInfo.applicationInfo.appProvisionType != AppExecFwk::Constants::APP_PROVISION_TYPE_DEBUG) {
9692 TAG_LOGE(AAFwkTag::ABILITYMGR, "release app not support debug");
9693 return ERR_NOT_IN_APP_PROVISION_MODE;
9694 }
9695
9696 return DelayedSingleton<AppScheduler>::GetInstance()->StartUserTest(want, observer, bundleInfo, GetUserId());
9697 }
9698
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName)9699 int AbilityManagerService::FinishUserTest(
9700 const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
9701 {
9702 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
9703 if (bundleName.empty()) {
9704 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name");
9705 return ERR_INVALID_VALUE;
9706 }
9707
9708 return DelayedSingleton<AppScheduler>::GetInstance()->FinishUserTest(msg, resultCode, bundleName);
9709 }
9710
GetTopAbility(sptr<IRemoteObject> & token)9711 int AbilityManagerService::GetTopAbility(sptr<IRemoteObject> &token)
9712 {
9713 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9714 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9715 if (!isSaCall) {
9716 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
9717 return CHECK_PERMISSION_FAILED;
9718 }
9719 #ifdef SUPPORT_SCREEN
9720 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9721 Rosen::FocusChangeInfo focusChangeInfo;
9722 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
9723 token = focusChangeInfo.abilityToken_;
9724 } else {
9725 if (!wmsHandler_) {
9726 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
9727 return ERR_INVALID_VALUE;
9728 }
9729 wmsHandler_->GetFocusWindow(token);
9730 }
9731
9732 if (!token) {
9733 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
9734 return ERR_INVALID_VALUE;
9735 }
9736 #endif
9737 return ERR_OK;
9738 }
9739
DelegatorDoAbilityForeground(const sptr<IRemoteObject> & token)9740 int AbilityManagerService::DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)
9741 {
9742 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
9743 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
9744 auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
9745 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
9746 int32_t callerPid = IPCSkeleton::GetCallingPid();
9747 int32_t appPid = abilityRecord->GetPid();
9748 TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
9749 if (callerPid != appPid) {
9750 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not application itself");
9751 return ERR_INVALID_VALUE;
9752 }
9753 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9754 auto sessionId = GetMissionIdByAbilityTokenInner(token);
9755 if (!sessionId) {
9756 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid session id");
9757 return ERR_INVALID_VALUE;
9758 }
9759 auto want = abilityRecord->GetWant();
9760 if (!IsAbilityControllerStart(want, want.GetBundle())) {
9761 TAG_LOGE(AAFwkTag::ABILITYMGR,
9762 "sceneBoard IsAbilityControllerStart failed:%{public}s", want.GetBundle().c_str());
9763 return ERR_WOULD_BLOCK;
9764 }
9765 return ERR_OK;
9766 }
9767 auto missionId = GetMissionIdByAbilityToken(token);
9768 if (missionId < 0) {
9769 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid mission id");
9770 return ERR_INVALID_VALUE;
9771 }
9772 return DelegatorMoveMissionToFront(missionId);
9773 }
9774
DelegatorDoAbilityBackground(const sptr<IRemoteObject> & token)9775 int AbilityManagerService::DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)
9776 {
9777 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
9778 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
9779 auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
9780 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
9781 int32_t appPid = abilityRecord->GetPid();
9782 int32_t callerPid = IPCSkeleton::GetCallingPid();
9783 TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
9784 if (callerPid != appPid) {
9785 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not application itself");
9786 return ERR_INVALID_VALUE;
9787 }
9788 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9789 return ERR_OK;
9790 }
9791 return MinimizeAbility(token, true);
9792 }
9793
DoAbilityForeground(const sptr<IRemoteObject> & token,uint32_t flag)9794 int AbilityManagerService::DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)
9795 {
9796 TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityForeground, sceneFlag:%{public}u", flag);
9797 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
9798 if (!VerificationToken(token) && !VerificationAllToken(token)) {
9799 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s token error", __func__);
9800 return ERR_INVALID_VALUE;
9801 }
9802
9803 std::lock_guard<ffrt::mutex> guard(globalLock_);
9804 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9805 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
9806 if (!JudgeSelfCalled(abilityRecord)) {
9807 return CHECK_PERMISSION_FAILED;
9808 }
9809
9810 auto type = abilityRecord->GetAbilityInfo().type;
9811 if (type != AppExecFwk::AbilityType::PAGE) {
9812 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except page ability");
9813 return ERR_WRONG_INTERFACE_CALL;
9814 }
9815
9816 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
9817 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerForeground false");
9818 return ERR_WOULD_BLOCK;
9819 }
9820
9821 auto missionListManager = GetCurrentMissionListManager();
9822 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
9823 return missionListManager->DoAbilityForeground(abilityRecord, flag);
9824 }
9825
DoAbilityBackground(const sptr<IRemoteObject> & token,uint32_t flag)9826 int AbilityManagerService::DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)
9827 {
9828 TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityBackground, sceneFlag:%{public}u", flag);
9829 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
9830
9831 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9832 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
9833
9834 abilityRecord->lifeCycleStateInfo_.sceneFlag = flag;
9835 int ret = MinimizeAbility(token);
9836 abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL;
9837 return ret;
9838 }
9839
DelegatorMoveMissionToFront(int32_t missionId)9840 int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId)
9841 {
9842 TAG_LOGI(AAFwkTag::ABILITYMGR, "enter missionId:%{public}d", missionId);
9843 auto missionListManager = GetCurrentMissionListManager();
9844 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
9845
9846 if (!IsAbilityControllerStartById(missionId)) {
9847 TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
9848 return ERR_WOULD_BLOCK;
9849 }
9850
9851 return missionListManager->MoveMissionToFront(missionId);
9852 }
9853
JudgeMultiUserConcurrency(const int32_t userId)9854 bool AbilityManagerService::JudgeMultiUserConcurrency(const int32_t userId)
9855 {
9856 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9857 if (userId == U0_USER_ID || userId == U1_USER_ID) {
9858 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, userId is 0 or 1.", __func__);
9859 return true;
9860 }
9861
9862 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, current userId : %{public}d", userId, GetUserId());
9863
9864 // Only non-concurrent mode is supported
9865 bool concurrencyMode = CONCURRENCY_MODE_FALSE;
9866 if (!concurrencyMode) {
9867 return (userId == GetUserId());
9868 }
9869
9870 return true;
9871 }
9872
SendExtensionReport(EventInfo & eventInfo,int32_t errCode,bool isService)9873 void AbilityManagerService::SendExtensionReport(EventInfo &eventInfo, int32_t errCode, bool isService)
9874 {
9875 eventInfo.errCode = errCode;
9876 eventInfo.callerBundleName = InsightIntentGetcallerBundleName();
9877 if (isService) {
9878 EventReport::SendExtensionEvent(EventName::UI_SERVICE_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
9879 } else {
9880 EventReport::SendExtensionEvent(EventName::UI_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
9881 }
9882 }
9883
SendIntentReport(EventInfo & eventInfo,int32_t errCode,const std::string & intentName)9884 void AbilityManagerService::SendIntentReport(EventInfo &eventInfo, int32_t errCode, const std::string &intentName)
9885 {
9886 eventInfo.errCode = errCode;
9887 eventInfo.callerBundleName = InsightIntentGetcallerBundleName();
9888 eventInfo.intentName = intentName;
9889 EventReport::SendExecuteIntentEvent(EventName::EXECUTE_INSIGHT_INTENT_ERROR, HiSysEventType::FAULT, eventInfo);
9890 }
9891
9892 #ifdef ABILITY_COMMAND_FOR_TEST
ForceTimeoutForTest(const std::string & abilityName,const std::string & state)9893 int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, const std::string &state)
9894 {
9895 if (abilityName.empty()) {
9896 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityName empty");
9897 return INVALID_DATA;
9898 }
9899 std::lock_guard guard(timeoutMapLock_);
9900 if (abilityName == "clean") {
9901 timeoutMap_.clear();
9902 return ERR_OK;
9903 }
9904 if (state != AbilityRecord::ConvertAbilityState(AbilityState::INITIAL) &&
9905 state != AbilityRecord::ConvertAbilityState(AbilityState::INACTIVE) &&
9906 state != AbilityRecord::ConvertAbilityState(AbilityState::FOREGROUND) &&
9907 state != AbilityRecord::ConvertAbilityState(AbilityState::BACKGROUND) &&
9908 state != AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) &&
9909 state != std::string("COMMAND")) {
9910 TAG_LOGE(AAFwkTag::ABILITYMGR, "lifecycle state invalid");
9911 return INVALID_DATA;
9912 }
9913 timeoutMap_.insert(std::make_pair(state, abilityName));
9914 return ERR_OK;
9915 }
9916 #endif
9917
CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo & abilityInfo,uint32_t tokenId)9918 int AbilityManagerService::CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo,
9919 uint32_t tokenId)
9920 {
9921 if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId,
9922 PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) {
9923 return AppExecFwk::Constants::PERMISSION_GRANTED;
9924 }
9925
9926 for (const auto &permission : abilityInfo.permissions) {
9927 if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
9928 AppExecFwk::Constants::PERMISSION_GRANTED) {
9929 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission:%{public}s",
9930 permission.c_str());
9931 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9932 }
9933 }
9934
9935 return AppExecFwk::Constants::PERMISSION_GRANTED;
9936 }
9937
CheckOneSkillPermission(const AppExecFwk::Skill & skill,uint32_t tokenId)9938 bool AbilityManagerService::CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId)
9939 {
9940 for (auto permission : skill.permissions) {
9941 if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
9942 AppExecFwk::Constants::PERMISSION_GRANTED) {
9943 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission:%{public}s",
9944 permission.c_str());
9945 return false;
9946 }
9947 }
9948
9949 return true;
9950 }
9951
CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest & abilityRequest,uint32_t tokenId)9952 int AbilityManagerService::CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest,
9953 uint32_t tokenId)
9954 {
9955 auto abilityInfo = abilityRequest.abilityInfo;
9956 auto resultAbilityPermission = CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
9957 if (resultAbilityPermission != AppExecFwk::Constants::PERMISSION_GRANTED) {
9958 return resultAbilityPermission;
9959 }
9960
9961 if (abilityInfo.skills.empty()) {
9962 return AppExecFwk::Constants::PERMISSION_GRANTED;
9963 }
9964 int32_t result = AppExecFwk::Constants::PERMISSION_GRANTED;
9965 for (auto skill : abilityInfo.skills) {
9966 if (skill.Match(abilityRequest.want)) {
9967 if (CheckOneSkillPermission(skill, tokenId)) {
9968 return AppExecFwk::Constants::PERMISSION_GRANTED;
9969 } else {
9970 result = AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9971 }
9972 }
9973 }
9974 return result;
9975 }
9976
CheckStaticCfgPermission(const AppExecFwk::AbilityRequest & abilityRequest,bool isStartAsCaller,uint32_t callerTokenId,bool isData,bool isSaCall,bool isImplicit)9977 int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest,
9978 bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit)
9979 {
9980 auto abilityInfo = abilityRequest.abilityInfo;
9981 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9982 if (AppUtils::GetInstance().IsSupportAncoApp() &&
9983 StartAbilityUtils::IsCallFromAncoShellOrBroker(abilityRequest.callerToken)) {
9984 TAG_LOGD(AAFwkTag::ABILITYMGR,
9985 "Check static permission, name is %{public}s.", abilityInfo.name.c_str());
9986 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9987 if (collaborator == nullptr) {
9988 TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator null");
9989 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9990 }
9991 int result = collaborator->CheckStaticCfgPermission(abilityRequest.want, isImplicit);
9992 if (result != ERR_OK) {
9993 TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker");
9994 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
9995 }
9996 }
9997 if (!isData) {
9998 isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9999 }
10000 if (isSaCall) {
10001 // do not need check static config permission when start ability by SA
10002 return AppExecFwk::Constants::PERMISSION_GRANTED;
10003 }
10004
10005 uint32_t tokenId;
10006 if (isStartAsCaller) {
10007 tokenId = callerTokenId;
10008 } else {
10009 tokenId = IPCSkeleton::GetCallingTokenID();
10010 }
10011
10012 if (abilityInfo.applicationInfo.accessTokenId == tokenId) {
10013 return AppExecFwk::Constants::PERMISSION_GRANTED;
10014 }
10015
10016 if (abilityRequest.want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME) ==
10017 AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
10018 abilityRequest.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
10019 return AppExecFwk::Constants::PERMISSION_GRANTED;
10020 }
10021
10022 if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
10023 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) ||
10024 (abilityInfo.type == AppExecFwk::AbilityType::DATA)) {
10025 // just need check the read permission and write permission of extension ability or data ability
10026 if (!abilityInfo.readPermission.empty()) {
10027 int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission, false);
10028 if (checkReadPermission == ERR_OK) {
10029 return AppExecFwk::Constants::PERMISSION_GRANTED;
10030 }
10031 TAG_LOGW(AAFwkTag::ABILITYMGR,
10032 "verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str());
10033 }
10034 if (!abilityInfo.writePermission.empty()) {
10035 int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission, false);
10036 if (checkWritePermission == ERR_OK) {
10037 return AppExecFwk::Constants::PERMISSION_GRANTED;
10038 }
10039 TAG_LOGW(AAFwkTag::ABILITYMGR,
10040 "verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str());
10041 }
10042
10043 if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) {
10044 // 'readPermission' and 'writePermission' take precedence over 'permission'
10045 // when 'readPermission' or 'writePermission' is not empty, no need check 'permission'
10046 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
10047 }
10048 }
10049
10050 if (!isImplicit) {
10051 return CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
10052 }
10053 return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId);
10054 }
10055
CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,const Want & want,const AbilityRequest & abilityRequest)10056 int AbilityManagerService::CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,
10057 const Want &want, const AbilityRequest &abilityRequest)
10058 {
10059 AppExecFwk::ExtensionAbilityType targetExtType = abilityRequest.abilityInfo.extensionAbilityType;
10060 if (targetExtType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
10061 return ERR_OK;
10062 }
10063 if (!want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
10064 TAG_LOGE(AAFwkTag::ABILITYMGR, "need UISERVICEHOSTPROXY_KEY connect UI_SERVICE");
10065 return ERR_WRONG_INTERFACE_CALL;
10066 }
10067 if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
10068 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface not support connect UI_SERVICE");
10069 return ERR_WRONG_INTERFACE_CALL;
10070 }
10071 if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
10072 TAG_LOGE(AAFwkTag::ABILITYMGR, "ABILITYMS_ENABLE_UISERVICE false");
10073 return ERR_CAPABILITY_NOT_SUPPORT;
10074 }
10075
10076 return ERR_OK;
10077 }
10078
IsNeedTimeoutForTest(const std::string & abilityName,const std::string & state) const10079 bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const
10080 {
10081 std::lock_guard guard(timeoutMapLock_);
10082 for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) {
10083 if (iter->first == state && iter->second == abilityName) {
10084 return true;
10085 }
10086 }
10087 return false;
10088 }
10089
GetValidDataAbilityUri(const std::string & abilityInfoUri,std::string & adjustUri)10090 bool AbilityManagerService::GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)
10091 {
10092 // note: do not use abilityInfo.uri directly, need check uri first.
10093 size_t firstSeparator = abilityInfoUri.find_first_of('/');
10094 size_t lastSeparator = abilityInfoUri.find_last_of('/');
10095 if (lastSeparator - firstSeparator != 1) {
10096 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability info uri error, uri: %{public}s", abilityInfoUri.c_str());
10097 return false;
10098 }
10099
10100 adjustUri = abilityInfoUri;
10101 adjustUri.insert(lastSeparator, "/");
10102 return true;
10103 }
10104
GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> & abilityInfos,const std::string & mainAbility,std::string & uri)10105 bool AbilityManagerService::GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos,
10106 const std::string &mainAbility, std::string &uri)
10107 {
10108 if (abilityInfos.empty() || mainAbility.empty()) {
10109 TAG_LOGE(AAFwkTag::ABILITYMGR,
10110 "abilityInfos or mainAbility empty mainAbility:%{public}s", mainAbility.c_str());
10111 return false;
10112 }
10113
10114 std::string dataAbilityUri;
10115 for (auto abilityInfo : abilityInfos) {
10116 if (abilityInfo.type == AppExecFwk::AbilityType::DATA &&
10117 abilityInfo.name == mainAbility) {
10118 dataAbilityUri = abilityInfo.uri;
10119 TAG_LOGI(AAFwkTag::ABILITYMGR, "get data ability uri:%{public}s", dataAbilityUri.c_str());
10120 break;
10121 }
10122 }
10123
10124 return GetValidDataAbilityUri(dataAbilityUri, uri);
10125 }
10126
GetAbilityRunningInfo(std::vector<AbilityRunningInfo> & info,std::shared_ptr<AbilityRecord> & abilityRecord)10127 void AbilityManagerService::GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info,
10128 std::shared_ptr<AbilityRecord> &abilityRecord)
10129 {
10130 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10131 AbilityRunningInfo runningInfo;
10132 AppExecFwk::RunningProcessInfo processInfo;
10133 CHECK_POINTER(abilityRecord);
10134 runningInfo.ability = abilityRecord->GetElementName();
10135 runningInfo.startTime = abilityRecord->GetStartTime();
10136 runningInfo.abilityState = static_cast<int>(abilityRecord->GetAbilityState());
10137
10138 DelayedSingleton<AppScheduler>::GetInstance()->
10139 GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
10140 runningInfo.pid = processInfo.pid_;
10141 runningInfo.uid = processInfo.uid_;
10142 runningInfo.processName = processInfo.processName_;
10143 runningInfo.appCloneIndex = processInfo.appCloneIndex;
10144 info.emplace_back(runningInfo);
10145 }
10146
VerifyAccountPermission(int32_t userId)10147 int AbilityManagerService::VerifyAccountPermission(int32_t userId)
10148 {
10149 if ((userId < 0) || (userController_ && (userController_->GetCurrentUserId() == userId))) {
10150 return ERR_OK;
10151 }
10152 return AAFwk::PermissionVerification::GetInstance()->VerifyAccountPermission();
10153 }
10154
FreeInstallAbilityFromRemote(const Want & want,const sptr<IRemoteObject> & callback,int32_t userId,int requestCode)10155 int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
10156 int32_t userId, int requestCode)
10157 {
10158 auto callingUid = IPCSkeleton::GetCallingUid();
10159 if (callingUid != DMS_UID) {
10160 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support DMS");
10161 return CHECK_PERMISSION_FAILED;
10162 }
10163 int32_t validUserId = GetValidUserId(userId);
10164 if (freeInstallManager_ == nullptr) {
10165 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
10166 return ERR_INVALID_VALUE;
10167 }
10168 return freeInstallManager_->FreeInstallAbilityFromRemote(want, callback, validUserId, requestCode);
10169 }
10170
GetTopAbility(bool isNeedLocalDeviceId)10171 AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId)
10172 {
10173 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10174 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
10175 AppExecFwk::ElementName elementName = {};
10176 if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
10177 auto callerPid = IPCSkeleton::GetCallingPid();
10178 AppExecFwk::RunningProcessInfo processInfo;
10179 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
10180 if (!processInfo.isTestProcess) {
10181 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't use system-api or not test process");
10182 return elementName;
10183 }
10184 }
10185 #ifdef SUPPORT_GRAPHICS
10186 sptr<IRemoteObject> token;
10187 int ret = IN_PROCESS_CALL(GetTopAbility(token));
10188 if (ret) {
10189 return elementName;
10190 }
10191 if (!token) {
10192 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
10193 return elementName;
10194 }
10195 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10196 if (abilityRecord == nullptr) {
10197 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
10198 return elementName;
10199 }
10200 elementName = abilityRecord->GetElementName();
10201 bool isDeviceEmpty = elementName.GetDeviceID().empty();
10202 std::string localDeviceId;
10203 if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
10204 elementName.SetDeviceID(localDeviceId);
10205 }
10206 #endif
10207 return elementName;
10208 }
10209
GetElementNameByToken(sptr<IRemoteObject> token,bool isNeedLocalDeviceId)10210 AppExecFwk::ElementName AbilityManagerService::GetElementNameByToken(sptr<IRemoteObject> token,
10211 bool isNeedLocalDeviceId)
10212 {
10213 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10214 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
10215 AppExecFwk::ElementName elementName = {};
10216 #ifdef SUPPORT_GRAPHICS
10217 if (!token) {
10218 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
10219 return elementName;
10220 }
10221 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10222 if (abilityRecord == nullptr) {
10223 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
10224 return elementName;
10225 }
10226 elementName = abilityRecord->GetElementName();
10227 bool isDeviceEmpty = elementName.GetDeviceID().empty();
10228 std::string localDeviceId;
10229 if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
10230 elementName.SetDeviceID(localDeviceId);
10231 }
10232 #endif
10233 return elementName;
10234 }
10235
Dump(int fd,const std::vector<std::u16string> & args)10236 int AbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
10237 {
10238 TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump begin fd: %{public}d", fd);
10239 std::string result;
10240 auto errCode = Dump(args, result);
10241 int ret = dprintf(fd, "%s\n", result.c_str());
10242 if (ret < 0) {
10243 TAG_LOGE(AAFwkTag::ABILITYMGR, "dprintf error");
10244 return ERR_AAFWK_HIDUMP_ERROR;
10245 }
10246 TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump end");
10247 return errCode;
10248 }
10249
Dump(const std::vector<std::u16string> & args,std::string & result)10250 int AbilityManagerService::Dump(const std::vector<std::u16string>& args, std::string& result)
10251 {
10252 ErrCode errCode = ERR_OK;
10253 auto size = args.size();
10254 if (size == 0) {
10255 ShowHelp(result);
10256 return errCode;
10257 }
10258
10259 std::vector<std::string> argsStr;
10260 for (auto arg : args) {
10261 argsStr.emplace_back(Str16ToStr8(arg));
10262 }
10263
10264 if (argsStr[0] == "-h") {
10265 ShowHelp(result);
10266 } else {
10267 errCode = ProcessMultiParam(argsStr, result);
10268 if (errCode == ERR_AAFWK_HIDUMP_INVALID_ARGS) {
10269 ShowIllegalInfomation(result);
10270 }
10271 }
10272 return errCode;
10273 }
10274
ProcessMultiParam(std::vector<std::string> & argsStr,std::string & result)10275 ErrCode AbilityManagerService::ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)
10276 {
10277 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
10278 bool isClient = false;
10279 bool isUser = false;
10280 int userID = DEFAULT_INVAL_VALUE;
10281 std::vector<std::string>::iterator it;
10282 for (it = argsStr.begin(); it != argsStr.end();) {
10283 if (*it == ARGS_CLIENT) {
10284 isClient = true;
10285 it = argsStr.erase(it);
10286 continue;
10287 }
10288 if (*it == ARGS_USER_ID) {
10289 it = argsStr.erase(it);
10290 if (it == argsStr.end()) {
10291 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
10292 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
10293 }
10294 (void)StrToInt(*it, userID);
10295 if (userID < 0) {
10296 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
10297 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
10298 }
10299 isUser = true;
10300 it = argsStr.erase(it);
10301 continue;
10302 }
10303 it++;
10304 }
10305 std::string cmd;
10306 for (unsigned int i = 0; i < argsStr.size(); i++) {
10307 cmd.append(argsStr[i]);
10308 if (i != argsStr.size() - 1) {
10309 cmd.append(" ");
10310 }
10311 }
10312 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, isClient:%{public}d, userID:%{public}d, cmd:%{public}s",
10313 __func__, isClient, userID, cmd.c_str());
10314
10315 std::vector<std::string> dumpResults;
10316 DumpSysState(cmd, dumpResults, isClient, isUser, userID);
10317 for (auto it : dumpResults) {
10318 result += it + "\n";
10319 }
10320 return ERR_OK;
10321 }
10322
ShowHelp(std::string & result)10323 void AbilityManagerService::ShowHelp(std::string& result)
10324 {
10325 result.append("Usage:\n")
10326 .append("-h ")
10327 .append("help text for the tool\n")
10328 .append("-a [-c | -u {UserId}] ")
10329 .append("dump all ability infomation in the system or all ability infomation of client/UserId\n")
10330 .append("-l ")
10331 .append("dump all mission list information in the system\n")
10332 .append("-i {AbilityRecordId} ")
10333 .append("dump an ability infomation by ability record id\n")
10334 .append("-e ")
10335 .append("dump all extension infomation in the system(FA: ServiceAbilityRecords, Stage: ExtensionRecords)\n")
10336 .append("-p [PendingWantRecordId] ")
10337 .append("dump all pendingwant record infomation in the system\n")
10338 .append("-r ")
10339 .append("dump all process in the system\n")
10340 .append("-d ")
10341 .append("dump all data ability infomation in the system");
10342 }
10343
ShowIllegalInfomation(std::string & result)10344 void AbilityManagerService::ShowIllegalInfomation(std::string& result)
10345 {
10346 result.append(ILLEGAL_INFOMATION);
10347 }
10348
DumpAbilityInfoDone(std::vector<std::string> & infos,const sptr<IRemoteObject> & callerToken)10349 int AbilityManagerService::DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)
10350 {
10351 TAG_LOGD(AAFwkTag::ABILITYMGR, "dumpAbilityInfoDone begin");
10352 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
10353 if (abilityRecord == nullptr) {
10354 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
10355 return ERR_INVALID_VALUE;
10356 }
10357 if (!JudgeSelfCalled(abilityRecord)) {
10358 return CHECK_PERMISSION_FAILED;
10359 }
10360 abilityRecord->DumpAbilityInfoDone(infos);
10361 return ERR_OK;
10362 }
10363
SetMissionContinueState(const sptr<IRemoteObject> & token,const AAFwk::ContinueState & state)10364 int AbilityManagerService::SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)
10365 {
10366 TAG_LOGD(AAFwkTag::ABILITYMGR, "SetMissionContinueState begin. State: %{public}d", state);
10367
10368 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
10369
10370 int32_t missionId = GetMissionIdByAbilityToken(token);
10371 if (missionId == -1) {
10372 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed state:%{public}d", state);
10373 return ERR_INVALID_VALUE;
10374 }
10375
10376 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10377 if (!abilityRecord) {
10378 TAG_LOGE(AAFwkTag::ABILITYMGR,
10379 "no such ability record missionId:%{public}d, state:%{public}d",
10380 missionId, state);
10381 return -1;
10382 }
10383
10384 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10385 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10386 if (callingTokenId != tokenID) {
10387 TAG_LOGE(AAFwkTag::ABILITYMGR,
10388 "setMissionContinueState not self, not enabled. missionId:%{public}d, state:%{public}d",
10389 missionId, state);
10390 return -1;
10391 }
10392
10393 auto userId = abilityRecord->GetOwnerMissionUserId();
10394 auto missionListManager = GetMissionListManagerByUserId(userId);
10395 if (!missionListManager) {
10396 TAG_LOGE(AAFwkTag::ABILITYMGR, "find missionListManager failed missionId:%{public}d, state:%{public}d",
10397 missionId, state);
10398 return -1;
10399 }
10400
10401 auto setResult = missionListManager->SetMissionContinueState(token, missionId, state);
10402 if (setResult != ERR_OK) {
10403 TAG_LOGE(AAFwkTag::ABILITYMGR,
10404 "missionListManager set failed, result:%{public}d, missionId:%{public}d, state:%{public}d",
10405 setResult, missionId, state);
10406 return setResult;
10407 }
10408
10409 DistributedClient dmsClient;
10410 int32_t callingUid = IPCSkeleton::GetCallingUid();
10411 auto result = dmsClient.SetMissionContinueState(missionId, state, callingUid);
10412 if (result != ERR_OK) {
10413 TAG_LOGE(AAFwkTag::ABILITYMGR,
10414 "Notify DMS client failed, result: %{public}d. Mission id: %{public}d, state: %{public}d",
10415 result, missionId, state);
10416 }
10417
10418 TAG_LOGD(AAFwkTag::ABILITYMGR,
10419 "SetMissionContinueState end. Mission id: %{public}d, state: %{public}d", missionId, state);
10420 return ERR_OK;
10421 }
10422
10423 #ifdef SUPPORT_SCREEN
SetMissionLabel(const sptr<IRemoteObject> & token,const std::string & label)10424 int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
10425 {
10426 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
10427 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10428 if (!abilityRecord) {
10429 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
10430 return -1;
10431 }
10432
10433 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10434 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10435 if (callingTokenId != tokenID) {
10436 TAG_LOGE(AAFwkTag::ABILITYMGR, "setMissionLabel not self, not enabled");
10437 return -1;
10438 }
10439
10440 auto userId = abilityRecord->GetOwnerMissionUserId();
10441 auto missionListManager = GetMissionListManagerByUserId(userId);
10442 if (!missionListManager) {
10443 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager find failed when set mission label");
10444 return -1;
10445 }
10446
10447 return missionListManager->SetMissionLabel(token, label);
10448 }
10449
SetMissionIcon(const sptr<IRemoteObject> & token,const std::shared_ptr<OHOS::Media::PixelMap> & icon)10450 int AbilityManagerService::SetMissionIcon(const sptr<IRemoteObject> &token,
10451 const std::shared_ptr<OHOS::Media::PixelMap> &icon)
10452 {
10453 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
10454 CHECK_CALLER_IS_SYSTEM_APP;
10455 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10456 if (!abilityRecord) {
10457 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
10458 return -1;
10459 }
10460
10461 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
10462 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
10463 if (callingTokenId != tokenID) {
10464 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self, not enable set mission icon");
10465 return -1;
10466 }
10467
10468 auto userId = abilityRecord->GetOwnerMissionUserId();
10469 auto missionListManager = GetMissionListManagerByUserId(userId);
10470 if (!missionListManager) {
10471 TAG_LOGE(AAFwkTag::ABILITYMGR, "find missionListManager failed");
10472 return -1;
10473 }
10474
10475 return missionListManager->SetMissionIcon(token, icon);
10476 }
10477
RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> & handler,bool animationEnabled)10478 int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler,
10479 bool animationEnabled)
10480 {
10481 if (IPCSkeleton::GetCallingUid() != SAMGR_UID) {
10482 TAG_LOGE(AAFwkTag::ABILITYMGR, "register wms handler permission fail:%{public}d", IPCSkeleton::GetCallingUid());
10483 return CHECK_PERMISSION_FAILED;
10484 }
10485 wmsHandler_ = handler;
10486 isAnimationEnabled_ = animationEnabled;
10487 TAG_LOGI(AAFwkTag::ABILITYMGR, "WMS handler registered successfully.");
10488 return ERR_OK;
10489 }
10490
GetWMSHandler() const10491 sptr<IWindowManagerServiceHandler> AbilityManagerService::GetWMSHandler() const
10492 {
10493 return wmsHandler_;
10494 }
10495
CompleteFirstFrameDrawing(const sptr<IRemoteObject> & abilityToken)10496 void AbilityManagerService::CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)
10497 {
10498 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10499 if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
10500 TAG_LOGE(AAFwkTag::ABILITYMGR, "not foundation call");
10501 return;
10502 }
10503 auto abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
10504 CHECK_POINTER(abilityRecord);
10505
10506 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
10507 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
10508 CHECK_POINTER(missionListManager);
10509 missionListManager->CompleteFirstFrameDrawing(abilityToken);
10510 }
10511
CompleteFirstFrameDrawing(int32_t sessionId)10512 void AbilityManagerService::CompleteFirstFrameDrawing(int32_t sessionId)
10513 {
10514 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10515 if (!IsCallerSceneBoard()) {
10516 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sceneboard called, not allowed");
10517 return;
10518 }
10519 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10520 CHECK_POINTER(uiAbilityManager);
10521 uiAbilityManager->CompleteFirstFrameDrawing(sessionId);
10522 }
10523
ShowPickerDialog(const Want & want,int32_t userId,const sptr<IRemoteObject> & callerToken)10524 int32_t AbilityManagerService::ShowPickerDialog(
10525 const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)
10526 {
10527 AAFwk::Want newWant = want;
10528 std::string sharePickerBundleName =
10529 OHOS::system::GetParameter(SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME);
10530 std::string sharePickerAbilityName =
10531 OHOS::system::GetParameter(SHARE_PICKER_DIALOG_ABILITY_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME);
10532 newWant.SetElementName(sharePickerBundleName, sharePickerAbilityName);
10533 newWant.SetParam(TOKEN_KEY, callerToken);
10534 // note: clear actions
10535 newWant.SetAction("");
10536 return IN_PROCESS_CALL(StartAbility(newWant, DEFAULT_INVAL_VALUE, userId));
10537 }
10538
CheckWindowMode(int32_t windowMode,const std::vector<AppExecFwk::SupportWindowMode> & windowModes) const10539 bool AbilityManagerService::CheckWindowMode(int32_t windowMode,
10540 const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const
10541 {
10542 TAG_LOGI(AAFwkTag::ABILITYMGR, "window mode:%{public}d", windowMode);
10543 if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED) {
10544 return true;
10545 }
10546
10547 auto bmsWindowMode = WindowOptionsUtils::WindowModeMap(windowMode);
10548 if (bmsWindowMode.first) {
10549 for (const auto& mode : windowModes) {
10550 if (mode == bmsWindowMode.second) {
10551 return true;
10552 }
10553 }
10554 }
10555 return false;
10556 }
10557
PrepareTerminateAbility(const sptr<IRemoteObject> & token,sptr<IPrepareTerminateCallback> & callback)10558 int AbilityManagerService::PrepareTerminateAbility(const sptr<IRemoteObject> &token,
10559 sptr<IPrepareTerminateCallback> &callback)
10560 {
10561 TAG_LOGD(AAFwkTag::ABILITYMGR, "call PrepareTerminateAbility");
10562 if (callback == nullptr) {
10563 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback null");
10564 return ERR_INVALID_VALUE;
10565 }
10566
10567 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10568 auto err = AbilityPermissionUtil::GetInstance().CheckPrepareTerminateEnable(abilityRecord);
10569 if (err != ERR_OK) {
10570 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckPrepareTerminateEnable failed: %{public}d", err);
10571 callback->DoPrepareTerminate();
10572 return err;
10573 }
10574
10575 if (!JudgeSelfCalled(abilityRecord)) {
10576 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self call");
10577 callback->DoPrepareTerminate();
10578 return CHECK_PERMISSION_FAILED;
10579 }
10580
10581 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10582 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10583 bool res = uiAbilityManager->PrepareTerminateAbility(abilityRecord, false);
10584 if (!res) {
10585 callback->DoPrepareTerminate();
10586 return ERR_OK;
10587 }
10588 std::lock_guard<std::mutex> guard(prepareTermiationCallbackMutex_);
10589 auto abilityRecordId = std::to_string(abilityRecord->GetAbilityRecordId());
10590 if (prepareTermiationCallbacks_.find(abilityRecordId) != prepareTermiationCallbacks_.end()) {
10591 TAG_LOGI(AAFwkTag::ABILITYMGR, "abilityRecordId=%{public}s already exists", abilityRecordId.c_str());
10592 return ERR_OK;
10593 }
10594 prepareTermiationCallbacks_[abilityRecordId] = callback;
10595
10596 auto timeoutTask = [callback]() {
10597 if (callback != nullptr) {
10598 callback->DoPrepareTerminate();
10599 }
10600 };
10601 if (taskHandler_) {
10602 taskHandler_->SubmitTask(timeoutTask, "PrepareTermiante_" + abilityRecordId,
10603 GlobalConstant::PREPARE_TERMINATE_TIMEOUT_TIME);
10604 }
10605 return ERR_OK;
10606 }
10607
PrepareTerminateAbilityDone(const sptr<IRemoteObject> & token,bool isTerminate)10608 void AbilityManagerService::PrepareTerminateAbilityDone(const sptr<IRemoteObject> &token, bool isTerminate)
10609 {
10610 TAG_LOGD(AAFwkTag::ABILITYMGR, "call PrepareTerminateAbilityDone, isTerminate=%{public}d", isTerminate);
10611 if (token == nullptr) {
10612 TAG_LOGE(AAFwkTag::ABILITYMGR, "null token");
10613 return;
10614 }
10615 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10616 CHECK_POINTER(uiAbilityManager);
10617 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10618 CHECK_POINTER(abilityRecord);
10619 if (!JudgeSelfCalled(abilityRecord)) {
10620 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self caller");
10621 return;
10622 }
10623 auto abilityRecordId = std::to_string(abilityRecord->GetAbilityRecordId());
10624 std::lock_guard<std::mutex> guard(prepareTermiationCallbackMutex_);
10625 auto iter = prepareTermiationCallbacks_.find(abilityRecordId);
10626 if (iter == prepareTermiationCallbacks_.end()) {
10627 TAG_LOGI(AAFwkTag::ABILITYMGR, "scb call, abilityRecordId=%{public}s not found", abilityRecordId.c_str());
10628 uiAbilityManager->PrepareTerminateAbilityDone(abilityRecord, isTerminate);
10629 return;
10630 }
10631 if (iter->second != nullptr && !isTerminate) {
10632 TAG_LOGI(AAFwkTag::ABILITYMGR, "abilityRecordId=%{public}s, calling callback", abilityRecordId.c_str());
10633 iter->second->DoPrepareTerminate();
10634 }
10635 prepareTermiationCallbacks_.erase(iter);
10636 if (taskHandler_) {
10637 taskHandler_->CancelTask("PrepareTermiante_" + abilityRecordId);
10638 }
10639 }
10640
KillProcessWithPrepareTerminateDone(const std::string & moduleName,int32_t prepareTermination,bool isExist)10641 void AbilityManagerService::KillProcessWithPrepareTerminateDone(const std::string &moduleName,
10642 int32_t prepareTermination, bool isExist)
10643 {
10644 TAG_LOGI(AAFwkTag::ABILITYMGR, "call KillProcessWithPrepareTerminateDone, moduleName=%{public}s, "
10645 "prepareTermination=%{public}d, isExist=%{public}d", moduleName.c_str(), prepareTermination, isExist);
10646 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10647 CHECK_POINTER(uiAbilityManager);
10648 uiAbilityManager->TryPrepareTerminateByPidsDone(moduleName, prepareTermination, isExist);
10649 }
10650
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)10651 void AbilityManagerService::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
10652 {
10653 TAG_LOGI(AAFwkTag::ABILITYMGR, "handle focused event");
10654 auto missionListManager = GetCurrentMissionListManager();
10655 CHECK_POINTER(missionListManager);
10656 CHECK_POINTER(focusChangeInfo);
10657 int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
10658 missionListManager->NotifyMissionFocused(missionId);
10659 }
10660
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)10661 void AbilityManagerService::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
10662 {
10663 TAG_LOGI(AAFwkTag::ABILITYMGR, "handle unfocused event");
10664 auto missionListManager = GetCurrentMissionListManager();
10665 CHECK_POINTER(missionListManager);
10666 CHECK_POINTER(focusChangeInfo);
10667 int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
10668 missionListManager->NotifyMissionUnfocused(missionId);
10669 }
10670
InitFocusListener()10671 void AbilityManagerService::InitFocusListener()
10672 {
10673 TAG_LOGI(AAFwkTag::ABILITYMGR, "init ability focus listener");
10674 if (focusListener_) {
10675 return;
10676 }
10677
10678 focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
10679 auto registerTask = [innerService = shared_from_this()]() {
10680 if (innerService) {
10681 TAG_LOGI(AAFwkTag::ABILITYMGR, "registerFocusListener task");
10682 innerService->RegisterFocusListener();
10683 }
10684 };
10685 if (taskHandler_) {
10686 taskHandler_->SubmitTaskJust(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
10687 }
10688 }
10689
RegisterFocusListener()10690 void AbilityManagerService::RegisterFocusListener()
10691 {
10692 TAG_LOGI(AAFwkTag::ABILITYMGR, "register focus listener");
10693 if (!focusListener_) {
10694 TAG_LOGE(AAFwkTag::ABILITYMGR, "no listener obj");
10695 return;
10696 }
10697 Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
10698 TAG_LOGI(AAFwkTag::ABILITYMGR, "register focus listener success");
10699 }
10700
RegisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer,const std::string & targetBundleName)10701 int AbilityManagerService::RegisterAbilityFirstFrameStateObserver(
10702 const sptr<IAbilityFirstFrameStateObserver> &observer, const std::string &targetBundleName)
10703 {
10704 return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
10705 RegisterAbilityFirstFrameStateObserver(observer, targetBundleName);
10706 }
10707
UnregisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer)10708 int AbilityManagerService::UnregisterAbilityFirstFrameStateObserver(
10709 const sptr<IAbilityFirstFrameStateObserver> &observer)
10710 {
10711 return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
10712 UnregisterAbilityFirstFrameStateObserver(observer);
10713 }
10714
GetAnimationFlag()10715 bool AbilityManagerService::GetAnimationFlag()
10716 {
10717 return isAnimationEnabled_;
10718 }
10719
10720 #endif
10721
CheckCallServicePermission(const AbilityRequest & abilityRequest)10722 int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest)
10723 {
10724 if (abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()) ==
10725 AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
10726 abilityRequest.want.GetElement().GetBundleName() == AppUtils::GetInstance().GetBrokerDelegateBundleName()) {
10727 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
10728 if (collaborator != nullptr) {
10729 TAG_LOGI(AAFwkTag::ABILITYMGR, "Collaborator CheckCallAbilityPermission");
10730 return collaborator->CheckCallAbilityPermission(abilityRequest.want);
10731 }
10732 }
10733 if (abilityRequest.abilityInfo.isStageBasedModel) {
10734 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
10735 TAG_LOGD(AAFwkTag::ABILITYMGR, "extensionType is %{public}d.", static_cast<int>(extensionType));
10736 if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE ||
10737 extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
10738 extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
10739 return CheckCallServiceExtensionPermission(abilityRequest);
10740 } else {
10741 return CheckCallOtherExtensionPermission(abilityRequest);
10742 }
10743 } else {
10744 return CheckCallServiceAbilityPermission(abilityRequest);
10745 }
10746 }
10747
CheckCallDataAbilityPermission(AbilityRequest & abilityRequest,bool isShell,bool isSACall)10748 int AbilityManagerService::CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)
10749 {
10750 abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo;
10751 abilityRequest.uid = abilityRequest.appInfo.uid;
10752 if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) {
10753 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app info acquiring");
10754 return ERR_INVALID_VALUE;
10755 }
10756 if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) {
10757 TAG_LOGE(AAFwkTag::ABILITYMGR, "BMS query result not data ability");
10758 return ERR_WRONG_INTERFACE_CALL;
10759 }
10760
10761 AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest,
10762 true, isShell, isSACall);
10763 if (isShell) {
10764 verificationInfo.isBackgroundCall = true;
10765 }
10766 if (!isShell && IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall, true) != ERR_OK) {
10767 return ERR_INVALID_VALUE;
10768 }
10769 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallDataAbilityPermission(verificationInfo,
10770 isShell);
10771 if (result != ERR_OK) {
10772 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start DataAbility permission");
10773 return result;
10774 }
10775
10776 return ERR_OK;
10777 }
10778
CreateVerificationInfo(const AbilityRequest & abilityRequest,bool isData,bool isShell,bool isSA)10779 AAFwk::PermissionVerification::VerificationInfo AbilityManagerService::CreateVerificationInfo(
10780 const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)
10781 {
10782 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
10783 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
10784 verificationInfo.visible = abilityRequest.abilityInfo.visible;
10785 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
10786 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call ServiceAbility or DataAbility, target bundleName: %{public}s.",
10787 abilityRequest.appInfo.bundleName.c_str());
10788 if (whiteListassociatedWakeUpFlag_ &&
10789 abilityRequest.appInfo.bundleName == BUNDLE_NAME_SETTINGSDATA) {
10790 TAG_LOGD(AAFwkTag::ABILITYMGR,
10791 "Call ServiceAbility or DataAbility, target bundle in white-list, allow associatedWakeUp.");
10792 verificationInfo.associatedWakeUp = true;
10793 } else {
10794 verificationInfo.associatedWakeUp = abilityRequest.appInfo.associatedWakeUp;
10795 }
10796 if (!isData) {
10797 isSA = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10798 isShell = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
10799 }
10800 if (isSA || isShell) {
10801 return verificationInfo;
10802 }
10803 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10804 if (callerAbility) {
10805 verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
10806 }
10807
10808 return verificationInfo;
10809 }
10810
CheckCallAppServiceExtensionPermission(const AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> targetService,bool isFromConnect)10811 int32_t AbilityManagerService::CheckCallAppServiceExtensionPermission(const AbilityRequest &abilityRequest,
10812 std::shared_ptr<AbilityRecord> targetService, bool isFromConnect)
10813 {
10814 int32_t result = CheckCallServiceExtensionPermission(abilityRequest);
10815 if (result != ERR_OK) {
10816 return result;
10817 }
10818 if (AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10819 return ERR_OK;
10820 }
10821 bool isVerifyAppIdentifierAllowList = true;
10822 if (targetService != nullptr && targetService->IsAbilityState(AbilityState::ACTIVE)) {
10823 isVerifyAppIdentifierAllowList = false;
10824 }
10825 if (!AppUtils::GetInstance().IsSupportAppServiceExtension()) {
10826 return ERR_CAPABILITY_NOT_SUPPORT;
10827 }
10828 if (isVerifyAppIdentifierAllowList && !VerifySameAppOrAppIdentifierAllowListPermission(abilityRequest)) {
10829 if (isFromConnect) {
10830 return ERR_TARGET_NOT_STARTED;
10831 }
10832 return ERR_TARGET_NOT_IN_APP_IDENTIFIER_ALLOW_LIST;
10833 }
10834 if (!PermissionVerification::GetInstance()->VerifyPermissionByTokenId(abilityRequest.appInfo.accessTokenId,
10835 PermissionConstants::PERMISSION_SUPPORT_APP_SERVICE_EXTENSION)) {
10836 return CHECK_PERMISSION_FAILED;
10837 }
10838 return ERR_OK;
10839 }
10840
CheckCallServiceExtensionPermission(const AbilityRequest & abilityRequest)10841 int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)
10842 {
10843 TAG_LOGD(AAFwkTag::ABILITYMGR, "begin");
10844
10845 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
10846 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
10847 verificationInfo.visible = abilityRequest.abilityInfo.visible;
10848 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
10849 verificationInfo.isBackgroundCall = false;
10850 if (isParamStartAbilityEnable_) {
10851 bool stopContinuousTaskFlag = ShouldPreventStartAbility(abilityRequest);
10852 if (stopContinuousTaskFlag) {
10853 TAG_LOGE(AAFwkTag::ABILITYMGR, "no have permission to start ServiceExtension");
10854 return CHECK_PERMISSION_FAILED;
10855 }
10856 }
10857
10858 if (abilityRequest.abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
10859 TAG_LOGE(AAFwkTag::ABILITYMGR, "background startup UI_SERVICE");
10860 verificationInfo.isBackgroundCall = true;
10861 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10862 if (callerAbility) {
10863 verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
10864 }
10865 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
10866 TAG_LOGE(AAFwkTag::ABILITYMGR, "not background startup UI_SERVICE");
10867 return ERR_INVALID_VALUE;
10868 }
10869 }
10870
10871 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo);
10872 if (result != ERR_OK) {
10873 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceExtension or sataShareExtension permission");
10874 }
10875 return result;
10876 }
10877
10878 #ifdef SUPPORT_AUTO_FILL
CheckCallAutoFillExtensionPermission(const AbilityRequest & abilityRequest)10879 int AbilityManagerService::CheckCallAutoFillExtensionPermission(const AbilityRequest &abilityRequest)
10880 {
10881 if (!abilityRequest.appInfo.isSystemApp) {
10882 TAG_LOGE(AAFwkTag::ABILITYMGR, "application requesting call isn't system application");
10883 return CHECK_PERMISSION_FAILED;
10884 }
10885 std::string jsonDataStr = abilityRequest.want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY);
10886 AbilityBase::ViewData viewData;
10887 viewData.FromJsonString(jsonDataStr.c_str());
10888 std::string callerName;
10889 int32_t uid = 0;
10890 auto callerPid = IPCSkeleton::GetCallingPid();
10891 DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
10892 if (viewData.bundleName != callerName) {
10893 TAG_LOGE(AAFwkTag::ABILITYMGR, "Not %{public}s called, no allowed", viewData.bundleName.c_str());
10894 return ERR_WRONG_INTERFACE_CALL;
10895 }
10896 return ERR_OK;
10897 }
10898 #endif // SUPPORT_AUTO_FILL
10899
CheckCallOtherExtensionPermission(const AbilityRequest & abilityRequest)10900 int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)
10901 {
10902 if (IPCSkeleton::GetCallingUid() != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
10903 AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10904 return ERR_OK;
10905 }
10906 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
10907 TAG_LOGD(AAFwkTag::ABILITYMGR, "OtherExtension type: %{public}d.", static_cast<int32_t>(extensionType));
10908 if (system::GetBoolParameter(DEVELOPER_MODE_STATE, false) &&
10909 PermissionVerification::GetInstance()->VerifyShellStartExtensionType(static_cast<int32_t>(extensionType))) {
10910 TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckCallOtherExtensionPermission, allow aa start with debug mode.");
10911 return ERR_OK;
10912 }
10913 if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) {
10914 CHECK_CALLER_IS_SYSTEM_APP;
10915 return ERR_OK;
10916 }
10917 if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) {
10918 return ERR_OK;
10919 }
10920 #ifdef SUPPORT_AUTO_FILL
10921 if (extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD ||
10922 extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART) {
10923 return CheckCallAutoFillExtensionPermission(abilityRequest);
10924 }
10925 #endif // SUPPORT_AUTO_FILL
10926 if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
10927 return CheckUIExtensionPermission(abilityRequest);
10928 }
10929 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
10930 return ERR_OK;
10931 }
10932 if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION) {
10933 return CheckFileAccessExtensionPermission(abilityRequest);
10934 }
10935 if (extensionType == AppExecFwk::ExtensionAbilityType::CALLER_INFO_QUERY) {
10936 return CheckCallerInfoQueryExtensionPermission(abilityRequest);
10937 }
10938 TAG_LOGE(AAFwkTag::ABILITYMGR, "not SA, can't start other extension");
10939 return CHECK_PERMISSION_FAILED;
10940 }
10941
CheckCallerInfoQueryExtensionPermission(const AbilityRequest & abilityRequest)10942 int AbilityManagerService::CheckCallerInfoQueryExtensionPermission(const AbilityRequest &abilityRequest)
10943 {
10944 auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
10945 PermissionConstants::PERMISSION_GET_TELEPHONY_STATE);
10946 if (!ret) {
10947 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny for callerInfoQueryExtension");
10948 return CHECK_PERMISSION_FAILED;
10949 }
10950 TAG_LOGI(AAFwkTag::ABILITYMGR, "check permission success");
10951 return ERR_OK;
10952 }
10953
CheckFileAccessExtensionPermission(const AbilityRequest & abilityRequest)10954 int AbilityManagerService::CheckFileAccessExtensionPermission(const AbilityRequest &abilityRequest)
10955 {
10956 auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
10957 PermissionConstants::PERMISSION_FILE_ACCESS_MANAGER);
10958 if (!ret) {
10959 return CHECK_PERMISSION_FAILED;
10960 }
10961 TAG_LOGD(AAFwkTag::ABILITYMGR, "Temporary, FILEACCESS_EXTENSION use serviceExtension start-up rule.");
10962 return CheckCallServiceExtensionPermission(abilityRequest);
10963 }
10964
CheckUIExtensionPermission(const AbilityRequest & abilityRequest)10965 int AbilityManagerService::CheckUIExtensionPermission(const AbilityRequest &abilityRequest)
10966 {
10967 if (abilityRequest.want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
10968 // If started by embedded atomic service, allow it.
10969 return ERR_OK;
10970 }
10971
10972 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
10973 if (AAFwk::UIExtensionUtils::IsSystemUIExtension(extensionType)) {
10974 auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10975 if (callerRecord == nullptr) {
10976 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid caller");
10977 return NO_FOUND_ABILITY_BY_CALLER;
10978 }
10979
10980 if (!abilityRequest.appInfo.isSystemApp) {
10981 TAG_LOGE(AAFwkTag::ABILITYMGR, "bundle %{public}s want start or caller bundle %{public}s "
10982 "isn't system app, type %{public}d not allowed", abilityRequest.appInfo.bundleName.c_str(),
10983 callerRecord->GetApplicationInfo().bundleName.c_str(), extensionType);
10984 return CHECK_PERMISSION_FAILED;
10985 }
10986 }
10987
10988 if (AAFwk::UIExtensionUtils::IsSystemCallerNeeded(extensionType)) {
10989 auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
10990 if (callerRecord == nullptr) {
10991 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid caller");
10992 return NO_FOUND_ABILITY_BY_CALLER;
10993 }
10994
10995 if (!callerRecord->GetApplicationInfo().isSystemApp
10996 && !AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10997 TAG_LOGE(AAFwkTag::ABILITYMGR,
10998 "bundle %{public}s want start but caller bundle %{public}s "
10999 "isn't system app, type %{public}d not allowed",
11000 abilityRequest.appInfo.bundleName.c_str(), callerRecord->GetApplicationInfo().bundleName.c_str(),
11001 extensionType);
11002 return CHECK_PERMISSION_FAILED;
11003 }
11004 }
11005
11006 if (!CheckUIExtensionCallerIsForeground(abilityRequest)) {
11007 return CHECK_PERMISSION_FAILED;
11008 }
11009
11010 if (!CheckUIExtensionCallerPidByHostWindowId(abilityRequest)) {
11011 return ERR_INVALID_CALLER;
11012 }
11013
11014 return ERR_OK;
11015 }
11016
CheckUIExtensionCallerIsForeground(const AbilityRequest & abilityRequest)11017 bool AbilityManagerService::CheckUIExtensionCallerIsForeground(const AbilityRequest &abilityRequest)
11018 {
11019 if (!CheckUIExtensionCallerIsUIAbility(abilityRequest)) {
11020 // Check only if the caller is uiability, if caller is not a uiability, don't check.
11021 return true;
11022 }
11023
11024 bool isBackgroundCall = true;
11025 auto ret = IsCallFromBackground(abilityRequest, isBackgroundCall);
11026 if (ret != ERR_OK) {
11027 TAG_LOGE(AAFwkTag::UI_EXT, "start uea when background");
11028 return false;
11029 }
11030
11031 if (!isBackgroundCall) {
11032 return true;
11033 }
11034
11035 if (CheckStartCallHasFloatingWindowForUIExtension(abilityRequest.callerToken)) {
11036 return true;
11037 }
11038
11039 auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11040 if (callerAbility != nullptr) {
11041 if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
11042 auto tokenId = callerAbility->GetApplicationInfo().accessTokenId;
11043 bool isFocused = false;
11044 if (CheckUIExtensionIsFocused(tokenId, isFocused) == ERR_OK && isFocused) {
11045 TAG_LOGD(AAFwkTag::ABILITYMGR, "Root caller is foreground");
11046 return true;
11047 }
11048 }
11049
11050 if (callerAbility->IsSceneBoard()) {
11051 return true;
11052 }
11053 }
11054
11055 if (PermissionVerification::GetInstance()->VerifyCallingPermission(
11056 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
11057 return true;
11058 }
11059
11060 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller app not foreground, can't start %{public}s",
11061 abilityRequest.want.GetElement().GetURI().c_str());
11062 return false;
11063 }
11064
CheckStartCallHasFloatingWindowForUIExtension(const sptr<IRemoteObject> & callerToken)11065 bool AbilityManagerService::CheckStartCallHasFloatingWindowForUIExtension(const sptr<IRemoteObject> &callerToken)
11066 {
11067 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11068 auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
11069 CHECK_POINTER_AND_RETURN_LOG(sceneSessionManager, CHECK_PERMISSION_FAILED, "sceneSessionManager is nullptr");
11070 bool hasFloatingWindow = false;
11071 auto err = sceneSessionManager->HasFloatingWindowForeground(callerToken, hasFloatingWindow);
11072 TAG_LOGI(AAFwkTag::ABILITYMGR,
11073 "check floatingwindow permission. Ret: %{public}d, hasFloatingWindow: %{public}d",
11074 static_cast<int32_t>(err), hasFloatingWindow);
11075 if (err != Rosen::WMError::WM_OK) {
11076 TAG_LOGE(AAFwkTag::ABILITYMGR,
11077 "checking floatingwindow err: %{public}d", static_cast<int32_t>(err));
11078 } else if (hasFloatingWindow) {
11079 return true;
11080 }
11081 }
11082 return false;
11083 }
11084
CheckUIExtensionCallerIsUIAbility(const AbilityRequest & abilityRequest)11085 bool AbilityManagerService::CheckUIExtensionCallerIsUIAbility(const AbilityRequest &abilityRequest)
11086 {
11087 auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11088 if (callerAbility == nullptr) {
11089 TAG_LOGE(AAFwkTag::UI_EXT, "caller ability invalid");
11090 return false;
11091 }
11092
11093 if (callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
11094 return true;
11095 }
11096
11097 if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
11098 callerAbility = GetUIExtensionRootCaller(abilityRequest.callerToken, abilityRequest.userId);
11099 if (callerAbility != nullptr && callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
11100 return true;
11101 }
11102 }
11103
11104 return false;
11105 }
11106
CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest & abilityRequest)11107 bool AbilityManagerService::CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest &abilityRequest)
11108 {
11109 #ifdef SUPPORT_SCREEN
11110 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11111 return true;
11112 }
11113
11114 auto sessionInfo = abilityRequest.sessionInfo;
11115 CHECK_POINTER_AND_RETURN(sessionInfo, false);
11116 auto hostWindowId = sessionInfo->hostWindowId;
11117 auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
11118 CHECK_POINTER_AND_RETURN(sceneSessionManager, false);
11119 pid_t hostPid = 0;
11120 // If host window id is scb, it will return with error.
11121 auto tokenId = abilityRequest.appInfo.accessTokenId;
11122 auto element = abilityRequest.want.GetElement();
11123 auto extType = abilityRequest.abilityInfo.extensionAbilityType;
11124 {
11125 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "Rosen::SceneSessionManager::CheckUIExtensionCreation");
11126 auto ret = sceneSessionManager->CheckUIExtensionCreation(hostWindowId, tokenId, element, extType, hostPid);
11127 if (ret == Rosen::WMError::WM_ERROR_INVALID_PERMISSION) {
11128 // If check permission failed, means target ability can't show on lock screen.
11129 TAG_LOGE(AAFwkTag::UI_EXT, "Check fail, tokenId: %{public}d, element: %{public}s, ret: %{public}d",
11130 tokenId, element.GetURI().c_str(), ret);
11131 return false;
11132 }
11133 }
11134
11135 TAG_LOGD(AAFwkTag::UI_EXT, "get pid %{public}d by windowId %{public}d", hostPid, hostWindowId);
11136 auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11137 CHECK_POINTER_AND_RETURN(callerAbility, false);
11138 if (callerAbility->IsSceneBoard()) {
11139 return true;
11140 }
11141 if (hostPid != 0 && callerAbility->GetPid() == hostPid) {
11142 return true;
11143 }
11144
11145 if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
11146 TAG_LOGD(AAFwkTag::UI_EXT, "caller is nested uiextability");
11147 auto connectManager = GetCurrentConnectManager();
11148 CHECK_POINTER_AND_RETURN(connectManager, false);
11149 bool matched = false;
11150 std::list<sptr<IRemoteObject>> callerList;
11151 connectManager->GetUIExtensionCallerTokenList(callerAbility, callerList);
11152 for (auto &item : callerList) {
11153 auto ability = AAFwk::Token::GetAbilityRecordByToken(item);
11154 if (ability == nullptr) {
11155 TAG_LOGW(AAFwkTag::UI_EXT, "wrong ability");
11156 continue;
11157 }
11158
11159 if ((hostPid != 0 && ability->GetPid() == hostPid) || ability->IsSceneBoard()) {
11160 matched = true;
11161 return true;
11162 }
11163 }
11164 if (!matched) {
11165 TAG_LOGE(AAFwkTag::UI_EXT, "Check nested uiextability failed");
11166 }
11167 }
11168
11169 TAG_LOGE(AAFwkTag::UI_EXT, "check pid %{public}d fail, got %{public}d actual %{public}d",
11170 hostWindowId, hostPid, callerAbility->GetPid());
11171 return false;
11172 #else
11173 return true;
11174 #endif // SUPPORT_SCREEN
11175 }
11176
CheckCallServiceAbilityPermission(const AbilityRequest & abilityRequest)11177 int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)
11178 {
11179 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
11180 AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest);
11181 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
11182 return ERR_INVALID_VALUE;
11183 }
11184
11185 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceAbilityPermission(verificationInfo);
11186 if (result != ERR_OK) {
11187 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceAbility permission");
11188 }
11189 return result;
11190 }
11191
CheckCallAbilityPermission(const AbilityRequest & abilityRequest,uint32_t specifyTokenId,bool isCallByShortcut)11192 int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId,
11193 bool isCallByShortcut)
11194 {
11195 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11196 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
11197
11198 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
11199 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
11200 verificationInfo.visible = abilityRequest.abilityInfo.visible;
11201 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
11202 verificationInfo.specifyTokenId = specifyTokenId;
11203 auto callerAbilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11204 if (callerAbilityRecord != nullptr &&
11205 callerAbilityRecord->GetAbilityInfo().extensionAbilityType == AppExecFwk::ExtensionAbilityType::APP_SERVICE) {
11206 verificationInfo.isBackgroundCall = false;
11207 } else if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
11208 return ERR_CHECK_CALL_FROM_BACKGROUND_FAILED;
11209 }
11210
11211 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission(
11212 verificationInfo, isCallByShortcut);
11213 if (result != ERR_OK) {
11214 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start pageAbility(FA) or ability(Stage) permission");
11215 }
11216 return result;
11217 }
11218
CheckStartByCallPermission(const AbilityRequest & abilityRequest)11219 int AbilityManagerService::CheckStartByCallPermission(const AbilityRequest &abilityRequest)
11220 {
11221 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
11222 // check whether the target ability is page type and not specified mode.
11223 if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::PAGE ||
11224 abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
11225 TAG_LOGE(AAFwkTag::ABILITYMGR, "called ability not common ability");
11226 return RESOLVE_CALL_ABILITY_TYPE_ERR;
11227 }
11228
11229 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
11230 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
11231 verificationInfo.visible = abilityRequest.abilityInfo.visible;
11232 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
11233 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
11234 return ERR_INVALID_VALUE;
11235 }
11236
11237 if (AAFwk::PermissionVerification::GetInstance()->CheckStartByCallPermission(verificationInfo) != ERR_OK) {
11238 TAG_LOGE(AAFwkTag::ABILITYMGR, "without startAbilityByCall permission");
11239 return RESOLVE_CALL_NO_PERMISSIONS;
11240 }
11241 TAG_LOGD(AAFwkTag::ABILITYMGR, "caller has permission to resolve the call proxy of common ability");
11242 return ERR_OK;
11243 }
11244
IsCallFromBackground(const AbilityRequest & abilityRequest,bool & isBackgroundCall,bool isData)11245 int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall,
11246 bool isData)
11247 {
11248 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11249 if (!isData && AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
11250 isBackgroundCall = true;
11251 return ERR_OK;
11252 }
11253
11254 if (!isData && (SupportSystemAbilityPermission::IsSupportSaCallPermission() ||
11255 AbilityUtil::IsStartFreeInstall(abilityRequest.want))) {
11256 isBackgroundCall = false;
11257 return ERR_OK;
11258 }
11259
11260 AppExecFwk::RunningProcessInfo processInfo;
11261 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11262 if (callerAbility && callerAbility->GetAbilityInfo().bundleName == BUNDLE_NAME_DIALOG) {
11263 callerAbility = callerAbility->GetCallerRecord();
11264 }
11265 if (callerAbility) {
11266 if (callerAbility->IsForeground() || callerAbility->GetAbilityForegroundingFlag()) {
11267 isBackgroundCall = false;
11268 return ERR_OK;
11269 }
11270 // CallerAbility is not foreground, so check process state
11271 DelayedSingleton<AppScheduler>::GetInstance()->
11272 GetRunningProcessInfoByToken(callerAbility->GetToken(), processInfo);
11273 if (IsDelegatorCall(processInfo, abilityRequest)) {
11274 TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
11275 isBackgroundCall = false;
11276 return ERR_OK;
11277 }
11278 #ifdef SUPPORT_SCREEN
11279 if (AppUtils::GetInstance().IsStartOptionsWithAnimation() &&
11280 callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
11281 AbilityPermissionUtil::GetInstance().CheckStartCallHasFloatingWindow(
11282 abilityRequest.callerToken) == ERR_OK) {
11283 isBackgroundCall = false;
11284 return ERR_OK;
11285 }
11286 #endif // SUPPORT_SCREEN
11287 auto abilityState = callerAbility->GetAbilityState();
11288 if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING ||
11289 // If uiability or uiextensionability ability state is foreground when terminate,
11290 // it will move to background firstly. So if startAbility in onBackground() lifecycle,
11291 // the actual ability state may be had changed to terminating from background or backgrounding.
11292 abilityState == AbilityState::TERMINATING) {
11293 return ERR_OK;
11294 }
11295 } else if (AbilityPermissionUtil::GetInstance().IsStartSelfUIAbility()) {
11296 TAG_LOGI(AAFwkTag::ABILITYMGR, "call from capi, already checked background call");
11297 isBackgroundCall = false;
11298 return ERR_OK;
11299 } else {
11300 auto callerPid = IPCSkeleton::GetCallingPid();
11301 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
11302 if (processInfo.processName_.empty()) {
11303 TAG_LOGD(AAFwkTag::ABILITYMGR, "Can not find caller application by callerPid: %{private}d.", callerPid);
11304 if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
11305 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
11306 TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller has PERMISSION_START_ABILITIES_FROM_BACKGROUND, PASS.");
11307 isBackgroundCall = false;
11308 return ERR_OK;
11309 }
11310 TAG_LOGE(AAFwkTag::ABILITYMGR, "without PERMISSION_START_ABILITIES_FROM_BACKGROUND, REJECT");
11311 return ERR_INVALID_VALUE;
11312 }
11313 }
11314 return SetBackgroundCall(processInfo, abilityRequest, isBackgroundCall);
11315 }
11316
SetBackgroundCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest,bool & isBackgroundCall) const11317 int32_t AbilityManagerService::SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo,
11318 const AbilityRequest &abilityRequest, bool &isBackgroundCall) const
11319 {
11320 if (IsDelegatorCall(processInfo, abilityRequest)) {
11321 TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
11322 isBackgroundCall = false;
11323 return ERR_OK;
11324 }
11325
11326 if (backgroundJudgeFlag_) {
11327 isBackgroundCall = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND &&
11328 !processInfo.isFocused && !processInfo.isAbilityForegrounding;
11329 } else {
11330 isBackgroundCall = !processInfo.isFocused;
11331 if (!processInfo.isFocused && processInfo.state_ == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) {
11332 // Allow background startup within 1 second after application startup if state is FOREGROUND
11333 int64_t aliveTime = AbilityUtil::SystemTimeMillis() - processInfo.startTimeMillis_;
11334 isBackgroundCall = aliveTime > APP_ALIVE_TIME_MS;
11335 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process %{public}s is alive %{public}s ms.",
11336 processInfo.processName_.c_str(), std::to_string(aliveTime).c_str());
11337 }
11338 }
11339 TAG_LOGD(AAFwkTag::ABILITYMGR,
11340 "backgroundJudgeFlag: %{public}d, isBackgroundCall: %{public}d, callerAppState: %{public}d.",
11341 static_cast<int32_t>(backgroundJudgeFlag_),
11342 static_cast<int32_t>(isBackgroundCall),
11343 static_cast<int32_t>(processInfo.state_));
11344
11345 return ERR_OK;
11346 }
11347
IsTargetPermission(const Want & want) const11348 bool AbilityManagerService::IsTargetPermission(const Want &want) const
11349 {
11350 std::string bundleName = PERMISSIONMGR_BUNDLE_NAME;
11351 std::string abilityName = PERMISSIONMGR_ABILITY_NAME;
11352 Security::AccessToken::PermissionGrantInfo info;
11353 Security::AccessToken::AccessTokenKit::GetPermissionManagerInfo(info);
11354 if (!info.grantBundleName.empty() && !info.grantServiceAbilityName.empty()) {
11355 bundleName = info.grantBundleName;
11356 abilityName = info.grantServiceAbilityName;
11357 }
11358 if (want.GetElement().GetBundleName() == bundleName &&
11359 want.GetElement().GetAbilityName() == abilityName) {
11360 return true;
11361 }
11362
11363 return false;
11364 }
11365
IsDelegatorCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest) const11366 inline bool AbilityManagerService::IsDelegatorCall(
11367 const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest) const
11368 {
11369 /* To make sure the AbilityDelegator is not counterfeited
11370 * 1. The caller-process must be test-process
11371 * 2. The callerToken must be nullptr
11372 */
11373 if (processInfo.isTestProcess &&
11374 !abilityRequest.callerToken && abilityRequest.want.GetBoolParam(IS_DELEGATOR_CALL, false)) {
11375 return true;
11376 }
11377 return false;
11378 }
11379
CheckNewRuleSwitchState(const std::string & param)11380 bool AbilityManagerService::CheckNewRuleSwitchState(const std::string ¶m)
11381 {
11382 char value[NEW_RULE_VALUE_SIZE] = "false";
11383 int retSysParam = GetParameter(param.c_str(), "false", value, NEW_RULE_VALUE_SIZE);
11384 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkNewRuleSwitchState, %{public}s value: %{public}s", param.c_str(), value);
11385 if (retSysParam > 0 && !std::strcmp(value, "true")) {
11386 return true;
11387 }
11388 return false;
11389 }
11390
GetStartUpNewRuleFlag() const11391 bool AbilityManagerService::GetStartUpNewRuleFlag() const
11392 {
11393 return startUpNewRule_;
11394 }
11395
CallRequestDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callStub)11396 void AbilityManagerService::CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)
11397 {
11398 {
11399 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
11400 callStubTokenMap_[callStub] = token;
11401 }
11402 auto abilityRecord = Token::GetAbilityRecordByToken(token);
11403 CHECK_POINTER(abilityRecord);
11404 if (!JudgeSelfCalled(abilityRecord)) {
11405 return;
11406 }
11407
11408 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11409 auto uiAbilityManager = GetCurrentUIAbilityManager();
11410 CHECK_POINTER(uiAbilityManager);
11411 uiAbilityManager->CallRequestDone(abilityRecord, callStub);
11412 return;
11413 }
11414
11415 auto missionListManager = GetCurrentMissionListManager();
11416 CHECK_POINTER(missionListManager);
11417 missionListManager->CallRequestDone(abilityRecord, callStub);
11418 }
11419
GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> & callStub,sptr<IRemoteObject> & token)11420 void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)
11421 {
11422 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
11423 auto it = callStubTokenMap_.find(callStub);
11424 if (it == callStubTokenMap_.end()) {
11425 token = nullptr;
11426 return;
11427 }
11428 token = callStubTokenMap_[callStub];
11429 }
11430
AddStartControlParam(Want & want,const sptr<IRemoteObject> & callerToken)11431 int AbilityManagerService::AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)
11432 {
11433 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11434 if (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
11435 AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
11436 return ERR_OK;
11437 }
11438 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
11439 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
11440 int32_t apiVersion = abilityRecord->GetApplicationInfo().apiTargetVersion;
11441 want.SetParam(DMS_API_VERSION, apiVersion);
11442 bool isCallerBackground = true;
11443 AppExecFwk::RunningProcessInfo processInfo;
11444 DelayedSingleton<AppScheduler>::GetInstance()->
11445 GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
11446 if (backgroundJudgeFlag_) {
11447 isCallerBackground = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND;
11448 } else {
11449 isCallerBackground = !processInfo.isFocused;
11450 }
11451 want.SetParam(DMS_IS_CALLER_BACKGROUND, isCallerBackground);
11452 return ERR_OK;
11453 }
11454
11455 #ifdef WITH_DLP
CheckDlpForExtension(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,EventInfo & eventInfo,const EventName & eventName)11456 int AbilityManagerService::CheckDlpForExtension(
11457 const Want &want, const sptr<IRemoteObject> &callerToken,
11458 int32_t userId, EventInfo &eventInfo, const EventName &eventName)
11459 {
11460 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11461 // check if form frs
11462 auto callingUid = IPCSkeleton::GetCallingUid();
11463 std::string bundleName = want.GetBundle();
11464 if (callingUid == FOUNDATION_UID && FRS_BUNDLE_NAME == bundleName) {
11465 return ERR_OK;
11466 }
11467
11468 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
11469 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
11470 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
11471 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
11472 eventInfo.errCode = CHECK_PERMISSION_FAILED;
11473 EventReport::SendExtensionEvent(eventName, HiSysEventType::FAULT, eventInfo);
11474 return CHECK_PERMISSION_FAILED;
11475 }
11476 return ERR_OK;
11477 }
11478 #endif // WITH_DLP
11479
JudgeSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)11480 bool AbilityManagerService::JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
11481 {
11482 if (IPCSkeleton::GetCallingPid() == getprocpid()) {
11483 return true;
11484 }
11485
11486 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
11487 CHECK_POINTER_RETURN_BOOL(abilityRecord);
11488 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
11489 if (abilityRecord->IsPluginAbility()) {
11490 auto caller = abilityRecord->GetCallerRecord();
11491 if (caller) {
11492 tokenID = caller->GetApplicationInfo().accessTokenId;
11493 }
11494 }
11495 if (callingTokenId != tokenID) {
11496 TAG_LOGE(AAFwkTag::ABILITYMGR, "no self, no enabled, callingTokenId:%{public}u, tokenId:%{public}u", callingTokenId, tokenID);
11497 return false;
11498 }
11499
11500 return true;
11501 }
11502
IsAppSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)11503 bool AbilityManagerService::IsAppSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
11504 {
11505 CHECK_POINTER_RETURN_BOOL(abilityRecord);
11506 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
11507 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
11508 if (callingTokenId != tokenID) {
11509 TAG_LOGE(AAFwkTag::ABILITYMGR, "not app self called");
11510 return false;
11511 }
11512 return true;
11513 }
11514
GetFocusAbility()11515 std::shared_ptr<AbilityRecord> AbilityManagerService::GetFocusAbility()
11516 {
11517 #ifdef SUPPORT_SCREEN
11518 sptr<IRemoteObject> token;
11519 if (!wmsHandler_) {
11520 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
11521 return nullptr;
11522 }
11523
11524 wmsHandler_->GetFocusWindow(token);
11525 if (!token) {
11526 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
11527 return nullptr;
11528 }
11529
11530 auto abilityRecord = Token::GetAbilityRecordByToken(token);
11531 if (!abilityRecord) {
11532 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
11533 }
11534 return abilityRecord;
11535 #endif
11536
11537 return nullptr;
11538 }
11539
CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId,bool & isFocused)11540 int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)
11541 {
11542 sptr<IRemoteObject> token;
11543 auto ret = GetTopAbility(token);
11544 if (ret != ERR_OK) {
11545 TAG_LOGE(AAFwkTag::ABILITYMGR, "getTopAbility failed");
11546 return ret;
11547 }
11548
11549 auto topAbility = Token::GetAbilityRecordByToken(token);
11550 if (topAbility != nullptr) {
11551 TAG_LOGD(AAFwkTag::ABILITYMGR, "top ability: %{public}s, pid: %{public}d, tokenId: %{public}d",
11552 topAbility->GetWant().GetElement().GetURI().c_str(), topAbility->GetPid(),
11553 topAbility->GetApplicationInfo().accessTokenId);
11554 }
11555
11556 bool focused = false;
11557 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
11558 auto connectManager = GetConnectManagerByUserId(userId);
11559 if (connectManager) {
11560 focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
11561 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
11562 } else {
11563 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:%{public}d", userId);
11564 }
11565 if (!focused && userId != U0_USER_ID) {
11566 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check connectManager in user0");
11567 connectManager = GetConnectManagerByUserId(U0_USER_ID);
11568 if (connectManager) {
11569 focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
11570 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
11571 } else {
11572 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId: 0");
11573 }
11574 }
11575 isFocused = focused;
11576 TAG_LOGD(AAFwkTag::ABILITYMGR, "isFocused: %{public}d", isFocused);
11577 return ERR_OK;
11578 }
11579
AddFreeInstallObserver(const sptr<IRemoteObject> & callerToken,const sptr<AbilityRuntime::IFreeInstallObserver> & observer)11580 int AbilityManagerService::AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken,
11581 const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
11582 {
11583 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11584 if (freeInstallManager_ == nullptr) {
11585 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
11586 return ERR_INVALID_VALUE;
11587 }
11588 return freeInstallManager_->AddFreeInstallObserver(callerToken, observer);
11589 }
11590
IsValidMissionIds(const std::vector<int32_t> & missionIds,std::vector<MissionValidResult> & results)11591 int32_t AbilityManagerService::IsValidMissionIds(
11592 const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)
11593 {
11594 auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11595 auto missionlistMgr = GetMissionListManagerByUserId(userId);
11596 if (missionlistMgr == nullptr) {
11597 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionlistMgr null");
11598 return ERR_INVALID_VALUE;
11599 }
11600
11601 return missionlistMgr->IsValidMissionIds(missionIds, results);
11602 }
11603
VerifyPermission(const std::string & permission,int pid,int uid)11604 int AbilityManagerService::VerifyPermission(const std::string &permission, int pid, int uid)
11605 {
11606 TAG_LOGI(AAFwkTag::ABILITYMGR, "permission=%{public}s, pid=%{public}d, uid=%{public}d",
11607 permission.c_str(), pid, uid);
11608 if (permission.empty()) {
11609 TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission permission invalid");
11610 return CHECK_PERMISSION_FAILED;
11611 }
11612
11613 auto bms = AbilityUtil::GetBundleManagerHelper();
11614 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
11615
11616 int32_t callerUid = IPCSkeleton::GetCallingUid();
11617 std::string callerBundleName;
11618 if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, callerBundleName)) != ERR_OK) {
11619 TAG_LOGE(AAFwkTag::ABILITYMGR, "get caller bundleName failed");
11620 return CHECK_PERMISSION_FAILED;
11621 }
11622
11623 int32_t userId = GetUserId();
11624 AppExecFwk::BundleInfo bundleInfo;
11625 bool queryBundleInfoRet = IN_PROCESS_CALL(
11626 bms->GetBundleInfo(callerBundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
11627 if (!queryBundleInfoRet) {
11628 TAG_LOGE(AAFwkTag::ABILITYMGR, "get caller bundleInfo failed, %{public}s", callerBundleName.c_str());
11629 return CHECK_PERMISSION_FAILED;
11630 }
11631 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
11632 if (it->isStageBasedModel == true) {
11633 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support fa mode");
11634 return CHECK_PERMISSION_FAILED;
11635 }
11636 }
11637
11638 std::string bundleName;
11639 if (IN_PROCESS_CALL(bms->GetNameForUid(uid, bundleName)) != ERR_OK) {
11640 TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission get bundle name failed");
11641 return CHECK_PERMISSION_FAILED;
11642 }
11643
11644 int account = -1;
11645 DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, account);
11646 TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName: %{public}s, account: %{private}d", bundleName.c_str(), account);
11647 AppExecFwk::ApplicationInfo appInfo;
11648 if (!IN_PROCESS_CALL(bms->GetApplicationInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
11649 account, appInfo))) {
11650 TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission get application info failed");
11651 return CHECK_PERMISSION_FAILED;
11652 }
11653
11654 int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false);
11655 if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
11656 TAG_LOGE(AAFwkTag::ABILITYMGR, "PERMISSION_DENIED");
11657 return CHECK_PERMISSION_FAILED;
11658 }
11659
11660 return ERR_OK;
11661 }
11662
AcquireShareData(const int32_t & missionId,const sptr<IAcquireShareDataCallback> & shareData)11663 int32_t AbilityManagerService::AcquireShareData(
11664 const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)
11665 {
11666 TAG_LOGD(AAFwkTag::ABILITYMGR, "missionId is %{public}d.", missionId);
11667 CHECK_CALLER_IS_SYSTEM_APP;
11668 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
11669 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11670 auto uiAbilityManager = GetCurrentUIAbilityManager();
11671 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11672 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
11673 } else {
11674 auto missionListManager = GetCurrentMissionListManager();
11675 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
11676 abilityRecord = missionListManager->GetAbilityRecordByMissionId(missionId);
11677 }
11678 if (!abilityRecord) {
11679 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
11680 return ERR_INVALID_VALUE;
11681 }
11682 std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
11683 uniqueId_ = (uniqueId_ == INT_MAX) ? 0 : (uniqueId_ + 1);
11684 std::pair<int64_t, const sptr<IAcquireShareDataCallback>> shareDataPair =
11685 std::make_pair(abilityRecord->GetAbilityRecordId(), shareData);
11686 iAcquireShareDataMap_.emplace(uniqueId_, shareDataPair);
11687 abilityRecord->ShareData(uniqueId_);
11688 return ERR_OK;
11689 }
11690
ShareDataDone(const sptr<IRemoteObject> & token,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)11691 int32_t AbilityManagerService::ShareDataDone(
11692 const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
11693 {
11694 TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d", resultCode, uniqueId);
11695 if (!VerificationAllToken(token)) {
11696 return ERR_INVALID_VALUE;
11697 }
11698 auto abilityRecord = Token::GetAbilityRecordByToken(token);
11699 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record is nullptr.");
11700 if (!JudgeSelfCalled(abilityRecord)) {
11701 return CHECK_PERMISSION_FAILED;
11702 }
11703 CHECK_POINTER_AND_RETURN_LOG(eventHandler_, ERR_INVALID_VALUE, "fail to get abilityEventHandler.");
11704 eventHandler_->RemoveEvent(SHAREDATA_TIMEOUT_MSG, uniqueId);
11705 return GetShareDataPairAndReturnData(abilityRecord, resultCode, uniqueId, wantParam);
11706 }
11707
NotifySaveAsResult(const Want & want,int resultCode,int requestCode)11708 int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCode, int requestCode)
11709 {
11710 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
11711 TAG_LOGD(AAFwkTag::ABILITYMGR, "requestCode is %{public}d.", requestCode);
11712 CHECK_CALLER_IS_SYSTEM_APP;
11713 #ifdef WITH_DLP
11714 //caller check
11715 if (!DlpUtils::CheckCallerIsDlpManager(AbilityUtil::GetBundleManagerHelper())) {
11716 TAG_LOGW(AAFwkTag::ABILITYMGR, "caller check failed");
11717 return CHECK_PERMISSION_FAILED;
11718 }
11719 #endif // WITH_DLP
11720 auto checkResult = AbilityUtil::CheckInstanceKey(want);
11721 if (checkResult != ERR_OK) {
11722 return checkResult;
11723 }
11724 for (const auto &item : startAbilityChain_) {
11725 if (item.second && item.second->GetHandlerName() == StartAbilitySandboxSavefile::handlerName_) {
11726 auto savefileHandler = (StartAbilitySandboxSavefile*)(item.second.get());
11727 CHECK_POINTER_AND_RETURN(savefileHandler, ERR_INVALID_VALUE);
11728 savefileHandler->HandleResult(want, resultCode, requestCode);
11729 break;
11730 }
11731 }
11732 return ERR_OK;
11733 }
11734
SetRootSceneSession(const sptr<IRemoteObject> & rootSceneSession)11735 void AbilityManagerService::SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)
11736 {
11737 if (!IsCallerSceneBoard()) {
11738 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11739 return;
11740 }
11741 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11742 CHECK_POINTER(uiAbilityManager);
11743 uiAbilityManager->SetRootSceneSession(rootSceneSession);
11744 }
11745
CallUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isColdStart)11746 void AbilityManagerService::CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isColdStart)
11747 {
11748 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
11749 if (!IsCallerSceneBoard()) {
11750 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11751 return;
11752 }
11753 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11754 CHECK_POINTER(uiAbilityManager);
11755 uiAbilityManager->CallUIAbilityBySCB(sessionInfo, isColdStart);
11756 }
11757
SetSessionManagerService(const sptr<IRemoteObject> & sessionManagerService)11758 int32_t AbilityManagerService::SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)
11759 {
11760 if (!IsCallerSceneBoard()) {
11761 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11762 return ERR_WRONG_INTERFACE_CALL;
11763 }
11764
11765 TAG_LOGI(AAFwkTag::ABILITYMGR, "call setSessionManagerService of WMS");
11766 bool ret = Rosen::MockSessionManagerService::GetInstance().SetSessionManagerService(sessionManagerService);
11767 if (ret) {
11768 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
11769 return ERR_OK;
11770 }
11771 TAG_LOGE(AAFwkTag::ABILITYMGR, "SMS setSessionManagerService return false");
11772 return SET_SMS_FAILED;
11773 }
11774
StartSpecifiedAbilityBySCB(const Want & want)11775 int32_t AbilityManagerService::StartSpecifiedAbilityBySCB(const Want &want)
11776 {
11777 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11778 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
11779 if (!IsCallerSceneBoard()) {
11780 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11781 return ERR_PERMISSION_DENIED;
11782 }
11783
11784 int32_t appIndex = 0;
11785 if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex)) {
11786 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app clone index");
11787 return ERR_APP_CLONE_INDEX_INVALID;
11788 }
11789 auto result = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
11790 GetUserId(), appIndex, nullptr, true);
11791 if (result != ERR_OK) {
11792 return result;
11793 }
11794
11795 AbilityRequest abilityRequest;
11796 result = GenerateAbilityRequest(want, -1, abilityRequest, want.GetRemoteObject(TOKEN_KEY), GetUserId());
11797 if (result != ERR_OK) {
11798 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request error");
11799 return result;
11800 }
11801 if (!HandleExecuteSAInterceptor(want, want.GetRemoteObject(TOKEN_KEY), abilityRequest, result)) {
11802 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptor prevented");
11803 return result;
11804 }
11805
11806 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11807 CHECK_POINTER_AND_RETURN_LOG(uiAbilityManager, INNER_ERR, "uiAbilityManager is nullptr.");
11808 return uiAbilityManager->StartSpecifiedAbilityBySCB(abilityRequest);
11809 }
11810
RegisterIAbilityManagerCollaborator(int32_t type,const sptr<IAbilityManagerCollaborator> & impl)11811 int32_t AbilityManagerService::RegisterIAbilityManagerCollaborator(
11812 int32_t type, const sptr<IAbilityManagerCollaborator> &impl)
11813 {
11814 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
11815 auto callingUid = IPCSkeleton::GetCallingUid();
11816 if (!isSaCall || (callingUid != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
11817 callingUid != AppUtils::GetInstance().GetCollaboratorBrokerReserveUID())) {
11818 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
11819 return CHECK_PERMISSION_FAILED;
11820 }
11821 if (!CheckCollaboratorType(type)) {
11822 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator register failed, invalid type");
11823 return ERR_INVALID_VALUE;
11824 }
11825 {
11826 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
11827 collaboratorMap_[type] = impl;
11828 }
11829 return ERR_OK;
11830 }
11831
UnregisterIAbilityManagerCollaborator(int32_t type)11832 int32_t AbilityManagerService::UnregisterIAbilityManagerCollaborator(int32_t type)
11833 {
11834 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
11835 auto callingUid = IPCSkeleton::GetCallingUid();
11836 if (!isSaCall || (callingUid != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
11837 callingUid != AppUtils::GetInstance().GetCollaboratorBrokerReserveUID())) {
11838 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
11839 return CHECK_PERMISSION_FAILED;
11840 }
11841 if (!CheckCollaboratorType(type)) {
11842 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator unregister failed, invalid type");
11843 return ERR_INVALID_VALUE;
11844 }
11845 {
11846 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
11847 collaboratorMap_.erase(type);
11848 }
11849 return ERR_OK;
11850 }
11851
GetCollaboratorType(const std::string & codePath) const11852 int32_t AbilityManagerService::GetCollaboratorType(const std::string &codePath) const
11853 {
11854 if (codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
11855 return CollaboratorType::RESERVE_TYPE;
11856 } else if (codePath == std::to_string(CollaboratorType::OTHERS_TYPE)) {
11857 return CollaboratorType::OTHERS_TYPE;
11858 }
11859 return 0;
11860 }
11861
GetAbilityManagerCollaborator()11862 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetAbilityManagerCollaborator()
11863 {
11864 if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
11865 TAG_LOGE(AAFwkTag::ABILITYMGR, "not foundation call");
11866 return nullptr;
11867 }
11868 return GetCollaborator(CollaboratorType::RESERVE_TYPE);
11869 }
11870
GetCollaborator(int32_t type)11871 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetCollaborator(int32_t type)
11872 {
11873 if (!CheckCollaboratorType(type)) {
11874 return nullptr;
11875 }
11876 {
11877 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
11878 auto it = collaboratorMap_.find(type);
11879 if (it != collaboratorMap_.end()) {
11880 return it->second;
11881 }
11882 }
11883 return nullptr;
11884 }
11885
CheckCollaboratorType(int32_t type)11886 bool AbilityManagerService::CheckCollaboratorType(int32_t type)
11887 {
11888 if (type != CollaboratorType::RESERVE_TYPE && type != CollaboratorType::OTHERS_TYPE) {
11889 return false;
11890 }
11891 return true;
11892 }
11893
GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> & sessionInfo,std::shared_ptr<AbilityConnectManager> & connectManager,std::shared_ptr<AbilityRecord> & targetAbility,bool needCheck)11894 void AbilityManagerService::GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo,
11895 std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility,
11896 bool needCheck)
11897 {
11898 targetAbility = nullptr;
11899 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
11900 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId=%{public}d", userId);
11901 connectManager = GetConnectManagerByUserId(userId);
11902 if (connectManager) {
11903 targetAbility = connectManager->GetUIExtensionBySessionInfo(sessionInfo);
11904 if (needCheck && targetAbility == nullptr) {
11905 targetAbility = connectManager->GetUIExtensionBySessionFromServiceMap(sessionInfo);
11906 }
11907 } else {
11908 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:%{public}d", userId);
11909 }
11910 if (targetAbility == nullptr && userId != U0_USER_ID) {
11911 TAG_LOGD(AAFwkTag::ABILITYMGR, "try to find UIExtension in user0");
11912 connectManager = GetConnectManagerByUserId(U0_USER_ID);
11913 if (connectManager) {
11914 targetAbility = connectManager->GetUIExtensionBySessionInfo(sessionInfo);
11915 if (needCheck && targetAbility == nullptr) {
11916 targetAbility = connectManager->GetUIExtensionBySessionFromServiceMap(sessionInfo);
11917 }
11918 } else {
11919 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:0");
11920 }
11921 }
11922 }
11923
RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)11924 int32_t AbilityManagerService::RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)
11925 {
11926 if (!IsCallerSceneBoard()) {
11927 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11928 return ERR_WRONG_INTERFACE_CALL;
11929 }
11930 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11931 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11932 return uiAbilityManager->RegisterStatusBarDelegate(delegate);
11933 }
11934
KillProcessWithPrepareTerminate(const std::vector<int32_t> & pids)11935 int32_t AbilityManagerService::KillProcessWithPrepareTerminate(const std::vector<int32_t>& pids)
11936 {
11937 if (!IsCallerSceneBoard()) {
11938 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11939 return ERR_WRONG_INTERFACE_CALL;
11940 }
11941 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11942 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11943 return uiAbilityManager->TryPrepareTerminateByPids(pids);
11944 }
11945
ProcessLowMemoryKill(int32_t pid,const ExitReason & reason,bool isKillPrecedeStart)11946 bool AbilityManagerService::ProcessLowMemoryKill(int32_t pid, const ExitReason &reason, bool isKillPrecedeStart)
11947 {
11948 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11949 if (!isKillPrecedeStart) {
11950 return false;
11951 }
11952 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11953 if (uiAbilityManager == nullptr) {
11954 TAG_LOGW(AAFwkTag::ABILITYMGR, "null uiAbilityManager");
11955 return false;
11956 }
11957 if (uiAbilityManager->IsBundleStarting(pid)) {
11958 return true;
11959 }
11960 // set ability record kill reason
11961 uiAbilityManager->RecordPidKilling(pid, reason.exitMsg, isKillPrecedeStart);
11962 return false;
11963 }
11964
KillProcessWithReason(int32_t pid,const ExitReason & reason)11965 int32_t AbilityManagerService::KillProcessWithReason(int32_t pid, const ExitReason &reason)
11966 {
11967 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11968 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
11969 bool isKillPrecedeStart =
11970 (reason.reason == Reason::REASON_RESOURCE_CONTROL && reason.exitMsg == GlobalConstant::LOW_MEMORY_KILL) ||
11971 reason.shouldSkipKillInStartup;
11972 EventInfo eventInfo;
11973 eventInfo.callerPid = IPCSkeleton::GetCallingPid();
11974 eventInfo.pid = pid;
11975 eventInfo.exitMsg = reason.exitMsg;
11976 eventInfo.shouldKillForeground = reason.shouldKillForeground;
11977 auto ret = KillProcessWithReasonInner(pid, reason, isKillPrecedeStart);
11978 TAG_LOGE(AAFwkTag::ABILITYMGR, "KillProcessWithReason ret: %{public}d, reason: %{public}s", ret,
11979 reason.exitMsg.c_str());
11980 if (isKillPrecedeStart) {
11981 eventHelper_.SendKillProcessWithReasonEvent(ret, "KillProcessWithReason", eventInfo);
11982 }
11983 return ret;
11984 }
11985
KillProcessWithReasonInner(int32_t pid,const ExitReason & reason,bool isKillPrecedeStart)11986 int32_t AbilityManagerService::KillProcessWithReasonInner(int32_t pid, const ExitReason &reason,
11987 bool isKillPrecedeStart)
11988 {
11989 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11990 bool supportShell = AmsConfigurationParameter::GetInstance().IsSupportAAKillWithReason();
11991 auto isShellCall = PermissionVerification::GetInstance()->IsShellCall();
11992 auto isCallingPerm = PermissionVerification::GetInstance()->VerifyCallingPermission(
11993 AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
11994 if (!isCallingPerm && !(supportShell && isShellCall)) {
11995 TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
11996 return ERR_PERMISSION_DENIED;
11997 }
11998
11999 if (!reason.shouldKillForeground) {
12000 AppExecFwk::RunningProcessInfo processInfo;
12001 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(pid, processInfo);
12002 if (processInfo.isAbilityForegrounding || processInfo.isFocused) {
12003 TAG_LOGI(AAFwkTag::ABILITYMGR, "do not kill foreground apps, pid = %{public}d", pid);
12004 return ERR_KILL_APP_WHILE_FOREGROUND;
12005 }
12006 }
12007
12008 if (ProcessLowMemoryKill(pid, reason, isKillPrecedeStart)) {
12009 // if app is already starting, return
12010 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}d is starting", pid);
12011 return ERR_KILL_APP_WHILE_STARTING;
12012 }
12013 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
12014 auto ret = appExitReasonHelper_->RecordProcessExitReason(pid, reason, true);
12015 if (ret != ERR_OK) {
12016 TAG_LOGW(AAFwkTag::ABILITYMGR, "RecordAppExitReason failed, ret:%{public}d", ret);
12017 }
12018 std::vector<int32_t> pidToBeKilled = { pid };
12019 return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->KillProcessesByPids(pidToBeKilled,
12020 reason.exitMsg, true, isKillPrecedeStart));
12021 }
12022
RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)12023 int32_t AbilityManagerService::RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
12024 {
12025 if (abilityAutoStartupService_ == nullptr) {
12026 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
12027 return ERR_NO_INIT;
12028 }
12029 return abilityAutoStartupService_->RegisterAutoStartupSystemCallback(callback);
12030 }
12031
UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)12032 int32_t AbilityManagerService::UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
12033 {
12034 if (abilityAutoStartupService_ == nullptr) {
12035 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
12036 return ERR_NO_INIT;
12037 }
12038 return abilityAutoStartupService_->UnregisterAutoStartupSystemCallback(callback);
12039 }
12040
SetApplicationAutoStartup(const AutoStartupInfo & info)12041 int32_t AbilityManagerService::SetApplicationAutoStartup(const AutoStartupInfo &info)
12042 {
12043 if (abilityAutoStartupService_ == nullptr) {
12044 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
12045 return ERR_NO_INIT;
12046 }
12047 return abilityAutoStartupService_->SetApplicationAutoStartup(info);
12048 }
12049
CancelApplicationAutoStartup(const AutoStartupInfo & info)12050 int32_t AbilityManagerService::CancelApplicationAutoStartup(const AutoStartupInfo &info)
12051 {
12052 if (abilityAutoStartupService_ == nullptr) {
12053 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
12054 return ERR_NO_INIT;
12055 }
12056 return abilityAutoStartupService_->CancelApplicationAutoStartup(info);
12057 }
12058
QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> & infoList)12059 int32_t AbilityManagerService::QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)
12060 {
12061 if (abilityAutoStartupService_ == nullptr) {
12062 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
12063 return ERR_NO_INIT;
12064 }
12065 return abilityAutoStartupService_->QueryAllAutoStartupApplications(infoList, GetUserId());
12066 }
12067
PrepareTerminateAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isTerminate)12068 int AbilityManagerService::PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)
12069 {
12070 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12071 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
12072 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
12073 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
12074 return ERR_INVALID_VALUE;
12075 }
12076
12077 if (!IsCallerSceneBoard()) {
12078 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sceneboard called, not allowed");
12079 return ERR_WRONG_INTERFACE_CALL;
12080 }
12081
12082 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12083 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12084 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
12085 isTerminate = uiAbilityManager->PrepareTerminateAbility(abilityRecord, true);
12086
12087 return ERR_OK;
12088 }
12089
RegisterSessionHandler(const sptr<IRemoteObject> & object)12090 int AbilityManagerService::RegisterSessionHandler(const sptr<IRemoteObject> &object)
12091 {
12092 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12093 if (!IsCallerSceneBoard()) {
12094 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
12095 return ERR_WRONG_INTERFACE_CALL;
12096 }
12097 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12098 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12099 sptr<ISessionHandler> handler = iface_cast<ISessionHandler>(object);
12100 uiAbilityManager->SetSessionHandler(handler);
12101 return ERR_OK;
12102 }
12103
RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)12104 int32_t AbilityManagerService::RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
12105 {
12106 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12107 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
12108 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
12109 return CHECK_PERMISSION_FAILED;
12110 }
12111 return DelayedSingleton<AppScheduler>::GetInstance()->RegisterAppDebugListener(listener);
12112 }
12113
UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)12114 int32_t AbilityManagerService::UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
12115 {
12116 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12117 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
12118 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
12119 return CHECK_PERMISSION_FAILED;
12120 }
12121 return DelayedSingleton<AppScheduler>::GetInstance()->UnregisterAppDebugListener(listener);
12122 }
12123
ConnectInitAbilityDebugDeal()12124 std::shared_ptr<AbilityDebugDeal> AbilityManagerService::ConnectInitAbilityDebugDeal()
12125 {
12126 if (abilityDebugDeal_ != nullptr) {
12127 return abilityDebugDeal_;
12128 }
12129
12130 std::unique_lock<ffrt::mutex> lock(abilityDebugDealLock_);
12131 if (abilityDebugDeal_ != nullptr) {
12132 return abilityDebugDeal_;
12133 }
12134
12135 TAG_LOGD(AAFwkTag::ABILITYMGR, "Creat ability debug deal object.");
12136 abilityDebugDeal_ = std::make_shared<AbilityDebugDeal>();
12137 if (abilityDebugDeal_ == nullptr) {
12138 TAG_LOGE(AAFwkTag::ABILITYMGR, "creat ability debug deal object failed");
12139 return nullptr;
12140 }
12141
12142 abilityDebugDeal_->RegisterAbilityDebugResponse();
12143 return abilityDebugDeal_;
12144 }
12145
AttachAppDebug(const std::string & bundleName,bool isDebugFromLocal)12146 int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName, bool isDebugFromLocal)
12147 {
12148 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12149 if (isDebugFromLocal &&
12150 !AAFwk::PermissionVerification::GetInstance()->VerifyStartLocalDebug(IPCSkeleton::GetCallingTokenID())) {
12151 TAG_LOGE(AAFwkTag::ABILITYMGR, "local debugging, permission denied");
12152 return CHECK_PERMISSION_FAILED;
12153 } else if (!isDebugFromLocal && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
12154 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
12155 return ERR_NOT_DEVELOPER_MODE;
12156 }
12157
12158 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
12159 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
12160 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
12161 return CHECK_PERMISSION_FAILED;
12162 }
12163
12164 int32_t err = ERR_OK;
12165 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
12166 if ((err = StartAbilityUtils::CheckAppProvisionMode(bundleName, userId)) != ERR_OK) {
12167 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckAppProvisionMode returns errcode=%{public}d", err);
12168 return err;
12169 }
12170
12171 ConnectInitAbilityDebugDeal();
12172 return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->AttachAppDebug(bundleName, isDebugFromLocal));
12173 }
12174
DetachAppDebug(const std::string & bundleName,bool isDebugFromLocal)12175 int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName, bool isDebugFromLocal)
12176 {
12177 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12178 if (isDebugFromLocal &&
12179 !AAFwk::PermissionVerification::GetInstance()->VerifyStartLocalDebug(IPCSkeleton::GetCallingTokenID())) {
12180 TAG_LOGE(AAFwkTag::ABILITYMGR, "local debugging, permission denied");
12181 return CHECK_PERMISSION_FAILED;
12182 } else if (!isDebugFromLocal && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
12183 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
12184 return ERR_NOT_DEVELOPER_MODE;
12185 }
12186
12187 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
12188 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
12189 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
12190 return CHECK_PERMISSION_FAILED;
12191 }
12192
12193 int32_t err = ERR_OK;
12194 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
12195 if ((err = StartAbilityUtils::CheckAppProvisionMode(bundleName, userId)) != ERR_OK) {
12196 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckAppProvisionMode returns errcode=%{public}d", err);
12197 return err;
12198 }
12199
12200 return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->DetachAppDebug(bundleName));
12201 }
12202
InsightIntentGetcallerBundleName()12203 std::string AbilityManagerService::InsightIntentGetcallerBundleName()
12204 {
12205 TAG_LOGD(AAFwkTag::ABILITYMGR, "InsightIntentGetcallerBundleName called");
12206 int32_t callerUid = IPCSkeleton::GetCallingUid();
12207 auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
12208 std::string callerBundlename;
12209 if (bundleMgr != nullptr) {
12210 IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, callerBundlename));
12211 }
12212 return callerBundlename;
12213 }
12214
ExecuteIntent(uint64_t key,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)12215 int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken,
12216 const InsightIntentExecuteParam ¶m)
12217 {
12218 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12219 auto callerBundlename = InsightIntentGetcallerBundleName();
12220 if (callerBundlename.empty()) {
12221 TAG_LOGD(AAFwkTag::ABILITYMGR, "callerBundlename is null");
12222 }
12223 AbilityRuntime::ExtractInsightIntentGenericInfo infos = GetInsightIntentGenericInfo(param);
12224 bool openLinkExecuteFlag = infos.decoratorType == AbilityRuntime::INSIGHT_INTENTS_DECORATOR_TYPE_LINK;
12225 bool ignoreAbilityName = openLinkExecuteFlag ||
12226 (infos.decoratorType == AbilityRuntime::INSIGHT_INTENTS_DECORATOR_TYPE_PAGE) ||
12227 (infos.decoratorType == AbilityRuntime::INSIGHT_INTENTS_DECORATOR_TYPE_FUNCTION);
12228 auto paramPtr = std::make_shared<InsightIntentExecuteParam>(param);
12229 int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateParam(key, callerToken,
12230 paramPtr, callerBundlename, ignoreAbilityName);
12231 if (ret != ERR_OK) {
12232 return ret;
12233 }
12234 TAG_LOGI(AAFwkTag::ABILITYMGR, "execute insight intent, bundleName: %{public}s, moduleName: %{public}s, "
12235 "intentName: %{public}s, intentId:%{public}" PRIu64", openLinkExecuteFlag: %{public}d, executeMode: %{public}d",
12236 param.bundleName_.c_str(), param.moduleName_.c_str(), param.insightIntentName_.c_str(), param.insightIntentId_,
12237 openLinkExecuteFlag, param.executeMode_);
12238
12239 if (openLinkExecuteFlag) {
12240 return IntentOpenLinkInner(paramPtr, infos, -1);
12241 }
12242
12243 Want want;
12244 ret = InsightIntentExecuteManager::GenerateWant(paramPtr, infos, want);
12245 if (ret != ERR_OK) {
12246 return ret;
12247 }
12248 EventInfo eventInfo = BuildEventInfo(want, GetUserId());
12249 switch (param.executeMode_) {
12250 case AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND:
12251 TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_FOREGROUND.");
12252 ret = StartAbilityWithInsightIntent(want);
12253 if (ret != ERR_OK) {
12254 eventInfo.errReason = "StartAbilityWithInsightIntent error";
12255 SendIntentReport(eventInfo, ret, param.insightIntentName_);
12256 }
12257 break;
12258 case AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND: {
12259 TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_BACKGROUND.");
12260 ret = StartAbilityByCallWithInsightIntent(want, callerToken, param);
12261 if (ret != ERR_OK) {
12262 eventInfo.errReason = "StartAbilityByCallWithInsightIntent error";
12263 SendIntentReport(eventInfo, ret, param.insightIntentName_);
12264 }
12265 break;
12266 }
12267 case AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY:
12268 TAG_LOGW(AAFwkTag::ABILITYMGR, "executeMode UI_EXTENSION_ABILITY not supported");
12269 ret = ERR_INVALID_OPERATION;
12270 break;
12271 case AppExecFwk::ExecuteMode::SERVICE_EXTENSION_ABILITY:
12272 TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode SERVICE_EXTENSION_ABILITY.");
12273 ret = StartExtensionAbilityWithInsightIntent(want, AppExecFwk::ExtensionAbilityType::SERVICE);
12274 if (ret != ERR_OK) {
12275 eventInfo.errReason = "StartExtensionAbilityWithInsightIntent error";
12276 SendIntentReport(eventInfo, ret, param.insightIntentName_);
12277 }
12278 break;
12279 default:
12280 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid executeMode");
12281 ret = ERR_INVALID_OPERATION;
12282 break;
12283 }
12284 if (ret == START_ABILITY_WAITING) {
12285 TAG_LOGI(AAFwkTag::ABILITYMGR, "Top ability is foregrounding. The intent will be queued for execution");
12286 ret = ERR_OK;
12287 }
12288 if (ret != ERR_OK) {
12289 DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->RemoveExecuteIntent(paramPtr->insightIntentId_);
12290 }
12291 TAG_LOGI(AAFwkTag::ABILITYMGR, "ExecuteIntent done, ret: %{public}d.", ret);
12292 return ret;
12293 }
12294
IsAbilityStarted(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord,const int32_t oriValidUserId)12295 bool AbilityManagerService::IsAbilityStarted(AbilityRequest &abilityRequest,
12296 std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)
12297 {
12298 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
12299 TAG_LOGI(AAFwkTag::ABILITYMGR, "scene board enable");
12300 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
12301 CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
12302 return uiAbilityManager->IsAbilityStarted(abilityRequest, targetRecord);
12303 }
12304
12305 auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
12306 if (missionListMgr == nullptr) {
12307 return false;
12308 }
12309 return missionListMgr->IsAbilityStarted(abilityRequest, targetRecord);
12310 }
12311
OnExecuteIntent(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord)12312 int32_t AbilityManagerService::OnExecuteIntent(AbilityRequest &abilityRequest,
12313 std::shared_ptr<AbilityRecord> &targetRecord)
12314 {
12315 TAG_LOGI(AAFwkTag::ABILITYMGR, "onExecuteIntent");
12316 if (targetRecord == nullptr || targetRecord->GetScheduler() == nullptr) {
12317 TAG_LOGE(AAFwkTag::ABILITYMGR, "null scheduler");
12318 return ERR_INVALID_VALUE;
12319 }
12320 targetRecord->GetScheduler()->OnExecuteIntent(abilityRequest.want);
12321
12322 return ERR_OK;
12323 }
12324
StartAbilityWithInsightIntent(const Want & want,int32_t userId,int requestCode)12325 int32_t AbilityManagerService::StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)
12326 {
12327 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12328 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
12329 if (startWithAccount || IsCrossUserCall(userId)) {
12330 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
12331 CHECK_CALLER_IS_SYSTEM_APP;
12332 }
12333 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
12334 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
12335 EventInfo eventInfo = BuildEventInfo(want, userId);
12336 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12337 int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
12338 if (ret != ERR_OK) {
12339 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbilityError:%{public}d", ret);
12340 }
12341 return ret;
12342 }
12343
StartExtensionAbilityWithInsightIntent(const Want & want,AppExecFwk::ExtensionAbilityType extensionType)12344 int32_t AbilityManagerService::StartExtensionAbilityWithInsightIntent(const Want &want,
12345 AppExecFwk::ExtensionAbilityType extensionType)
12346 {
12347 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12348 return StartExtensionAbilityInner(want, nullptr, DEFAULT_INVAL_VALUE, extensionType, true);
12349 }
12350
StartAbilityByCallWithInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)12351 int32_t AbilityManagerService::StartAbilityByCallWithInsightIntent(const Want &want,
12352 const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam ¶m)
12353 {
12354 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12355 sptr<IAbilityConnection> connect = sptr<AbilityBackgroundConnection>::MakeSptr();
12356 if (connect == nullptr) {
12357 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid connect");
12358 return ERR_INVALID_VALUE;
12359 }
12360
12361 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
12362 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
12363 AbilityRequest abilityRequest;
12364 abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
12365 abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
12366 abilityRequest.callerToken = callerToken;
12367 abilityRequest.startSetting = nullptr;
12368 abilityRequest.want = want;
12369 abilityRequest.connect = connect;
12370 int32_t result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
12371 if (result != ERR_OK) {
12372 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request error");
12373 return result;
12374 }
12375 std::shared_ptr<AbilityRecord> targetRecord;
12376 int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
12377 auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
12378 if (IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId)) {
12379 TAG_LOGI(AAFwkTag::ABILITYMGR, "ability has already started");
12380 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
12381 result = OnExecuteIntent(abilityRequest, targetRecord);
12382 } else {
12383 result = StartAbilityByCall(want, connect, callerToken);
12384 }
12385 ResSchedUtil::GetInstance().ReportAbilityIntentExemptionInfoToRSS(abilityRequest.uid, 0);
12386 DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->SetIntentExemptionInfo(
12387 abilityRequest.uid);
12388 TAG_LOGD(AAFwkTag::ABILITYMGR, "startAbilityByCallWithInsightIntent %{public}d uid:%{public}d",
12389 result, abilityRequest.uid);
12390 return result;
12391 }
12392
IsAbilityControllerStart(const Want & want)12393 bool AbilityManagerService::IsAbilityControllerStart(const Want &want)
12394 {
12395 auto callingUid = IPCSkeleton::GetCallingUid();
12396 bool isBrokerCall = (callingUid == AppUtils::GetInstance().GetCollaboratorBrokerUID() ||
12397 callingUid == AppUtils::GetInstance().GetCollaboratorBrokerReserveUID());
12398 if (isBrokerCall) {
12399 return IsAbilityControllerStart(want, want.GetBundle());
12400 }
12401 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
12402 return true;
12403 }
12404
ExecuteInsightIntentDone(const sptr<IRemoteObject> & token,uint64_t intentId,const InsightIntentExecuteResult & result)12405 int32_t AbilityManagerService::ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId,
12406 const InsightIntentExecuteResult &result)
12407 {
12408 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12409 auto abilityRecord = Token::GetAbilityRecordByToken(token);
12410 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
12411 if (!JudgeSelfCalled(abilityRecord)) {
12412 return CHECK_PERMISSION_FAILED;
12413 }
12414
12415 // check send by same bundleName.
12416 std::string bundleNameStored = "";
12417 auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetBundleName(intentId, bundleNameStored);
12418 if (ret != ERR_OK) {
12419 TAG_LOGE(AAFwkTag::ABILITYMGR, "matched bundleName failed, intentId:%{public}" PRIu64"", intentId);
12420 return ERR_INVALID_VALUE;
12421 }
12422
12423 std::string bundleName = abilityRecord->GetAbilityInfo().bundleName;
12424 if (bundleNameStored != bundleName) {
12425 TAG_LOGE(AAFwkTag::ABILITYMGR,
12426 "bundleName %{public}s and %{public}s mismatch", bundleName.c_str(), bundleNameStored.c_str());
12427 return ERR_INVALID_VALUE;
12428 }
12429
12430 std::string callerBundleName;
12431 DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetCallerBundleName(intentId, callerBundleName);
12432 uint32_t initiatorTokenId = abilityRecord->GetApplicationInfo().accessTokenId;
12433 #ifdef SUPPORT_UPMS
12434 if (!callerBundleName.empty()) {
12435 abilityRecord->GrantUriPermission(result.uris, result.flags, callerBundleName, initiatorTokenId);
12436 }
12437 #endif // SUPPORT_UPMS
12438
12439 return DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
12440 intentId, result.innerErr, result);
12441 }
12442
SetApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)12443 int32_t AbilityManagerService::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
12444 {
12445 if (abilityAutoStartupService_ == nullptr) {
12446 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
12447 return ERR_NO_INIT;
12448 }
12449 return abilityAutoStartupService_->SetApplicationAutoStartupByEDM(info, flag);
12450 }
12451
CancelApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)12452 int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
12453 {
12454 if (abilityAutoStartupService_ == nullptr) {
12455 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
12456 return ERR_NO_INIT;
12457 }
12458 return abilityAutoStartupService_->CancelApplicationAutoStartupByEDM(info, flag);
12459 }
12460
GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> & list)12461 int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)
12462 {
12463 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12464 CHECK_CALLER_IS_SYSTEM_APP;
12465 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
12466 if (!isPerm) {
12467 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
12468 return CHECK_PERMISSION_FAILED;
12469 }
12470
12471 std::vector<AbilityRunningInfo> abilityRunningInfos;
12472 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
12473 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12474 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12475 uiAbilityManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
12476 } else {
12477 auto missionListManager = GetCurrentMissionListManager();
12478 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NULL_OBJECT);
12479 missionListManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
12480 }
12481
12482 for (auto &info : abilityRunningInfos) {
12483 if (info.abilityState != AbilityState::FOREGROUND) {
12484 continue;
12485 }
12486
12487 AppExecFwk::AbilityStateData abilityData;
12488 abilityData.bundleName = info.ability.GetBundleName();
12489 abilityData.moduleName = info.ability.GetModuleName();
12490 abilityData.abilityName = info.ability.GetAbilityName();
12491 abilityData.abilityState = info.abilityState;
12492 abilityData.pid = info.pid;
12493 abilityData.uid = info.uid;
12494 abilityData.abilityType = static_cast<int32_t>(AppExecFwk::AbilityType::PAGE);
12495 abilityData.appCloneIndex = info.appCloneIndex;
12496 AppExecFwk::ApplicationInfo appInfo;
12497 if (!StartAbilityUtils::GetApplicationInfo(abilityData.bundleName, GetUserId(), appInfo)) {
12498 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't get applicationInfo through bundleName");
12499 } else if (appInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
12500 abilityData.isAtomicService = true;
12501 }
12502 list.push_back(abilityData);
12503 }
12504 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get foreground ui abilities end, list.size = %{public}zu.", list.size());
12505 return ERR_OK;
12506 }
12507
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)12508 void AbilityManagerService::NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)
12509 {
12510 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
12511 if (collaborator == nullptr) {
12512 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator getCollaborator null");
12513 return;
12514 }
12515 collaborator->UpdateConfiguration(config, userId);
12516 }
12517
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)12518 void AbilityManagerService::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
12519 {
12520 if (userController_ == nullptr) {
12521 TAG_LOGE(AAFwkTag::ABILITYMGR, "userController_ null");
12522 return;
12523 }
12524 auto currentUser = userController_->GetCurrentUserId();
12525 std::vector<AppExecFwk::BundleInfo> bundleInfosForU0;
12526 std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
12527 for (const auto &item: bundleInfos) {
12528 auto user = item.uid / BASE_USER_RANGE;
12529 if (user == U0_USER_ID) {
12530 bundleInfosForU0.push_back(item);
12531 } else if (user == currentUser) {
12532 bundleInfosForCurrentUser.push_back(item);
12533 }
12534 }
12535
12536 auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
12537 CHECK_POINTER(residentProcessMgr);
12538
12539 residentProcessMgr->StartResidentProcessWithMainElement(
12540 bundleInfosForU0, U0_USER_ID);
12541 if (!bundleInfosForU0.empty()) {
12542 residentProcessMgr->StartResidentProcess(bundleInfosForU0);
12543 }
12544
12545 residentProcessMgr->StartResidentProcessWithMainElement(
12546 bundleInfosForCurrentUser, currentUser);
12547 if (!bundleInfosForCurrentUser.empty()) {
12548 residentProcessMgr->StartResidentProcess(bundleInfosForCurrentUser);
12549 }
12550 }
12551
NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)12552 void AbilityManagerService::NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
12553 {
12554 if (!system::GetBoolParameter(PRODUCT_ENTERPRISE_FEATURE_SETTING_ENABLED, false)) {
12555 return;
12556 }
12557
12558 auto userId = GetUserId();
12559 std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
12560 std::vector<AppExecFwk::BundleInfo> bundleInfosForU1;
12561 for (const auto &item: bundleInfos) {
12562 if (item.uid / BASE_USER_RANGE == U1_USER_ID) {
12563 bundleInfosForU1.push_back(item);
12564 } else if (item.uid / BASE_USER_RANGE == userId) {
12565 bundleInfosForCurrentUser.push_back(item);
12566 } else {
12567 TAG_LOGI(AAFwkTag::ABILITYMGR, "keepAlive not U1 or current user.");
12568 KeepAliveProcessManager::GetInstance().AddNeedRestartKeepAliveUid(item.uid);
12569 }
12570 }
12571
12572 if (bundleInfosForCurrentUser.size() != 0) {
12573 KeepAliveProcessManager::GetInstance().StartKeepAliveProcessWithMainElement(bundleInfosForCurrentUser, userId);
12574 }
12575
12576 if (bundleInfosForU1.size() != 0) {
12577 KeepAliveProcessManager::GetInstance().StartKeepAliveAppServiceExtension(bundleInfosForU1);
12578 }
12579 }
12580
NotifyAppPreCache(int32_t pid,int32_t userId)12581 void AbilityManagerService::NotifyAppPreCache(int32_t pid, int32_t userId)
12582 {
12583 ForceTerminateServiceExtensionByPid(pid, userId);
12584 }
12585
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> & abilityTokens)12586 void AbilityManagerService::OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens)
12587 {
12588 std::shared_ptr<AbilityRecord> abilityRecord;
12589 for (auto &token : abilityTokens) {
12590 abilityRecord = Token::GetAbilityRecordByToken(token);
12591 if (abilityRecord == nullptr) {
12592 continue;
12593 }
12594 TAG_LOGI(AAFwkTag::ABILITYMGR, "app onRemoteDied, ability:%{public}s, app:%{public}s",
12595 abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
12596 abilityRecord->OnProcessDied();
12597 }
12598 }
12599
OnStartProcessFailed(const std::vector<sptr<IRemoteObject>> & abilityTokens)12600 void AbilityManagerService::OnStartProcessFailed(const std::vector<sptr<IRemoteObject>> &abilityTokens)
12601 {
12602 std::shared_ptr<AbilityRecord> abilityRecord;
12603 for (auto &token : abilityTokens) {
12604 abilityRecord = Token::GetAbilityRecordByToken(token);
12605 if (abilityRecord == nullptr) {
12606 continue;
12607 }
12608 TAG_LOGW(AAFwkTag::ABILITYMGR, "NotifyStartProcessFailed, ability:%{public}s, bundle:%{public}s",
12609 abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
12610 if (abilityRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::EXTENSION) {
12611 auto connectManager = GetConnectManagerByToken(token);
12612 if (connectManager == nullptr) {
12613 TAG_LOGE(AAFwkTag::ABILITYMGR, "null connectManager");
12614 continue;
12615 }
12616 connectManager->OnLoadAbilityFailed(abilityRecord);
12617 }
12618 }
12619 }
12620
OnCacheExitInfo(uint32_t accessTokenId,const AppExecFwk::RunningProcessInfo & exitInfo,const std::string & bundleName,const std::vector<std::string> & abilityNames,const std::vector<std::string> & uiExtensionNames)12621 void AbilityManagerService::OnCacheExitInfo(uint32_t accessTokenId, const AppExecFwk::RunningProcessInfo &exitInfo,
12622 const std::string &bundleName, const std::vector<std::string> &abilityNames,
12623 const std::vector<std::string> &uiExtensionNames)
12624 {
12625 ExitCacheInfo cacheInfo = {};
12626 cacheInfo.exitInfo = exitInfo;
12627 cacheInfo.bundleName = bundleName;
12628 cacheInfo.abilityNames = abilityNames;
12629 cacheInfo.uiExtensionNames = uiExtensionNames;
12630 if (!ExitInfoDataManager::GetInstance().AddExitInfo(accessTokenId, cacheInfo)) {
12631 TAG_LOGE(AAFwkTag::ABILITYMGR, "AddExitInfo failed");
12632 return;
12633 }
12634 auto delayClearReason = [ accessTokenId ]() {
12635 if (!ExitInfoDataManager::GetInstance().DeleteExitInfo(accessTokenId)) {
12636 TAG_LOGE(AAFwkTag::ABILITYMGR, "DeleteExitInfo failed");
12637 return;
12638 }
12639 };
12640 ffrt::submit(std::move(delayClearReason), ffrt::task_attr()
12641 .delay(CLEAR_REASON_DELAY_TIME).name("delayClearReason")
12642 .timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
12643 }
12644
OpenFile(const Uri & uri,uint32_t flag)12645 int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag)
12646 {
12647 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
12648 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
12649 if (collaborator == nullptr) {
12650 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator getCollaborator null");
12651 return -1;
12652 }
12653 return collaborator->OpenFile(uri, flag, accessTokenId);
12654 }
12655
12656 #ifdef SUPPORT_SCREEN
GetDialogSessionInfo(const std::string & dialogSessionId,sptr<DialogSessionInfo> & dialogSessionInfo)12657 int AbilityManagerService::GetDialogSessionInfo(const std::string &dialogSessionId,
12658 sptr<DialogSessionInfo> &dialogSessionInfo)
12659 {
12660 CHECK_CALLER_IS_SYSTEM_APP;
12661 dialogSessionInfo = DialogSessionManager::GetInstance().GetDialogSessionInfo(dialogSessionId);
12662 if (dialogSessionInfo) {
12663 TAG_LOGD(AAFwkTag::ABILITYMGR, "success");
12664 return ERR_OK;
12665 }
12666 TAG_LOGD(AAFwkTag::ABILITYMGR, "fail");
12667 return INNER_ERR;
12668 }
12669
SendDialogResult(const Want & want,const std::string & dialogSessionId,bool isAllowed)12670 int AbilityManagerService::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed)
12671 {
12672 CHECK_CALLER_IS_SYSTEM_APP;
12673 return DialogSessionManager::GetInstance().SendDialogResult(want, dialogSessionId, isAllowed);
12674 }
12675
CreateCloneSelectorDialog(AbilityRequest & request,int32_t userId,const std::string & replaceWantString)12676 int AbilityManagerService::CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId,
12677 const std::string &replaceWantString)
12678 {
12679 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
12680 auto ret = implicitStartProcessor_->ImplicitStartAbility(request, userId, 0, replaceWantString, true);
12681 return AbilityErrorUtil::ConvertToOriginErrorCode(ret);
12682 }
12683 #endif // SUPPORT_SCREEN
RemoveSelectorIdentity(int32_t tokenId)12684 void AbilityManagerService::RemoveSelectorIdentity(int32_t tokenId)
12685 {
12686 CHECK_POINTER(implicitStartProcessor_);
12687 implicitStartProcessor_->RemoveIdentity(tokenId);
12688 }
12689
RemoveLauncherDeathRecipient(int32_t userId)12690 void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId)
12691 {
12692 auto connectManager = GetConnectManagerByUserId(userId);
12693 if (connectManager == nullptr) {
12694 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
12695 return;
12696 }
12697 connectManager->RemoveLauncherDeathRecipient();
12698 }
12699
GenerateEmbeddableUIAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)12700 int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest(
12701 const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
12702 {
12703 int32_t screenMode = want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
12704 int32_t result = ERR_OK;
12705 if (IsEmbeddableStart(screenMode)) {
12706 result = GenerateAbilityRequest(want, -1, request, callerToken, userId);
12707 request.abilityInfo.isModuleJson = true;
12708 request.abilityInfo.isStageBasedModel = true;
12709 request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
12710 request.abilityInfo.extensionAbilityType = AppExecFwk::ExtensionAbilityType::UI;
12711 struct timespec time = {0, 0};
12712 clock_gettime(CLOCK_MONOTONIC, &time);
12713 int64_t times = static_cast<int64_t>(time.tv_sec);
12714 request.abilityInfo.process = request.abilityInfo.bundleName + PROCESS_SUFFIX + std::to_string(times);
12715 } else {
12716 result = GenerateExtensionAbilityRequest(want, request, callerToken, userId);
12717 }
12718 return result;
12719 }
12720
CheckDebugAssertPermission()12721 int32_t AbilityManagerService::CheckDebugAssertPermission()
12722 {
12723 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12724 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12725 if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
12726 TAG_LOGE(AAFwkTag::ABILITYMGR, "assert fault product dialog not enabled");
12727 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
12728 }
12729 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
12730 TAG_LOGE(AAFwkTag::ABILITYMGR, "developer mode false");
12731 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
12732 }
12733
12734 auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
12735 CHECK_POINTER_AND_RETURN(bundleMgr, ERR_INVALID_VALUE);
12736 int32_t flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
12737 AppExecFwk::BundleInfo bundleInfo;
12738 auto ret = bundleMgr->GetBundleInfoForSelf(flags, bundleInfo);
12739 if (ret != ERR_OK) {
12740 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle info failed");
12741 return ret;
12742 }
12743 if (!bundleInfo.applicationInfo.debug) {
12744 TAG_LOGE(AAFwkTag::ABILITYMGR, "non-debug version app");
12745 return ERR_INVALID_VALUE;
12746 }
12747 return ERR_OK;
12748 }
12749
VerifySameAppOrAppIdentifierAllowListPermission(const AbilityRequest & abilityRequest)12750 bool AbilityManagerService::VerifySameAppOrAppIdentifierAllowListPermission(const AbilityRequest &abilityRequest)
12751 {
12752 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12753 std::string targetBundleName = abilityRequest.abilityInfo.bundleName;
12754 int32_t callerUid = IPCSkeleton::GetCallingUid();
12755 int32_t targetUid = abilityRequest.uid;
12756 if (callerUid == targetUid) {
12757 TAG_LOGD(AAFwkTag::ABILITYMGR, "same app");
12758 return true;
12759 }
12760 auto bms = AbilityUtil::GetBundleManagerHelper();
12761 CHECK_POINTER_AND_RETURN(bms, false);
12762 AppExecFwk::BundleInfo targetBundleInfo;
12763 int32_t userId = GetUserId();
12764 std::string callerAppIdentifier = abilityRequest.want.GetStringParam(Want::PARAM_RESV_CALLER_APP_IDENTIFIER);
12765 if (callerAppIdentifier.empty()) {
12766 AppExecFwk::SignatureInfo signatureInfo;
12767 auto abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
12768 if (abilityRecord == nullptr) {
12769 return false;
12770 }
12771 std::string callerBundleName = abilityRecord->GetApplicationInfo().bundleName;
12772 if (IN_PROCESS_CALL(bms->GetSignatureInfoByBundleName(callerBundleName,
12773 signatureInfo)) != ERR_OK) {
12774 TAG_LOGE(AAFwkTag::ABILITYMGR,
12775 "bms GetSignatureInfoByBundleName error, bundleName: %{public}s", callerBundleName.c_str());
12776 return false;
12777 };
12778 callerAppIdentifier = signatureInfo.appIdentifier;
12779 }
12780 if (!IN_PROCESS_CALL(bms->GetBundleInfo(targetBundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_EXTENSION_INFO,
12781 targetBundleInfo, userId))) {
12782 TAG_LOGE(AAFwkTag::ABILITYMGR, "bms GetBundleInfo error, BundleFlag: GET_BUNDLE_WITH_EXTENSION_INFO");
12783 return false;
12784 }
12785 for (const AppExecFwk::ExtensionAbilityInfo& info: targetBundleInfo.extensionInfos) {
12786 if (info.type == AppExecFwk::ExtensionAbilityType::APP_SERVICE &&
12787 info.name == abilityRequest.abilityInfo.name) {
12788 if (std::find(info.appIdentifierAllowList.begin(), info.appIdentifierAllowList.end(),
12789 callerAppIdentifier) != info.appIdentifierAllowList.end()) {
12790 return true;
12791 }
12792 return false;
12793 }
12794 }
12795 return false;
12796 }
12797
CloseAssertDialog(const std::string & assertSessionId)12798 void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId)
12799 {
12800 TAG_LOGD(AAFwkTag::ABILITYMGR, "Close assert fault dialog begin.");
12801 auto validUserId = GetUserId();
12802 auto connectManager = GetConnectManagerByUserId(validUserId);
12803 if (connectManager == nullptr) {
12804 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId: %{public}d", validUserId);
12805 return;
12806 }
12807
12808 connectManager->CloseAssertDialog(assertSessionId);
12809 }
12810
SetResidentProcessEnabled(const std::string & bundleName,bool enable)12811 int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable)
12812 {
12813 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
12814 if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) {
12815 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
12816 return ERR_NOT_SYSTEM_APP;
12817 }
12818
12819 auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
12820 CHECK_POINTER_AND_RETURN(residentProcessManager, INNER_ERR);
12821
12822 std::string callerName;
12823 int32_t uid = 0;
12824 auto callerPid = IPCSkeleton::GetCallingPid();
12825 DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
12826 if (callerName.empty()) {
12827 TAG_LOGE(AAFwkTag::ABILITYMGR, "obtain caller name failed");
12828 return INNER_ERR;
12829 }
12830
12831 return residentProcessManager->SetResidentProcessEnabled(bundleName, callerName, enable);
12832 }
12833
RequestAssertFaultDialog(const sptr<IRemoteObject> & callback,const AAFwk::WantParams & wantParams)12834 int32_t AbilityManagerService::RequestAssertFaultDialog(
12835 const sptr<IRemoteObject> &callback, const AAFwk::WantParams &wantParams)
12836 {
12837 TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog begin.");
12838 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12839 auto checkRet = CheckDebugAssertPermission();
12840 if (checkRet != ERR_OK) {
12841 TAG_LOGE(AAFwkTag::ABILITYMGR, "check debug assert permission error");
12842 return checkRet;
12843 }
12844 sptr<IRemoteObject> remoteCallback = callback;
12845 if (remoteCallback == nullptr) {
12846 TAG_LOGE(AAFwkTag::ABILITYMGR, "params remote callback null");
12847 return ERR_INVALID_VALUE;
12848 }
12849 auto debugDeal = ConnectInitAbilityDebugDeal();
12850 Want want;
12851 #ifdef SUPPORT_SCREEN
12852 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
12853 if (sysDialog == nullptr || debugDeal == nullptr) {
12854 TAG_LOGE(AAFwkTag::ABILITYMGR, "sysDialog or debugDeal null");
12855 return ERR_INVALID_VALUE;
12856 }
12857 if (!sysDialog->GetAssertFaultDialogWant(want)) {
12858 TAG_LOGE(AAFwkTag::ABILITYMGR, "get assert fault dialog want failed");
12859 return ERR_INVALID_VALUE;
12860 }
12861 #endif // SUPPORT_SCREEN
12862 uint64_t assertFaultSessionId = reinterpret_cast<uint64_t>(remoteCallback.GetRefPtr());
12863 want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, std::to_string(assertFaultSessionId));
12864 want.SetParam(ASSERT_FAULT_DETAIL, wantParams.GetStringParam(ASSERT_FAULT_DETAIL));
12865 auto &connection = AbilityRuntime::ModalSystemAssertUIExtension::GetInstance();
12866 want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
12867 if (!IN_PROCESS_CALL(connection.CreateModalUIExtension(want))) {
12868 TAG_LOGE(AAFwkTag::ABILITYMGR, "create modal ui extension failed");
12869 return ERR_INVALID_VALUE;
12870 }
12871 auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
12872 if (callbackDeathMgr == nullptr) {
12873 TAG_LOGE(AAFwkTag::ABILITYMGR, "get callback death manager instance null");
12874 return ERR_INVALID_VALUE;
12875 }
12876 auto callbackTask = [weak = weak_from_this()] (const std::string &assertSessionId) {
12877 auto abilityMgr = weak.lock();
12878 if (abilityMgr == nullptr) {
12879 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability manager instance null");
12880 return;
12881 }
12882 abilityMgr->CloseAssertDialog(assertSessionId);
12883 };
12884 callbackDeathMgr->AddAssertFaultCallback(remoteCallback, callbackTask);
12885 TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog end.");
12886 return ERR_OK;
12887 }
12888
NotifyDebugAssertResult(uint64_t assertFaultSessionId,AAFwk::UserStatus userStatus)12889 int32_t AbilityManagerService::NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus)
12890 {
12891 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12892 if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
12893 TAG_LOGE(AAFwkTag::ABILITYMGR, "assert fault dialog product not enabled");
12894 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
12895 }
12896
12897 CHECK_CALLER_IS_SYSTEM_APP;
12898 auto permissionSA = PermissionVerification::GetInstance();
12899 if (permissionSA == nullptr) {
12900 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification instance null");
12901 return ERR_INVALID_VALUE;
12902 }
12903 if (!permissionSA->VerifyCallingPermission(PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT)) {
12904 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
12905 PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT);
12906 return ERR_PERMISSION_DENIED;
12907 }
12908
12909 auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
12910 if (callbackDeathMgr == nullptr) {
12911 TAG_LOGE(AAFwkTag::ABILITYMGR, "get callback death manager instance null");
12912 return ERR_INVALID_VALUE;
12913 }
12914 callbackDeathMgr->CallAssertFaultCallback(assertFaultSessionId, userStatus);
12915 return ERR_OK;
12916 }
12917
UpdateSessionInfoBySCB(std::list<SessionInfo> & sessionInfos,int32_t userId,std::vector<int32_t> & sessionIds)12918 int32_t AbilityManagerService::UpdateSessionInfoBySCB(std::list<SessionInfo> &sessionInfos, int32_t userId,
12919 std::vector<int32_t> &sessionIds)
12920 {
12921 if (!IsCallerSceneBoard()) {
12922 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
12923 return ERR_WRONG_INTERFACE_CALL;
12924 }
12925 TAG_LOGI(AAFwkTag::ABILITYMGR, "sceneboard being restored");
12926 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12927 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12928 return uiAbilityManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds);
12929 }
12930
CheckSenderWantInfo(int32_t callerUid,const WantSenderInfo & wantSenderInfo)12931 bool AbilityManagerService::CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)
12932 {
12933 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
12934 auto bms = AbilityUtil::GetBundleManagerHelper();
12935 CHECK_POINTER_AND_RETURN(bms, false);
12936
12937 std::string bundleName;
12938 if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
12939 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle name failed");
12940 return false;
12941 }
12942 if (wantSenderInfo.bundleName != bundleName) {
12943 TAG_LOGE(AAFwkTag::ABILITYMGR, "wantSender bundleName check failed");
12944 return false;
12945 }
12946 }
12947 return true;
12948 }
12949
CheckCallerIsDmsProcess()12950 bool AbilityManagerService::CheckCallerIsDmsProcess()
12951 {
12952 Security::AccessToken::NativeTokenInfo nativeTokenInfo;
12953 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
12954 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
12955 int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
12956 if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
12957 result != ERR_OK || nativeTokenInfo.processName != DMS_PROCESS_NAME) {
12958 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not dms");
12959 return false;
12960 }
12961 return true;
12962 }
12963
WaitBootAnimationStart()12964 void AbilityManagerService::WaitBootAnimationStart()
12965 {
12966 char value[BOOTEVENT_BOOT_ANIMATION_READY_SIZE] = "";
12967 int32_t ret = GetParameter(BOOTEVENT_BOOT_ANIMATION_READY, "", value,
12968 BOOTEVENT_BOOT_ANIMATION_READY_SIZE);
12969 if (ret > 0 && !std::strcmp(value, "false")) {
12970 // Get new param success and new param is not ready, wait the new param.
12971 WaitParameter(BOOTEVENT_BOOT_ANIMATION_READY, "true",
12972 AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
12973 } else if (ret <= 0 || !std::strcmp(value, "")) {
12974 // Get new param failed or new param is not set, wait the old param.
12975 WaitParameter(BOOTEVENT_BOOT_ANIMATION_STARTED, "true",
12976 AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
12977 }
12978 // other, the animation is ready, not wait.
12979 }
12980
GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,UIExtensionHostInfo & hostInfo,int32_t userId)12981 int32_t AbilityManagerService::GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,
12982 UIExtensionHostInfo &hostInfo, int32_t userId)
12983 {
12984 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12985 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
12986 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
12987
12988 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
12989 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
12990 return ERR_PERMISSION_DENIED;
12991 }
12992
12993 auto callerRecord = GetUIExtensionRootCaller(token, userId);
12994 if (callerRecord == nullptr) {
12995 TAG_LOGE(AAFwkTag::UI_EXT, "get root host info failed");
12996 return ERR_INVALID_VALUE;
12997 }
12998
12999 hostInfo.elementName_ = callerRecord->GetElementName();
13000 auto sessionInfo = callerRecord->GetSessionInfo();
13001 if (sessionInfo != nullptr) {
13002 hostInfo.sessionName = sessionInfo->sessionName;
13003 }
13004 TAG_LOGD(AAFwkTag::UI_EXT, "uri: %{public}s, sessionName: %{public}s.",
13005 hostInfo.elementName_.GetURI().c_str(), hostInfo.sessionName.c_str());
13006 return ERR_OK;
13007 }
13008
GetUIExtensionRootCaller(const sptr<IRemoteObject> token,int32_t userId)13009 std::shared_ptr<AbilityRecord> AbilityManagerService::GetUIExtensionRootCaller(const sptr<IRemoteObject> token,
13010 int32_t userId)
13011 {
13012 auto validUserId = GetValidUserId(userId);
13013 auto connectManager = GetConnectManagerByUserId(validUserId);
13014 if (connectManager == nullptr) {
13015 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId:%{public}d", validUserId);
13016 return nullptr;
13017 }
13018
13019 auto callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
13020 if (callerRecord == nullptr && validUserId != U0_USER_ID) {
13021 connectManager = GetConnectManagerByUserId(U0_USER_ID);
13022 if (connectManager == nullptr) {
13023 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId: %{public}d", U0_USER_ID);
13024 return nullptr;
13025 }
13026 callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
13027 }
13028
13029 return callerRecord;
13030 }
13031
GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,UIExtensionSessionInfo & uiExtensionSessionInfo,int32_t userId)13032 int32_t AbilityManagerService::GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,
13033 UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId)
13034 {
13035 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13036 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
13037 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
13038
13039 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
13040 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
13041 return ERR_PERMISSION_DENIED;
13042 }
13043
13044 auto validUserId = GetValidUserId(userId);
13045 auto connectManager = GetConnectManagerByUserId(validUserId);
13046 if (connectManager == nullptr) {
13047 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId:%{public}d", validUserId);
13048 return ERR_INVALID_VALUE;
13049 }
13050
13051 auto ret = connectManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo);
13052 if (ret != ERR_OK) {
13053 TAG_LOGE(AAFwkTag::ABILITYMGR, "get ui extension session info failed");
13054 return ret;
13055 }
13056
13057 return ERR_OK;
13058 }
13059
RestartApp(const AAFwk::Want & want,bool isAppRecovery)13060 int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want, bool isAppRecovery)
13061 {
13062 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
13063 TAG_LOGI(AAFwkTag::ABILITYMGR, "RestartApp, isAppRecovery: %{public}d", isAppRecovery);
13064 auto callerPid = IPCSkeleton::GetCallingPid();
13065 AppExecFwk::RunningProcessInfo processInfo;
13066 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
13067 int32_t callerUid = IPCSkeleton::GetCallingUid();
13068 int32_t userId = callerUid / BASE_USER_RANGE;
13069 auto result = CheckRestartAppWant(want, processInfo.appCloneIndex, userId);
13070 if (result != ERR_OK) {
13071 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkRestartAppWant error");
13072 return result;
13073 }
13074 if (!processInfo.isFocused && !processInfo.isAbilityForegrounding) {
13075 TAG_LOGE(AAFwkTag::ABILITYMGR, "restartApp, is not foreground");
13076 return AAFwk::NOT_TOP_ABILITY;
13077 }
13078
13079 RestartAppKeyType key(processInfo.instanceKey, callerUid);
13080 int64_t now = time(nullptr);
13081 if (!isAppRecovery && RestartAppManager::GetInstance().IsRestartAppFrequent(key, now)) {
13082 return AAFwk::ERR_RESTART_APP_FREQUENT;
13083 }
13084
13085 SignRestartAppFlagParam param =
13086 { userId, callerUid, processInfo.instanceKey, processInfo.appMode, isAppRecovery, false };
13087 result = SignRestartAppFlag(param);
13088 if (!isAppRecovery && result != ERR_OK) {
13089 TAG_LOGE(AAFwkTag::ABILITYMGR, "signRestartAppFlag error");
13090 return result;
13091 }
13092
13093 (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, processInfo.appCloneIndex);
13094 (const_cast<Want &>(want)).SetParam(AAFwk::Want::APP_INSTANCE_KEY, processInfo.instanceKey);
13095 (const_cast<Want &>(want)).RemoveParam(Want::CREATE_APP_INSTANCE_KEY);
13096 result = StartAbilityWrap(want, nullptr, DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, 0, true);
13097 if (result != ERR_OK) {
13098 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility error");
13099 return result;
13100 }
13101 if (!isAppRecovery) {
13102 RestartAppManager::GetInstance().AddRestartAppHistory(key, now);
13103 }
13104 return result;
13105 }
13106
CheckRestartAppWant(const AAFwk::Want & want,int32_t appIndex,int32_t userId)13107 int32_t AbilityManagerService::CheckRestartAppWant(const AAFwk::Want &want, int32_t appIndex, int32_t userId)
13108 {
13109 std::string bundleName = want.GetElement().GetBundleName();
13110 if (!CheckCallingTokenId(bundleName, userId, appIndex)) {
13111 TAG_LOGE(AAFwkTag::ABILITYMGR, "no itself called, no allowed");
13112 return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
13113 }
13114
13115 auto bms = AbilityUtil::GetBundleManagerHelper();
13116 CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
13117 auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
13118
13119 TAG_LOGD(AAFwkTag::ABILITYMGR,
13120 "bundleName: %{public}s, abilityName: %{public}s, appIndex: %{public}d, userId: %{public}d",
13121 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), appIndex, userId);
13122 AppExecFwk::AbilityInfo abilityInfo;
13123 auto queryResult = IN_PROCESS_CALL(
13124 bms->QueryCloneAbilityInfo(want.GetElement(), abilityInfoFlag, appIndex, abilityInfo, userId));
13125 if (queryResult != ERR_OK || abilityInfo.name.empty() || abilityInfo.bundleName.empty() ||
13126 abilityInfo.type != AbilityType::PAGE) {
13127 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability invalid or not UIAbility");
13128 return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
13129 }
13130 return ERR_OK;
13131 }
13132
SignRestartAppFlag(const SignRestartAppFlagParam & param)13133 int32_t AbilityManagerService::SignRestartAppFlag(const SignRestartAppFlagParam ¶m)
13134 {
13135 auto appMgr = AppMgrUtil::GetAppMgr();
13136 if (appMgr == nullptr) {
13137 TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
13138 return ERR_INVALID_VALUE;
13139 }
13140 auto ret = IN_PROCESS_CALL(appMgr->SignRestartAppFlag(param.uid, param.instanceKey));
13141 if (!param.isAppRecovery && ret != ERR_OK) {
13142 TAG_LOGE(AAFwkTag::ABILITYMGR, "appMgr signRestartAppFlag error");
13143 return ret;
13144 }
13145
13146 auto connectManager = GetConnectManagerByUserId(param.userId);
13147 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
13148 connectManager->SignRestartAppFlag(param.uid, param.instanceKey);
13149 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
13150 auto uiAbilityManager = GetUIAbilityManagerByUserId(param.userId);
13151 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
13152 uiAbilityManager->SignRestartAppFlag(param.uid, param.instanceKey, param.isAppRecovery);
13153 } else {
13154 auto missionListManager = GetMissionListManagerByUserId(param.userId);
13155 if (missionListManager == nullptr) {
13156 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId:%{public}d", param.userId);
13157 return ERR_INVALID_VALUE;
13158 }
13159 missionListManager->SignRestartAppFlag(param.uid, param.instanceKey);
13160 }
13161
13162 if (param.type == AppExecFwk::MultiAppModeType::MULTI_INSTANCE) {
13163 return appMgr->KillAppSelfWithInstanceKey(param.instanceKey, false, "RestartInstance");
13164 }
13165 if (param.isAtomicService) {
13166 return DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->KillApplicationSelf(false,
13167 "RestartSelfAtomicService");
13168 }
13169 return DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->KillApplicationSelf(false, "RestartApp");
13170 }
13171
IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken,const std::string & appId)13172 bool AbilityManagerService::IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken, const std::string &appId)
13173 {
13174 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13175 if (!AppUtils::GetInstance().IsLaunchEmbededUIAbility()) {
13176 TAG_LOGE(AAFwkTag::ABILITYMGR, "device type not allowd");
13177 return false;
13178 }
13179 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
13180 auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
13181 if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
13182 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not hap");
13183 return false;
13184 }
13185 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
13186 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
13187 auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
13188 if (callerAbility == nullptr) {
13189 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
13190 return false;
13191 }
13192 if (callerAbility->GetApplicationInfo().accessTokenId != accessTokenId) {
13193 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken don't belong caller");
13194 return false;
13195 }
13196 if (!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag()) {
13197 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not foreground");
13198 return false;
13199 }
13200 CHECK_POINTER_AND_RETURN(freeInstallManager_, false);
13201 std::string bundleName = ATOMIC_SERVICE_PREFIX + appId;
13202 Want want;
13203 want.SetBundle(bundleName);
13204 want.SetParam("send_to_erms_embedded", 1);
13205 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(want, callerToken);
13206 int32_t ret = freeInstallManager_->StartFreeInstall(want, GetUserId(), 0, callerToken);
13207 if (ret != ERR_OK) {
13208 TAG_LOGE(AAFwkTag::ABILITYMGR, "target not allowed free install");
13209 return false;
13210 }
13211 want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
13212 auto erms = std::make_shared<EcologicalRuleInterceptor>();
13213 return erms->DoProcess(want, GetUserId());
13214 }
13215
AddQueryERMSObserver(sptr<IRemoteObject> callerToken,sptr<AbilityRuntime::IQueryERMSObserver> observer)13216 int32_t AbilityManagerService::AddQueryERMSObserver(sptr<IRemoteObject> callerToken,
13217 sptr<AbilityRuntime::IQueryERMSObserver> observer)
13218 {
13219 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13220 if (callerToken == nullptr || !JudgeSelfCalled(Token::GetAbilityRecordByToken(callerToken))) {
13221 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
13222 return ERR_PERMISSION_DENIED;
13223 }
13224 return QueryERMSManager::GetInstance().AddQueryERMSObserver(callerToken, observer);
13225 }
13226
QueryAtomicServiceStartupRule(sptr<IRemoteObject> callerToken,const std::string & appId,const std::string & startTime,AtomicServiceStartupRule & rule)13227 int32_t AbilityManagerService::QueryAtomicServiceStartupRule(sptr<IRemoteObject> callerToken,
13228 const std::string &appId, const std::string &startTime, AtomicServiceStartupRule &rule)
13229 {
13230 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13231 CHECK_TRUE_RETURN_RET(!AppUtils::GetInstance().IsLaunchEmbededUIAbility(),
13232 ERR_CAPABILITY_NOT_SUPPORT, "device type not allowd");
13233 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
13234 auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
13235 CHECK_TRUE_RETURN_RET(type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP, INNER_ERR, "caller not hap");
13236 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
13237 CHECK_POINTER_AND_RETURN(uiAbilityManager, INNER_ERR);
13238 auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
13239 CHECK_POINTER_AND_RETURN(callerAbility, INNER_ERR);
13240 CHECK_TRUE_RETURN_RET(callerAbility->GetApplicationInfo().accessTokenId != accessTokenId,
13241 INNER_ERR, "callerToken don't belong caller");
13242 CHECK_TRUE_RETURN_RET(!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag(),
13243 INNER_ERR, "caller not foreground");
13244
13245 Want want;
13246 want.SetBundle(ATOMIC_SERVICE_PREFIX + appId);
13247 want.SetParam("send_to_erms_embedded", 1);
13248 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(want, callerToken);
13249 auto userId = GetUserId();
13250 int32_t ret = freeInstallManager_->StartFreeInstall(want, userId, 0, callerToken);
13251 if (ret != ERR_OK) {
13252 TAG_LOGE(AAFwkTag::ABILITYMGR, "free install failed:%{public}d", ret);
13253 rule.isOpenAllowed = false;
13254 rule.isEmbeddedAllowed = false;
13255 return ERR_OK;
13256 }
13257
13258 want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
13259 auto erms = std::make_shared<EcologicalRuleInterceptor>();
13260 sptr<Want> replaceWant = nullptr;
13261 ret = erms->QueryAtomicServiceStartupRule(want, callerToken, GetUserId(), rule, replaceWant);
13262 if (ret == ERR_OK) {
13263 TAG_LOGI(AAFwkTag::ABILITYMGR, "QueryAtomicServiceStartupRule succeeded");
13264 return ERR_OK;
13265 }
13266 if (ret != ERR_ECOLOGICAL_CONTROL_STATUS) {
13267 TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryAtomicServiceStartupRule failed:%{public}d", ret);
13268 if (ret == ERR_CAPABILITY_NOT_SUPPORT) {
13269 TAG_LOGE(AAFwkTag::ABILITYMGR, "not supported");
13270 return ret;
13271 }
13272 return INNER_ERR;
13273 }
13274 AbilityRequest abilityRequest;
13275 ret = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, userId);
13276 CHECK_TRUE_RETURN_RET(ret != ERR_OK, INNER_ERR, "GenerateAbilityRequest failed");
13277
13278 abilityRequest.isQueryERMS = true;
13279 abilityRequest.appId = appId;
13280 abilityRequest.startTime = startTime;
13281 abilityRequest.isEmbeddedAllowed = rule.isEmbeddedAllowed;
13282 ret = DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, userId, *replaceWant);
13283 TAG_LOGI(AAFwkTag::ABILITYMGR, "HandleErmsResult: ret=%{public}d", ret);
13284 CHECK_TRUE_RETURN_RET(ret != ERR_OK, INNER_ERR, "HandleErmsResult failed");
13285 return ERR_ECOLOGICAL_CONTROL_STATUS;
13286 }
13287
CheckProcessIsBackground(int32_t pid,AbilityState currentState)13288 bool AbilityManagerService::CheckProcessIsBackground(int32_t pid, AbilityState currentState)
13289 {
13290 TAG_LOGI(AAFwkTag::ABILITYMGR, "pid:%{public}d, currentState:%{public}d", pid, currentState);
13291 std::lock_guard<ffrt::mutex> myLockGuard(windowVisibleListLock_);
13292 if (currentState == AAFwk::AbilityState::BACKGROUND &&
13293 windowVisibleList_.find(pid) != windowVisibleList_.end()) {
13294 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process window is occluded");
13295 return false;
13296 }
13297
13298 if (currentState != AAFwk::AbilityState::BACKGROUND) {
13299 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is not on background Pass");
13300 return false;
13301 }
13302 return true;
13303 }
13304
InitWindowVisibilityChangedListener()13305 void AbilityManagerService::InitWindowVisibilityChangedListener()
13306 {
13307 if (windowVisibilityChangedListener_ != nullptr) {
13308 TAG_LOGW(AAFwkTag::ABILITYMGR, "visibility already initiate");
13309 return;
13310 }
13311
13312 windowVisibilityChangedListener_ =
13313 new (std::nothrow) WindowVisibilityChangedListener(weak_from_this(), taskHandler_);
13314 if (windowVisibilityChangedListener_ == nullptr) {
13315 TAG_LOGE(AAFwkTag::ABILITYMGR, "window visibility changed listener null");
13316 return;
13317 }
13318
13319 Rosen::WindowManager::GetInstance().RegisterVisibilityChangedListener(windowVisibilityChangedListener_);
13320 }
13321
FreeWindowVisibilityChangedListener()13322 void AbilityManagerService::FreeWindowVisibilityChangedListener()
13323 {
13324 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
13325 if (windowVisibilityChangedListener_ == nullptr) {
13326 TAG_LOGW(AAFwkTag::ABILITYMGR, "visibility listener already free");
13327 return;
13328 }
13329 Rosen::WindowManager::GetInstance().UnregisterVisibilityChangedListener(windowVisibilityChangedListener_);
13330 windowVisibilityChangedListener_ = nullptr;
13331 }
13332
HandleWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)13333 void AbilityManagerService::HandleWindowVisibilityChanged(
13334 const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
13335 {
13336 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
13337 if (windowVisibilityInfos.empty()) {
13338 TAG_LOGW(AAFwkTag::ABILITYMGR, "window visibility info empty");
13339 return;
13340 }
13341 std::lock_guard<ffrt::mutex> myLockGuard(windowVisibleListLock_);
13342 for (const auto &info : windowVisibilityInfos) {
13343 if (info == nullptr) {
13344 TAG_LOGE(AAFwkTag::ABILITYMGR, "null info");
13345 continue;
13346 }
13347 int uid = 0;
13348 std::string bundleName;
13349 if (info->windowType_ == Rosen::WindowType::WINDOW_TYPE_DESKTOP &&
13350 info->visibilityState_ == Rosen::WINDOW_VISIBILITY_STATE_NO_OCCLUSION) {
13351 TAG_LOGD(AAFwkTag::ABILITYMGR, "desktop is visible clear windowVisibleList_");
13352 windowVisibleList_.clear();
13353 continue;
13354 }
13355 DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(info->pid_, bundleName, uid);
13356 if (info->visibilityState_ == Rosen::WINDOW_VISIBILITY_STATE_NO_OCCLUSION &&
13357 bundleName != SCENEBOARD_BUNDLE_NAME) {
13358 windowVisibleList_.insert(info->pid_);
13359 }
13360 }
13361 }
13362
ShouldPreventStartAbility(const AbilityRequest & abilityRequest)13363 bool AbilityManagerService::ShouldPreventStartAbility(const AbilityRequest &abilityRequest)
13364 {
13365 std::shared_ptr<AbilityRecord> abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
13366 if (abilityRecord == nullptr) {
13367 TAG_LOGD(AAFwkTag::ABILITYMGR, "No matched token pass");
13368 return false;
13369 }
13370 auto abilityInfo = abilityRequest.abilityInfo;
13371 auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
13372 PrintStartAbilityInfo(callerAbilityInfo, abilityInfo);
13373 if (abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD < API12) {
13374 TAG_LOGD(AAFwkTag::ABILITYMGR, "API version %{public}d pass",
13375 abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD);
13376 return false;
13377 }
13378 bool continuousFlag = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
13379 if(!IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->
13380 IsProcessContainsOnlyUIAbility(abilityRecord->GetPid()))) {
13381 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has other extension except UIAbility, pass");
13382 return false;
13383 }
13384 if (abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::DATASHARE &&
13385 abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
13386 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process did not call service or datashare extension Pass");
13387 return false;
13388 }
13389 if (abilityInfo.applicationInfo.uid == IPCSkeleton::GetCallingUid()) {
13390 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in same bundle Pass");
13391 return false;
13392 }
13393 if (callerAbilityInfo.type != AppExecFwk::AbilityType::PAGE) {
13394 TAG_LOGD(AAFwkTag::ABILITYMGR, "Is not UI Ability Pass");
13395 return false;
13396 }
13397 if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckIntentIsExemption(
13398 abilityRecord->GetUid())) {
13399 TAG_LOGD(AAFwkTag::ABILITYMGR, "Is Exemption Pass");
13400 return false;
13401 }
13402 if (!CheckProcessIsBackground(abilityRecord->GetPid(), abilityRecord->GetAbilityState())) {
13403 return false;
13404 }
13405 if (continuousFlag) {
13406 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has continuous task Pass");
13407 return false;
13408 }
13409 if (IsInWhiteList(callerAbilityInfo.bundleName, abilityInfo.bundleName, abilityInfo.name)) {
13410 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in white list Pass");
13411 return false;
13412 }
13413 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceExtension %{public}s permission",
13414 abilityRecord->GetURI().c_str());
13415 ReportPreventStartAbilityResult(callerAbilityInfo, abilityInfo);
13416 return true;
13417 }
13418
PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo,AppExecFwk::AbilityInfo calledInfo)13419 void AbilityManagerService::PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo, AppExecFwk::AbilityInfo calledInfo)
13420 {
13421 TAG_LOGD(AAFwkTag::ABILITYMGR, "calledAbilityInfo toString: "
13422 "calledUid is: %{public}d, "
13423 "name is: %{public}s, "
13424 "bundleName is: %{public}s, "
13425 "type is: %{public}d, "
13426 "extensionAbilityType is: %{public}d, "
13427 "moduleName is: %{public}s, "
13428 "applicationName is: %{public}s",
13429 calledInfo.applicationInfo.uid,
13430 calledInfo.name.c_str(),
13431 calledInfo.bundleName.c_str(),
13432 static_cast<int32_t>(calledInfo.type),
13433 static_cast<int32_t>(calledInfo.extensionAbilityType),
13434 calledInfo.moduleName.c_str(),
13435 calledInfo.applicationName.c_str());
13436
13437
13438 TAG_LOGD(AAFwkTag::ABILITYMGR, "callerAbilityInfo toString: "
13439 "callerUid is: %{public}d, "
13440 "callerPid is: %{public}d, "
13441 "name is: %{public}s, "
13442 "bundleName is: %{public}s, "
13443 "type is: %{public}d, "
13444 "extensionAbilityType is: %{public}d, "
13445 "moduleName is: %{public}s, "
13446 "applicationName is: %{public}s",
13447 IPCSkeleton::GetCallingUid(),
13448 IPCSkeleton::GetCallingPid(),
13449 callerInfo.name.c_str(),
13450 callerInfo.bundleName.c_str(),
13451 static_cast<int32_t>(callerInfo.type),
13452 static_cast<int32_t>(callerInfo.extensionAbilityType),
13453 callerInfo.moduleName.c_str(),
13454 callerInfo.applicationName.c_str());
13455 }
13456
ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo & callerAbilityInfo,const AppExecFwk::AbilityInfo & abilityInfo)13457 void AbilityManagerService::ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo,
13458 const AppExecFwk::AbilityInfo &abilityInfo)
13459 {
13460 int32_t callerUid = IPCSkeleton::GetCallingUid();
13461 int32_t callerPid = IPCSkeleton::GetCallingPid();
13462 int32_t extensionAbilityType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
13463 TAG_LOGD(AAFwkTag::ABILITYMGR,
13464 "Prevent start ability debug log CALLER_BUNDLE_NAME %{public}s CALLEE_BUNDLE_NAME"
13465 "%{public}s ABILITY_NAME %{public}s",
13466 callerAbilityInfo.bundleName.c_str(), abilityInfo.name.c_str(), abilityInfo.name.c_str());
13467 HiSysEventWrite(HiSysEvent::Domain::AAFWK, "PREVENT_START_ABILITY", HiSysEvent::EventType::BEHAVIOR,
13468 "CALLER_UID", callerUid,
13469 "CALLER_PID", callerPid,
13470 "CALLER_PROCESS_NAME", callerAbilityInfo.process,
13471 "CALLER_BUNDLE_NAME", callerAbilityInfo.bundleName,
13472 "CALLEE_BUNDLE_NAME", abilityInfo.bundleName,
13473 "CALLEE_PROCESS_NAME", abilityInfo.process,
13474 "EXTENSION_ABILITY_TYPE", extensionAbilityType,
13475 "ABILITY_NAME", abilityInfo.name);
13476 }
13477
IsInWhiteList(const std::string & callerBundleName,const std::string & calleeBundleName,const std::string & calleeAbilityName)13478 bool AbilityManagerService::IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName,
13479 const std::string &calleeAbilityName)
13480 {
13481 std::lock_guard<std::mutex> locker(whiteListMutex_);
13482 std::map<std::string, std::list<std::string>>::iterator iter = whiteListMap_.find(callerBundleName);
13483 std::string uri = calleeBundleName + "/" + calleeAbilityName;
13484 if (iter != whiteListMap_.end()) {
13485 if (std::find(std::begin(iter->second), std::end(iter->second), uri) != std::end(iter->second)) {
13486 return true;
13487 }
13488 }
13489 std::list<std::string>::iterator it = std::find(exportWhiteList_.begin(), exportWhiteList_.end(), uri);
13490 if (it != exportWhiteList_.end()) {
13491 return true;
13492 }
13493 return false;
13494 }
13495
ParseJsonFromBoot(const std::string & relativePath)13496 bool AbilityManagerService::ParseJsonFromBoot(const std::string &relativePath)
13497 {
13498 nlohmann::json jsonObj;
13499 std::string absolutePath = GetConfigFileAbsolutePath(relativePath);
13500 if (ParseJsonValueFromFile(jsonObj, absolutePath) != ERR_OK) {
13501 return false;
13502 }
13503 std::lock_guard<std::mutex> locker(whiteListMutex_);
13504 nlohmann::json whiteListJsonList = jsonObj[WHITE_LIST];
13505 for (const auto& [key, value] : whiteListJsonList.items()) {
13506 if (!value.is_array()) {
13507 continue;
13508 }
13509 whiteListMap_.emplace(key, std::list<std::string>());
13510 for (const auto& it : value) {
13511 if (it.is_string()) {
13512 whiteListMap_[key].push_back(it);
13513 }
13514 }
13515 }
13516 if (!jsonObj.contains("exposed_white_list")) {
13517 return false;
13518 }
13519 nlohmann::json exportWhiteJsonList = jsonObj["exposed_white_list"];
13520 for (const auto& it : exportWhiteJsonList) {
13521 if (it.is_string()) {
13522 exportWhiteList_.push_back(it);
13523 }
13524 }
13525 return true;
13526 }
13527
GetConfigFileAbsolutePath(const std::string & relativePath)13528 std::string AbilityManagerService::GetConfigFileAbsolutePath(const std::string &relativePath)
13529 {
13530 if (relativePath.empty()) {
13531 TAG_LOGE(AAFwkTag::ABILITYMGR, "relativePath empty");
13532 return "";
13533 }
13534 char buf[PATH_MAX];
13535 char *tmpPath = GetOneCfgFile(relativePath.c_str(), buf, PATH_MAX);
13536 char absolutePath[PATH_MAX] = {0};
13537 if (!tmpPath || strlen(tmpPath) > PATH_MAX || !realpath(tmpPath, absolutePath)) {
13538 TAG_LOGE(AAFwkTag::ABILITYMGR, "get file fail");
13539 return "";
13540 }
13541 return std::string(absolutePath);
13542 }
13543
ParseJsonValueFromFile(nlohmann::json & value,const std::string & filePath)13544 int32_t AbilityManagerService::ParseJsonValueFromFile(nlohmann::json &value, const std::string &filePath)
13545 {
13546 std::ifstream fin;
13547 std::string realPath;
13548 if (!ConvertFullPath(filePath, realPath)) {
13549 TAG_LOGE(AAFwkTag::ABILITYMGR, "get real path failed");
13550 return ERR_INVALID_VALUE;
13551 }
13552 fin.open(realPath, std::ios::in);
13553 if (!fin.is_open()) {
13554 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't open file %{private}s", realPath.c_str());
13555 return ERR_INVALID_VALUE;
13556 }
13557 char buffer[MAX_BUFFER];
13558 std::ostringstream os;
13559 while (fin.getline(buffer, MAX_BUFFER)) {
13560 os << buffer;
13561 }
13562 const std::string data = os.str();
13563 value = nlohmann::json::parse(data, nullptr, false);
13564 if (value.is_discarded()) {
13565 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed due data discarded");
13566 return ERR_INVALID_VALUE;
13567 }
13568 return ERR_OK;
13569 }
13570
ConvertFullPath(const std::string & partialPath,std::string & fullPath)13571 bool AbilityManagerService::ConvertFullPath(const std::string& partialPath, std::string& fullPath)
13572 {
13573 if (partialPath.empty() || partialPath.length() >= PATH_MAX) {
13574 return false;
13575 }
13576 char tmpPath[PATH_MAX] = {0};
13577 if (realpath(partialPath.c_str(), tmpPath) == nullptr) {
13578 return false;
13579 }
13580 fullPath = tmpPath;
13581 return true;
13582 }
13583
StartShortcut(const Want & want,const StartOptions & startOptions)13584 int32_t AbilityManagerService::StartShortcut(const Want &want, const StartOptions &startOptions)
13585 {
13586 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13587 if (!PermissionVerification::GetInstance()->IsSystemAppCall()) {
13588 TAG_LOGE(AAFwkTag::ABILITYMGR, "non-system app calling system api");
13589 return ERR_NOT_SYSTEM_APP;
13590 }
13591 if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
13592 PermissionConstants::PERMISSION_START_SHORTCUT)) {
13593 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
13594 PermissionConstants::PERMISSION_START_SHORTCUT);
13595 return ERR_PERMISSION_DENIED;
13596 }
13597 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
13598 return StartUIAbilityForOptionWrap(want, startOptions, nullptr, false, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE,
13599 0, false, true);
13600 }
13601
GetAbilityStateByPersistentId(int32_t persistentId,bool & state)13602 int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentId, bool &state)
13603 {
13604 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13605 if (!CheckCallerIsDmsProcess()) {
13606 TAG_LOGE(AAFwkTag::ABILITYMGR, "getAbilityStateByPersistentId, caller not dms");
13607 return ERR_PERMISSION_DENIED;
13608 }
13609
13610 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
13611 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
13612 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
13613 return uiAbilityManager->GetAbilityStateByPersistentId(persistentId, state);
13614 }
13615 TAG_LOGE(AAFwkTag::ABILITYMGR, "getAbilityStateByPersistentId, mission without persistent id");
13616 return INNER_ERR;
13617 }
13618
TransferAbilityResultForExtension(const sptr<IRemoteObject> & callerToken,int32_t resultCode,const Want & want)13619 int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptr<IRemoteObject> &callerToken,
13620 int32_t resultCode, const Want &want)
13621 {
13622 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13623 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
13624 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
13625 if (!JudgeSelfCalled(abilityRecord)) {
13626 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller mismatch");
13627 return ERR_INVALID_VALUE;
13628 }
13629 auto type = abilityRecord->GetAbilityInfo().type;
13630 if (type != AppExecFwk::AbilityType::EXTENSION) {
13631 TAG_LOGE(AAFwkTag::ABILITYMGR, "type not uiextension");
13632 return ERR_INVALID_VALUE;
13633 }
13634 // save result to caller AbilityRecord.
13635 (const_cast<Want &>(want)).RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
13636 abilityRecord->SaveResultToCallers(resultCode, &want);
13637 abilityRecord->SendResultToCallers();
13638 return ERR_OK;
13639 }
13640
NotifyFrozenProcessByRSS(const std::vector<int32_t> & pidList,int32_t uid)13641 void AbilityManagerService::NotifyFrozenProcessByRSS(const std::vector<int32_t> &pidList, int32_t uid)
13642 {
13643 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(RSS_PROCESS_NAME)) {
13644 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not RSS");
13645 return;
13646 }
13647 auto userId = uid / BASE_USER_RANGE;
13648 auto connectManager = GetConnectManagerByUserId(userId);
13649 CHECK_POINTER_LOG(connectManager, "can't find user connect manager");
13650 connectManager->HandleProcessFrozen(pidList, uid);
13651 }
13652
HandleRestartResidentProcessDependedOnWeb()13653 void AbilityManagerService::HandleRestartResidentProcessDependedOnWeb()
13654 {
13655 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
13656 auto appMgr = AppMgrUtil::GetAppMgr();
13657 CHECK_POINTER_LOG(appMgr, "get appMgr fail");
13658 appMgr->RestartResidentProcessDependedOnWeb();
13659 }
13660
PreStartMission(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & startTime)13661 int32_t AbilityManagerService::PreStartMission(const std::string& bundleName, const std::string& moduleName,
13662 const std::string& abilityName, const std::string& startTime)
13663 {
13664 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
13665 CHECK_CALLER_IS_SYSTEM_APP;
13666
13667 if (!PermissionVerification::GetInstance()->VerifyPreStartAtomicServicePermission()) {
13668 TAG_LOGE(AAFwkTag::ABILITYMGR, "calling user not ag");
13669 return ERR_PERMISSION_DENIED;
13670 }
13671
13672 if (!freeInstallManager_) {
13673 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
13674 return ERR_INVALID_VALUE;
13675 }
13676
13677 FreeInstallInfo taskInfo;
13678 if (!freeInstallManager_->GetFreeInstallTaskInfo(bundleName, abilityName, startTime, taskInfo)) {
13679 TAG_LOGE(AAFwkTag::ABILITYMGR,
13680 "failed find free install task info:bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
13681 bundleName.c_str(), abilityName.c_str(), startTime.c_str());
13682 return ERR_FREE_INSTALL_TASK_NOT_EXIST;
13683 }
13684
13685 if (taskInfo.isFreeInstallFinished) {
13686 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install finished");
13687 if (!taskInfo.isInstalled) {
13688 TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
13689 taskInfo.resultCode);
13690 } else {
13691 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeded");
13692 }
13693 // if free install is already finished then either the window is opened (on success)
13694 // or the user is informed of the error (on failure).
13695 return taskInfo.resultCode;
13696 }
13697
13698 return PreStartInner(taskInfo);
13699 }
13700
PreStartInner(const FreeInstallInfo & taskInfo)13701 int32_t AbilityManagerService::PreStartInner(const FreeInstallInfo& taskInfo)
13702 {
13703 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
13704
13705 const Want& want = taskInfo.want;
13706 sptr<IRemoteObject> callerToken = taskInfo.callerToken;
13707
13708 EventInfo eventInfo = BuildEventInfo(want, taskInfo.userId);
13709 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
13710
13711 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
13712 TAG_LOGE(AAFwkTag::ABILITYMGR, "PreStartInner StartAbilityError:%{public}d", ERR_INVALID_CALLER);
13713 eventHelper_.SendStartAbilityErrorEvent(eventInfo, ERR_INVALID_CALLER,
13714 "PreStartInner StartAbilityError");
13715 return ERR_INVALID_CALLER;
13716 }
13717
13718 int32_t oriValidUserId = GetValidUserId(taskInfo.userId);
13719
13720 int32_t appIndex = 0;
13721 StartAbilityInfoWrap threadLocalInfo(want, oriValidUserId,
13722 StartAbilityUtils::GetAppIndex(want, callerToken, appIndex), callerToken);
13723
13724 AbilityRequest abilityRequest = {
13725 .requestCode = taskInfo.requestCode,
13726 .callerToken = callerToken,
13727 .startSetting = nullptr,
13728 .want = want
13729 };
13730
13731 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
13732 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
13733
13734 // sceneboard
13735 abilityRequest.userId = oriValidUserId;
13736 abilityRequest.want.SetParam(ServerConstant::IS_CALL_BY_SCB, false);
13737 std::string sessionId = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
13738 std::chrono::system_clock::now().time_since_epoch()).count());
13739 abilityRequest.want.SetParam(KEY_SESSION_ID, sessionId);
13740 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
13741 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
13742 sptr<SessionInfo> sessionInfo = nullptr;
13743 auto errCode = uiAbilityManager->NotifySCBToPreStartUIAbility(abilityRequest, sessionInfo);
13744 if (errCode != ERR_OK) {
13745 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed notify sceneboard pre-start uiability");
13746 return errCode;
13747 }
13748 CHECK_POINTER_AND_RETURN(freeInstallManager_, ERR_INVALID_VALUE);
13749 freeInstallManager_->SetFreeInstallTaskSessionId(taskInfo.want.GetElement().GetBundleName(),
13750 taskInfo.want.GetElement().GetAbilityName(),
13751 taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), sessionId);
13752
13753 freeInstallManager_->SetPreStartMissionCallStatus(taskInfo.want.GetElement().GetBundleName(),
13754 taskInfo.want.GetElement().GetAbilityName(),
13755 taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME),
13756 true);
13757 return ERR_OK;
13758 }
13759
StartUIAbilityByPreInstall(const FreeInstallInfo & taskInfo)13760 int32_t AbilityManagerService::StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo)
13761 {
13762 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
13763 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
13764 if (!taskInfo.isFreeInstallFinished || !taskInfo.isInstalled) {
13765 TAG_LOGE(AAFwkTag::ABILITYMGR, "free install not finished or failed");
13766 return ERR_INVALID_VALUE;
13767 }
13768 if (!taskInfo.isStartUIAbilityBySCBCalled) {
13769 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install finished, startUIAbilityBySCB not called");
13770 return ERR_OK;
13771 }
13772
13773 const auto& want = taskInfo.want;
13774 auto sessionId = want.GetStringParam(KEY_SESSION_ID);
13775 if (sessionId.empty()) {
13776 TAG_LOGE(AAFwkTag::ABILITYMGR, "session id empty");
13777 return ERR_INVALID_VALUE;
13778 }
13779 auto bundleName = want.GetElement().GetBundleName();
13780 auto abilityName = want.GetElement().GetAbilityName();
13781 auto startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME);
13782 TAG_LOGI(AAFwkTag::ABILITYMGR, "call"
13783 "sessionId=%{public}s,bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
13784 sessionId.c_str(), bundleName.c_str(), abilityName.c_str(), startTime.c_str());
13785 sptr<SessionInfo> sessionInfo = nullptr;
13786 {
13787 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
13788 auto it = preStartSessionMap_.find(sessionId);
13789 if (it == preStartSessionMap_.end()) {
13790 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed find session info with sessionId=%{public}s",
13791 sessionId.c_str());
13792 return ERR_INVALID_VALUE;
13793 }
13794 sessionInfo = it->second;
13795 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
13796 (sessionInfo->want).SetElement(want.GetElement());
13797 }
13798
13799 if (sessionInfo->isMinimizedDuringFreeInstall) {
13800 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability is already minimized");
13801 return ATOMIC_SERVICE_MINIMIZED;
13802 }
13803
13804 bool isColdStart = true;
13805 int errCode = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, 0, isColdStart);
13806 if (errCode != ERR_OK) {
13807 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUIAbilityByPreInstallInner failed,errCode=%{public}d", errCode);
13808 return errCode;
13809 }
13810 RemovePreStartSession(sessionId);
13811 return errCode;
13812 }
13813
13814 // StartUIAbilityByPreInstallInner is called when free install task is already finished
StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo,uint32_t specifyTokenId,uint32_t sceneFlag,bool & isColdStart)13815 int AbilityManagerService::StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo, uint32_t specifyTokenId,
13816 uint32_t sceneFlag, bool &isColdStart)
13817 {
13818 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
13819 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
13820 auto callerToken = sessionInfo->callerToken;
13821 const auto& want = sessionInfo->want;
13822 const auto userId = sessionInfo->userId;
13823 const auto requestCode = sessionInfo->requestCode;
13824 bool isStartAsCaller = false;
13825
13826 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
13827 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
13828 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
13829 if (!isSpecificSA) {
13830 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
13831 return ERR_INVALID_CALLER;
13832 }
13833 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: caller specific system ability", __func__);
13834 }
13835
13836 int32_t oriValidUserId = GetValidUserId(userId);
13837 int32_t validUserId = oriValidUserId;
13838
13839 int32_t appIndex = 0;
13840 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
13841 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s GetAppIndex failed", __func__);
13842 return ERR_APP_CLONE_INDEX_INVALID;
13843 }
13844 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
13845 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
13846 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
13847 true, nullptr, shouldBlockFunc);
13848 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
13849 interceptorExecuter_->DoProcess(interceptorParam);
13850 if (result != ERR_OK) {
13851 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
13852 return result;
13853 }
13854
13855 AbilityRequest abilityRequest;
13856 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
13857 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
13858 std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
13859
13860 if (result != ERR_OK) {
13861 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
13862 return result;
13863 }
13864
13865 if (!HandleExecuteSAInterceptor(want, callerToken, abilityRequest, result)) {
13866 return result;
13867 }
13868
13869 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
13870 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
13871 } else if (!isStartAsCaller) {
13872 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
13873 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
13874 } else if (callerBundleName == BUNDLE_NAME_DIALOG) {
13875 #ifdef SUPPORT_SCREEN
13876 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
13877 implicitStartProcessor_->ResetCallingIdentityAsCaller(
13878 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), true);
13879 #endif // SUPPORT_SCREEN
13880 }
13881
13882 auto abilityInfo = abilityRequest.abilityInfo;
13883 validUserId = abilityInfo.applicationInfo.uid / BASE_USER_RANGE;
13884 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
13885 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
13886
13887 result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
13888 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false);
13889 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
13890 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
13891 return ERR_STATIC_CFG_PERMISSION;
13892 }
13893
13894 result = CheckCallPermission(want, abilityInfo, abilityRequest, false,
13895 false, specifyTokenId, callerBundleName);
13896 if (result != ERR_OK) {
13897 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkCallPermission error, result:%{public}d", result);
13898 return result;
13899 }
13900
13901 Want newWant = abilityRequest.want;
13902 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
13903 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
13904 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
13905 afterCheckExecuter_->DoProcess(afterCheckParam);
13906 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
13907 newWant.RemoveParam("queryWantFromErms");
13908 if (result != ERR_OK && isReplaceWantExist == false) {
13909 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
13910 return result;
13911 }
13912 #ifdef SUPPORT_SCREEN
13913 if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
13914 return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
13915 }
13916 if (result == ERR_OK &&
13917 DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
13918 TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
13919 return CreateCloneSelectorDialog(abilityRequest, GetUserId());
13920 }
13921 #endif // SUPPORT_SCREEN
13922
13923 if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
13924 abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
13925 TAG_LOGD(AAFwkTag::ABILITYMGR, "start ability by connectManager, type:%{public}d",
13926 static_cast<int32_t>(abilityInfo.type));
13927 return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
13928 }
13929
13930 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
13931 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", abilityInfo.bundleName.c_str());
13932 return ERR_WOULD_BLOCK;
13933 }
13934
13935 abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
13936 if (specifyTokenId > 0) {
13937 TAG_LOGD(AAFwkTag::ABILITYMGR, "set specifyTokenId, the specifyTokenId is %{public}d", specifyTokenId);
13938 abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
13939 abilityRequest.specifyTokenId = specifyTokenId;
13940 }
13941 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
13942
13943 auto uiAbilityManager = GetCurrentUIAbilityManager();
13944 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
13945
13946 return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
13947 }
13948
NotifySCBToHandleAtomicServiceException(const std::string & sessionId,int32_t errCode,const std::string & reason)13949 void AbilityManagerService::NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode,
13950 const std::string& reason)
13951 {
13952 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
13953 sptr<SessionInfo> sessionInfo = nullptr;
13954 {
13955 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
13956 auto it = preStartSessionMap_.find(sessionId);
13957 if (it == preStartSessionMap_.end()) {
13958 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed find session info with sessionId=%{public}s",
13959 sessionId.c_str());
13960 return;
13961 }
13962 sessionInfo = it->second;
13963 preStartSessionMap_.erase(it);
13964 }
13965 if (sessionInfo == nullptr) {
13966 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
13967 return;
13968 }
13969 auto uiAbilityManager = GetCurrentUIAbilityManager();
13970 CHECK_POINTER(uiAbilityManager);
13971 return uiAbilityManager->NotifySCBToHandleAtomicServiceException(sessionInfo, errCode, reason);
13972 }
13973
RemovePreStartSession(const std::string & sessionId)13974 void AbilityManagerService::RemovePreStartSession(const std::string& sessionId)
13975 {
13976 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
13977 preStartSessionMap_.erase(sessionId);
13978 }
13979
GetInsightIntentGenericInfo(const InsightIntentExecuteParam & param)13980 AbilityRuntime::ExtractInsightIntentGenericInfo AbilityManagerService::GetInsightIntentGenericInfo(
13981 const InsightIntentExecuteParam ¶m)
13982 {
13983 AbilityRuntime::ExtractInsightIntentGenericInfo infos;
13984 DelayedSingleton<AbilityRuntime::InsightIntentDbCache>::GetInstance()->GetInsightIntentGenericInfo(
13985 param.bundleName_, param.moduleName_, param.insightIntentName_, infos);
13986 TAG_LOGD(AAFwkTag::INTENT,
13987 "getLinkInfo:bundleName:%{public}s,moduleName:%{public}s,"
13988 "intentName:%{public}s,decoratorType:%{public}s",
13989 param.bundleName_.c_str(), param.moduleName_.c_str(), param.insightIntentName_.c_str(),
13990 infos.decoratorType.c_str());
13991 return infos;
13992 }
13993
CombinLinkInfo(const std::vector<AbilityRuntime::LinkIntentParamMapping> & paramMappings,std::string & uri,AAFwk::Want & want)13994 void AbilityManagerService::CombinLinkInfo(
13995 const std::vector<AbilityRuntime::LinkIntentParamMapping> ¶mMappings, std::string &uri, AAFwk::Want &want)
13996 {
13997 bool linkQuestionChatFlag = true;
13998 if (uri.find('?') != std::string::npos) {
13999 linkQuestionChatFlag = false;
14000 }
14001 for (auto &mapInfo : paramMappings) {
14002 TAG_LOGD(AAFwkTag::INTENT,
14003 "paramMapping info paramName:%{public}s paramMappingName:%{public}s paramCategory:%{public}s",
14004 mapInfo.paramName.c_str(),
14005 mapInfo.paramMappingName.c_str(),
14006 mapInfo.paramCategory.c_str());
14007 if (!want.HasParameter(mapInfo.paramName)) {
14008 continue;
14009 }
14010 std::string value = want.GetStringParam(mapInfo.paramName);
14011 if (mapInfo.paramCategory == "link") {
14012 if (linkQuestionChatFlag) {
14013 uri += ("?" + mapInfo.paramMappingName + "=" + value);
14014 linkQuestionChatFlag = false;
14015 } else {
14016 uri += ("&" + mapInfo.paramMappingName + "=" + value);
14017 }
14018 TAG_LOGD(AAFwkTag::INTENT, "link uri=%{public}s", uri.c_str());
14019 } else {
14020 want.RemoveParam(mapInfo.paramName);
14021 want.SetParam(mapInfo.paramMappingName, value);
14022 TAG_LOGD(AAFwkTag::INTENT,
14023 "want setparam key:%{public}s value:%{public}s",
14024 mapInfo.paramMappingName.c_str(),
14025 value.c_str());
14026 }
14027 }
14028 }
14029
IntentOpenLinkInner(const std::shared_ptr<AppExecFwk::InsightIntentExecuteParam> & param,AbilityRuntime::ExtractInsightIntentGenericInfo & linkInfo,const int32_t userId)14030 ErrCode AbilityManagerService::IntentOpenLinkInner(const std::shared_ptr<AppExecFwk::InsightIntentExecuteParam> ¶m,
14031 AbilityRuntime::ExtractInsightIntentGenericInfo &linkInfo, const int32_t userId)
14032 {
14033 if (param->uris_.empty()) {
14034 TAG_LOGE(AAFwkTag::INTENT, "Intent OpenLink failed uris is empty");
14035 return INNER_ERR;
14036 }
14037 std::string linkUri = linkInfo.get<AbilityRuntime::InsightIntentLinkInfo>().uri;
14038 if (linkUri != param->uris_[0].substr(0, linkUri.size())) {
14039 TAG_LOGE(AAFwkTag::INTENT,
14040 "Intent OpenLink failed uris is mismatch,linkUri:%{public}s, param uris:%{public}s",
14041 linkUri.c_str(), param->uris_[0].c_str());
14042 return INNER_ERR;
14043 }
14044
14045 AAFwk::Want want;
14046 want.SetParams(*param->insightIntentParam_);
14047 std::string openLinkUri = param->uris_[0];
14048 CombinLinkInfo(linkInfo.get<AbilityRuntime::InsightIntentLinkInfo>().paramMapping, openLinkUri, want);
14049
14050 want.SetUri(openLinkUri);
14051 want.SetElementName("", param->bundleName_, "", param->moduleName_);
14052 TAG_LOGD(AAFwkTag::INTENT, "openLinkUri=%{public}s", openLinkUri.c_str());
14053 if (!want.HasParameter(APP_LINKING_ONLY)) {
14054 want.SetParam(APP_LINKING_ONLY, false);
14055 }
14056 want.SetParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_PARAM_NAME, param->insightIntentName_);
14057 want.SetParam(AppExecFwk::INSIGHT_INTENT_EXECUTE_OPENLINK_FLAG, 1);
14058
14059 auto resultCode = OpenLinkInner(want, nullptr, userId, DEFAULT_INVAL_VALUE, false);
14060 if (resultCode == ERR_OK || resultCode == ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK) {
14061 TAG_LOGD(AAFwkTag::INTENT, "Intent OpenLink success");
14062 InsightIntentExecuteResult result;
14063 DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
14064 param->insightIntentId_, result.innerErr, result);
14065 return ERR_OK;
14066 }
14067 //mapping error code 16000019->16000050
14068 if (resultCode == ERR_IMPLICIT_START_ABILITY_FAIL) {
14069 resultCode = INNER_ERR;
14070 }
14071 TAG_LOGD(AAFwkTag::INTENT, "Intent OpenLink failed:%{public}d", resultCode);
14072 return resultCode;
14073 }
14074
OpenLink(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int32_t requestCode)14075 ErrCode AbilityManagerService::OpenLink(const Want& want, sptr<IRemoteObject> callerToken,
14076 int32_t userId, int32_t requestCode)
14077 {
14078 return OpenLinkInner(want, callerToken, userId, requestCode, true);
14079 }
14080
OpenLinkInner(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int32_t requestCode,bool removeInsightIntentFlag)14081 ErrCode AbilityManagerService::OpenLinkInner(const Want& want, sptr<IRemoteObject> callerToken,
14082 int32_t userId, int32_t requestCode, bool removeInsightIntentFlag)
14083 {
14084 if (AppUtils::GetInstance().IsForbidStart()) {
14085 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
14086 return INNER_ERR;
14087 }
14088 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
14089 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
14090 TAG_LOGI(AAFwkTag::ABILITYMGR, "call OpenLink");
14091 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
14092 std::string callerBundleName;
14093 Want convertedWant = want;
14094 if (!WantUtils::IsShortUrl(want) ||
14095 WantUtils::GetCallerBundleName(callerBundleName) != ERR_OK) {
14096 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
14097 int retCode = StartAbilityWithRemoveIntentFlag(want, callerToken, userId, requestCode, removeInsightIntentFlag);
14098 CHECK_RET_RETURN_RET(retCode, "startAbility failed");
14099 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
14100 }
14101
14102 TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName=%{public}s", callerBundleName.c_str());
14103 convertedWant.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
14104 uint32_t targetType = TARGET_TYPE_INIT;
14105 if (WantUtils::ConvertToExplicitWant(convertedWant, targetType) != ERR_OK) {
14106 TAG_LOGI(AAFwkTag::ABILITYMGR, "ConvertToExplicitWant fail. start ability by default");
14107 int retCode = StartAbilityWithRemoveIntentFlag(want, callerToken, userId, requestCode, removeInsightIntentFlag);
14108 CHECK_RET_RETURN_RET(retCode, "startAbility failed");
14109 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
14110 }
14111
14112 if (WantUtils::IsNormalApp(targetType)) {
14113 int retCode = StartAbilityWithRemoveIntentFlag(convertedWant, callerToken, userId, requestCode,
14114 removeInsightIntentFlag);
14115 CHECK_RET_RETURN_RET(retCode, "startAbility failed");
14116 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
14117 }
14118 if (WantUtils::IsAtomicService(targetType)) {
14119 return OpenLinkFreeInstallAtomicService(convertedWant, want, callerToken, userId, requestCode,
14120 removeInsightIntentFlag);
14121 }
14122 bool curAppLinkingOnlyFlag = convertedWant.GetBoolParam(APP_LINKING_ONLY, false);
14123 TAG_LOGD(AAFwkTag::ABILITYMGR, "openLink not specific app or atomicService. AppLinkingOnly: %{public}d",
14124 curAppLinkingOnlyFlag);
14125 if (curAppLinkingOnlyFlag) {
14126 return RESOLVE_ABILITY_ERR;
14127 }
14128 int retCode = StartAbilityWithRemoveIntentFlag(convertedWant, callerToken, userId, requestCode,
14129 removeInsightIntentFlag);
14130 CHECK_RET_RETURN_RET(retCode, "startAbility failed");
14131 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
14132 }
14133
OpenLinkFreeInstallAtomicService(Want & convertedWant,const Want & originalWant,sptr<IRemoteObject> callerToken,int32_t userId,int32_t requestCode,bool removeInsightIntentFlag)14134 int32_t AbilityManagerService::OpenLinkFreeInstallAtomicService(Want &convertedWant,
14135 const Want &originalWant, sptr<IRemoteObject> callerToken, int32_t userId, int32_t requestCode,
14136 bool removeInsightIntentFlag)
14137 {
14138 if (freeInstallManager_ == nullptr) {
14139 TAG_LOGI(AAFwkTag::ABILITYMGR, "freeInstallManager_ nullptr. start ability by default");
14140 auto retCode = StartAbilityWithRemoveIntentFlag(originalWant, callerToken, userId, requestCode,
14141 removeInsightIntentFlag);
14142 CHECK_RET_RETURN_RET(retCode, "startAbility failed");
14143 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
14144 }
14145 convertedWant.AddFlags(Want::FLAG_INSTALL_ON_DEMAND);
14146 auto param = std::make_shared<FreeInstallParams>();
14147 param->isAsync = true;
14148 param->isOpenAtomicServiceShortUrl = true;
14149 param->originalWant = std::make_shared<Want>(originalWant);
14150 ErrCode retCode = freeInstallManager_->StartFreeInstall(convertedWant, GetValidUserId(userId),
14151 requestCode, callerToken, param);
14152 if (retCode != ERR_OK) {
14153 TAG_LOGW(AAFwkTag::ABILITYMGR, "startFreeInstall returns errCode=%{public}d", retCode);
14154 if (retCode == NOT_TOP_ABILITY) {
14155 TAG_LOGE(AAFwkTag::ABILITYMGR, "start from background not allowed");
14156 return retCode;
14157 }
14158 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
14159 retCode = StartAbilityWithRemoveIntentFlag(originalWant, callerToken, userId, requestCode,
14160 removeInsightIntentFlag);
14161 CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
14162 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
14163 }
14164 return ERR_OK;
14165 }
14166
CleanUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool isUserRequestedExit,uint32_t sceneFlag)14167 int32_t AbilityManagerService::CleanUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool isUserRequestedExit,
14168 uint32_t sceneFlag)
14169 {
14170 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
14171 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
14172 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
14173 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo invalid");
14174 return ERR_INVALID_VALUE;
14175 }
14176
14177 if (!IsCallerSceneBoard()) {
14178 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support sceneboard call");
14179 return ERR_WRONG_INTERFACE_CALL;
14180 }
14181
14182 SetMinimizedDuringFreeInstall(sessionInfo);
14183
14184 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
14185 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
14186 TAG_LOGI(AAFwkTag::ABILITYMGR, "user request clean session: %{public}d", sessionInfo->persistentId);
14187 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
14188 if(!abilityRecord){
14189 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
14190 DeleteAbilityRecoverInfoBySessionId(sessionInfo->persistentId);
14191 }
14192 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
14193 abilityRecord->SetSceneFlag(sceneFlag);
14194 if (isUserRequestedExit) {
14195 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
14196 AAFwk::ExitReason exitReason = { REASON_NORMAL, "User Request" };
14197 appExitReasonHelper_->RecordUIAbilityExitReason(abilityRecord->GetPid(), abilityRecord->GetAbilityInfo().name,
14198 exitReason);
14199 }
14200 int32_t errCode = uiAbilityManager->CleanUIAbility(abilityRecord);
14201 ReportCleanSession(sessionInfo, abilityRecord, errCode);
14202 return errCode;
14203 }
14204
ForceTerminateServiceExtensionByPid(int32_t pid,int32_t userId)14205 void AbilityManagerService::ForceTerminateServiceExtensionByPid(int32_t pid, int32_t userId)
14206 {
14207 std::vector<sptr<IRemoteObject>> tokens;
14208 IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppScheduler>::GetInstance()->GetAbilityRecordsByProcessID(
14209 pid, tokens));
14210 auto connectManager = GetConnectManagerByUserId(userId);
14211 if (connectManager) {
14212 for (const auto& token : tokens) {
14213 auto abilityRecord = Token::GetAbilityRecordByToken(token);
14214 if (abilityRecord &&
14215 abilityRecord->GetAbilityInfo().extensionAbilityType ==
14216 AppExecFwk::ExtensionAbilityType::SERVICE) {
14217 TAG_LOGI(AAFwkTag::ABILITYMGR, "app ForceTerminateServiceExtensionByPid, pid is %{public}d", pid);
14218 connectManager->TerminateAbility(token);
14219 }
14220 }
14221 }
14222 }
14223
ReportCleanSession(const sptr<SessionInfo> & sessionInfo,const std::shared_ptr<AbilityRecord> & abilityRecord,int32_t errCode)14224 void AbilityManagerService::ReportCleanSession(const sptr<SessionInfo> &sessionInfo,
14225 const std::shared_ptr<AbilityRecord> &abilityRecord, int32_t errCode)
14226 {
14227 if (!sessionInfo || !abilityRecord) {
14228 return;
14229 }
14230
14231 const auto &abilityInfo = abilityRecord->GetAbilityInfo();
14232 std::string abilityName = abilityInfo.name;
14233 if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
14234 abilityName += std::to_string(sessionInfo->persistentId);
14235 }
14236 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
14237 DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
14238
14239 EventInfo eventInfo = BuildEventInfoByAbilityRecord(abilityRecord);
14240 eventInfo.errCode = errCode;
14241 SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
14242 if (eventInfo.errCode != ERR_OK) {
14243 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to terminate ability: %{public}d", eventInfo.errCode);
14244 SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
14245 }
14246 }
14247
SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want,uint32_t specifyTokenId)14248 void AbilityManagerService::SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo& abilityInfo,
14249 const Want& want, uint32_t specifyTokenId)
14250 {
14251 if (abilityInfo.type != AppExecFwk::AbilityType::EXTENSION ||
14252 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
14253 return;
14254 }
14255 EventInfo eventInfo;
14256 eventInfo.bundleName = abilityInfo.bundleName;
14257 eventInfo.moduleName = abilityInfo.moduleName;
14258 eventInfo.abilityName = abilityInfo.name;
14259 eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
14260 if (specifyTokenId > 0) {
14261 // come from want agent or form
14262 Security::AccessToken::HapTokenInfo hapInfo;
14263 if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(specifyTokenId, hapInfo) == ERR_OK) {
14264 eventInfo.callerBundleName = hapInfo.bundleName;
14265 }
14266 } else {
14267 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
14268 if (eventInfo.callerBundleName.empty()) {
14269 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
14270 }
14271 }
14272 TAG_LOGI(AAFwkTag::ABILITYMGR,
14273 "SendStartAbilityOtherExtensionEvent, bundleName:%{public}s, extensionAbilityType:%{public}d",
14274 eventInfo.bundleName.c_str(), eventInfo.extensionType);
14275 EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
14276 }
14277
SetAbilityRequestSessionInfo(AbilityRequest & abilityRequest,AppExecFwk::ExtensionAbilityType extensionType)14278 void AbilityManagerService::SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest,
14279 AppExecFwk::ExtensionAbilityType extensionType)
14280 {
14281 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
14282 if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
14283 return;
14284 }
14285
14286 abilityRequest.want.RemoveParam(WANT_PARAMS_HOST_WINDOW_ID_KEY);
14287 auto callerAbilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
14288 CHECK_POINTER_LOG(callerAbilityRecord, "callerAbilityRecord is nullptr");
14289 sptr<SessionInfo> callerSessionInfo = callerAbilityRecord->GetSessionInfo();
14290 CHECK_POINTER_LOG(callerSessionInfo, "callerSessionInfo is nullptr");
14291
14292 if (callerAbilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
14293 TAG_LOGI(AAFwkTag::ABILITYMGR, "UIAbility Caller");
14294 abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, callerSessionInfo->persistentId);
14295 } else if (AAFwk::UIExtensionUtils::IsUIExtension(callerAbilityRecord->GetAbilityInfo().extensionAbilityType)) {
14296 int32_t mainWindowId = -1;
14297 auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().
14298 GetSceneSessionManagerLiteProxy();
14299 CHECK_POINTER_LOG(sceneSessionManager, "sceneSessionManager is nullptr");
14300 auto err = sceneSessionManager->GetRootMainWindowId(static_cast<int32_t>(callerSessionInfo->hostWindowId),mainWindowId);
14301 TAG_LOGI(AAFwkTag::ABILITYMGR, "callerSessionInfo->hostWindowId = %{public}d, mainWindowId = %{public}d, err = %{public}d",
14302 callerSessionInfo->hostWindowId, mainWindowId, err);
14303 abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, mainWindowId);
14304 } else {
14305 abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, 0);
14306 }
14307 }
14308
TerminateMission(int32_t missionId)14309 int32_t AbilityManagerService::TerminateMission(int32_t missionId)
14310 {
14311 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
14312 TAG_LOGI(AAFwkTag::ABILITYMGR, "TerminateMission");
14313 auto missionListManager = GetCurrentMissionListManager();
14314 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
14315 CHECK_CALLER_IS_SYSTEM_APP;
14316
14317 if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
14318 PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
14319 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
14320 return CHECK_PERMISSION_FAILED;
14321 }
14322
14323 return missionListManager->ClearMission(missionId);
14324 }
14325
BlockAllAppStart(bool flag)14326 int32_t AbilityManagerService::BlockAllAppStart(bool flag)
14327 {
14328 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
14329 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
14330
14331 if (!AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
14332 TAG_LOGD(AAFwkTag::ABILITYMGR, "not supported device");
14333 return ERR_PERMISSION_DENIED;
14334 }
14335
14336 if (!PermissionVerification::GetInstance()->VerifyBlockAllAppStartPermission()) {
14337 TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
14338 return ERR_PERMISSION_DENIED;
14339 }
14340
14341 std::unique_lock<ffrt::mutex> lock(shouldBlockAllAppStartMutex_);
14342 shouldBlockAllAppStart_ = flag;
14343 return ERR_OK;
14344 }
14345
ShouldBlockAllAppStart()14346 bool AbilityManagerService::ShouldBlockAllAppStart()
14347 {
14348 if (!AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
14349 return false;
14350 }
14351
14352 std::unique_lock<ffrt::mutex> lock(shouldBlockAllAppStartMutex_);
14353 return shouldBlockAllAppStart_;
14354 }
14355
UpdateAssociateConfigList(const std::map<std::string,std::list<std::string>> & configs,const std::list<std::string> & exportConfigs,int32_t flag)14356 int32_t AbilityManagerService::UpdateAssociateConfigList(const std::map<std::string, std::list<std::string>>& configs,
14357 const std::list<std::string>& exportConfigs, int32_t flag)
14358 {
14359 if (IPCSkeleton::GetCallingUid() != RESOURCE_SCHEDULE_UID) {
14360 TAG_LOGE(AAFwkTag::ABILITYMGR, "Update associate config, current process not rss process");
14361 return CHECK_PERMISSION_FAILED;
14362 }
14363 std::lock_guard<std::mutex> locker(whiteListMutex_);
14364 if (flag == UPDATE_CONFIG_FLAG_COVER) {
14365 whiteListMap_ = configs;
14366 exportWhiteList_ = exportConfigs;
14367 } else if (flag == UPDATE_CONFIG_FLAG_APPEND) {
14368 for (const auto& config : configs) {
14369 for (const auto& item : config.second) {
14370 whiteListMap_[config.first].push_back(item);
14371 }
14372 }
14373 for (const auto& config : exportConfigs) {
14374 exportWhiteList_.push_back(config);
14375 }
14376 }
14377 return ERR_OK;
14378 }
14379
EnableListForSCBRecovery(int32_t userId) const14380 void AbilityManagerService::EnableListForSCBRecovery(int32_t userId) const
14381 {
14382 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
14383 CHECK_POINTER_LOG(uiAbilityManager, "UIAbilityMgr not exist.");
14384 uiAbilityManager->EnableListForSCBRecovery();
14385 }
14386
UpdateKeepAliveEnableState(const std::string & bundleName,const std::string & moduleName,const std::string & mainElement,bool updateEnable,int32_t userId)14387 int32_t AbilityManagerService::UpdateKeepAliveEnableState(const std::string &bundleName,
14388 const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId)
14389 {
14390 auto connectManager = GetConnectManagerByUserId(userId);
14391 CHECK_POINTER_AND_RETURN(connectManager, ERR_NULL_OBJECT);
14392 int32_t ret = connectManager->UpdateKeepAliveEnableState(bundleName, moduleName, mainElement, updateEnable);
14393 if (ret != ERR_OK) {
14394 TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateKeepAliveEnableState failed, err:%{public}d", ret);
14395 }
14396 return ret;
14397 }
14398
IsInStatusBar(uint32_t accessTokenId,int32_t uid,bool isMultiInstance)14399 bool AbilityManagerService::IsInStatusBar(uint32_t accessTokenId, int32_t uid, bool isMultiInstance)
14400 {
14401 auto uiAbilityManager = GetUIAbilityManagerByUid(uid);
14402 CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
14403
14404 return uiAbilityManager->IsInStatusBar(accessTokenId, isMultiInstance);
14405 }
14406
IsSupportStatusBar(int32_t uid)14407 bool AbilityManagerService::IsSupportStatusBar(int32_t uid)
14408 {
14409 auto uiAbilityManager = GetUIAbilityManagerByUid(uid);
14410 CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
14411
14412 return uiAbilityManager->IsSupportStatusBar();
14413 }
14414
SetApplicationKeepAlive(const std::string & bundleName,int32_t userId,bool flag)14415 int32_t AbilityManagerService::SetApplicationKeepAlive(const std::string &bundleName, int32_t userId, bool flag)
14416 {
14417 return KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(
14418 bundleName, userId, flag, false, false);
14419 }
14420
QueryKeepAliveApplications(int32_t appType,int32_t userId,std::vector<KeepAliveInfo> & list)14421 int32_t AbilityManagerService::QueryKeepAliveApplications(int32_t appType, int32_t userId,
14422 std::vector<KeepAliveInfo> &list)
14423 {
14424 return KeepAliveProcessManager::GetInstance().QueryKeepAliveApplications(
14425 appType, userId, list, false);
14426 }
14427
SetApplicationKeepAliveByEDM(const std::string & bundleName,int32_t userId,bool flag,bool isAllowUserToCancel)14428 int32_t AbilityManagerService::SetApplicationKeepAliveByEDM(const std::string &bundleName, int32_t userId,
14429 bool flag, bool isAllowUserToCancel)
14430 {
14431 if (userId != U1_USER_ID && isAllowUserToCancel) {
14432 return ERR_CAPABILITY_NOT_SUPPORT;
14433 }
14434
14435 auto bms = AbilityUtil::GetBundleManagerHelper();
14436 AppExecFwk::BundleInfo bundleInfo;
14437 if (bms && userId == U1_USER_ID) {
14438 if (IN_PROCESS_CALL(bms->GetBundleInfo(
14439 bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
14440 std::string mainElementName;
14441 if (MainElementUtils::CheckAppServiceExtension(bundleInfo, mainElementName)) {
14442 return KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(
14443 bundleName, flag, true, isAllowUserToCancel);
14444 }
14445 }
14446 }
14447
14448 return KeepAliveProcessManager::GetInstance().SetApplicationKeepAlive(
14449 bundleName, userId, flag, true, false);
14450 }
14451
QueryKeepAliveApplicationsByEDM(int32_t appType,int32_t userId,std::vector<KeepAliveInfo> & list)14452 int32_t AbilityManagerService::QueryKeepAliveApplicationsByEDM(int32_t appType, int32_t userId,
14453 std::vector<KeepAliveInfo> &list)
14454 {
14455 return KeepAliveProcessManager::GetInstance().QueryKeepAliveApplications(
14456 appType, userId, list, true);
14457 }
14458
StartSelfUIAbilityInner(StartSelfUIAbilityParam param)14459 int AbilityManagerService::StartSelfUIAbilityInner(StartSelfUIAbilityParam param)
14460 {
14461 CHECK_TRUE_RETURN_RET(!AppUtils::GetInstance().IsStartOptionsWithAnimation(),
14462 ERR_CAPABILITY_NOT_SUPPORT, "not supported");
14463
14464 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
14465 CHECK_POINTER_AND_RETURN(bundleMgrHelper, INNER_ERR);
14466
14467 AppExecFwk::AbilityInfo abilityInfo;
14468 CHECK_TRUE_RETURN_RET(!IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(param.want,
14469 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION, GetUserId(), abilityInfo)),
14470 TARGET_BUNDLE_NOT_EXIST, "bundle or ability not exist");
14471
14472 CHECK_TRUE_RETURN_RET(abilityInfo.type != AppExecFwk::AbilityType::PAGE,
14473 RESOLVE_CALL_ABILITY_TYPE_ERR, "not UIAbility");
14474
14475 auto callingPid = IPCSkeleton::GetCallingPid();
14476 AppExecFwk::RunningProcessInfo processInfo;
14477 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByChildProcessPid(callingPid, processInfo);
14478 CHECK_TRUE_RETURN_RET(processInfo.bundleNames.empty(), INNER_ERR, "failed to get by child process pid");
14479
14480 auto iter = std::find_if(processInfo.bundleNames.begin(), processInfo.bundleNames.end(),
14481 [targetBundleName = param.want.GetBundle()](const std::string &bundleName) {
14482 return bundleName == targetBundleName;
14483 });
14484 CHECK_TRUE_RETURN_RET(iter == processInfo.bundleNames.end(), ERR_START_OTHER_APP_FAILED, "cannot start other app");
14485
14486 param.want.RemoveParam(Want::PARAM_APP_CLONE_INDEX_KEY);
14487 if (processInfo.appMode == AppExecFwk::MultiAppModeType::APP_CLONE) {
14488 TAG_LOGI(AAFwkTag::ABILITYMGR, "set appIndex: %{public}d", processInfo.appCloneIndex);
14489 param.want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, processInfo.appCloneIndex);
14490 }
14491
14492 if (processInfo.appMode == AppExecFwk::MultiAppModeType::MULTI_INSTANCE &&
14493 !param.want.HasParameter(Want::APP_INSTANCE_KEY) &&
14494 !param.want.GetBoolParam(Want::CREATE_APP_INSTANCE_KEY, false)) {
14495 TAG_LOGI(AAFwkTag::ABILITYMGR, "set instanceKey: %{public}s", processInfo.instanceKey.c_str());
14496 param.want.SetParam(Want::APP_INSTANCE_KEY, processInfo.instanceKey);
14497 }
14498
14499 auto tokenId = abilityInfo.applicationInfo.accessTokenId;
14500 StartSelfUIAbilityRecordGuard startSelfUIAbilityRecordGuard(callingPid, tokenId);
14501 CHECK_TRUE_RETURN_RET(!PermissionVerification::GetInstance()->VerifyStartSelfUIAbility(tokenId),
14502 CHECK_PERMISSION_FAILED, "permission denied");
14503
14504 CHECK_TRUE_RETURN_RET(processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND,
14505 NOT_TOP_ABILITY, "caller not foreground");
14506
14507 if (!param.hasStartOptions) {
14508 return StartAbility(param.want);
14509 }
14510 return StartAbility(param.want, param.options, nullptr);
14511 }
14512
StartSelfUIAbility(const Want & want)14513 int AbilityManagerService::StartSelfUIAbility(const Want &want)
14514 {
14515 if (AppUtils::GetInstance().IsForbidStart()) {
14516 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
14517 return INNER_ERR;
14518 }
14519 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
14520
14521 StartSelfUIAbilityParam param;
14522 param.want = want;
14523 return StartSelfUIAbilityInner(param);
14524 }
14525
StartSelfUIAbilityWithStartOptions(const Want & want,const StartOptions & options)14526 int AbilityManagerService::StartSelfUIAbilityWithStartOptions(const Want &want, const StartOptions &options)
14527 {
14528 if (AppUtils::GetInstance().IsForbidStart()) {
14529 TAG_LOGW(AAFwkTag::ABILITYMGR, "forbid start: %{public}s", want.GetElement().GetBundleName().c_str());
14530 return INNER_ERR;
14531 }
14532 XCOLLIE_TIMER_LESS(__PRETTY_FUNCTION__);
14533 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartSelfUIAbility with startOptions");
14534
14535 if(options.processOptions != nullptr) {
14536 options.processOptions->isStartFromNDK = true;
14537 }
14538
14539 StartSelfUIAbilityParam param = { want, options, true };
14540 return StartSelfUIAbilityInner(param);
14541 }
14542
CheckCrossUser(const int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)14543 bool AbilityManagerService::CheckCrossUser(const int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
14544 {
14545 if (AAFwk::UIExtensionUtils::IsEnterpriseAdmin(extensionType) || JudgeMultiUserConcurrency(userId)) {
14546 return true;
14547 }
14548 if (AppUtils::GetInstance().IsConnectSupportCrossUser() && (extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE
14549 || extensionType == AppExecFwk::ExtensionAbilityType::SERVICE)) {
14550 return true;
14551 }
14552 return false;
14553 }
14554
KillProcessForPermissionUpdate(uint32_t accessTokenId)14555 int32_t AbilityManagerService::KillProcessForPermissionUpdate(uint32_t accessTokenId)
14556 {
14557 int32_t callingUid = IPCSkeleton::GetCallingUid();
14558 TAG_LOGI(AAFwkTag::ABILITYMGR,
14559 "Call KillProcessForPermissionUpdate. callingUid: %{public}d", callingUid);
14560 auto isCallingPerm = PermissionVerification::GetInstance()->VerifyCallingPermission(
14561 PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
14562 if (!isCallingPerm) {
14563 TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to kill processes.");
14564 return ERR_PERMISSION_DENIED;
14565 }
14566
14567 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
14568 auto uiAbilityManager = GetUIAbilityManagerByUid(callingUid);
14569 CHECK_POINTER_AND_RETURN_LOG(uiAbilityManager, ERR_NULL_OBJECT, "uiAbilityLifecycleManager nullptr");
14570 uiAbilityManager->SetKillForPermissionUpdateFlag(accessTokenId);
14571 }
14572
14573 int32_t ret =
14574 DelayedSingleton<AppScheduler>::GetInstance()->KillProcessesByAccessTokenId(accessTokenId);
14575 if (ret != ERR_OK) {
14576 TAG_LOGE(AAFwkTag::ABILITYMGR, "KillProcessesByAccessTokenId error");
14577 return ret;
14578 }
14579
14580 return ERR_OK;
14581 }
14582
RegisterHiddenStartObserver(const sptr<IHiddenStartObserver> & observer)14583 int32_t AbilityManagerService::RegisterHiddenStartObserver(const sptr<IHiddenStartObserver> &observer)
14584 {
14585 if (!AAFwk::PermissionVerification::GetInstance()->VerifyStartUIAbilityToHiddenPermission()) {
14586 TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterHiddenStartObserver permission verification failed");
14587 return ERR_PERMISSION_DENIED;
14588 }
14589 return HiddenStartObserverManager::GetInstance().RegisterObserver(observer);
14590 }
14591
UnregisterHiddenStartObserver(const sptr<IHiddenStartObserver> & observer)14592 int32_t AbilityManagerService::UnregisterHiddenStartObserver(const sptr<IHiddenStartObserver> &observer)
14593 {
14594 if (!AAFwk::PermissionVerification::GetInstance()->VerifyStartUIAbilityToHiddenPermission()) {
14595 TAG_LOGE(AAFwkTag::ABILITYMGR, "UnregisterHiddenStartObserver permission verification failed");
14596 return ERR_PERMISSION_DENIED;
14597 }
14598 return HiddenStartObserverManager::GetInstance().UnregisterObserver(observer);
14599 }
14600
QueryPreLoadUIExtensionRecord(const AppExecFwk::ElementName & element,const std::string & moduleName,const std::string & hostBundleName,int32_t & recordNum,int32_t userId)14601 int32_t AbilityManagerService::QueryPreLoadUIExtensionRecord(const AppExecFwk::ElementName &element,
14602 const std::string &moduleName,
14603 const std::string &hostBundleName,
14604 int32_t &recordNum,
14605 int32_t userId)
14606 {
14607 // check preload ui extension permission.
14608 CHECK_CALLER_IS_SYSTEM_APP;
14609 if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
14610 PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
14611 TAG_LOGE(AAFwkTag::UI_EXT, "permission %{public}s verification failed",
14612 PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
14613 return ERR_PERMISSION_DENIED;
14614 }
14615 int32_t validUserId = GetValidUserId(userId);
14616 auto connectManager = GetConnectManagerByUserId(validUserId);
14617 if (!connectManager) {
14618 TAG_LOGE(AAFwkTag::UI_EXT, "connectManager null. userId=%{public}d", userId);
14619 return ERR_INVALID_VALUE;
14620 }
14621 return connectManager->QueryPreLoadUIExtensionRecordInner(
14622 element, moduleName, hostBundleName, recordNum);
14623 }
14624
RevokeDelegator(sptr<IRemoteObject> token)14625 int32_t AbilityManagerService::RevokeDelegator(sptr<IRemoteObject> token)
14626 {
14627 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
14628 TAG_LOGE(AAFwkTag::ABILITYMGR, "capability not support");
14629 return ERR_CAPABILITY_NOT_SUPPORT;
14630 }
14631 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
14632 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(callingTokenId);
14633 if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_HAP) {
14634 TAG_LOGE(AAFwkTag::URIPERMMGR, "Not TOKEN_HAP");
14635 return ERR_NO_PERMISSION_CALLER;
14636 }
14637 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
14638 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
14639 return uiAbilityManager->RevokeDelegator(token);
14640 }
14641
StartAbilityWithWait(Want & want,sptr<IAbilityStartWithWaitObserver> & observer)14642 int32_t AbilityManagerService::StartAbilityWithWait(Want &want, sptr<IAbilityStartWithWaitObserver> &observer)
14643 {
14644 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
14645 TAG_LOGD(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartAbilityWithWait called");
14646 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
14647 if (!isShellCall) {
14648 TAG_LOGE(AAFwkTag::ABILITYMGR, "not shell call");
14649 return ERR_PERMISSION_DENIED;
14650 }
14651 // 1.regist observer
14652 int32_t result = AbilityStartWithWaitObserverManager::GetInstance().RegisterObserver(want, observer);
14653 if (result != ERR_OK) {
14654 TAG_LOGE(AAFwkTag::ABILITYMGR, "register ability start with wait observer fail, result:%{public}d", result);
14655 return result;
14656 }
14657 // 2.start ability
14658 result = StartAbility(want, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE);
14659 if (result != ERR_OK) {
14660 TAG_LOGE(AAFwkTag::ABILITYMGR, "start ability wait fail, result:%{public}d", result);
14661 return result;
14662 }
14663 return ERR_OK;
14664 }
14665
CheckStartPlugin(const Want & want,sptr<IRemoteObject> callerToken)14666 int32_t AbilityManagerService::CheckStartPlugin(const Want& want, sptr<IRemoteObject> callerToken)
14667 {
14668 if (!AbilityRuntime::StartupUtil::IsStartPlugin(want)) {
14669 return ERR_OK;
14670 }
14671 TAG_LOGI(AAFwkTag::ABILITYMGR, "start plugin ability");
14672 // bundleName, abilityName, moduoleName not empty
14673 auto element = want.GetElement();
14674 if (element.GetBundleName().empty() || element.GetAbilityName().empty() || element.GetModuleName().empty()) {
14675 return INVALID_PARAMETERS_ERR;
14676 }
14677 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
14678 if (!abilityRecord) {
14679 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
14680 return ERR_CHECK_PLUGIN_NULL_RECORD;
14681 }
14682 if (!(abilityRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE ||
14683 (abilityRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::EXTENSION &&
14684 abilityRecord->GetAbilityInfo().extensionAbilityType == AppExecFwk::ExtensionAbilityType::EMBEDDED_UI))) {
14685 TAG_LOGE(AAFwkTag::ABILITYMGR, "type is not UIAbility or embedded_ui");
14686 return ERR_CHECK_PLUGIN_INVALID_TYPE;
14687 }
14688 if (abilityRecord->IsPluginAbility()) {
14689 TAG_LOGE(AAFwkTag::ABILITYMGR, "not host ability");
14690 return ERR_CALLER_IS_PLUGIN_ABILITY;
14691 }
14692 return ERR_OK;
14693 }
14694
GetAllInsightIntentInfo(AbilityRuntime::GetInsightIntentFlag flag,std::vector<InsightIntentInfoForQuery> & infos)14695 int32_t AbilityManagerService::GetAllInsightIntentInfo(
14696 AbilityRuntime::GetInsightIntentFlag flag,
14697 std::vector<InsightIntentInfoForQuery> &infos)
14698 {
14699 TAG_LOGI(AAFwkTag::INTENT, "GetAllInsightIntentInfo");
14700 int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckGetInsightIntenInfoPermission();
14701 if (ret != ERR_OK) {
14702 TAG_LOGD(AAFwkTag::INTENT, "not system app or permission denied");
14703 return ret;
14704 }
14705 if (flag & AbilityRuntime::GetInsightIntentFlag::GET_FULL_INSIGHT_INTENT) {
14706 std::vector<ExtractInsightIntentInfo> intentInfos;
14707 const int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
14708 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetAllInsightIntentInfo(userId, intentInfos);
14709 if (intentInfos.empty()) {
14710 TAG_LOGD(AAFwkTag::INTENT, "extractInsightIntentInfos empty");
14711 return ERR_OK;
14712 }
14713 TAG_LOGD(AAFwkTag::INTENT, "intentInfos size: %{public}zu", intentInfos.size());
14714 bool getEntity = (flag & AbilityRuntime::GetInsightIntentFlag::GET_ENTITY_INFO);
14715 for (auto &info : intentInfos) {
14716 InsightIntentInfoForQuery intentInfoQuery;
14717 InsightIntentUtils::ConvertExtractInsightIntentInfo(info, intentInfoQuery, getEntity);
14718 infos.emplace_back(intentInfoQuery);
14719 }
14720 } else if (flag & AbilityRuntime::GetInsightIntentFlag::GET_SUMMARY_INSIGHT_INTENT) {
14721 std::vector<ExtractInsightIntentGenericInfo> genericInfos;
14722 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetAllInsightIntentGenericInfo(genericInfos);
14723 if (genericInfos.empty()) {
14724 return ERR_OK;
14725 }
14726 TAG_LOGD(AAFwkTag::INTENT, "genericInfos size: %{public}zu", genericInfos.size());
14727
14728 if (flag & AbilityRuntime::GetInsightIntentFlag::GET_ENTITY_INFO) {
14729 std::vector<ExtractInsightIntentInfo> intentInfos;
14730 const int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
14731 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetAllInsightIntentInfo(userId, intentInfos);
14732 if (intentInfos.empty()) {
14733 TAG_LOGI(AAFwkTag::INTENT, "extractInsightIntentInfos empty");
14734 return ERR_OK;
14735 }
14736 for (auto &info : intentInfos) {
14737 InsightIntentInfoForQuery intentInfoQuery;
14738 InsightIntentUtils::ConvertExtractInsightIntentEntityInfo(info, intentInfoQuery);
14739 infos.emplace_back(intentInfoQuery);
14740 }
14741 return ERR_OK;
14742 }
14743
14744 for (auto &info : genericInfos) {
14745 InsightIntentInfoForQuery intentInfoQuery;
14746 InsightIntentUtils::ConvertExtractInsightIntentGenericInfo(info, intentInfoQuery);
14747 infos.emplace_back(intentInfoQuery);
14748 }
14749 } else {
14750 TAG_LOGW(AAFwkTag::INTENT, "invalid flag: %{public}d", flag);
14751 }
14752
14753 return ERR_OK;
14754 }
14755
GetInsightIntentInfoByBundleName(AbilityRuntime::GetInsightIntentFlag flag,const std::string & bundleName,std::vector<InsightIntentInfoForQuery> & infos)14756 int32_t AbilityManagerService::GetInsightIntentInfoByBundleName(
14757 AbilityRuntime::GetInsightIntentFlag flag,
14758 const std::string &bundleName,
14759 std::vector<InsightIntentInfoForQuery> &infos)
14760 {
14761 TAG_LOGI(AAFwkTag::INTENT, "GetInsightIntentInfoByBundleName");
14762 int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckGetInsightIntenInfoPermission();
14763 if (ret != ERR_OK) {
14764 TAG_LOGD(AAFwkTag::INTENT, "not system app or permission denied");
14765 return ret;
14766 }
14767 if (flag & AbilityRuntime::GetInsightIntentFlag::GET_FULL_INSIGHT_INTENT) {
14768 std::vector<ExtractInsightIntentInfo> intentInfos;
14769 const int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
14770 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetInsightIntentInfoByName(
14771 bundleName, userId, intentInfos);
14772 if (intentInfos.empty()) {
14773 TAG_LOGD(AAFwkTag::INTENT, "extractInsightIntentInfos empty");
14774 return ERR_OK;
14775 }
14776 TAG_LOGD(AAFwkTag::INTENT, "intentInfos size: %{public}zu", intentInfos.size());
14777 bool getEntity = (flag & AbilityRuntime::GetInsightIntentFlag::GET_ENTITY_INFO);
14778 for (auto &info : intentInfos) {
14779 InsightIntentInfoForQuery intentInfoQuery;
14780 InsightIntentUtils::ConvertExtractInsightIntentInfo(info, intentInfoQuery, getEntity);
14781 infos.emplace_back(intentInfoQuery);
14782 }
14783 } else if (flag & AbilityRuntime::GetInsightIntentFlag::GET_SUMMARY_INSIGHT_INTENT) {
14784 std::vector<ExtractInsightIntentGenericInfo> genericInfos;
14785 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetInsightIntentGenericInfoByName(
14786 bundleName, genericInfos);
14787 if (genericInfos.empty()) {
14788 return ERR_OK;
14789 }
14790 TAG_LOGD(AAFwkTag::INTENT, "genericInfos size: %{public}zu", genericInfos.size());
14791
14792 if (flag & AbilityRuntime::GetInsightIntentFlag::GET_ENTITY_INFO) {
14793 std::vector<ExtractInsightIntentInfo> intentInfos;
14794 const int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
14795 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetInsightIntentInfoByName(
14796 bundleName, userId, intentInfos);
14797 if (intentInfos.empty()) {
14798 TAG_LOGI(AAFwkTag::INTENT, "extractInsightIntentInfos empty");
14799 return ERR_OK;
14800 }
14801 for (auto &info : intentInfos) {
14802 InsightIntentInfoForQuery intentInfoQuery;
14803 InsightIntentUtils::ConvertExtractInsightIntentEntityInfo(info, intentInfoQuery);
14804 infos.emplace_back(intentInfoQuery);
14805 }
14806 return ERR_OK;
14807 }
14808 for (auto &info : genericInfos) {
14809 InsightIntentInfoForQuery intentInfoQuery;
14810 InsightIntentUtils::ConvertExtractInsightIntentGenericInfo(info, intentInfoQuery);
14811 infos.emplace_back(intentInfoQuery);
14812 }
14813 } else {
14814 TAG_LOGW(AAFwkTag::INTENT, "invalid flag: %{public}d", flag);
14815 }
14816 return ERR_OK;
14817 }
14818
GetInsightIntentInfoByIntentName(AbilityRuntime::GetInsightIntentFlag flag,const std::string & bundleName,const std::string & moduleName,const std::string & intentName,InsightIntentInfoForQuery & info)14819 int32_t AbilityManagerService::GetInsightIntentInfoByIntentName(
14820 AbilityRuntime::GetInsightIntentFlag flag,
14821 const std::string &bundleName,
14822 const std::string &moduleName,
14823 const std::string &intentName,
14824 InsightIntentInfoForQuery &info)
14825 {
14826 TAG_LOGI(AAFwkTag::INTENT, "GetInsightIntentInfoByIntentName");
14827 int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckGetInsightIntenInfoPermission();
14828 if (ret != ERR_OK) {
14829 TAG_LOGD(AAFwkTag::INTENT, "not system app or permission denied");
14830 return ret;
14831 }
14832 if (flag & AbilityRuntime::GetInsightIntentFlag::GET_FULL_INSIGHT_INTENT) {
14833 ExtractInsightIntentInfo intentInfo;
14834 const int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
14835 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetInsightIntentInfo(
14836 bundleName, moduleName, intentName, userId, intentInfo);
14837 bool getEntity = (flag & AbilityRuntime::GetInsightIntentFlag::GET_ENTITY_INFO);
14838 InsightIntentUtils::ConvertExtractInsightIntentInfo(intentInfo, info, getEntity);
14839 } else if (flag & AbilityRuntime::GetInsightIntentFlag::GET_SUMMARY_INSIGHT_INTENT) {
14840 if (flag & AbilityRuntime::GetInsightIntentFlag::GET_ENTITY_INFO) {
14841 ExtractInsightIntentInfo intentInfo;
14842 const int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
14843 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetInsightIntentInfo(
14844 bundleName, moduleName, intentName, userId, intentInfo);
14845 InsightIntentUtils::ConvertExtractInsightIntentEntityInfo(intentInfo, info);
14846
14847 return ERR_OK;
14848 }
14849
14850 ExtractInsightIntentGenericInfo genericInfo;
14851 DelayedSingleton<InsightIntentDbCache>::GetInstance()->GetInsightIntentGenericInfo(
14852 bundleName, moduleName, intentName, genericInfo);
14853 InsightIntentUtils::ConvertExtractInsightIntentGenericInfo(genericInfo, info);
14854
14855 } else {
14856 TAG_LOGW(AAFwkTag::INTENT, "invalid flag: %{public}d", flag);
14857 }
14858 return ERR_OK;
14859 }
14860
IsCrossUserCall(int32_t userId) const14861 bool AbilityManagerService::IsCrossUserCall(int32_t userId) const
14862 {
14863 return userId != INVALID_USER_ID && userId != U0_USER_ID && userId != U1_USER_ID && userId != GetUserId();
14864 }
14865
RestartSelfAtomicService(sptr<IRemoteObject> callerToken)14866 int32_t AbilityManagerService::RestartSelfAtomicService(sptr<IRemoteObject> callerToken)
14867 {
14868 TAG_LOGI(AAFwkTag::ABILITYMGR, "RestartSelfAtomicService");
14869 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
14870 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
14871
14872 if (abilityRecord->GetApplicationInfo().bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE) {
14873 TAG_LOGE(AAFwkTag::ABILITYMGR, "not atomic service");
14874 return ERR_CALLER_NOT_ATOMIC_SERVICE;
14875 }
14876
14877 auto callerPid = IPCSkeleton::GetCallingPid();
14878 AppExecFwk::RunningProcessInfo processInfo;
14879 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
14880 int32_t callerUid = IPCSkeleton::GetCallingUid();
14881 int32_t userId = callerUid / BASE_USER_RANGE;
14882 if (!processInfo.isFocused && !processInfo.isAbilityForegrounding) {
14883 TAG_LOGE(AAFwkTag::ABILITYMGR, "restartApp, is not foreground");
14884 return AAFwk::NOT_TOP_ABILITY;
14885 }
14886
14887 RestartAppKeyType key(processInfo.instanceKey, callerUid);
14888 int64_t now = time(nullptr);
14889 if (RestartAppManager::GetInstance().IsRestartAppFrequent(key, now)) {
14890 return AAFwk::ERR_RESTART_APP_FREQUENT;
14891 }
14892
14893 SignRestartAppFlagParam param =
14894 { userId, callerUid, processInfo.instanceKey, processInfo.appMode, false, true };
14895 auto result = SignRestartAppFlag(param);
14896 if (result != ERR_OK) {
14897 TAG_LOGE(AAFwkTag::ABILITYMGR, "signRestartAppFlag error: %{public}d", result);
14898 return result;
14899 }
14900
14901 auto want = abilityRecord->GetWant();
14902 std::string startTime = std::to_string(now);
14903 want.SetParam(Want::PARAM_RESV_START_TIME, startTime);
14904 want.AddFlags(Want::FLAG_INSTALL_ON_DEMAND);
14905 result = IN_PROCESS_CALL(StartAbilityByFreeInstall(want, nullptr, userId, DEFAULT_INVAL_VALUE));
14906 if (result != ERR_OK) {
14907 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbilityByFreeInstall failed:%{public}d", result);
14908 return result;
14909 }
14910 RestartAppManager::GetInstance().AddRestartAppHistory(key, now);
14911 return result;
14912 }
14913
UpdateKioskApplicationList(const std::vector<std::string> & appList)14914 int32_t AbilityManagerService::UpdateKioskApplicationList(const std::vector<std::string> &appList)
14915 {
14916 TAG_LOGD(AAFwkTag::ABILITYMGR, "request UpdateKioskApplicationList");
14917 return KioskManager::GetInstance().UpdateKioskApplicationList(appList);
14918 }
14919
EnterKioskMode(sptr<IRemoteObject> callerToken)14920 int32_t AbilityManagerService::EnterKioskMode(sptr<IRemoteObject> callerToken)
14921 {
14922 TAG_LOGD(AAFwkTag::ABILITYMGR, "request EnterKioskMode");
14923 auto record = Token::GetAbilityRecordByToken(callerToken);
14924 if (!record) {
14925 TAG_LOGE(AAFwkTag::ABILITYMGR, "record null");
14926 return INVALID_PARAMETERS_ERR;
14927 }
14928 if (!JudgeSelfCalled(record)) {
14929 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self call");
14930 return CHECK_PERMISSION_FAILED;
14931 }
14932 return KioskManager::GetInstance().EnterKioskMode(callerToken);
14933 }
14934
ExitKioskMode(sptr<IRemoteObject> callerToken)14935 int32_t AbilityManagerService::ExitKioskMode(sptr<IRemoteObject> callerToken)
14936 {
14937 TAG_LOGD(AAFwkTag::ABILITYMGR, "request ExitKioskMode");
14938 auto record = Token::GetAbilityRecordByToken(callerToken);
14939 if (!record) {
14940 TAG_LOGE(AAFwkTag::ABILITYMGR, "record null");
14941 return INVALID_PARAMETERS_ERR;
14942 }
14943 if (!JudgeSelfCalled(record)) {
14944 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self call");
14945 return CHECK_PERMISSION_FAILED;
14946 }
14947 return KioskManager::GetInstance().ExitKioskMode(callerToken);
14948 }
14949
GetKioskStatus(KioskStatus & kioskStatus)14950 int32_t AbilityManagerService::GetKioskStatus(KioskStatus &kioskStatus)
14951 {
14952 TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetKioskStatus");
14953 return KioskManager::GetInstance().GetKioskStatus(kioskStatus);
14954 }
14955
GetAbilityInterceptorExecuter()14956 std::shared_ptr<AbilityInterceptorExecuter> AbilityManagerService::GetAbilityInterceptorExecuter()
14957 {
14958 return interceptorExecuter_;
14959 }
14960
RegisterSAInterceptor(sptr<AbilityRuntime::ISAInterceptor> interceptor)14961 int32_t AbilityManagerService::RegisterSAInterceptor(sptr<AbilityRuntime::ISAInterceptor> interceptor)
14962 {
14963 TAG_LOGI(AAFwkTag::ABILITYMGR, "call RegisterSaInterceptor");
14964 if (IPCSkeleton::GetCallingUid() != PENG_LAI_UID) {
14965 TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission call");
14966 return CHECK_PERMISSION_FAILED;
14967 }
14968
14969 return SAInterceptorManager::GetInstance().AddSAInterceptor(interceptor);
14970 }
14971
HandleExecuteSAInterceptor(const Want & want,sptr<IRemoteObject> callerToken,AbilityRequest & abilityRequest,int32_t & result)14972 bool AbilityManagerService::HandleExecuteSAInterceptor(const Want &want, sptr<IRemoteObject> callerToken,
14973 AbilityRequest &abilityRequest, int32_t &result)
14974 {
14975 if (SAInterceptorManager::GetInstance().SAInterceptorListIsEmpty()) {
14976 return true;
14977 }
14978 Rule rule;
14979 auto dialogSessionId = DialogSessionManager::GetInstance().GenerateDialogSessionId();
14980 auto params = SAInterceptorManager::GetInstance().GenerateSAInterceptorParams(want, callerToken,
14981 abilityRequest.abilityInfo, dialogSessionId);
14982 auto ret = SAInterceptorManager::GetInstance().ExecuteSAInterceptor(params, rule);
14983
14984 if (ret != ERR_OK || rule.type == RuleType::NOT_ALLOW) {
14985 TAG_LOGE(AAFwkTag::ABILITYMGR, "sa interceptor OnCheckStarting failed");
14986 result = static_cast<int32_t>(AbilityRuntime::AbilityErrorCode::ERROR_CODE_CONTROLLED);
14987 return false;
14988 }
14989
14990 if (rule.type == RuleType::USER_SELECTION) {
14991 TAG_LOGW(AAFwkTag::ABILITYMGR, "sa interceptor OnCheckStarting failed, set dialog caller info");
14992 DialogSessionManager::GetInstance().OnlySetDialogCallerInfo(abilityRequest, GetUserId(),
14993 SelectorType::INTERCEPTOR_SELECTOR, dialogSessionId, false);
14994 result = ERR_OK;
14995 return false;
14996 }
14997
14998 return true;
14999 }
15000
HandleExtensionAbility(sptr<IAbilityConnection> connect,std::function<int32_t (std::shared_ptr<AbilityConnectManager>,sptr<IAbilityConnection>)> func)15001 int32_t AbilityManagerService::HandleExtensionAbility(sptr<IAbilityConnection> connect,
15002 std::function<int32_t(std::shared_ptr<AbilityConnectManager>, sptr<IAbilityConnection>)> func)
15003 {
15004 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
15005 auto currentConnectManager = GetCurrentConnectManager();
15006 CHECK_POINTER_AND_RETURN(currentConnectManager, ERR_NO_INIT);
15007 if (func(currentConnectManager, connect) == ERR_OK) {
15008 return ERR_OK;
15009 }
15010 // If current connectManager does not exist connect, then try connectManagerU0
15011 auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
15012 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
15013 if (func(connectManager, connect) == ERR_OK) {
15014 return ERR_OK;
15015 }
15016
15017 connectManager = GetConnectManagerByUserId(U1_USER_ID);
15018 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
15019 if (func(connectManager, connect) == ERR_OK) {
15020 return ERR_OK;
15021 }
15022
15023 auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
15024 if (userId == U0_USER_ID || userId == U1_USER_ID) {
15025 auto connectManagers = GetConnectManagers();
15026 for (auto& item : connectManagers) {
15027 if (item.second && func(item.second, connect) == ERR_OK) {
15028 return ERR_OK;
15029 }
15030 }
15031 }
15032 connectManager = GetConnectManagerByUserId(userId);
15033 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
15034 return func(connectManager, connect);
15035 }
15036
SuspendExtensionAbility(sptr<IAbilityConnection> connect)15037 int AbilityManagerService::SuspendExtensionAbility(sptr<IAbilityConnection> connect)
15038 {
15039 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
15040 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
15041 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
15042 return CHECK_PERMISSION_FAILED;
15043 }
15044 TAG_LOGI(AAFwkTag::SERVICE_EXT, "Suspend extension ability begin.");
15045 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
15046 auto err = HandleExtensionAbility(connect,
15047 [](std::shared_ptr<AbilityConnectManager> connectManager, sptr<IAbilityConnection> connect) {
15048 return connectManager->SuspendExtensionAbilityLocked(connect);
15049 });
15050 if (err == ERR_OK) {
15051 return ERR_OK;
15052 }
15053
15054 TAG_LOGE(AAFwkTag::SERVICE_EXT, "Suspend extension ability error %{public}d", err);
15055 return err;
15056 }
15057
ResumeExtensionAbility(sptr<IAbilityConnection> connect)15058 int AbilityManagerService::ResumeExtensionAbility(sptr<IAbilityConnection> connect)
15059 {
15060 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
15061 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
15062 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
15063 return CHECK_PERMISSION_FAILED;
15064 }
15065 TAG_LOGI(AAFwkTag::SERVICE_EXT, "Resume extension ability begin.");
15066 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
15067 auto err = HandleExtensionAbility(connect,
15068 [](std::shared_ptr<AbilityConnectManager> connectManager, sptr<IAbilityConnection> connect) {
15069 return connectManager->ResumeExtensionAbilityLocked(connect);
15070 });
15071 if (err == ERR_OK) {
15072 return ERR_OK;
15073 }
15074
15075 TAG_LOGE(AAFwkTag::SERVICE_EXT, "Resume extension ability error %{public}d", err);
15076 return err;
15077 }
15078
SetAppServiceExtensionKeepAlive(const std::string & bundleName,bool flag)15079 int32_t AbilityManagerService::SetAppServiceExtensionKeepAlive(const std::string &bundleName, bool flag)
15080 {
15081 return KeepAliveProcessManager::GetInstance().SetAppServiceExtensionKeepAlive(
15082 bundleName, flag, false, false);
15083 }
15084
QueryKeepAliveAppServiceExtensions(std::vector<KeepAliveInfo> & list)15085 int32_t AbilityManagerService::QueryKeepAliveAppServiceExtensions(std::vector<KeepAliveInfo> &list)
15086 {
15087 return KeepAliveProcessManager::GetInstance().QueryKeepAliveAppServiceExtensions(list, false);
15088 }
15089
SetOnNewWantSkipScenarios(sptr<IRemoteObject> callerToken,int32_t scenarios)15090 int32_t AbilityManagerService::SetOnNewWantSkipScenarios(sptr<IRemoteObject> callerToken, int32_t scenarios)
15091 {
15092 auto record = Token::GetAbilityRecordByToken(callerToken);
15093 if (record == nullptr) {
15094 TAG_LOGE(AAFwkTag::ABILITYMGR, "The toke from context is invalid");
15095 return ERR_INVALID_CONTEXT;
15096 }
15097 if (!JudgeSelfCalled(record)) {
15098 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid callerToken");
15099 return ERR_INVALID_CALLER;
15100 }
15101 record->SetOnNewWantSkipScenarios(scenarios);
15102 return ERR_OK;
15103 }
15104
NotifyStartupExceptionBySCB(int32_t requestId)15105 int32_t AbilityManagerService::NotifyStartupExceptionBySCB(int32_t requestId)
15106 {
15107 if (!IsCallerSceneBoard()) {
15108 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
15109 return ERR_PERMISSION_DENIED;
15110 }
15111 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
15112 CHECK_POINTER_AND_RETURN_LOG(uiAbilityManager, ERR_NULL_OBJECT, "uiAbilityLifecycleManager nullptr");
15113 std::string reason = "SCB intercepted this startup attempt";
15114 return uiAbilityManager->NotifyStartupExceptionBySCB(requestId, reason);
15115 }
15116
PreloadApplication(const std::string & bundleName,int32_t userId,int32_t appIndex)15117 int32_t AbilityManagerService::PreloadApplication(const std::string &bundleName, int32_t userId, int32_t appIndex)
15118 {
15119 return PreloadManagerService::GetInstance().PreloadApplication(bundleName, userId, appIndex);
15120 }
15121 } // namespace AAFwk
15122 } // namespace OHOS
15123