1 /*
2 * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "ability_manager_service.h"
17
18 #include "ability_background_connection.h"
19 #include "ability_connect_manager.h"
20 #include "ability_manager_radar.h"
21 #include "ability_resident_process_rdb.h"
22 #include "accesstoken_kit.h"
23 #include "ability_manager_xcollie.h"
24 #include "app_exception_handler.h"
25 #include "app_utils.h"
26 #include "app_exit_reason_data_manager.h"
27 #include "application_util.h"
28 #include "app_mgr_util.h"
29 #include "recovery_info_timer.h"
30 #include "assert_fault_callback_death_mgr.h"
31 #include "concurrent_task_client.h"
32 #include "connection_state_manager.h"
33 #include "display_manager.h"
34 #include "distributed_client.h"
35 #ifdef WITH_DLP
36 #include "dlp_utils.h"
37 #endif // WITH_DLP
38 #include "freeze_util.h"
39 #include "global_constant.h"
40 #include "hitrace_meter.h"
41 #include "insight_intent_execute_manager.h"
42 #include "interceptor/ability_jump_interceptor.h"
43 #include "interceptor/block_all_app_start_interceptor.h"
44 #include "interceptor/control_interceptor.h"
45 #include "interceptor/crowd_test_interceptor.h"
46 #include "interceptor/disposed_rule_interceptor.h"
47 #include "interceptor/ecological_rule_interceptor.h"
48 #include "interceptor/extension_control_interceptor.h"
49 #include "interceptor/screen_unlock_interceptor.h"
50 #include "interceptor/start_other_app_interceptor.h"
51 #include "ipc_skeleton.h"
52 #include "iservice_registry.h"
53 #include "mock_session_manager_service.h"
54 #include "modal_system_dialog/modal_system_dialog_ui_extension.h"
55 #include "modal_system_ui_extension.h"
56 #include "multi_app_utils.h"
57 #include "os_account_manager_wrapper.h"
58 #include "permission_constants.h"
59 #include "process_options.h"
60 #include "recovery_param.h"
61 #include "res_sched_util.h"
62 #include "restart_app_manager.h"
63 #include "scene_board_judgement.h"
64 #include "server_constant.h"
65 #include "session_manager_lite.h"
66 #include "softbus_bus_center.h"
67 #include "start_ability_handler/start_ability_sandbox_savefile.h"
68 #include "start_ability_utils.h"
69 #include "startup_util.h"
70 #include "status_bar_delegate_interface.h"
71 #include "string_wrapper.h"
72 #include "ui_extension_utils.h"
73 #include "ui_service_extension_connection_constants.h"
74 #include "unlock_screen_manager.h"
75 #include "uri_permission_manager_client.h"
76 #include "uri_utils.h"
77 #include "view_data.h"
78 #include "xcollie/watchdog.h"
79 #include "config_policy_utils.h"
80 #include "uri_utils.h"
81 #include "utils/ability_permission_util.h"
82 #include "utils/dump_utils.h"
83 #include "utils/extension_permissions_util.h"
84 #include "utils/modal_system_dialog_util.h"
85 #include "utils/update_caller_info_util.h"
86 #include "utils/want_utils.h"
87 #include "utils/window_options_utils.h"
88 #ifdef SUPPORT_GRAPHICS
89 #include "dialog_session_manager.h"
90 #include "application_anr_listener.h"
91 #include "input_manager.h"
92 #include "ability_first_frame_state_observer_manager.h"
93 #include "session_manager_lite.h"
94 #include "window_focus_changed_listener.h"
95 #endif
96
97 using OHOS::AppExecFwk::ElementName;
98 using OHOS::Security::AccessToken::AccessTokenKit;
99
100 namespace OHOS {
101 using AbilityRuntime::FreezeUtil;
102 namespace AAFwk {
103 using AutoStartupInfo = AbilityRuntime::AutoStartupInfo;
104 using GetExtensionAbilityInfoFlag = AppExecFwk::GetExtensionAbilityInfoFlag;
105 namespace {
106 #define CHECK_CALLER_IS_SYSTEM_APP \
107 if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
108 TAG_LOGE(AAFwkTag::ABILITYMGR, \
109 "caller no system-app, can not use system-api"); \
110 return ERR_NOT_SYSTEM_APP; \
111 }
112
113 constexpr const char* ARGS_USER_ID = "-u";
114 constexpr const char* ARGS_CLIENT = "-c";
115 constexpr const char* ILLEGAL_INFOMATION = "The arguments are illegal and you can enter '-h' for help.";
116
117
118 constexpr int32_t NEW_RULE_VALUE_SIZE = 6;
119 constexpr int32_t APP_ALIVE_TIME_MS = 1000; // Allow background startup within 1 second after application startup
120 constexpr int32_t REGISTER_FOCUS_DELAY = 5000;
121 constexpr size_t OFFSET = 32;
122 constexpr const char* IS_DELEGATOR_CALL = "isDelegatorCall";
123
124 // Startup rule switch
125 constexpr const char* COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
126 constexpr const char* NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI = "component.startup.newRules.except.LauncherSystemUI";
127 constexpr const char* BACKGROUND_JUDGE_FLAG = "component.startup.backgroundJudge.flag";
128 constexpr const char* WHITE_LIST_ASS_WAKEUP_FLAG = "component.startup.whitelist.associatedWakeUp";
129
130 // White list app
131 constexpr const char* BUNDLE_NAME_SETTINGSDATA = "com.ohos.settingsdata";
132 // Support prepare terminate
133 constexpr int32_t PREPARE_TERMINATE_ENABLE_SIZE = 6;
134 constexpr const char* PREPARE_TERMINATE_ENABLE_PARAMETER = "persist.sys.prepare_terminate";
135 // UIExtension type
136 constexpr const char* UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType";
137 constexpr const char* UIEXTENSION_TARGET_TYPE_KEY = "ability.want.params.uiExtensionTargetType";
138 // Share picker params
139 constexpr char SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY[] = "const.system.sharePicker.bundleName";
140 constexpr char SHARE_PICKER_DIALOG_ABILITY_NAME_KEY[] = "const.system.sharePicker.abilityName";
141 constexpr char SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME[] = "com.ohos.sharepickerdialog";
142 constexpr char SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME[] = "PickerDialog";
143 constexpr char TOKEN_KEY[] = "ohos.ability.params.token";
144 // Developer mode param
145 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
146 constexpr char PRODUCT_APPBOOT_SETTING_ENABLED[] = "const.product.appboot.setting.enabled";
147 // Broker params key
148 constexpr const char* KEY_VISIBLE_ID = "ohos.anco.param.visible";
149 constexpr const char* START_ABILITY_TYPE = "ABILITY_INNER_START_WITH_ACCOUNT";
150 constexpr const char* BUNDLE_NAME_DIALOG = "com.ohos.amsdialog";
151 constexpr const char* STR_PHONE = "phone";
152 constexpr const char* PARAM_RESV_ANCO_CALLER_UID = "ohos.anco.param.callerUid";
153 constexpr const char* PARAM_RESV_ANCO_CALLER_BUNDLENAME = "ohos.anco.param.callerBundleName";
154 // Distributed continued session Id
155 constexpr const char* DMS_CONTINUED_SESSION_ID = "ohos.dms.continueSessionId";
156 constexpr const char* DMS_PERSISTENT_ID = "ohos.dms.persistentId";
157
158 constexpr const char* DEBUG_APP = "debugApp";
159 constexpr const char* NATIVE_DEBUG = "nativeDebug";
160 constexpr const char* AUTO_FILL_PASSWORD_TYPE = "autoFill/password";
161 constexpr const char* AUTO_FILL_SMART_TYPE = "autoFill/smart";
162 constexpr size_t INDEX_ZERO = 0;
163 constexpr size_t INDEX_ONE = 1;
164 constexpr size_t INDEX_TWO = 2;
165 constexpr size_t ARGC_THREE = 3;
166 constexpr static char WANT_PARAMS_VIEW_DATA_KEY[] = "ohos.ability.params.viewData";
167 constexpr const char* WANT_PARAMS_HOST_WINDOW_ID_KEY = "ohos.extra.param.key.hostwindowid";
168
169 constexpr int32_t FOUNDATION_UID = 5523;
170 constexpr const char* FRS_BUNDLE_NAME = "com.ohos.formrenderservice";
171 constexpr const char* FOUNDATION_PROCESS_NAME = "foundation";
172 constexpr const char* RSS_PROCESS_NAME = "resource_schedule_service";
173 constexpr const char* IS_PRELOAD_UIEXTENSION_ABILITY = "ability.want.params.is_preload_uiextension_ability";
174 constexpr const char* UIEXTENSION_MODAL_TYPE = "ability.want.params.modalType";
175 constexpr const char* SUPPORT_CLOSE_ON_BLUR = "supportCloseOnBlur";
176 constexpr const char* ATOMIC_SERVICE_PREFIX = "com.atomicservice.";
177 constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohosSpecifiedProcessFlag";
178
179 constexpr char ASSERT_FAULT_DETAIL[] = "assertFaultDialogDetail";
180 constexpr char PRODUCT_ASSERT_FAULT_DIALOG_ENABLED[] = "persisit.sys.abilityms.support_assert_fault_dialog";
181 constexpr const char* ABILITYMS_ENABLE_UISERVICE = "const.abilityms.enable_uiservice";
182
183 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
184
185 constexpr int32_t RESOURCE_SCHEDULE_UID = 1096;
186 constexpr int32_t UPDATE_CONFIG_FLAG_COVER = 1;
187 constexpr int32_t UPDATE_CONFIG_FLAG_APPEND = 2;
188
189 const std::unordered_set<std::string> COMMON_PICKER_TYPE = {
190 "share", "action"
191 };
192 std::atomic<bool> g_isDmsAlive = false;
193
SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo)194 void SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo)
195 {
196 auto taskHandler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
197 if (taskHandler == nullptr) {
198 TAG_LOGI(AAFwkTag::ABILITYMGR, "task handler null");
199 return;
200 }
201 taskHandler->SubmitTask([eventName, type, eventInfo]() {
202 EventReport::SendAbilityEvent(eventName, type, eventInfo);
203 });
204 }
205 } // namespace
206
207 using namespace std::chrono;
208 using namespace std::chrono_literals;
209 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
210 using namespace BackgroundTaskMgr;
211 #endif
212 const bool CONCURRENCY_MODE_FALSE = false;
213 constexpr int32_t MAIN_USER_ID = 100;
214 constexpr auto DATA_ABILITY_START_TIMEOUT = 5s;
215 constexpr int32_t NON_ANONYMIZE_LENGTH = 6;
216 constexpr uint32_t SCENE_FLAG_NORMAL = 0;
217 constexpr int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20;
218 constexpr int32_t SWITCH_ACCOUNT_TRY = 3;
219 constexpr const char* EMPTY_DEVICE_ID = "";
220 constexpr int32_t APP_MEMORY_SIZE = 512;
221 constexpr int32_t GET_PARAMETER_INCORRECT = -9;
222 constexpr int32_t GET_PARAMETER_OTHER = -1;
223 constexpr int32_t SIZE_10 = 10;
224 constexpr int32_t HIDUMPER_SERVICE_UID = 1212;
225 constexpr int32_t ACCOUNT_MGR_SERVICE_UID = 3058;
226 constexpr int32_t DMS_UID = 5522;
227 constexpr int32_t BOOTEVENT_COMPLETED_DELAY_TIME = 1000;
228 constexpr int32_t BOOTEVENT_BOOT_ANIMATION_READY_SIZE = 6;
229 constexpr const char* BUNDLE_NAME_KEY = "bundleName";
230 constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager";
231 constexpr const char* ACTION_CHOOSE = "ohos.want.action.select";
232 constexpr const char* HIGHEST_PRIORITY_ABILITY_ENTITY = "flag.home.intent.from.system";
233 constexpr const char* DMS_API_VERSION = "dmsApiVersion";
234 constexpr const char* DMS_IS_CALLER_BACKGROUND = "dmsIsCallerBackGround";
235 constexpr const char* DMS_PROCESS_NAME = "distributedsched";
236 constexpr const char* DMS_MISSION_ID = "dmsMissionId";
237 constexpr const char* BOOTEVENT_APPFWK_READY = "bootevent.appfwk.ready";
238 constexpr const char* BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed";
239 constexpr const char* BOOTEVENT_BOOT_ANIMATION_STARTED = "bootevent.bootanimation.started";
240 constexpr const char* BOOTEVENT_BOOT_ANIMATION_READY = "bootevent.bootanimation.ready";
241 constexpr const char* NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
242 constexpr const char* PERMISSIONMGR_BUNDLE_NAME = "com.ohos.permissionmanager";
243 constexpr const char* PERMISSIONMGR_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility";
244 constexpr const char* IS_CALL_BY_SCB = "isCallBySCB";
245 constexpr const char* SPECIFY_TOKEN_ID = "specifyTokenId";
246 constexpr const char* PROCESS_SUFFIX = "embeddable";
247 constexpr int32_t DEFAULT_DMS_MISSION_ID = -1;
248 constexpr const char* PARAM_PREVENT_STARTABILITY = "persist.sys.abilityms.prevent_startability";
249 constexpr const char* SUSPEND_SERVICE_CONFIG_FILE = "/etc/efficiency_manager/prevent_startability_whitelist.json";
250 constexpr int32_t MAX_BUFFER = 2048;
251 constexpr int32_t API12 = 12;
252 constexpr int32_t API_VERSION_MOD = 100;
253 constexpr const char* WHITE_LIST = "white_list";
254
255 const bool REGISTER_RESULT =
256 SystemAbility::MakeAndRegisterAbility(DelayedSingleton<AbilityManagerService>::GetInstance().get());
257 sptr<AbilityManagerService> AbilityManagerService::instance_;
258
AbilityManagerService()259 AbilityManagerService::AbilityManagerService()
260 : SystemAbility(ABILITY_MGR_SERVICE_ID, true),
261 state_(ServiceRunningState::STATE_NOT_START)
262 {}
263
~AbilityManagerService()264 AbilityManagerService::~AbilityManagerService()
265 {}
266
GetPubInstance()267 std::shared_ptr<AbilityManagerService> AbilityManagerService::GetPubInstance()
268 {
269 return DelayedSingleton<AbilityManagerService>::GetInstance();
270 }
271
OnStart()272 void AbilityManagerService::OnStart()
273 {
274 if (state_ == ServiceRunningState::STATE_RUNNING) {
275 TAG_LOGI(AAFwkTag::ABILITYMGR, "started");
276 return;
277 }
278 TAG_LOGI(AAFwkTag::ABILITYMGR, "starting");
279 if (!Init()) {
280 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed init");
281 return;
282 }
283 state_ = ServiceRunningState::STATE_RUNNING;
284 /* Publish service maybe failed, so we need call this function at the last,
285 * so it can't affect the TDD test program */
286 instance_ = DelayedSingleton<AbilityManagerService>::GetInstance().get();
287 if (instance_ == nullptr) {
288 TAG_LOGE(AAFwkTag::ABILITYMGR, "instance_ null");
289 return;
290 }
291 bool ret = Publish(instance_);
292 if (!ret) {
293 TAG_LOGE(AAFwkTag::ABILITYMGR, "publish failed");
294 return;
295 }
296
297 SetParameter(BOOTEVENT_APPFWK_READY, "true");
298 AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
299 AddSystemAbilityListener(DISTRIBUTED_SCHED_SA_ID);
300 AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
301 #ifdef SUPPORT_SCREEN
302 AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
303 #endif
304 TAG_LOGI(AAFwkTag::ABILITYMGR, "onStart success");
305 auto pid = getpid();
306 std::unordered_map<std::string, std::string> payload;
307 payload["pid"] = std::to_string(pid);
308 OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload);
309 }
310
Init()311 bool AbilityManagerService::Init()
312 {
313 HiviewDFX::Watchdog::GetInstance().InitFfrtWatchdog(); // For ffrt watchdog available in foundation
314 taskHandler_ = TaskHandlerWrap::CreateQueueHandler(AbilityConfig::NAME_ABILITY_MGR_SERVICE);
315 eventHandler_ = std::make_shared<AbilityEventHandler>(taskHandler_, weak_from_this());
316 freeInstallManager_ = std::make_shared<FreeInstallManager>(weak_from_this());
317 CHECK_POINTER_RETURN_BOOL(freeInstallManager_);
318
319 // init user controller.
320 userController_ = std::make_shared<UserController>();
321 userController_->Init();
322 AmsConfigurationParameter::GetInstance().Parse();
323 TAG_LOGI(AAFwkTag::ABILITYMGR, "config parse");
324 subManagersHelper_ = std::make_shared<SubManagersHelper>(taskHandler_, eventHandler_);
325 subManagersHelper_->InitSubManagers(MAIN_USER_ID, true);
326 SwitchManagers(U0_USER_ID, false);
327 #ifdef SUPPORT_SCREEN
328 implicitStartProcessor_ = std::make_shared<ImplicitStartProcessor>();
329 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
330 InitFocusListener();
331 }
332 AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().Init();
333 #endif
334
335 DelayedSingleton<ConnectionStateManager>::GetInstance()->Init(taskHandler_);
336
337 InitInterceptor();
338 InitStartAbilityChain();
339 InitDeepLinkReserve();
340
341 abilityAutoStartupService_ = std::make_shared<AbilityRuntime::AbilityAutoStartupService>();
342 InitPushTask();
343 AbilityCacheManager::GetInstance().Init(AppUtils::GetInstance().GetLimitMaximumExtensionsPerDevice(),
344 AppUtils::GetInstance().GetLimitMaximumExtensionsPerProc());
345
346 SubscribeScreenUnlockedEvent();
347 appExitReasonHelper_ = std::make_shared<AppExitReasonHelper>(subManagersHelper_);
348 TAG_LOGI(AAFwkTag::ABILITYMGR, "init success");
349 return true;
350 }
351
InitDeepLinkReserve()352 void AbilityManagerService::InitDeepLinkReserve()
353 {
354 if (!DeepLinkReserveConfig::GetInstance().LoadConfiguration()) {
355 TAG_LOGE(AAFwkTag::ABILITYMGR, "initDeepLinkReserve failed");
356 }
357 }
358
InitInterceptor()359 void AbilityManagerService::InitInterceptor()
360 {
361 interceptorExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
362 interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
363 interceptorExecuter_->AddInterceptor("CrowdTest", std::make_shared<CrowdTestInterceptor>());
364 interceptorExecuter_->AddInterceptor("Control", std::make_shared<ControlInterceptor>());
365 afterCheckExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
366 afterCheckExecuter_->AddInterceptor("ExtensionControl", std::make_shared<ExtensionControlInterceptor>());
367 afterCheckExecuter_->AddInterceptor("StartOtherApp", std::make_shared<StartOtherAppInterceptor>());
368 afterCheckExecuter_->AddInterceptor("DisposedRule", std::make_shared<DisposedRuleInterceptor>());
369 afterCheckExecuter_->AddInterceptor("EcologicalRule", std::make_shared<EcologicalRuleInterceptor>());
370 afterCheckExecuter_->SetTaskHandler(taskHandler_);
371 bool isAppJumpEnabled = OHOS::system::GetBoolParameter(
372 OHOS::AppExecFwk::PARAMETER_APP_JUMP_INTERCEPTOR_ENABLE, false);
373 if (isAppJumpEnabled) {
374 TAG_LOGI(AAFwkTag::ABILITYMGR, "app jump enabled, add abilityJumpInterceptor");
375 interceptorExecuter_->AddInterceptor("AbilityJump", std::make_shared<AbilityJumpInterceptor>());
376 }
377 if (AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
378 TAG_LOGI(AAFwkTag::ABILITYMGR, "add BlockAllAppStartInterceptor");
379 interceptorExecuter_->AddInterceptor("BlockAllAppStart", std::make_shared<BlockAllAppStartInterceptor>());
380 }
381 }
382
InitInterceptorForScreenUnlock()383 void AbilityManagerService::InitInterceptorForScreenUnlock()
384 {
385 if (interceptorExecuter_) {
386 interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
387 }
388 }
389
InitPushTask()390 void AbilityManagerService::InitPushTask()
391 {
392 if (taskHandler_ == nullptr) {
393 TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler_ null");
394 return;
395 }
396
397 auto initStartupFlagTask = [aams = shared_from_this()]() { aams->InitStartupFlag(); };
398 taskHandler_->SubmitTask(initStartupFlagTask, "InitStartupFlag");
399 #ifdef SUPPORT_SCREEN
400 auto initPrepareTerminateConfigTask = [aams = shared_from_this()]() { aams->InitPrepareTerminateConfig(); };
401 taskHandler_->SubmitTask(initPrepareTerminateConfigTask, "InitPrepareTerminateConfig");
402 #endif // SUPPORT_SCREEN
403
404 auto initExtensionConfigTask = []() {
405 DelayedSingleton<ExtensionConfig>::GetInstance()->LoadExtensionConfiguration();
406 };
407 taskHandler_->SubmitTask(initExtensionConfigTask, "InitExtensionConfigTask");
408
409 auto bootCompletedTask = [handler = taskHandler_]() {
410 if (ApplicationUtil::IsBootCompleted()) {
411 auto task = []() {
412 ApplicationUtil::AppFwkBootEventCallback(BOOTEVENT_BOOT_COMPLETED, "true", nullptr);
413 };
414 handler->SubmitTask(task, "BootCompletedDelayTask", BOOTEVENT_COMPLETED_DELAY_TIME);
415 } else {
416 WatchParameter(BOOTEVENT_BOOT_COMPLETED, ApplicationUtil::AppFwkBootEventCallback, nullptr);
417 TAG_LOGI(AAFwkTag::ABILITYMGR, "init call, InitPushTask suc");
418 }
419 };
420 if (!ParseJsonFromBoot(SUSPEND_SERVICE_CONFIG_FILE)) {
421 TAG_LOGE(AAFwkTag::ABILITYMGR, "parse json fail");
422 }
423 isParamStartAbilityEnable_ = system::GetBoolParameter(PARAM_PREVENT_STARTABILITY, false);
424 taskHandler_->SubmitTask(bootCompletedTask, "BootCompletedTask");
425 }
426
InitStartupFlag()427 void AbilityManagerService::InitStartupFlag()
428 {
429 startUpNewRule_ = CheckNewRuleSwitchState(COMPONENT_STARTUP_NEW_RULES);
430 newRuleExceptLauncherSystemUI_ = CheckNewRuleSwitchState(NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI);
431 backgroundJudgeFlag_ = CheckNewRuleSwitchState(BACKGROUND_JUDGE_FLAG);
432 whiteListassociatedWakeUpFlag_ = CheckNewRuleSwitchState(WHITE_LIST_ASS_WAKEUP_FLAG);
433 }
434
InitStartAbilityChain()435 void AbilityManagerService::InitStartAbilityChain()
436 {
437 auto startSandboxSaveFile = std::make_shared<StartAbilitySandboxSavefile>();
438 startAbilityChain_.emplace(startSandboxSaveFile->GetPriority(), startSandboxSaveFile);
439 }
440
OnStop()441 void AbilityManagerService::OnStop()
442 {
443 TAG_LOGI(AAFwkTag::ABILITYMGR, "stop");
444 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
445 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
446 if (bgtaskObserver_) {
447 int ret = BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver_);
448 if (ret != ERR_OK) {
449 TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bgtask failed, err:%{public}d", ret);
450 }
451 }
452 #endif
453 if (abilityBundleEventCallback_) {
454 auto bms = AbilityUtil::GetBundleManagerHelper();
455 if (bms) {
456 bool ret = IN_PROCESS_CALL(bms->UnregisterBundleEventCallback(abilityBundleEventCallback_));
457 if (ret != ERR_OK) {
458 TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bundle event failed, err:%{public}d", ret);
459 }
460 }
461 }
462 eventHandler_.reset();
463 taskHandler_.reset();
464 state_ = ServiceRunningState::STATE_NOT_START;
465 }
466
QueryServiceState() const467 ServiceRunningState AbilityManagerService::QueryServiceState() const
468 {
469 return state_;
470 }
471
StartAbility(const Want &want, int32_t userId, int requestCode)472 int AbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode)
473 {
474 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
475 bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
476 bool isNativeDebugApp = want.GetBoolParam(NATIVE_DEBUG, false);
477 bool hasWindowOptions = (want.HasParameter(Want::PARAM_RESV_WINDOW_LEFT) ||
478 want.HasParameter(Want::PARAM_RESV_WINDOW_TOP) ||
479 want.HasParameter(Want::PARAM_RESV_WINDOW_HEIGHT) ||
480 want.HasParameter(Want::PARAM_RESV_WINDOW_WIDTH));
481 TAG_LOGD(AAFwkTag::ABILITYMGR, "isDebugApp=%{public}d, hasWindowOptions=%{public}d, isNativeDebugApp=%{public}d",
482 static_cast<int>(isDebugApp), static_cast<int>(hasWindowOptions), static_cast<int>(isNativeDebugApp));
483 bool checkDeveloperModeFlag = (isDebugApp || hasWindowOptions || isNativeDebugApp);
484 if (checkDeveloperModeFlag) {
485 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
486 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
487 return ERR_NOT_DEVELOPER_MODE;
488 }
489 int32_t err = ERR_OK;
490 if (userId == DEFAULT_INVAL_VALUE) {
491 userId = GetValidUserId(userId);
492 }
493 if ((err = StartAbilityUtils::CheckAppProvisionMode(want, userId)) != ERR_OK) {
494 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkAppProvisionMode returns errcode=%{public}d", err);
495 return err;
496 }
497 }
498 if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
499 TAG_LOGE(AAFwkTag::ABILITYMGR, "need passord to unlock");
500 return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
501 }
502 TAG_LOGD(AAFwkTag::ABILITYMGR, "coldStart:%{public}d", want.GetBoolParam("coldStart", false));
503 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
504 if (startWithAccount || IsCrossUserCall(userId)) {
505 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
506 CHECK_CALLER_IS_SYSTEM_APP;
507 }
508 if (hasWindowOptions && !AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
509 TAG_LOGE(AAFwkTag::ABILITYMGR, "window options not supported");
510 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
511 }
512 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
513 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
514 EventInfo eventInfo = BuildEventInfo(want, userId);
515 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
516 auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId), 0);
517 if (checkFileShareRet != ERR_OK) {
518 return checkFileShareRet;
519 }
520 int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
521 AAFWK::ContinueRadar::GetInstance().ClickIconStartAbility("StartAbilityWrap", want.GetFlags(), ret);
522 if (ret != ERR_OK) {
523 eventInfo.errCode = ret;
524 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
525 }
526 return ret;
527 }
528
StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)529 int AbilityManagerService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
530 int32_t userId, int requestCode)
531 {
532 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
533 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
534 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
535 auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId), 0);
536 if (checkFileShareRet != ERR_OK) {
537 return checkFileShareRet;
538 }
539 return StartAbilityByFreeInstall(want, callerToken, userId, requestCode);
540 }
541
StartAbilityByFreeInstall(const Want &want, sptr<IRemoteObject> callerToken, int32_t userId, int32_t requestCode)542 int32_t AbilityManagerService::StartAbilityByFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
543 int32_t userId, int32_t requestCode)
544 {
545 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
546 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
547 if (startWithAccount || IsCrossUserCall(userId)) {
548 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
549 CHECK_CALLER_IS_SYSTEM_APP;
550 }
551 auto flags = want.GetFlags();
552 EventInfo eventInfo = BuildEventInfo(want, userId);
553 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
554 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
555 TAG_LOGE(AAFwkTag::ABILITYMGR, "not allow startAbility with continuation flags");
556 eventInfo.errCode = ERR_INVALID_VALUE;
557 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
558 return ERR_INVALID_CONTINUATION_FLAG;
559 }
560
561 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d",
562 want.GetElement().GetAbilityName().c_str(), userId);
563
564 int32_t ret = StartAbilityWrap(want, callerToken, requestCode, false, userId);
565 if (ret != ERR_OK) {
566 eventInfo.errCode = ret;
567 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
568 }
569 return ret;
570 }
571
StartAbilityWithSpecifyTokenId(const Want &want, const sptr<IRemoteObject> &callerToken, uint32_t specifyTokenId, int32_t userId, int requestCode)572 int AbilityManagerService::StartAbilityWithSpecifyTokenId(const Want &want, const sptr<IRemoteObject> &callerToken,
573 uint32_t specifyTokenId, int32_t userId, int requestCode)
574 {
575 if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
576 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with specialId, current process not foundation process");
577 return ERR_INVALID_CONTINUATION_FLAG;
578 }
579 return StartAbilityWithSpecifyTokenIdInner(want, callerToken, specifyTokenId, false, userId, requestCode);
580 }
581
StartAbilityWithSpecifyTokenIdInner(const Want &want, const sptr<IRemoteObject> &callerToken, uint32_t specifyTokenId, bool isPendingWantCaller, int32_t userId, int requestCode)582 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const sptr<IRemoteObject> &callerToken,
583 uint32_t specifyTokenId, bool isPendingWantCaller, int32_t userId, int requestCode)
584 {
585 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
586 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
587 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
588 auto flags = want.GetFlags();
589 EventInfo eventInfo = BuildEventInfo(want, userId);
590 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
591 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
592 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with continuation flags not allowed");
593 eventInfo.errCode = ERR_INVALID_VALUE;
594 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
595 return ERR_INVALID_CONTINUATION_FLAG;
596 }
597
598 TAG_LOGI(AAFwkTag::ABILITYMGR,
599 "start ability come, ability:%{public}s, userId:%{public}d, specifyTokenId:%{public}u",
600 want.GetElement().GetAbilityName().c_str(), userId, specifyTokenId);
601 auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId),
602 specifyTokenId);
603 if (checkFileShareRet != ERR_OK) {
604 return checkFileShareRet;
605 }
606 int32_t ret = StartAbilityWrap(want, callerToken, requestCode, isPendingWantCaller, userId, false, specifyTokenId);
607 if (ret != ERR_OK) {
608 eventInfo.errCode = ret;
609 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
610 }
611 return ret;
612 }
613
StartAbilityWithSpecifyTokenIdInner(const Want &want, const StartOptions &startOptions, const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode, uint32_t callerTokenId)614 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const StartOptions &startOptions,
615 const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller,
616 int32_t userId, int requestCode, uint32_t callerTokenId)
617 {
618 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions by trigger.");
619 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
620 auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId),
621 callerTokenId);
622 if (checkFileShareRet != ERR_OK) {
623 return checkFileShareRet;
624 }
625 return StartUIAbilityForOptionWrap(
626 want, startOptions, callerToken, isPendingWantCaller, userId, requestCode, callerTokenId);
627 }
628
StartAbilityByInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken, uint64_t intentId, int32_t userId)629 int32_t AbilityManagerService::StartAbilityByInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken,
630 uint64_t intentId, int32_t userId)
631 {
632 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
633 std::string bundleNameFromWant = want.GetElement().GetBundleName();
634 std::string bundleNameFromIntentMgr = "";
635 if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->
636 GetBundleName(intentId, bundleNameFromIntentMgr) != ERR_OK) {
637 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched intentId");
638 return ERR_INVALID_VALUE;
639 }
640 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
641 if (abilityRecord == nullptr) {
642 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched token");
643 return ERR_INVALID_VALUE;
644 }
645 std::string bundleNameFromAbilityRecord = abilityRecord->GetAbilityInfo().bundleName;
646 if (!bundleNameFromWant.empty() && bundleNameFromWant == bundleNameFromIntentMgr &&
647 bundleNameFromWant == bundleNameFromAbilityRecord) {
648 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
649 TAG_LOGI(AAFwkTag::ABILITYMGR, "bundleName match");
650 return StartAbility(want, callerToken, userId, -1);
651 }
652 TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleName not match");
653 return ERR_INSIGHT_INTENT_START_INVALID_COMPONENT;
654 }
655
StartAbilityByUIContentSession(const Want &want, const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)656 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const sptr<IRemoteObject> &callerToken,
657 const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
658 {
659 if (!callerToken || !sessionInfo) {
660 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo null");
661 return ERR_INVALID_VALUE;
662 }
663 sptr<IRemoteObject> token;
664 #ifdef SUPPORT_SCREEN
665 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
666 Rosen::FocusChangeInfo focusChangeInfo;
667 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
668 token = focusChangeInfo.abilityToken_;
669 } else {
670 if (!wmsHandler_) {
671 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
672 return ERR_INVALID_VALUE;
673 }
674 wmsHandler_->GetFocusWindow(token);
675 }
676 #endif // SUPPORT_SCREEN
677 if (!token) {
678 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
679 return ERR_INVALID_VALUE;
680 }
681
682 if (token != sessionInfo->callerToken) {
683 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken unequal to top ability token");
684 return NOT_TOP_ABILITY;
685 }
686 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
687 return StartAbility(want, callerToken, userId, requestCode);
688 }
689
StartAbilityByUIContentSession(const Want &want, const StartOptions &startOptions, const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)690 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const StartOptions &startOptions,
691 const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
692 {
693 if (!callerToken || !sessionInfo) {
694 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo null");
695 return ERR_INVALID_VALUE;
696 }
697 sptr<IRemoteObject> token;
698 #ifdef SUPPORT_SCREEN
699 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
700 Rosen::FocusChangeInfo focusChangeInfo;
701 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
702 token = focusChangeInfo.abilityToken_;
703 } else {
704 if (!wmsHandler_) {
705 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
706 return ERR_INVALID_VALUE;
707 }
708 wmsHandler_->GetFocusWindow(token);
709 }
710 #endif // SUPPORT_SCREEN
711
712 if (!token) {
713 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
714 return ERR_INVALID_VALUE;
715 }
716
717 if (token != sessionInfo->callerToken) {
718 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken unequal to top ability token");
719 return NOT_TOP_ABILITY;
720 }
721 return StartAbility(want, startOptions, callerToken, userId, requestCode);
722 }
723
StartAbilityOnlyUIAbility(const Want &want, const sptr<IRemoteObject> &callerToken, uint32_t specifyTokenId)724 int AbilityManagerService::StartAbilityOnlyUIAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
725 uint32_t specifyTokenId)
726 {
727 if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
728 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with specialId, process not foundation process");
729 return ERR_INVALID_CONTINUATION_FLAG;
730 }
731
732 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
733 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
734 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
735 auto flags = want.GetFlags();
736 EventInfo eventInfo = BuildEventInfo(want, DEFAULT_INVAL_VALUE);
737 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
738 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
739 TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility not allowed");
740 eventInfo.errCode = ERR_INVALID_VALUE;
741 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
742 return ERR_INVALID_CONTINUATION_FLAG;
743 }
744
745 TAG_LOGI(AAFwkTag::ABILITYMGR,
746 "start, ability: %{public}s, userId: %{public}d, specifyTokenId: %{public}u",
747 want.GetElement().GetAbilityName().c_str(), DEFAULT_INVAL_VALUE, specifyTokenId);
748
749 int32_t ret = StartAbilityWrap(want, callerToken, DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, specifyTokenId, false, false, true);
750 if (ret != ERR_OK) {
751 eventInfo.errCode = ret;
752 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
753 }
754 return ret;
755 }
756
StartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)757 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
758 sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
759 {
760 return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, requestCode);
761 }
762
ImplicitStartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)763 int AbilityManagerService::ImplicitStartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
764 sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
765 {
766 return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId,
767 requestCode, true);
768 }
769
StartAbilityAsCallerDetails(const Want &want, const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode, bool isImplicit)770 int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const sptr<IRemoteObject> &callerToken,
771 sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode, bool isImplicit)
772 {
773 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
774 CHECK_CALLER_IS_SYSTEM_APP;
775 auto flags = want.GetFlags();
776 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
777 EventInfo eventInfo = BuildEventInfo(want, userId);
778 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
779 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
780 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility with continuation flags not allowed");
781 eventInfo.errCode = ERR_INVALID_VALUE;
782 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
783 return ERR_INVALID_CONTINUATION_FLAG;
784 }
785
786 AAFwk::Want newWant = want;
787 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
788 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability come, ability:%{public}s, userId:%{public}d",
789 want.GetElement().GetAbilityName().c_str(), userId);
790 std::string callerPkg;
791 std::string targetPkg;
792 if (AbilityUtil::CheckJumpInterceptorWant(newWant, callerPkg, targetPkg)) {
793 TAG_LOGI(AAFwkTag::ABILITYMGR,
794 "call from interceptor dialog, callerPkg:%{public}s, targetPkg:%{public}s",
795 callerPkg.c_str(), targetPkg.c_str());
796 AbilityUtil::AddAbilityJumpRuleToBms(callerPkg, targetPkg, GetUserId());
797 }
798 int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true,
799 0, false, isImplicit);
800 if (ret != ERR_OK) {
801 eventInfo.errCode = ret;
802 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
803 }
804 return ret;
805 }
806
StartAbilityPublicPrechainCheck(StartAbilityParams ¶ms)807 int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams ¶ms)
808 {
809 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
810 // 1. CheckCallerToken
811 if (params.callerToken != nullptr && !VerificationAllToken(params.callerToken)) {
812 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
813 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
814 if (!isSpecificSA) {
815 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
816 return ERR_INVALID_CALLER;
817 }
818 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: caller specific system ability", __func__);
819 }
820
821 // 2. validUserId, multi-user
822 if (!JudgeMultiUserConcurrency(params.GetValidUserId())) {
823 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
824 return ERR_CROSS_USER;
825 }
826
827 return ERR_OK;
828 }
829
StartAbilityPrechainInterceptor(StartAbilityParams ¶ms)830 int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams ¶ms)
831 {
832 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
833 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
834 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(params.want, params.requestCode,
835 GetUserId(), true, nullptr, shouldBlockFunc);
836 auto interceptorResult = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
837 interceptorExecuter_->DoProcess(interceptorParam);
838 if (interceptorResult != ERR_OK) {
839 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
840 return interceptorResult;
841 }
842
843 return ERR_OK;
844 }
845
StartAbilityInChain(StartAbilityParams ¶ms, int &result)846 bool AbilityManagerService::StartAbilityInChain(StartAbilityParams ¶ms, int &result)
847 {
848 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
849 std::shared_ptr<StartAbilityHandler> reqHandler;
850 for (const auto &item : startAbilityChain_) {
851 if (item.second->MatchStartRequest(params)) {
852 reqHandler = item.second;
853 break;
854 }
855 }
856
857 if (!reqHandler) {
858 return false;
859 }
860
861 result = StartAbilityPublicPrechainCheck(params);
862 if (result != ERR_OK) {
863 return true;
864 }
865 result = StartAbilityPrechainInterceptor(params);
866 if (result != ERR_OK) {
867 return true;
868 }
869 result = reqHandler->HandleStartRequest(params);
870 return true;
871 }
872
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)873 int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr<IRemoteObject> &callerToken,
874 int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyToken,
875 bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
876 {
877 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
878 StartAbilityParams startParams(const_cast<Want &>(want));
879 startParams.callerToken = callerToken;
880 startParams.userId = userId;
881 startParams.requestCode = requestCode;
882 startParams.isStartAsCaller = isStartAsCaller;
883 startParams.SetValidUserId(GetValidUserId(userId));
884
885 int result = ERR_OK;
886 if (StartAbilityInChain(startParams, result)) {
887 return result;
888 }
889
890 OHOS::AAFwk::Want newWant = want;
891 WindowOptionsUtils::UpdateWantToSetDisplayID(newWant, callerToken);
892 return StartAbilityInner(newWant, callerToken,
893 requestCode, isPendingWantCaller, userId, isStartAsCaller, specifyToken, isForegroundToRestartApp, isImplicit,
894 isUIAbilityOnly);
895 }
896
SetReserveInfo(const std::string &linkString, AbilityRequest& abilityRequest)897 void AbilityManagerService::SetReserveInfo(const std::string &linkString, AbilityRequest& abilityRequest)
898 {
899 if (!linkString.size()) {
900 return;
901 }
902
903 #ifdef SUPPORT_SCREEN
904 abilityRequest.uriReservedFlag =
905 DeepLinkReserveConfig::GetInstance().isLinkReserved(linkString, abilityRequest.reservedBundleName);
906 #endif // SUPPORT_SCREEN
907 }
908
CheckExtensionCallPermission(const Want& want, const AbilityRequest& abilityRequest, uint32_t specifyTokenId)909 int AbilityManagerService::CheckExtensionCallPermission(const Want& want, const AbilityRequest& abilityRequest,
910 uint32_t specifyTokenId)
911 {
912 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "startExtensionCheck");
913 auto isSACall = AAFwk::PermissionVerification::GetInstance()->IsSACallByTokenId(specifyTokenId);
914 auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCallByTokenId(specifyTokenId);
915 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCallByTokenId(specifyTokenId);
916 auto isToPermissionMgr = IsTargetPermission(want);
917 if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) {
918 TAG_LOGE(AAFwkTag::ABILITYMGR,
919 "cannot start, use startServiceExtensionAbility");
920 return ERR_WRONG_INTERFACE_CALL;
921 }
922 int result = CheckCallServicePermission(abilityRequest);
923 if (result != ERR_OK) {
924 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
925 }
926 return result;
927 }
928
CheckServiceCallPermission(const AbilityRequest& abilityRequest, const AppExecFwk::AbilityInfo& abilityInfo)929 int AbilityManagerService::CheckServiceCallPermission(const AbilityRequest& abilityRequest,
930 const AppExecFwk::AbilityInfo& abilityInfo)
931 {
932 TAG_LOGD(AAFwkTag::ABILITYMGR,
933 "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
934 int result = CheckCallServicePermission(abilityRequest);
935 if (result != ERR_OK) {
936 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
937 }
938 return result;
939 }
940
CheckBrokerCallPermission(const AbilityRequest& abilityRequest, const AppExecFwk::AbilityInfo& abilityInfo)941 int AbilityManagerService::CheckBrokerCallPermission(const AbilityRequest& abilityRequest,
942 const AppExecFwk::AbilityInfo& abilityInfo)
943 {
944 // temp add for broker, remove when delete issacall
945 if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) {
946 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check permission failed");
947 return CHECK_PERMISSION_FAILED;
948 }
949 TAG_LOGD(AAFwkTag::ABILITYMGR,
950 "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
951 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
952 if (collaborator == nullptr) {
953 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator null");
954 return CHECK_PERMISSION_FAILED;
955 }
956 int result = collaborator->CheckCallAbilityPermission(abilityRequest.want);
957 if (result != ERR_OK) {
958 TAG_LOGE(AAFwkTag::ABILITYMGR, "check broker permission failed");
959 return CHECK_PERMISSION_FAILED;
960 }
961 return result;
962 }
963
CheckAbilityCallPermission(const AbilityRequest& abilityRequest, const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId)964 int AbilityManagerService::CheckAbilityCallPermission(const AbilityRequest& abilityRequest,
965 const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId)
966 {
967 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
968 int result = CheckCallAbilityPermission(abilityRequest, specifyTokenId);
969 if (result != ERR_OK) {
970 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
971 }
972 return result;
973 }
974
CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo, const AbilityRequest& abilityRequest, bool isForegroundToRestartApp, bool isSendDialogResult, uint32_t specifyTokenId, const std::string& callerBundleName)975 int AbilityManagerService::CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
976 const AbilityRequest& abilityRequest, bool isForegroundToRestartApp,
977 bool isSendDialogResult, uint32_t specifyTokenId,
978 const std::string& callerBundleName)
979 {
980 auto type = abilityInfo.type;
981 if (type == AppExecFwk::AbilityType::DATA) {
982 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot start data ability by start ability");
983 return ERR_WRONG_INTERFACE_CALL;
984 }
985 if (type == AppExecFwk::AbilityType::EXTENSION) {
986 return CheckExtensionCallPermission(want, abilityRequest, specifyTokenId);
987 }
988 if (type == AppExecFwk::AbilityType::SERVICE) {
989 return CheckServiceCallPermission(abilityRequest, abilityInfo);
990 }
991 if ((callerBundleName == AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
992 AppUtils::GetInstance().IsSupportAncoApp()) ||
993 IPCSkeleton::GetCallingUid() == AppUtils::GetInstance().GetCollaboratorBrokerUID()) {
994 return CheckBrokerCallPermission(abilityRequest, abilityInfo);
995 }
996 if (!isForegroundToRestartApp && (!isSendDialogResult || want.GetBoolParam("isSelector", false))) {
997 return CheckAbilityCallPermission(abilityRequest, abilityInfo, specifyTokenId);
998 }
999 return ERR_OK;
1000 }
1001
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)1002 int AbilityManagerService::StartAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
1003 int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyTokenId,
1004 bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
1005 {
1006 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1007 std::string dialogSessionId = want.GetStringParam("dialogSessionId");
1008 bool isSendDialogResult = false;
1009 #ifdef SUPPORT_SCREEN
1010 if (!dialogSessionId.empty() &&
1011 DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId) != nullptr) {
1012 isSendDialogResult = true;
1013 }
1014 #endif // SUPPORT_SCREEN
1015
1016 // prevent the app from dominating the screen
1017 if (callerToken == nullptr && !IsCallerSceneBoard() && !isSendDialogResult && !isForegroundToRestartApp &&
1018 AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1019 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
1020 return ERR_INVALID_CALLER;
1021 }
1022 if (callerToken != nullptr) {
1023 bool isAppKilling = IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->IsAppKilling(callerToken));
1024 if (isAppKilling) {
1025 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller killing");
1026 return ERR_INVALID_CALLER;
1027 }
1028 }
1029 {
1030 #ifdef WITH_DLP
1031 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1032 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1033 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1034 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1035 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
1036 return CHECK_PERMISSION_FAILED;
1037 }
1038
1039 if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1040 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1041 return StartExtensionAbilityInner(want, callerToken, userId,
1042 AppExecFwk::ExtensionAbilityType::SERVICE, false, false, true, isStartAsCaller);
1043 }
1044 #endif // WITH_DLP
1045 }
1046
1047 AbilityUtil::RemoveWindowModeKey(const_cast<Want &>(want));
1048 if (callerToken != nullptr && !VerificationAllToken(callerToken) && !isSendDialogResult) {
1049 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
1050 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
1051 if (!isSpecificSA) {
1052 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
1053 return ERR_INVALID_CALLER;
1054 }
1055 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:caller specific system ability", __func__);
1056 }
1057
1058 int32_t oriValidUserId = GetValidUserId(userId);
1059 int32_t validUserId = oriValidUserId;
1060 SetTargetCloneIndexInSameBundle(want, callerToken);
1061 int32_t appIndex = 0;
1062 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1063 return ERR_APP_CLONE_INDEX_INVALID;
1064 }
1065 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1066 validUserId, appIndex, callerToken);
1067 if (checkRet != ERR_OK) {
1068 return checkRet;
1069 }
1070 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1071 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1072 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1073 true, nullptr, shouldBlockFunc);
1074 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1075 interceptorExecuter_->DoProcess(interceptorParam);
1076 if (result != ERR_OK) {
1077 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
1078 return result;
1079 }
1080
1081 if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1082 IPCSkeleton::GetCallingUid() != DMS_UID) {
1083 TAG_LOGE(AAFwkTag::ABILITYMGR, "flag only support DMS, flag:%{public}d", want.GetFlags());
1084 return ERR_INVALID_CONTINUATION_FLAG;
1085 }
1086
1087 if (callerToken != nullptr && CheckIfOperateRemote(want)) {
1088 TAG_LOGI(AAFwkTag::ABILITYMGR, "try to StartRemoteAbility");
1089 return StartRemoteAbility(want, requestCode, validUserId, callerToken);
1090 }
1091
1092 if (!JudgeMultiUserConcurrency(validUserId)) {
1093 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
1094 return ERR_CROSS_USER;
1095 }
1096
1097 AbilityRequest abilityRequest;
1098 #ifdef SUPPORT_SCREEN
1099 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1100 auto checkResult = AbilityUtil::CheckInstanceKey(want);
1101 if (checkResult != ERR_OK) {
1102 return checkResult;
1103 }
1104 abilityRequest.Voluation(want, requestCode, callerToken);
1105 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1106 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1107 } else if (!isStartAsCaller) {
1108 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1109 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1110 } else {
1111 TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1112 }
1113 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1114 SetReserveInfo(want.GetUriString(), abilityRequest);
1115 return implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1116 }
1117 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1118 return ShowPickerDialog(want, validUserId, callerToken);
1119 }
1120 #endif
1121 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1122 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1123 std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
1124 bool selfFreeInstallEnable = (result == RESOLVE_ABILITY_ERR && want.GetElement().GetModuleName() != "" &&
1125 want.GetElement().GetBundleName() == callerBundleName);
1126 bool isStartFreeInstallByWant = AbilityUtil::IsStartFreeInstall(want);
1127 if (isStartFreeInstallByWant || selfFreeInstallEnable) {
1128 Want localWant;
1129 auto freeInstallResult = PreStartFreeInstall(want, callerToken, specifyTokenId, isStartAsCaller, localWant);
1130 if (freeInstallResult != ERR_OK) {
1131 TAG_LOGE(AAFwkTag::ABILITYMGR, "preStartFreeInstall failed");
1132 return freeInstallResult;
1133 }
1134
1135 if (isStartFreeInstallByWant) {
1136 return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode,
1137 callerToken, true, specifyTokenId);
1138 }
1139 int32_t ret = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, false);
1140 if (ret == ERR_OK) {
1141 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1142 }
1143 }
1144
1145 if (result != ERR_OK) {
1146 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
1147 return result;
1148 }
1149
1150 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1151 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1152 } else if (!isStartAsCaller) {
1153 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1154 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1155 } else if (callerBundleName == BUNDLE_NAME_DIALOG ||
1156 (isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1157 #ifdef SUPPORT_SCREEN
1158 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1159 int32_t flag = false;
1160 if (callerBundleName == BUNDLE_NAME_DIALOG) {
1161 flag = true;
1162 }
1163 implicitStartProcessor_->ResetCallingIdentityAsCaller(
1164 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), flag);
1165 #endif // SUPPORT_SCREEN
1166 }
1167
1168 auto abilityInfo = abilityRequest.abilityInfo;
1169 if (isUIAbilityOnly && abilityInfo.type != AbilityType::PAGE) {
1170 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability type no UIAbility");
1171 return ERR_INVALID_VALUE;
1172 }
1173 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1174 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
1175 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1176
1177 if ((isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1178 isImplicit = true;
1179 }
1180 result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1181 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1182 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1183 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
1184 return ERR_STATIC_CFG_PERMISSION;
1185 }
1186
1187 result = CheckCallPermission(want, abilityInfo, abilityRequest, isForegroundToRestartApp,
1188 isSendDialogResult, specifyTokenId, callerBundleName);
1189 if (result != ERR_OK) {
1190 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkCallPermission error, result:%{public}d", result);
1191 return result;
1192 }
1193
1194 Want newWant = abilityRequest.want;
1195 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1196 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1197 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1198 afterCheckExecuter_->DoProcess(afterCheckParam);
1199 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1200 newWant.RemoveParam("queryWantFromErms");
1201 if (result != ERR_OK && isReplaceWantExist == false) {
1202 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
1203 return result;
1204 }
1205 #ifdef SUPPORT_SCREEN
1206 if (result != ERR_OK && isReplaceWantExist && !isSendDialogResult &&
1207 callerBundleName != BUNDLE_NAME_DIALOG) {
1208 return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1209 }
1210 if (result == ERR_OK &&
1211 DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1212 TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1213 return CreateCloneSelectorDialog(abilityRequest, GetUserId());
1214 }
1215 #endif // SUPPORT_SCREEN
1216
1217 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1218 TAG_LOGD(AAFwkTag::ABILITYMGR, "PreLoadAppDataAbilities:%{public}s.", abilityInfo.bundleName.c_str());
1219 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1220 if (result != ERR_OK) {
1221 TAG_LOGE(AAFwkTag::ABILITYMGR,
1222 "startAbility:app data ability preloading failed, '%{public}s', %{public}d",
1223 abilityInfo.bundleName.c_str(), result);
1224 return result;
1225 }
1226 }
1227
1228 if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
1229 abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
1230 SendStartAbilityOtherExtensionEvent(abilityInfo, abilityRequest.want, specifyTokenId);
1231 return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
1232 }
1233
1234 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1235 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", abilityInfo.bundleName.c_str());
1236 return ERR_WOULD_BLOCK;
1237 }
1238
1239 auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1240 UpdateCallerInfoUtil::GetInstance().UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1241 StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1242
1243 abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1244 if (specifyTokenId > 0) {
1245 TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
1246 abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1247 abilityRequest.specifyTokenId = specifyTokenId;
1248 }
1249 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1250 // sceneboard
1251 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1252 ReportEventToRSS(abilityInfo, abilityRequest.callerToken);
1253 abilityRequest.userId = oriValidUserId;
1254 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1255 // other sa or shell can not use continueSessionId and persistentId
1256 auto abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
1257 if (abilityRecord == nullptr &&
1258 !PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
1259 TAG_LOGW(AAFwkTag::ABILITYMGR, "startAbilityInner, remove continueSessionId and persistentId");
1260 abilityRequest.want.RemoveParam(DMS_CONTINUED_SESSION_ID);
1261 abilityRequest.want.RemoveParam(DMS_PERSISTENT_ID);
1262 }
1263 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1264 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1265 return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1266 }
1267
1268 auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1269 if (missionListManager == nullptr) {
1270 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", validUserId);
1271 return ERR_INVALID_VALUE;
1272 }
1273
1274 ReportAbilityStartInfoToRSS(abilityInfo);
1275 ReportEventToRSS(abilityInfo, callerToken);
1276 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability, name is %{public}s.", abilityInfo.name.c_str());
1277 return missionListManager->StartAbility(abilityRequest);
1278 }
1279
PreStartFreeInstall(const Want &want, sptr<IRemoteObject> callerToken, uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant)1280 int AbilityManagerService::PreStartFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
1281 uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant)
1282 {
1283 if (freeInstallManager_ == nullptr) {
1284 return ERR_INVALID_VALUE;
1285 }
1286 (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1287 localWant = want;
1288 if (!localWant.GetDeviceId().empty()) {
1289 localWant.SetDeviceId("");
1290 }
1291 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1292 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(localWant, callerToken);
1293 } else if (!isStartAsCaller) {
1294 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1295 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1296 } else {
1297 TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1298 }
1299 return ERR_OK;
1300 }
1301
StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest, const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr<IRemoteObject> callerToken)1302 int AbilityManagerService::StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest,
1303 const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr<IRemoteObject> callerToken)
1304 {
1305 auto connectManager = GetConnectManagerByUserId(validUserId);
1306 if (!connectManager) {
1307 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
1308 return ERR_INVALID_VALUE;
1309 }
1310 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start service or extension, name is %{public}s.", abilityInfo.name.c_str());
1311 ReportEventToRSS(abilityInfo, callerToken);
1312 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1313 UriUtils::GetInstance().CheckUriPermissionForServiceExtension(const_cast<Want &>(abilityRequest.want),
1314 abilityRequest.abilityInfo.extensionAbilityType);
1315 return connectManager->StartAbility(abilityRequest);
1316 }
1317
StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)1318 int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1319 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1320 {
1321 OHOS::AAFwk::Want newWant = want;
1322 WindowOptionsUtils::UpdateWantToSetDisplayID(newWant, callerToken);
1323 auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(newWant, GetValidUserId(userId), 0);
1324 if (checkFileShareRet != ERR_OK) {
1325 return checkFileShareRet;
1326 }
1327 return StartAbilityDetails(newWant, abilityStartSetting, callerToken, userId, requestCode);
1328 }
1329
ImplicitStartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting, const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)1330 int AbilityManagerService::ImplicitStartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1331 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1332 {
1333 return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode, true);
1334 }
1335
StartAbilityDetails(const Want &want, const AbilityStartSetting &abilityStartSetting, const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isImplicit)1336 int AbilityManagerService::StartAbilityDetails(const Want &want, const AbilityStartSetting &abilityStartSetting,
1337 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isImplicit)
1338 {
1339 if (want.GetBoolParam(DEBUG_APP, false)) {
1340 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
1341 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
1342 return ERR_NOT_DEVELOPER_MODE;
1343 }
1344 int32_t err = ERR_OK;
1345 if (userId == DEFAULT_INVAL_VALUE) {
1346 userId = GetValidUserId(userId);
1347 }
1348 if ((err = StartAbilityUtils::CheckAppProvisionMode(want, userId)) != ERR_OK) {
1349 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkAppProvisionMode returns errcode=%{public}d", err);
1350 return err;
1351 }
1352 }
1353 if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
1354 TAG_LOGE(AAFwkTag::ABILITYMGR, "screen need passord unlock");
1355 return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
1356 }
1357 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1358 StartAbilityParams startParams(const_cast<Want &>(want));
1359 startParams.callerToken = callerToken;
1360 startParams.userId = userId;
1361 startParams.requestCode = requestCode;
1362 startParams.SetValidUserId(GetValidUserId(userId));
1363
1364 int result = ERR_OK;
1365 if (StartAbilityInChain(startParams, result)) {
1366 return result;
1367 }
1368
1369 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1370 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability setting.");
1371 if (IsCrossUserCall(userId)) {
1372 CHECK_CALLER_IS_SYSTEM_APP;
1373 }
1374 EventInfo eventInfo = BuildEventInfo(want, userId);
1375 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1376
1377 #ifdef WITH_DLP
1378 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1379 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1380 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1381 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
1382 eventInfo.errCode = CHECK_PERMISSION_FAILED;
1383 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1384 return CHECK_PERMISSION_FAILED;
1385 }
1386 #endif // WITH_DLP
1387
1388 if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1389 IPCSkeleton::GetCallingUid() != DMS_UID) {
1390 TAG_LOGE(AAFwkTag::ABILITYMGR, "The flag only support for DMS, flag is %{public}d", want.GetFlags());
1391 eventInfo.errCode = ERR_INVALID_VALUE;
1392 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1393 return ERR_INVALID_CONTINUATION_FLAG;
1394 }
1395
1396 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1397 eventInfo.errCode = ERR_INVALID_VALUE;
1398 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1399 return ERR_INVALID_CALLER;
1400 }
1401
1402 int32_t oriValidUserId = GetValidUserId(userId);
1403 int32_t validUserId = oriValidUserId;
1404 int32_t appIndex = 0;
1405 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1406 return ERR_APP_CLONE_INDEX_INVALID;
1407 }
1408 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1409 validUserId, appIndex, callerToken);
1410 if (checkRet != ERR_OK) {
1411 return checkRet;
1412 }
1413 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1414 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1415 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1416 true, nullptr, shouldBlockFunc);
1417 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1418 interceptorExecuter_->DoProcess(interceptorParam);
1419 if (result != ERR_OK) {
1420 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
1421 eventInfo.errCode = result;
1422 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1423 return result;
1424 }
1425
1426 if (AbilityUtil::IsStartFreeInstall(want)) {
1427 if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1428 TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1429 return ERR_INVALID_VALUE;
1430 }
1431 (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1432 Want localWant = want;
1433 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1434 return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true);
1435 }
1436
1437 if (!JudgeMultiUserConcurrency(validUserId)) {
1438 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
1439 eventInfo.errCode = ERR_INVALID_VALUE;
1440 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1441 return ERR_CROSS_USER;
1442 }
1443
1444 AbilityRequest abilityRequest;
1445 #ifdef SUPPORT_SCREEN
1446 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1447 auto checkResult = AbilityUtil::CheckInstanceKey(want);
1448 if (checkResult != ERR_OK) {
1449 return checkResult;
1450 }
1451 abilityRequest.Voluation(
1452 want, requestCode, callerToken, std::make_shared<AbilityStartSetting>(abilityStartSetting));
1453 abilityRequest.callType = AbilityCallType::START_SETTINGS_TYPE;
1454 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1455 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1456 if (result != ERR_OK) {
1457 TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error");
1458 eventInfo.errCode = result;
1459 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1460 }
1461 return result;
1462 }
1463 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1464 return ShowPickerDialog(want, validUserId, callerToken);
1465 }
1466 #endif
1467 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1468 if (result != ERR_OK) {
1469 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
1470 eventInfo.errCode = result;
1471 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1472 return result;
1473 }
1474 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1475
1476 auto abilityInfo = abilityRequest.abilityInfo;
1477 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1478 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1479 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1480
1481 result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
1482 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1483 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
1484 eventInfo.errCode = result;
1485 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1486 return ERR_STATIC_CFG_PERMISSION;
1487 }
1488 result = CheckCallAbilityPermission(abilityRequest);
1489 if (result != ERR_OK) {
1490 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s checkCallAbilityPermission error", __func__);
1491 eventInfo.errCode = result;
1492 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1493 return result;
1494 }
1495
1496 abilityRequest.startSetting = std::make_shared<AbilityStartSetting>(abilityStartSetting);
1497
1498 if (abilityInfo.type == AppExecFwk::AbilityType::DATA) {
1499 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot start data ability, use 'AcquireDataAbility()'");
1500 eventInfo.errCode = ERR_INVALID_VALUE;
1501 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1502 return ERR_WRONG_INTERFACE_CALL;
1503 }
1504
1505 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
1506 GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
1507 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1508 afterCheckExecuter_->DoProcess(afterCheckParam);
1509 if (result != ERR_OK) {
1510 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
1511 return result;
1512 }
1513
1514 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1515 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1516 if (result != ERR_OK) {
1517 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility: app data ability preloading failed, '%{public}s', %{public}d",
1518 abilityInfo.bundleName.c_str(),
1519 result);
1520 eventInfo.errCode = result;
1521 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1522 return result;
1523 }
1524 }
1525 #ifdef SUPPORT_GRAPHICS
1526 if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1527 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability");
1528 eventInfo.errCode = ERR_INVALID_VALUE;
1529 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1530 return ERR_WRONG_INTERFACE_CALL;
1531 }
1532 #endif
1533 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1534 eventInfo.errCode = ERR_WOULD_BLOCK;
1535 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1536 return ERR_WOULD_BLOCK;
1537 }
1538 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1539 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1540 abilityRequest.userId = oriValidUserId;
1541 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1542 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1543 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1544 return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1545 }
1546 auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1547 if (missionListManager == nullptr) {
1548 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", validUserId);
1549 eventInfo.errCode = ERR_INVALID_VALUE;
1550 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1551 return ERR_INVALID_VALUE;
1552 }
1553 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1554 auto ret = missionListManager->StartAbility(abilityRequest);
1555 if (ret != ERR_OK) {
1556 eventInfo.errCode = ret;
1557 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1558 }
1559 return ret;
1560 }
1561
StartAbility(const Want &want, const StartOptions &startOptions, const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)1562 int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions,
1563 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1564 {
1565 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1566 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions.");
1567 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1568 auto checkFileShareRet = UriUtils::GetInstance().CheckNonImplicitShareFileUri(want, GetValidUserId(userId), 0);
1569 if (checkFileShareRet != ERR_OK) {
1570 return checkFileShareRet;
1571 }
1572 return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode);
1573 }
1574
ImplicitStartAbility(const Want &want, const StartOptions &startOptions, const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)1575 int AbilityManagerService::ImplicitStartAbility(const Want &want, const StartOptions &startOptions,
1576 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1577 {
1578 TAG_LOGD(AAFwkTag::ABILITYMGR, "Implicit Start ability with startOptions.");
1579 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1580 return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode, 0, true);
1581 }
1582
StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options, sptr<IRemoteObject> callerToken, bool isPendingWantCaller, int32_t userId, int requestCode, uint32_t callerTokenId, bool isImplicit, bool isCallByShortcut)1583 int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options,
1584 sptr<IRemoteObject> callerToken, bool isPendingWantCaller, int32_t userId,
1585 int requestCode, uint32_t callerTokenId, bool isImplicit,
1586 bool isCallByShortcut)
1587 {
1588 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1589 auto ret = CheckProcessOptions(want, options, userId);
1590 if (ret != ERR_OK) {
1591 return ret;
1592 }
1593 return StartAbilityForOptionWrap(want, options, callerToken, isPendingWantCaller, userId, requestCode, false,
1594 callerTokenId, isImplicit, isCallByShortcut);
1595 }
1596
StartAbilityAsCaller(const Want &want, const StartOptions &startOptions, const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)1597 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOptions &startOptions,
1598 const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken,
1599 int32_t userId, int requestCode)
1600 {
1601 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability as caller with startOptions.");
1602 CHECK_CALLER_IS_SYSTEM_APP;
1603
1604 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1605 AAFwk::Want newWant = want;
1606 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1607 return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1608 }
1609
StartAbilityForResultAsCaller( const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)1610 int AbilityManagerService::StartAbilityForResultAsCaller(
1611 const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1612 {
1613 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1614 CHECK_CALLER_IS_SYSTEM_APP;
1615
1616 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1617 AAFwk::Want newWant = want;
1618 auto connectManager = GetCurrentConnectManager();
1619 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1620 auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1621 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1622 return StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true);
1623 }
1624
StartAbilityForResultAsCaller(const Want &want, const StartOptions &startOptions, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)1625 int AbilityManagerService::StartAbilityForResultAsCaller(const Want &want, const StartOptions &startOptions,
1626 const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1627 {
1628 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1629 CHECK_CALLER_IS_SYSTEM_APP;
1630
1631 AAFwk::Want newWant = want;
1632 auto connectManager = GetCurrentConnectManager();
1633 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1634 auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1635 UpdateCallerInfoUtil::GetInstance().UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1636 return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1637 }
1638
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)1639 int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const StartOptions &startOptions,
1640 const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1641 bool isStartAsCaller, uint32_t callerTokenId, bool isImplicit, bool isCallByShortcut)
1642 {
1643 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1644 StartAbilityParams startParams(const_cast<Want &>(want));
1645 startParams.callerToken = callerToken;
1646 startParams.userId = userId;
1647 startParams.requestCode = requestCode;
1648 startParams.isStartAsCaller = isStartAsCaller;
1649 startParams.startOptions = &startOptions;
1650 startParams.SetValidUserId(GetValidUserId(userId));
1651
1652 int result = ERR_OK;
1653 if (StartAbilityInChain(startParams, result)) {
1654 return result;
1655 }
1656
1657 OHOS::AAFwk::StartOptions newStartOptions = startOptions;
1658 WindowOptionsUtils::UpdateStartOptionsToSetDisplayID(newStartOptions, callerToken);
1659 return StartAbilityForOptionInner(want, newStartOptions, callerToken, isPendingWantCaller, userId, requestCode,
1660 isStartAsCaller, callerTokenId, isImplicit, isCallByShortcut);
1661 }
1662
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)1663 int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const StartOptions &startOptions,
1664 const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1665 bool isStartAsCaller, uint32_t specifyTokenId, bool isImplicit, bool isCallByShortcut)
1666 {
1667 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1668 // prevent the app from dominating the screen
1669 if (callerToken == nullptr && !IsCallerSceneBoard() && !isCallByShortcut &&
1670 AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1671 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
1672 return ERR_INVALID_CALLER;
1673 }
1674
1675 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
1676 if (startWithAccount || IsCrossUserCall(userId)) {
1677 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
1678 CHECK_CALLER_IS_SYSTEM_APP;
1679 }
1680 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1681 EventInfo eventInfo = BuildEventInfo(want, userId);
1682 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1683
1684 #ifdef WITH_DLP
1685 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1686 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1687 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1688 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
1689 eventInfo.errCode = CHECK_PERMISSION_FAILED;
1690 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1691 return CHECK_PERMISSION_FAILED;
1692 }
1693 #endif // WITH_DLP
1694
1695 if ((want.GetFlags() & Want::FLAG_ABILITY_PREPARE_CONTINUATION) == Want::FLAG_ABILITY_PREPARE_CONTINUATION &&
1696 IPCSkeleton::GetCallingUid() != DMS_UID) {
1697 TAG_LOGE(AAFwkTag::ABILITYMGR, "The flag only support for DMS, flag is %{public}d", want.GetFlags());
1698 eventInfo.errCode = ERR_INVALID_VALUE;
1699 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1700 return ERR_INVALID_CONTINUATION_FLAG;
1701 }
1702
1703 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1704 eventInfo.errCode = ERR_INVALID_VALUE;
1705 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1706 return ERR_INVALID_CALLER;
1707 }
1708
1709 int32_t oriValidUserId = GetValidUserId(userId);
1710 int32_t validUserId = oriValidUserId;
1711 SetTargetCloneIndexInSameBundle(want, callerToken);
1712 int32_t appIndex = 0;
1713 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1714 return ERR_APP_CLONE_INDEX_INVALID;
1715 }
1716 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
1717 validUserId, appIndex, callerToken);
1718 if (checkRet != ERR_OK) {
1719 return checkRet;
1720 }
1721 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1722 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
1723 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1724 true, nullptr, shouldBlockFunc);
1725 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1726 interceptorExecuter_->DoProcess(interceptorParam);
1727 if (result != ERR_OK) {
1728 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
1729 eventInfo.errCode = result;
1730 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1731 return result;
1732 }
1733
1734 if (AbilityUtil::IsStartFreeInstall(want)) {
1735 if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1736 TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1737 return ERR_INVALID_VALUE;
1738 }
1739 (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1740 Want localWant = want;
1741 if (!isStartAsCaller) {
1742 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1743 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(localWant, callerToken);
1744 }
1745 return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode,
1746 callerToken, true, specifyTokenId);
1747 }
1748 if (!JudgeMultiUserConcurrency(validUserId)) {
1749 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
1750 eventInfo.errCode = ERR_INVALID_VALUE;
1751 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1752 return ERR_CROSS_USER;
1753 }
1754
1755 AbilityRequest abilityRequest;
1756 #ifdef SUPPORT_SCREEN
1757 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1758 auto checkResult = AbilityUtil::CheckInstanceKey(want);
1759 if (checkResult != ERR_OK) {
1760 return checkResult;
1761 }
1762 abilityRequest.Voluation(want, requestCode, callerToken);
1763 if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
1764 bool windowFocused = startOptions.GetWindowFocused();
1765 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowFocused);
1766 } else {
1767 abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
1768 }
1769 if (startOptions.GetDisplayID() == 0) {
1770 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1771 static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1772 } else {
1773 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1774 }
1775 WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
1776 abilityRequest.callType = AbilityCallType::START_OPTIONS_TYPE;
1777 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1778 if (specifyTokenId > 0 && callerToken) { // for sa specify tokenId and caller token
1779 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1780 } else if (!isStartAsCaller) {
1781 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1782 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1783 }
1784 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId,
1785 startOptions.GetWindowMode());
1786 if (result != ERR_OK) {
1787 TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error");
1788 eventInfo.errCode = result;
1789 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1790 }
1791 return result;
1792 }
1793 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1794 return ShowPickerDialog(want, validUserId, callerToken);
1795 }
1796 #endif
1797 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1798 if (result != ERR_OK) {
1799 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
1800 eventInfo.errCode = result;
1801 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1802 return result;
1803 }
1804
1805 if (!isStartAsCaller) {
1806 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1807 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
1808 }
1809 auto abilityInfo = abilityRequest.abilityInfo;
1810 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1811 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1812 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1813
1814 if (startOptions.processOptions != nullptr &&
1815 abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED &&
1816 !ProcessOptions::IsAttachToStatusBarItemMode(startOptions.processOptions->processMode)) {
1817 TAG_LOGE(AAFwkTag::ABILITYMGR, "processMode is not attach to status bar item.");
1818 return ERR_START_OPTIONS_CHECK_FAILED;
1819 }
1820
1821 result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1822 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1823 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1824 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result=%{public}d", result);
1825 eventInfo.errCode = result;
1826 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1827 return ERR_STATIC_CFG_PERMISSION;
1828 }
1829 result = CheckCallAbilityPermission(abilityRequest, 0, isCallByShortcut);
1830 if (result != ERR_OK) {
1831 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error", __func__);
1832 eventInfo.errCode = result;
1833 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1834 return result;
1835 }
1836
1837 if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1838 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability");
1839 eventInfo.errCode = ERR_INVALID_VALUE;
1840 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1841 return ERR_INVALID_VALUE;
1842 }
1843
1844 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1845 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1846 if (result != ERR_OK) {
1847 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility:app data ability preloading failed, '%{public}s', %{public}d",
1848 abilityInfo.bundleName.c_str(),
1849 result);
1850 eventInfo.errCode = result;
1851 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1852 return result;
1853 }
1854 }
1855
1856 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1857 eventInfo.errCode = ERR_WOULD_BLOCK;
1858 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1859 return ERR_WOULD_BLOCK;
1860 }
1861 #ifdef SUPPORT_SCREEN
1862 if (abilityInfo.isStageBasedModel && !CheckWindowMode(startOptions.GetWindowMode(), abilityInfo.windowModes)) {
1863 return ERR_AAFWK_INVALID_WINDOW_MODE;
1864 }
1865 #endif
1866 if (startOptions.GetDisplayID() == 0) {
1867 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1868 static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1869 } else {
1870 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1871 }
1872 AbilityUtil::ProcessWindowMode(abilityRequest.want, abilityInfo.applicationInfo.accessTokenId,
1873 startOptions.GetWindowMode());
1874
1875 WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
1876
1877 if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
1878 bool focused = abilityRequest.want.GetBoolParam(Want::PARAM_RESV_WINDOW_FOCUSED, true);
1879 if (focused) {
1880 bool windowfocused = startOptions.GetWindowFocused();
1881 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowfocused);
1882 }
1883 } else {
1884 abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
1885 }
1886
1887 Want newWant = abilityRequest.want;
1888 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1889 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1890 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1891 afterCheckExecuter_->DoProcess(afterCheckParam);
1892 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1893 newWant.RemoveParam("queryWantFromErms");
1894 if (result != ERR_OK && isReplaceWantExist == false) {
1895 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
1896 return result;
1897 }
1898 #ifdef SUPPORT_SCREEN
1899 if (result != ERR_OK && isReplaceWantExist) {
1900 return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1901 }
1902 if (result == ERR_OK &&
1903 DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1904 TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1905 return CreateCloneSelectorDialog(abilityRequest, GetUserId());
1906 }
1907 #endif // SUPPORT_GRAPHICS
1908 auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1909 UpdateCallerInfoUtil::GetInstance().UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1910 StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1911
1912 abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1913 if (specifyTokenId > 0) {
1914 TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
1915 abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1916 abilityRequest.specifyTokenId = specifyTokenId;
1917 }
1918 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1919 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1920 abilityRequest.userId = oriValidUserId;
1921 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1922 abilityRequest.processOptions = startOptions.processOptions;
1923 if (IPCSkeleton::GetCallingTokenID() == abilityRequest.appInfo.accessTokenId) {
1924 abilityRequest.startWindowOption = startOptions.startWindowOption;
1925 }
1926 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1927 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1928 return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1929 }
1930 auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1931 if (missionListManager == nullptr) {
1932 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", oriValidUserId);
1933 eventInfo.errCode = ERR_INVALID_VALUE;
1934 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1935 return ERR_INVALID_VALUE;
1936 }
1937
1938 auto ret = missionListManager->StartAbility(abilityRequest);
1939 if (ret != ERR_OK) {
1940 eventInfo.errCode = ret;
1941 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1942 }
1943 return ret;
1944 }
1945
RequestDialogService(const Want &want, const sptr<IRemoteObject> &callerToken)1946 int32_t AbilityManagerService::RequestDialogService(const Want &want, const sptr<IRemoteObject> &callerToken)
1947 {
1948 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1949 auto flags = want.GetFlags();
1950 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
1951 TAG_LOGE(AAFwkTag::ABILITYMGR, "requestDialogService with continuation flags not allowed");
1952 return ERR_INVALID_CONTINUATION_FLAG;
1953 }
1954
1955 TAG_LOGI(AAFwkTag::ABILITYMGR, "request dialog service, target:%{public}s", want.GetElement().GetURI().c_str());
1956 return RequestDialogServiceInner(want, callerToken, -1, -1);
1957 }
1958
ReportDrawnCompleted(const sptr<IRemoteObject> &callerToken)1959 int32_t AbilityManagerService::ReportDrawnCompleted(const sptr<IRemoteObject> &callerToken)
1960 {
1961 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1962 if (callerToken == nullptr) {
1963 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken null");
1964 return INNER_ERR;
1965 }
1966
1967 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1968 if (abilityRecord == nullptr) {
1969 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
1970 return INNER_ERR;
1971 }
1972 auto abilityInfo = abilityRecord->GetAbilityInfo();
1973
1974 EventInfo eventInfo;
1975 eventInfo.userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
1976 eventInfo.pid = IPCSkeleton::GetCallingPid();
1977 eventInfo.bundleName = abilityInfo.bundleName;
1978 eventInfo.moduleName = abilityInfo.moduleName;
1979 eventInfo.abilityName = abilityInfo.name;
1980 EventReport::SendAppEvent(EventName::DRAWN_COMPLETED, HiSysEventType::BEHAVIOR, eventInfo);
1981 return ERR_OK;
1982 }
1983
RequestDialogServiceInner(const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)1984 int32_t AbilityManagerService::RequestDialogServiceInner(const Want &want, const sptr<IRemoteObject> &callerToken,
1985 int requestCode, int32_t userId)
1986 {
1987 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1988 if (callerToken == nullptr || !VerificationAllToken(callerToken)) {
1989 TAG_LOGW(AAFwkTag::ABILITYMGR, "caller invalid");
1990 return ERR_INVALID_CALLER;
1991 }
1992
1993 {
1994 #ifdef WITH_DLP
1995 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1996 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1997 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1998 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
1999 return CHECK_PERMISSION_FAILED;
2000 }
2001
2002 if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
2003 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot handle dlp by requestDialogService");
2004 return ERR_WRONG_INTERFACE_CALL;
2005 }
2006 #endif // WITH_DLP
2007 }
2008
2009 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
2010 int32_t validUserId = GetValidUserId(userId);
2011 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2012 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
2013 true, nullptr, shouldBlockFunc);
2014 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2015 interceptorExecuter_->DoProcess(interceptorParam);
2016 if (result != ERR_OK) {
2017 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
2018 return result;
2019 }
2020
2021 if (!JudgeMultiUserConcurrency(validUserId)) {
2022 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
2023 return ERR_CROSS_USER;
2024 }
2025 AbilityRequest abilityRequest;
2026 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2027 if (result != ERR_OK) {
2028 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error when requestDialogService");
2029 return result;
2030 }
2031 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
2032
2033 auto abilityInfo = abilityRequest.abilityInfo;
2034 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2035 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
2036 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2037
2038 result = CheckStaticCfgPermission(abilityRequest, false, -1);
2039 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2040 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
2041 return ERR_STATIC_CFG_PERMISSION;
2042 }
2043
2044 auto type = abilityInfo.type;
2045 if (type == AppExecFwk::AbilityType::EXTENSION &&
2046 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
2047 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
2048 result = CheckCallServicePermission(abilityRequest);
2049 if (result != ERR_OK) {
2050 TAG_LOGE(AAFwkTag::ABILITYMGR, "check permission failed");
2051 return result;
2052 }
2053 } else {
2054 TAG_LOGE(AAFwkTag::ABILITYMGR, "requestDialogService no support other component");
2055 return ERR_WRONG_INTERFACE_CALL;
2056 }
2057
2058 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
2059 GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
2060 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2061 afterCheckExecuter_->DoProcess(afterCheckParam);
2062 if (result != ERR_OK) {
2063 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or DoProcess error");
2064 return result;
2065 }
2066
2067 auto connectManager = GetConnectManagerByUserId(validUserId);
2068 if (!connectManager) {
2069 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
2070 return ERR_INVALID_VALUE;
2071 }
2072 TAG_LOGD(AAFwkTag::ABILITYMGR,
2073 "request dialog service, start service extension,name is %{public}s.", abilityInfo.name.c_str());
2074 ReportEventToRSS(abilityInfo, callerToken);
2075 UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
2076 abilityRequest.abilityInfo.extensionAbilityType);
2077 return connectManager->StartAbility(abilityRequest);
2078 }
2079
OpenAtomicService(AAFwk::Want& want, const StartOptions &options, sptr<IRemoteObject> callerToken, int32_t requestCode, int32_t userId)2080 int32_t AbilityManagerService::OpenAtomicService(AAFwk::Want& want, const StartOptions &options,
2081 sptr<IRemoteObject> callerToken, int32_t requestCode, int32_t userId)
2082 {
2083 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2084 auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
2085 if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
2086 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not hap");
2087 return CHECK_PERMISSION_FAILED;
2088 }
2089 want.SetParam(AAFwk::SCREEN_MODE_KEY, AAFwk::ScreenMode::JUMP_SCREEN_MODE);
2090 return StartUIAbilityForOptionWrap(want, options, callerToken, false, userId, requestCode);
2091 }
2092
SetWantForSessionInfo(sptr<SessionInfo> sessionInfo)2093 int AbilityManagerService::SetWantForSessionInfo(sptr<SessionInfo> sessionInfo)
2094 {
2095 if (!(sessionInfo->want).GetElement().GetAbilityName().empty() &&
2096 !(sessionInfo->want).GetElement().GetModuleName().empty()) {
2097 return ERR_OK;
2098 }
2099 auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
2100 CHECK_POINTER_AND_RETURN(bundleMgrHelper, ERR_INVALID_VALUE);
2101 Want launchWant;
2102 auto errCode = IN_PROCESS_CALL(bundleMgrHelper->GetLaunchWantForBundle(
2103 (sessionInfo->want).GetBundle(), launchWant, GetValidUserId(sessionInfo->userId)));
2104 if (errCode != ERR_OK) {
2105 TAG_LOGE(AAFwkTag::ABILITYMGR, "getLaunchWantForBundle returns %{public}d", errCode);
2106 return errCode;
2107 }
2108 (sessionInfo->want).SetElement(launchWant.GetElement());
2109 return ERR_OK;
2110 }
2111
StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo, bool &isColdStart, uint32_t sceneFlag)2112 int AbilityManagerService::StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo, bool &isColdStart, uint32_t sceneFlag)
2113 {
2114 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2115 TAG_LOGI(AAFwkTag::ABILITYMGR, "call, sceneFlag:%{public}u", sceneFlag);
2116 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
2117 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
2118 return ERR_INVALID_VALUE;
2119 }
2120
2121 if (!IsCallerSceneBoard()) {
2122 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
2123 return ERR_WRONG_INTERFACE_CALL;
2124 }
2125
2126 if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
2127 return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2128 }
2129
2130 std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
2131 if (sessionId.empty()) {
2132 return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2133 }
2134
2135 TAG_LOGI(AAFwkTag::ABILITYMGR, "sessionId=%{public}s", sessionId.c_str());
2136
2137 if (freeInstallManager_ == nullptr) {
2138 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
2139 return ERR_INVALID_VALUE;
2140 }
2141 FreeInstallInfo taskInfo;
2142 if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
2143 TAG_LOGW(AAFwkTag::ABILITYMGR, "failed find free install task");
2144 auto err = SetWantForSessionInfo(sessionInfo);
2145 if (err != ERR_OK) {
2146 TAG_LOGE(AAFwkTag::ABILITYMGR, "SetWantForSessionInfo failed");
2147 return err;
2148 }
2149 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2150 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2151 if (uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo) == nullptr) {
2152 TAG_LOGI(AAFwkTag::ABILITYMGR, "first time open");
2153 return StartUIAbilityByPreInstallInner(sessionInfo, 0, sceneFlag, isColdStart);
2154 }
2155 return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2156 }
2157
2158 if (taskInfo.isFreeInstallFinished) {
2159 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
2160 if (!taskInfo.isInstalled) {
2161 TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
2162 taskInfo.resultCode);
2163 return taskInfo.resultCode;
2164 }
2165 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeds");
2166 return StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, sceneFlag, isColdStart);
2167 }
2168
2169 {
2170 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
2171 preStartSessionMap_[sessionId] = sessionInfo;
2172 }
2173
2174 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task in progress");
2175 const Want& want = sessionInfo->want;
2176 freeInstallManager_->SetSCBCallStatus(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(),
2177 want.GetStringParam(Want::PARAM_RESV_START_TIME), true);
2178 return ERR_OK;
2179 }
2180
StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo, uint32_t sceneFlag, bool &isColdStart)2181 int AbilityManagerService::StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo, uint32_t sceneFlag,
2182 bool &isColdStart)
2183 {
2184 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2185 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
2186
2187 auto currentUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2188 if (sessionInfo->userId == DEFAULT_INVAL_VALUE) {
2189 sessionInfo->userId = currentUserId;
2190 }
2191
2192 (sessionInfo->want).RemoveParam(AAFwk::SCREEN_MODE_KEY);
2193 EventInfo eventInfo = BuildEventInfo(sessionInfo->want, currentUserId);
2194 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
2195
2196 auto requestCode = sessionInfo->requestCode;
2197 int32_t appIndex = 0;
2198 if (!StartAbilityUtils::GetAppIndex(sessionInfo->want, sessionInfo->callerToken, appIndex)) {
2199 return ERR_APP_CLONE_INDEX_INVALID;
2200 }
2201 StartAbilityInfoWrap threadLocalInfo(sessionInfo->want, currentUserId, appIndex, sessionInfo->callerToken);
2202 if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2203 TAG_LOGD(AAFwkTag::ABILITYMGR, "interceptorExecuter_ called");
2204 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2205 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(sessionInfo->want, requestCode,
2206 currentUserId, true, nullptr, shouldBlockFunc);
2207 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2208 interceptorExecuter_->DoProcess(interceptorParam);
2209 if (result != ERR_OK) {
2210 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or DoProcess error");
2211 eventInfo.errCode = result;
2212 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2213 return result;
2214 }
2215 }
2216
2217 AbilityRequest abilityRequest;
2218 auto result = GenerateAbilityRequest(sessionInfo->want, requestCode, abilityRequest,
2219 sessionInfo->callerToken, currentUserId);
2220 if (result != ERR_OK) {
2221 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
2222 return result;
2223 }
2224
2225 if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2226 if (sessionInfo->startSetting != nullptr) {
2227 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb, last not.");
2228 sessionInfo->startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2229 }
2230
2231 if (abilityRequest.startSetting != nullptr) {
2232 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start by scb.");
2233 abilityRequest.startSetting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "true");
2234 }
2235 }
2236
2237 abilityRequest.collaboratorType = sessionInfo->collaboratorType;
2238 uint32_t specifyTokenId = static_cast<uint32_t>(sessionInfo->want.GetIntParam(SPECIFY_TOKEN_ID, 0));
2239 (sessionInfo->want).RemoveParam(SPECIFY_TOKEN_ID);
2240 abilityRequest.specifyTokenId = specifyTokenId;
2241
2242 auto abilityInfo = abilityRequest.abilityInfo;
2243 if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall() &&
2244 abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
2245 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support page type ability");
2246 return ERR_INVALID_VALUE;
2247 }
2248
2249 if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2250 TAG_LOGD(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ called");
2251 if (sessionInfo->want.GetBoolParam("ohos.ability.params.isSkipErmsFromSCB", false)) {
2252 abilityRequest.want.RemoveParam("ohos.ability.params.isSkipErmsFromSCB");
2253 StartAbilityUtils::skipErms = true;
2254 }
2255 Want newWant = abilityRequest.want;
2256 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(), true,
2257 sessionInfo->callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2258 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2259 afterCheckExecuter_->DoProcess(afterCheckParam);
2260 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2261 newWant.RemoveParam("queryWantFromErms");
2262 if (result != ERR_OK) {
2263 if (isReplaceWantExist == false) {
2264 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
2265 return result;
2266 }
2267 return DialogSessionManager::GetInstance().HandleErmsResultBySCB(abilityRequest, newWant);
2268 }
2269 }
2270
2271 return StartUIAbilityBySCBDefaultCommon(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2272 }
2273
StartUIAbilityBySCBDefaultCommon(AbilityRequest &abilityRequest, sptr<SessionInfo> sessionInfo, uint32_t sceneFlag, bool &isColdStart)2274 int32_t AbilityManagerService::StartUIAbilityBySCBDefaultCommon(AbilityRequest &abilityRequest,
2275 sptr<SessionInfo> sessionInfo, uint32_t sceneFlag, bool &isColdStart)
2276 {
2277 auto abilityInfo = abilityRequest.abilityInfo;
2278 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
2279 int32_t result = PreLoadAppDataAbilities(abilityInfo.bundleName, IPCSkeleton::GetCallingUid() / BASE_USER_RANGE);
2280 if (result != ERR_OK) {
2281 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility: app data ability preloading failed, '%{public}s', %{public}d",
2282 abilityInfo.bundleName.c_str(), result);
2283 return result;
2284 }
2285 }
2286
2287 ReportAbilityStartInfoToRSS(abilityInfo);
2288 ReportAbilityAssociatedStartInfoToRSS(abilityInfo, RES_TYPE_SCB_START_ABILITY, sessionInfo->callerToken);
2289 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2290 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2291 // here we don't need want param "IS_CALL_BY_SCB" any more, remove it.
2292 (sessionInfo->want).RemoveParam(IS_CALL_BY_SCB);
2293 return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2294 }
2295
NotifySCBToRecoveryAfterInterception(const AbilityRequest &abilityRequest)2296 int32_t AbilityManagerService::NotifySCBToRecoveryAfterInterception(const AbilityRequest &abilityRequest)
2297 {
2298 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2299 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2300 return uiAbilityManager->NotifySCBToRecoveryAfterInterception(abilityRequest);
2301 }
2302
CheckCallingTokenId(const std::string &bundleName, int32_t userId, int32_t appIndex)2303 bool AbilityManagerService::CheckCallingTokenId(const std::string &bundleName, int32_t userId, int32_t appIndex)
2304 {
2305 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2306 auto bundleMgrHelper = DelayedSingleton<AppExecFwk::BundleMgrHelper>::GetInstance();
2307 CHECK_POINTER_AND_RETURN(bundleMgrHelper, false);
2308 auto validUserId = GetValidUserId(userId);
2309 AppExecFwk::ApplicationInfo appInfo;
2310 IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->GetApplicationInfoWithAppIndex(bundleName,
2311 appIndex, validUserId, appInfo));
2312 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2313 if (accessTokenId != appInfo.accessTokenId) {
2314 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
2315 return false;
2316 }
2317 return true;
2318 }
2319
IsCallerSceneBoard()2320 bool AbilityManagerService::IsCallerSceneBoard()
2321 {
2322 int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2323 auto connectManager = GetConnectManagerByUserId(userId);
2324 CHECK_POINTER_AND_RETURN(connectManager, false);
2325 auto sceneBoardTokenId = connectManager->GetSceneBoardTokenId();
2326 if (sceneBoardTokenId != 0 && IPCSkeleton::GetCallingTokenID() == sceneBoardTokenId) {
2327 return true;
2328 }
2329 return false;
2330 }
2331
IsBackgroundTaskUid(const int uid)2332 bool AbilityManagerService::IsBackgroundTaskUid(const int uid)
2333 {
2334 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2335 std::lock_guard<ffrt::mutex> lock(bgtaskObserverMutex_);
2336 if (bgtaskObserver_) {
2337 return bgtaskObserver_->IsBackgroundTaskUid(uid);
2338 }
2339 return false;
2340 #else
2341 return false;
2342 #endif
2343 }
2344
IsDmsAlive() const2345 bool AbilityManagerService::IsDmsAlive() const
2346 {
2347 return g_isDmsAlive.load();
2348 }
2349
AppUpgradeCompleted(const std::string &bundleName, int32_t uid)2350 void AbilityManagerService::AppUpgradeCompleted(const std::string &bundleName, int32_t uid)
2351 {
2352 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2353 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
2354 return;
2355 }
2356
2357 auto bms = AbilityUtil::GetBundleManagerHelper();
2358 CHECK_POINTER(bms);
2359 auto userId = uid / BASE_USER_RANGE;
2360 if (userId != U0_USER_ID && userId != GetUserId()) {
2361 TAG_LOGI(AAFwkTag::ABILITYMGR, "not current user");
2362 return;
2363 }
2364
2365 AppExecFwk::BundleInfo bundleInfo;
2366 if (!IN_PROCESS_CALL(
2367 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId))) {
2368 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundle info");
2369 return;
2370 }
2371
2372 bool keepAliveEnable = bundleInfo.isKeepAlive;
2373 AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfo.name, keepAliveEnable);
2374 if (!keepAliveEnable) {
2375 TAG_LOGW(AAFwkTag::ABILITYMGR, "not resident application");
2376 return;
2377 }
2378
2379 std::vector<AppExecFwk::BundleInfo> bundleInfos = { bundleInfo };
2380 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId);
2381
2382 if (!bundleInfos.empty()) {
2383 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
2384 }
2385 }
2386
RecordAppExitReason(const ExitReason &exitReason)2387 int32_t AbilityManagerService::RecordAppExitReason(const ExitReason &exitReason)
2388 {
2389 TAG_LOGI(AAFwkTag::ABILITYMGR, "recordAppExitReason reason:%{public}d, exitMsg:%{public}s", exitReason.reason,
2390 exitReason.exitMsg.c_str());
2391
2392 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2393 return appExitReasonHelper_->RecordAppExitReason(exitReason);
2394 }
2395
RecordProcessExitReason(const int32_t pid, const ExitReason &exitReason)2396 int32_t AbilityManagerService::RecordProcessExitReason(const int32_t pid, const ExitReason &exitReason)
2397 {
2398 TAG_LOGI(AAFwkTag::ABILITYMGR, "recordProcessExitReason pid:%{public}d, reason:%{public}d, exitMsg:%{public}s",
2399 pid, exitReason.reason, exitReason.exitMsg.c_str());
2400
2401 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
2402 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
2403 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa call");
2404 return ERR_PERMISSION_DENIED;
2405 }
2406
2407 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2408 return appExitReasonHelper_->RecordProcessExitReason(pid, exitReason);
2409 }
2410
ForceExitApp(const int32_t pid, const ExitReason &exitReason)2411 int32_t AbilityManagerService::ForceExitApp(const int32_t pid, const ExitReason &exitReason)
2412 {
2413 TAG_LOGI(AAFwkTag::ABILITYMGR, "forceExitApp pid:%{public}d, reason:%{public}d, exitMsg:%{public}s",
2414 pid, exitReason.reason, exitReason.exitMsg.c_str());
2415
2416 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
2417 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
2418 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sa or shell call");
2419 return ERR_PERMISSION_DENIED;
2420 }
2421
2422 AppExecFwk::ApplicationInfo application;
2423 bool debug = false;
2424 auto ret = IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->GetApplicationInfoByProcessID(pid,
2425 application, debug));
2426 if (ret != ERR_OK) {
2427 TAG_LOGE(AAFwkTag::ABILITYMGR, "getApplicationInfoByProcessID failed");
2428 return ret;
2429 }
2430
2431 std::string bundleName = application.bundleName;
2432 int32_t uid = application.uid;
2433 int32_t appIndex = application.appIndex;
2434
2435 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2436 appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
2437
2438 return DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName);
2439 }
2440
GetConfiguration(AppExecFwk::Configuration& config)2441 int32_t AbilityManagerService::GetConfiguration(AppExecFwk::Configuration& config)
2442 {
2443 auto appMgr = AppMgrUtil::GetAppMgr();
2444 if (appMgr == nullptr) {
2445 TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
2446 return -1;
2447 }
2448
2449 return appMgr->GetConfiguration(config);
2450 }
2451
CheckOptExtensionAbility(const Want &want, AbilityRequest &abilityRequest, int32_t validUserId, AppExecFwk::ExtensionAbilityType extensionType, bool isImplicit, bool isStartAsCaller)2452 int AbilityManagerService::CheckOptExtensionAbility(const Want &want, AbilityRequest &abilityRequest,
2453 int32_t validUserId, AppExecFwk::ExtensionAbilityType extensionType, bool isImplicit, bool isStartAsCaller)
2454 {
2455 auto abilityInfo = abilityRequest.abilityInfo;
2456 auto type = abilityInfo.type;
2457 if (type != AppExecFwk::AbilityType::EXTENSION) {
2458 TAG_LOGE(AAFwkTag::ABILITYMGR, "not extension ability");
2459 return ERR_WRONG_INTERFACE_CALL;
2460 }
2461 if (extensionType != AppExecFwk::ExtensionAbilityType::UNSPECIFIED &&
2462 extensionType != abilityInfo.extensionAbilityType) {
2463 TAG_LOGE(AAFwkTag::ABILITYMGR, "extension ability type not match, set type:%{public}d, real type: %{public}d",
2464 static_cast<int32_t>(extensionType), static_cast<int32_t>(abilityInfo.extensionAbilityType));
2465 return ERR_WRONG_INTERFACE_CALL;
2466 }
2467
2468 auto result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
2469 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2470 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result=%{public}d", result);
2471 return ERR_STATIC_CFG_PERMISSION;
2472 }
2473
2474 if (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
2475 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE ||
2476 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2477 result = CheckCallServiceExtensionPermission(abilityRequest);
2478 if (result != ERR_OK) {
2479 return result;
2480 }
2481 } else {
2482 result = CheckCallOtherExtensionPermission(abilityRequest);
2483 if (result != ERR_OK) {
2484 return result;
2485 }
2486 }
2487 if (!isStartAsCaller) {
2488 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
2489 }
2490 return ERR_OK;
2491 }
2492
OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)2493 void AbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2494 {
2495 TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d add", systemAbilityId);
2496 switch (systemAbilityId) {
2497 case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2498 SubscribeBackgroundTask();
2499 break;
2500 }
2501 case DISTRIBUTED_SCHED_SA_ID: {
2502 g_isDmsAlive.store(true);
2503 break;
2504 }
2505 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2506 SubscribeBundleEventCallback();
2507 break;
2508 }
2509 #ifdef SUPPORT_SCREEN
2510 case MULTIMODAL_INPUT_SERVICE_ID: {
2511 auto anrListener = std::make_shared<ApplicationAnrListener>();
2512 MMI::InputManager::GetInstance()->SetAnrObserver(anrListener);
2513 break;
2514 }
2515 #endif
2516 default:
2517 break;
2518 }
2519 }
2520
OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)2521 void AbilityManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2522 {
2523 TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d remove", systemAbilityId);
2524 switch (systemAbilityId) {
2525 case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2526 UnSubscribeBackgroundTask();
2527 break;
2528 }
2529 case DISTRIBUTED_SCHED_SA_ID: {
2530 g_isDmsAlive.store(false);
2531 break;
2532 }
2533 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2534 UnsubscribeBundleEventCallback();
2535 break;
2536 }
2537 default:
2538 break;
2539 }
2540 }
2541
SubscribeBackgroundTask()2542 void AbilityManagerService::SubscribeBackgroundTask()
2543 {
2544 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2545 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2546 if (!bgtaskObserver_) {
2547 bgtaskObserver_ = std::make_shared<BackgroundTaskObserver>();
2548 }
2549 int ret = BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver_);
2550 if (ret != ERR_OK) {
2551 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s failed, err:%{public}d", __func__, ret);
2552 return;
2553 }
2554 bgtaskObserver_->GetContinuousTaskApps();
2555 bgtaskObserver_->GetEfficiencyResourcesTaskApps();
2556 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success", __func__);
2557 #endif
2558 }
2559
UnSubscribeBackgroundTask()2560 void AbilityManagerService::UnSubscribeBackgroundTask()
2561 {
2562 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2563 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2564 if (!bgtaskObserver_) {
2565 return;
2566 }
2567 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success", __func__);
2568 #endif
2569 }
2570
SubscribeBundleEventCallback()2571 void AbilityManagerService::SubscribeBundleEventCallback()
2572 {
2573 TAG_LOGI(AAFwkTag::ABILITYMGR, "subscribeBundleEventCallback begin");
2574 if (taskHandler_) {
2575 TAG_LOGI(AAFwkTag::ABILITYMGR, "submit startResidentApps task");
2576 auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(U0_USER_ID); };
2577 taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps");
2578 }
2579
2580 if (abilityBundleEventCallback_) {
2581 return;
2582 }
2583
2584 // Register abilityBundleEventCallback to receive hap updates
2585 abilityBundleEventCallback_ =
2586 new (std::nothrow) AbilityBundleEventCallback(taskHandler_, abilityAutoStartupService_);
2587 auto bms = AbilityUtil::GetBundleManagerHelper();
2588 if (bms) {
2589 bool ret = IN_PROCESS_CALL(bms->RegisterBundleEventCallback(abilityBundleEventCallback_));
2590 if (!ret) {
2591 TAG_LOGE(AAFwkTag::ABILITYMGR, "registerBundleEventCallback failed");
2592 }
2593 } else {
2594 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundleManager failed");
2595 }
2596 TAG_LOGD(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback success.");
2597 }
2598
UnsubscribeBundleEventCallback()2599 void AbilityManagerService::UnsubscribeBundleEventCallback()
2600 {
2601 if (!abilityBundleEventCallback_) {
2602 return;
2603 }
2604 abilityBundleEventCallback_ = nullptr;
2605 TAG_LOGD(AAFwkTag::ABILITYMGR, "UnsubscribeBundleEventCallback success.");
2606 }
2607
ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo)2608 void AbilityManagerService::ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo)
2609 {
2610 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2611 if (abilityInfo.type == AppExecFwk::AbilityType::PAGE &&
2612 abilityInfo.launchMode != AppExecFwk::LaunchMode::SPECIFIED) {
2613 std::vector<AppExecFwk::RunningProcessInfo> runningProcessInfos;
2614 if (IN_PROCESS_CALL(GetProcessRunningInfos(runningProcessInfos)) != ERR_OK) {
2615 return;
2616 }
2617 bool isColdStart = true;
2618 int32_t pid = 0;
2619 for (auto const &info : runningProcessInfos) {
2620 if (info.uid_ == abilityInfo.applicationInfo.uid) {
2621 isColdStart = false;
2622 pid = info.pid_;
2623 break;
2624 }
2625 }
2626 ResSchedUtil::GetInstance().ReportAbilityStartInfoToRSS(abilityInfo, pid, isColdStart);
2627 }
2628 }
2629
ReportAbilityAssociatedStartInfoToRSS( const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr<IRemoteObject> &callerToken)2630 void AbilityManagerService::ReportAbilityAssociatedStartInfoToRSS(
2631 const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr<IRemoteObject> &callerToken)
2632 {
2633 CHECK_POINTER_LOG(callerToken, "null callerToken");
2634 auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2635 CHECK_POINTER_LOG(callerAbility, "null callerAbility");
2636 int32_t callerUid = callerAbility->GetUid();
2637 int32_t callerPid = callerAbility->GetPid();
2638 ResSchedUtil::GetInstance().ReportAbilityAssociatedStartInfoToRSS(abilityInfo, type, callerUid, callerPid);
2639 }
2640
ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo, sptr<IRemoteObject> callerToken)2641 void AbilityManagerService::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo,
2642 sptr<IRemoteObject> callerToken)
2643 {
2644 CHECK_POINTER_LOG(taskHandler_, "taskhandler null");
2645 std::string reason = ResSchedUtil::GetInstance().GetThawReasonByAbilityType(abilityInfo);
2646 const auto uid = abilityInfo.applicationInfo.uid;
2647 const auto bundleName = abilityInfo.applicationInfo.bundleName;
2648 auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2649 const int32_t callerPid = (callerAbility != nullptr) ? callerAbility->GetPid() : IPCSkeleton::GetCallingPid();
2650 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}d_%{public}s reason=%{public}s callerPid=%{public}d", uid,
2651 bundleName.c_str(), reason.c_str(), callerPid);
2652 taskHandler_->SubmitTask([reason, uid, bundleName, callerPid]() {
2653 ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason, -1, callerPid);
2654 });
2655 }
2656
StartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken, int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)2657 int32_t AbilityManagerService::StartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2658 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2659 {
2660 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2661 if (extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2662 if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
2663 TAG_LOGE(AAFwkTag::ABILITYMGR, "uiServiceExtensionAbility disable");
2664 return ERR_CAPABILITY_NOT_SUPPORT;
2665 }
2666 }
2667 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2668 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN ||
2669 extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
2670 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false);
2671 }
2672 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true);
2673 }
2674
ImplicitStartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken, int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)2675 int AbilityManagerService::ImplicitStartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2676 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2677 {
2678 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2679 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
2680 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false, true);
2681 }
2682 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true, true);
2683 }
2684
PreloadUIExtensionAbility(const Want &want, std::string &bundleName, int32_t userId)2685 int AbilityManagerService::PreloadUIExtensionAbility(const Want &want, std::string &bundleName, int32_t userId)
2686 {
2687 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
2688 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2689 // check preload ui extension permission.
2690 CHECK_CALLER_IS_SYSTEM_APP;
2691 if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
2692 PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
2693 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
2694 PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
2695 return ERR_PERMISSION_DENIED;
2696 }
2697 return PreloadUIExtensionAbilityInner(want, bundleName, userId);
2698 }
2699
PreloadUIExtensionAbilityInner(const Want &want, std::string &hostBundleName, int32_t userId)2700 int AbilityManagerService::PreloadUIExtensionAbilityInner(const Want &want, std::string &hostBundleName, int32_t userId)
2701 {
2702 TAG_LOGD(AAFwkTag::ABILITYMGR, "Preload ui extension called, elementName: %{public}s.",
2703 want.GetElement().GetURI().c_str());
2704 int32_t validUserId = GetValidUserId(userId);
2705 AbilityRequest abilityRequest;
2706 ErrCode result = ERR_OK;
2707 result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, validUserId);
2708 if (result != ERR_OK) {
2709 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate abilityReq error");
2710 return result;
2711 }
2712 abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
2713 abilityRequest.want.SetParam(IS_PRELOAD_UIEXTENSION_ABILITY, true);
2714 auto abilityInfo = abilityRequest.abilityInfo;
2715 auto res = JudgeAbilityVisibleControl(abilityInfo);
2716 if (res != ERR_OK) {
2717 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability invisible");
2718 return res;
2719 }
2720 auto connectManager = GetConnectManagerByUserId(validUserId);
2721 if (connectManager == nullptr) {
2722 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null, userId:%{public}d", validUserId);
2723 return ERR_INVALID_VALUE;
2724 }
2725 return connectManager->PreloadUIExtensionAbilityLocked(abilityRequest, hostBundleName);
2726 }
2727
UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> &abilityRecord, std::string &hostBundleName)2728 int AbilityManagerService::UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> &abilityRecord,
2729 std::string &hostBundleName)
2730 {
2731 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
2732 auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
2733 if (connectManager == nullptr) {
2734 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null");
2735 return ERR_INVALID_VALUE;
2736 }
2737 return connectManager->UnloadUIExtensionAbility(abilityRecord, hostBundleName);
2738 }
2739
RequestModalUIExtension(const Want &want)2740 int AbilityManagerService::RequestModalUIExtension(const Want &want)
2741 {
2742 CHECK_CALLER_IS_SYSTEM_APP;
2743 return RequestModalUIExtensionInner(want);
2744 }
2745
RequestModalUIExtensionInner(Want want)2746 int AbilityManagerService::RequestModalUIExtensionInner(Want want)
2747 {
2748 sptr<IRemoteObject> token = nullptr;
2749 int ret = IN_PROCESS_CALL(GetTopAbility(token));
2750 if (ret == ERR_OK && token != nullptr) {
2751 // Gets the record corresponding to the current focus appliaction
2752 auto record = Token::GetAbilityRecordByToken(token);
2753 if (!record) {
2754 TAG_LOGE(AAFwkTag::ABILITYMGR, "record null");
2755 return ERR_INVALID_VALUE;
2756 }
2757
2758 // Gets the bundleName corresponding to the
2759 // current focus appliaction
2760 std::string focusName = record->GetAbilityInfo().bundleName;
2761
2762 // Gets the bundleName corresponding to the
2763 // current focus appliaction
2764 std::string callerName = want.GetParams().GetStringParam("bundleName");
2765
2766 TAG_LOGI(AAFwkTag::ABILITYMGR,
2767 "focusbundlename: %{public}s, callerbundlename: %{public}s",
2768 focusName.c_str(), callerName.c_str());
2769
2770 // Compare
2771 if (record->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
2772 focusName == callerName) {
2773 TAG_LOGD(AAFwkTag::ABILITYMGR, "CreateModalUIExtension is called!");
2774 return record->CreateModalUIExtension(want);
2775 }
2776 } else {
2777 TAG_LOGW(AAFwkTag::ABILITYMGR, "token null");
2778 }
2779
2780 TAG_LOGD(AAFwkTag::ABILITYMGR, "Window Modal System Create UIExtension is called!");
2781 want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
2782 auto connection = std::make_shared<Rosen::ModalSystemUiExtension>();
2783 return connection->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR;
2784 }
2785
ChangeAbilityVisibility(sptr<IRemoteObject> token, bool isShow)2786 int AbilityManagerService::ChangeAbilityVisibility(sptr<IRemoteObject> token, bool isShow)
2787 {
2788 bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
2789 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
2790 TAG_LOGE(AAFwkTag::ABILITYMGR, "capability not support");
2791 return ERR_CAPABILITY_NOT_SUPPORT;
2792 }
2793 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2794 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2795 return uiAbilityManager->ChangeAbilityVisibility(token, isShow);
2796 }
2797
ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo, bool isShow)2798 int AbilityManagerService::ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo, bool isShow)
2799 {
2800 if (!IsCallerSceneBoard()) {
2801 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
2802 return ERR_WRONG_INTERFACE_CALL;
2803 }
2804 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2805 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2806 return uiAbilityManager->ChangeUIAbilityVisibilityBySCB(sessionInfo, isShow);
2807 }
2808
CheckWorkSchedulerPermission(const sptr<IRemoteObject> &callerToken, const uint32_t uid)2809 bool AbilityManagerService::CheckWorkSchedulerPermission(const sptr<IRemoteObject> &callerToken, const uint32_t uid)
2810 {
2811 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2812 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2813 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2814 if (bgtaskObserver_ && abilityRecord) {
2815 auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
2816 if (callerAbilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER) {
2817 return true;
2818 }
2819
2820 if (!bgtaskObserver_->IsEfficiencyResourcesTaskUid(uid)) {
2821 TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to start extension by WorkScheduler");
2822 return false;
2823 }
2824 }
2825 #endif
2826 return true;
2827 }
2828
StartExtensionAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken, int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller, bool isImplicit, bool isDlp, bool isStartAsCaller)2829 int32_t AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
2830 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller, bool isImplicit,
2831 bool isDlp, bool isStartAsCaller)
2832 {
2833 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2834 TAG_LOGI(AAFwkTag::ABILITYMGR,
2835 "Start extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
2836 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
2837 if (checkSystemCaller) {
2838 CHECK_CALLER_IS_SYSTEM_APP;
2839 }
2840 EventInfo eventInfo = BuildEventInfo(want, userId);
2841 eventInfo.extensionType = static_cast<int32_t>(extensionType);
2842
2843 int result;
2844 #ifdef WITH_DLP
2845 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::START_EXTENSION_ERROR);
2846 if (result != ERR_OK) {
2847 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error");
2848 eventInfo.errCode = result;
2849 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2850 return result;
2851 }
2852 #endif // WITH_DLP
2853
2854 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2855 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
2856 eventInfo.errCode = ERR_INVALID_VALUE;
2857 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2858 return ERR_INVALID_CALLER;
2859 }
2860
2861 int32_t validUserId = GetValidUserId(userId);
2862 int32_t appIndex = 0;
2863 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
2864 eventInfo.errCode = ERR_APP_CLONE_INDEX_INVALID;
2865 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2866 return ERR_APP_CLONE_INDEX_INVALID;
2867 }
2868 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken, true);
2869 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
2870 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
2871 shouldBlockFunc);
2872 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2873 interceptorExecuter_->DoProcess(interceptorParam);
2874 if (result != ERR_OK) {
2875 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
2876 eventInfo.errCode = result;
2877 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2878 return result;
2879 }
2880
2881 if (!JudgeMultiUserConcurrency(validUserId)) {
2882 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
2883 eventInfo.errCode = ERR_CROSS_USER;
2884 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2885 return ERR_CROSS_USER;
2886 }
2887
2888 AbilityRequest abilityRequest;
2889 #ifdef SUPPORT_SCREEN
2890 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
2891 abilityRequest.Voluation(want, DEFAULT_INVAL_VALUE, callerToken);
2892 abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
2893 abilityRequest.extensionType = extensionType;
2894 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
2895 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
2896 if (result != ERR_OK) {
2897 TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error");
2898 eventInfo.errCode = result;
2899 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2900 }
2901 return result;
2902 }
2903 #endif
2904 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2905 if (result != ERR_OK) {
2906 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
2907 eventInfo.errCode = result;
2908 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2909 return result;
2910 }
2911
2912 if (!CheckWorkSchedulerPermission(callerToken, abilityRequest.abilityInfo.applicationInfo.uid)) {
2913 return CHECK_PERMISSION_FAILED;
2914 }
2915 auto abilityInfo = abilityRequest.abilityInfo;
2916 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2917 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
2918 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2919
2920 result = isDlp ? IN_PROCESS_CALL(
2921 CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller)) :
2922 CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller);
2923 if (result != ERR_OK) {
2924 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkOptExtensionAbility error");
2925 eventInfo.errCode = result;
2926 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2927 return result;
2928 }
2929
2930 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
2931 false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2932 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2933 afterCheckExecuter_->DoProcess(afterCheckParam);
2934 if (result != ERR_OK) {
2935 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
2936 eventInfo.errCode = result;
2937 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2938 return result;
2939 }
2940
2941 auto connectManager = GetConnectManagerByUserId(validUserId);
2942 if (!connectManager) {
2943 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
2944 eventInfo.errCode = ERR_INVALID_VALUE;
2945 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2946 return ERR_INVALID_VALUE;
2947 }
2948 if (!isStartAsCaller) {
2949 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
2950 }
2951
2952 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
2953 SetAbilityRequestSessionInfo(abilityRequest, extensionType);
2954 UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
2955 abilityRequest.abilityInfo.extensionAbilityType);
2956 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
2957 if (eventInfo.errCode != ERR_OK) {
2958 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2959 }
2960 ReportAbilityAssociatedStartInfoToRSS(abilityRequest.abilityInfo, RES_TYPE_EXTENSION_START_ABILITY, callerToken);
2961 return eventInfo.errCode;
2962 }
2963
SetPickerElementName(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)2964 void AbilityManagerService::SetPickerElementName(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
2965 {
2966 CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
2967 std::string targetType = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TARGET_TYPE_KEY);
2968 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
2969 extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
2970 extensionSessionInfo->want.GetElement().GetAbilityName().empty() &&
2971 COMMON_PICKER_TYPE.find(targetType) != COMMON_PICKER_TYPE.end()) {
2972 std::string abilityName = "CommonSelectPickerAbility";
2973 std::string bundleName = "com.ohos.amsdialog";
2974 extensionSessionInfo->want.SetElementName(bundleName, abilityName);
2975 WantParams ¶meters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
2976 parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box("sys/commonUI"));
2977 extensionSessionInfo->want.SetParams(parameters);
2978 return;
2979 }
2980 if (extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
2981 extensionSessionInfo->want.GetElement().GetAbilityName().empty() && !targetType.empty()) {
2982 std::string abilityName;
2983 std::string bundleName;
2984 std::string pickerType;
2985 std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
2986 auto pickerMap = AmsConfigurationParameter::GetInstance().GetPickerMap();
2987 auto it = pickerMap.find(targetType);
2988 if (it == pickerMap.end()) {
2989 TAG_LOGE(AAFwkTag::ABILITYMGR, "can not find targetType:%{public}s", targetType.c_str());
2990 return;
2991 }
2992 pickerType = it->second;
2993 auto bms = AbilityUtil::GetBundleManagerHelper();
2994 CHECK_POINTER(bms);
2995 int32_t validUserId = GetValidUserId(userId);
2996 TAG_LOGI(AAFwkTag::ABILITYMGR, "targetType: %{public}s, pickerType: %{public}s, userId: %{public}d",
2997 targetType.c_str(), pickerType.c_str(), validUserId);
2998 auto flags = static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION) |
2999 static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_BY_TYPE_NAME);
3000 auto ret = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfosOnlyWithTypeName(pickerType,
3001 flags,
3002 validUserId,
3003 extensionInfos));
3004 if (ret != ERR_OK) {
3005 TAG_LOGE(AAFwkTag::ABILITYMGR, "queryExtensionAbilityInfosOnlyWithTypeName failed");
3006 return;
3007 }
3008 abilityName = extensionInfos[0].name;
3009 bundleName = extensionInfos[0].bundleName;
3010 TAG_LOGI(AAFwkTag::ABILITYMGR,
3011 "abilityName: %{public}s, bundleName: %{public}s", abilityName.c_str(), bundleName.c_str());
3012 extensionSessionInfo->want.SetElementName(bundleName, abilityName);
3013 WantParams ¶meters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
3014 parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box(pickerType));
3015 extensionSessionInfo->want.SetParams(parameters);
3016 }
3017 }
3018
SetAutoFillElementName(const sptr<SessionInfo> &extensionSessionInfo)3019 void AbilityManagerService::SetAutoFillElementName(const sptr<SessionInfo> &extensionSessionInfo)
3020 {
3021 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
3022 CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
3023 std::vector<std::string> argList;
3024 if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_PASSWORD_TYPE) {
3025 SplitStr(KEY_AUTO_FILL_ABILITY, "/", argList);
3026 } else if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_SMART_TYPE) {
3027 SplitStr(KEY_SMART_AUTO_FILL_ABILITY, "/", argList);
3028 } else {
3029 TAG_LOGW(AAFwkTag::ABILITYMGR, "not autofill");
3030 return;
3031 }
3032
3033 if (argList.size() != ARGC_THREE) {
3034 TAG_LOGE(AAFwkTag::ABILITYMGR, "parse extension element name failed");
3035 return;
3036 }
3037 extensionSessionInfo->want.SetElementName(argList[INDEX_ZERO], argList[INDEX_TWO]);
3038 extensionSessionInfo->want.SetModuleName(argList[INDEX_ONE]);
3039 }
3040
CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage, AppExecFwk::ExtensionAbilityType extensionType)3041 int AbilityManagerService::CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,
3042 AppExecFwk::ExtensionAbilityType extensionType)
3043 {
3044 if (uiExtensionUsage == UIExtensionUsage::EMBEDDED &&
3045 !AAFwk::UIExtensionUtils::IsPublicForEmbedded(extensionType)) {
3046 CHECK_CALLER_IS_SYSTEM_APP;
3047 }
3048
3049 if (uiExtensionUsage == UIExtensionUsage::CONSTRAINED_EMBEDDED &&
3050 !AAFwk::UIExtensionUtils::IsPublicForConstrainedEmbedded(extensionType)) {
3051 TAG_LOGE(AAFwkTag::ABILITYMGR, "secureConstrainedEmbedded extension type error:%u.", extensionType);
3052 return ERR_INVALID_VALUE;
3053 }
3054 return ERR_OK;
3055 }
3056
StartUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)3057 int AbilityManagerService::StartUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
3058 {
3059 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3060 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ui extension ability come");
3061 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3062 SetPickerElementName(extensionSessionInfo, userId);
3063 SetAutoFillElementName(extensionSessionInfo);
3064
3065 if (extensionSessionInfo->want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
3066 int32_t screenMode = extensionSessionInfo->want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
3067 if (screenMode != AAFwk::EMBEDDED_FULL_SCREEN_MODE) {
3068 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support embedded pull-ups");
3069 return ERR_INVALID_VALUE;
3070 }
3071 auto bms = AbilityUtil::GetBundleManagerHelper();
3072 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3073 AppExecFwk::BundleInfo bundleInfo;
3074 if (!IN_PROCESS_CALL(bms->GetBundleInfo(extensionSessionInfo->want.GetBundle(),
3075 AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, GetValidUserId(userId)))) {
3076 TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission failed get application info");
3077 return CHECK_PERMISSION_FAILED;
3078 }
3079 if (bundleInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE) {
3080 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support atomicService");
3081 return ERR_INVALID_CALLER;
3082 }
3083 if (extensionSessionInfo->want.GetElement().GetAbilityName().empty()) {
3084 if (bundleInfo.abilityInfos.empty()) {
3085 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get abilityInfos");
3086 return ERR_INVALID_VALUE;
3087 }
3088 extensionSessionInfo->want.SetElementName(bundleInfo.name, bundleInfo.abilityInfos.begin()->name);
3089 }
3090 extensionSessionInfo->want.SetParam("send_to_erms_embedded", 1);
3091 }
3092 std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY);
3093 AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ?
3094 AppExecFwk::ExtensionAbilityType::UI : AppExecFwk::ConvertToExtensionAbilityType(extensionTypeStr);
3095 if (extensionType == AppExecFwk::ExtensionAbilityType::UNSPECIFIED) {
3096 TAG_LOGE(AAFwkTag::ABILITYMGR, "input extension ability type invalid");
3097 return ERR_INVALID_VALUE;
3098 }
3099 EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, userId);
3100 eventInfo.extensionType = static_cast<int32_t>(extensionType);
3101
3102 auto ret = CheckUIExtensionUsage(extensionSessionInfo->uiExtensionUsage, extensionType);
3103 if (ret != ERR_OK) {
3104 TAG_LOGE(AAFwkTag::ABILITYMGR, "check usage failed");
3105 return ret;
3106 }
3107
3108 if (InsightIntentExecuteParam::IsInsightIntentExecute(extensionSessionInfo->want)) {
3109 int32_t result = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateWant(
3110 extensionSessionInfo->want, AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY);
3111 if (result != ERR_OK) {
3112 eventInfo.errCode = ERR_INVALID_VALUE;
3113 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3114 return result;
3115 }
3116 }
3117
3118 sptr<IRemoteObject> callerToken = extensionSessionInfo->callerToken;
3119
3120 #ifdef WITH_DLP
3121 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, extensionSessionInfo->want) ||
3122 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
3123 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, extensionSessionInfo->want)) {
3124 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUIExtensionAbility: permission verification failed");
3125 eventInfo.errCode = CHECK_PERMISSION_FAILED;
3126 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3127 return CHECK_PERMISSION_FAILED;
3128 }
3129 #endif // WITH_DLP
3130
3131 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3132 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUIExtensionAbility verificationAllToken failed");
3133 eventInfo.errCode = ERR_INVALID_VALUE;
3134 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3135 return ERR_INVALID_CALLER;
3136 }
3137
3138 auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
3139 if (callerRecord == nullptr || !JudgeSelfCalled(callerRecord)) {
3140 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid callerToken");
3141 eventInfo.errCode = ERR_INVALID_VALUE;
3142 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3143 return ERR_INVALID_CALLER;
3144 }
3145
3146 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
3147 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(extensionSessionInfo->want, 0, GetUserId(),
3148 true, nullptr, shouldBlockFunc);
3149 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3150 interceptorExecuter_->DoProcess(interceptorParam);
3151 if (result != ERR_OK) {
3152 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
3153 eventInfo.errCode = result;
3154 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3155 return result;
3156 }
3157
3158 int32_t validUserId = GetValidUserId(userId);
3159 if (!JudgeMultiUserConcurrency(validUserId)) {
3160 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
3161 eventInfo.errCode = ERR_INVALID_VALUE;
3162 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3163 return ERR_INVALID_VALUE;
3164 }
3165 #ifdef SUPPORT_GRAPHICS
3166 if (ImplicitStartProcessor::IsImplicitStartAction(extensionSessionInfo->want)) {
3167 TAG_LOGE(AAFwkTag::ABILITYMGR, "UI extension ability not support implicit start");
3168 eventInfo.errCode = ERR_INVALID_VALUE;
3169 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3170 return ERR_INVALID_VALUE;
3171 }
3172 #endif // SUPPORT_GRAPHICS
3173 AbilityRequest abilityRequest;
3174 abilityRequest.Voluation(extensionSessionInfo->want, DEFAULT_INVAL_VALUE, callerToken);
3175 abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
3176 abilityRequest.sessionInfo = extensionSessionInfo;
3177 result = GenerateEmbeddableUIAbilityRequest(extensionSessionInfo->want, abilityRequest, callerToken, validUserId);
3178 CHECK_POINTER_AND_RETURN(abilityRequest.sessionInfo, ERR_INVALID_VALUE);
3179 abilityRequest.sessionInfo->uiExtensionComponentId = (
3180 static_cast<uint64_t>(callerRecord->GetRecordId()) << OFFSET) |
3181 static_cast<uint64_t>(abilityRequest.sessionInfo->persistentId);
3182 TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
3183 abilityRequest.sessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3184 if (result != ERR_OK) {
3185 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
3186 eventInfo.errCode = result;
3187 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3188 return result;
3189 }
3190 abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
3191
3192 auto abilityInfo = abilityRequest.abilityInfo;
3193 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3194 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
3195 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3196
3197 result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType);
3198 if (result != ERR_OK) {
3199 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkOptExtensionAbility error");
3200 eventInfo.errCode = result;
3201 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3202 return result;
3203 }
3204
3205 sptr<IRemoteObject> parentToken = extensionSessionInfo->parentToken;
3206 if (parentToken && parentToken != callerToken) {
3207 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, parentToken);
3208 }
3209
3210 result = JudgeAbilityVisibleControl(abilityInfo);
3211 if (result != ERR_OK) {
3212 TAG_LOGE(AAFwkTag::ABILITYMGR, "judgeAbilityVisibleControl error");
3213 eventInfo.errCode = result;
3214 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3215 return result;
3216 }
3217
3218 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
3219 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
3220 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
3221 afterCheckExecuter_->DoProcess(afterCheckParam);
3222 if (result != ERR_OK) {
3223 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
3224 return result;
3225 }
3226
3227 auto connectManager = GetConnectManagerByUserId(validUserId);
3228 if (!connectManager) {
3229 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
3230 eventInfo.errCode = ERR_INVALID_VALUE;
3231 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3232 return ERR_INVALID_VALUE;
3233 }
3234 ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
3235 TAG_LOGD(AAFwkTag::ABILITYMGR, "name:%{public}s", abilityInfo.name.c_str());
3236 UriUtils::GetInstance().CheckUriPermissionForUIExtension(abilityRequest.want,
3237 abilityRequest.abilityInfo.extensionAbilityType);
3238 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
3239 if (eventInfo.errCode != ERR_OK) {
3240 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3241 }
3242 return eventInfo.errCode;
3243 }
3244
StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken, int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)3245 int AbilityManagerService::StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
3246 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
3247 {
3248 TAG_LOGI(AAFwkTag::ABILITYMGR,
3249 "bundlename:%{public}s, ability:%{public}s, userId:%{public}d",
3250 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3251 if (extensionType != AppExecFwk::ExtensionAbilityType::VPN) {
3252 CHECK_CALLER_IS_SYSTEM_APP;
3253 }
3254 EventInfo eventInfo = BuildEventInfo(want, userId);
3255 eventInfo.extensionType = static_cast<int32_t>(extensionType);
3256
3257 int result;
3258 #ifdef WITH_DLP
3259 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::STOP_EXTENSION_ERROR);
3260 if (result != ERR_OK) {
3261 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error");
3262 return result;
3263 }
3264 #endif // WITH_DLP
3265
3266 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3267 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
3268 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
3269 TAG_LOGE(AAFwkTag::ABILITYMGR, "verificationAllToken failed");
3270 eventInfo.errCode = ERR_INVALID_VALUE;
3271 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3272 return ERR_INVALID_CALLER;
3273 }
3274 TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller is specific system ability.");
3275 }
3276
3277 int32_t validUserId = GetValidUserId(userId);
3278 if (!JudgeMultiUserConcurrency(validUserId)) {
3279 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
3280 eventInfo.errCode = ERR_INVALID_VALUE;
3281 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3282 return ERR_CROSS_USER;
3283 }
3284
3285 if (callerToken != nullptr && CheckIfOperateRemote(want)) {
3286 auto callerUid = IPCSkeleton::GetCallingUid();
3287 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3288 DistributedClient dmsClient;
3289 return dmsClient.StopRemoteExtensionAbility(want, callerUid, accessToken, eventInfo.extensionType);
3290 }
3291
3292 AbilityRequest abilityRequest;
3293 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
3294 if (result != ERR_OK) {
3295 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
3296 eventInfo.errCode = result;
3297 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3298 return result;
3299 }
3300
3301 auto abilityInfo = abilityRequest.abilityInfo;
3302 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3303 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
3304 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3305
3306 result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
3307 if (result != ERR_OK) {
3308 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkOptExtensionAbility error");
3309 eventInfo.errCode = result;
3310 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3311 return result;
3312 }
3313
3314 auto connectManager = GetConnectManagerByUserId(validUserId);
3315 if (!connectManager) {
3316 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
3317 eventInfo.errCode = ERR_INVALID_VALUE;
3318 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3319 return ERR_INVALID_VALUE;
3320 }
3321 TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop extension begin, name:%{public}s", abilityInfo.name.c_str());
3322 eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3323 if (eventInfo.errCode != ERR_OK) {
3324 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3325 }
3326 return eventInfo.errCode;
3327 }
3328
StopSwitchUserDialog()3329 void AbilityManagerService::StopSwitchUserDialog()
3330 {
3331 TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog extension ability come");
3332 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3333 TAG_LOGE(AAFwkTag::ABILITYMGR, "scene board enabled");
3334 return;
3335 }
3336
3337 if (userController_ == nullptr || userController_->GetFreezingNewUserId() == DEFAULT_INVAL_VALUE) {
3338 TAG_LOGE(AAFwkTag::ABILITYMGR, "get last userId error");
3339 return;
3340 }
3341 #ifdef SUPPORT_GRAPHICS
3342 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
3343 if (sysDialog == nullptr) {
3344 TAG_LOGE(AAFwkTag::ABILITYMGR, "system dialog scheduler instance null");
3345 return;
3346 }
3347 Want stopWant = sysDialog->GetSwitchUserDialogWant();
3348 StopSwitchUserDialogInner(stopWant, userController_->GetFreezingNewUserId());
3349 #endif // SUPPORT_GRAPHICS
3350 userController_->SetFreezingNewUserId(DEFAULT_INVAL_VALUE);
3351 return;
3352 }
3353
StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)3354 void AbilityManagerService::StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)
3355 {
3356 TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog inner come");
3357 EventInfo eventInfo = BuildEventInfo(want, lastUserId);
3358 eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
3359 AbilityRequest abilityRequest;
3360 auto result =
3361 GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
3362 if (result != ERR_OK) {
3363 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
3364 eventInfo.errCode = result;
3365 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3366 return;
3367 }
3368
3369 auto abilityInfo = abilityRequest.abilityInfo;
3370 auto stopUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
3371 result = CheckOptExtensionAbility(want, abilityRequest, stopUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
3372 if (result != ERR_OK) {
3373 TAG_LOGE(AAFwkTag::ABILITYMGR, "check extensionAbility type error");
3374 eventInfo.errCode = result;
3375 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3376 return;
3377 }
3378
3379 auto connectManager = GetConnectManagerByUserId(stopUserId);
3380 if (connectManager == nullptr) {
3381 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId:%{public}d", stopUserId);
3382 eventInfo.errCode = ERR_INVALID_VALUE;
3383 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3384 return;
3385 }
3386
3387 eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3388 if (eventInfo.errCode != ERR_OK) {
3389 TAG_LOGE(AAFwkTag::ABILITYMGR, "eventInfo errCode=%{public}d", eventInfo.errCode);
3390 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3391 }
3392 }
3393
MoveAbilityToBackground(const sptr<IRemoteObject> &token)3394 int AbilityManagerService::MoveAbilityToBackground(const sptr<IRemoteObject> &token)
3395 {
3396 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3397 TAG_LOGD(AAFwkTag::ABILITYMGR, "Move ability to background begin");
3398 if (!VerificationAllToken(token)) {
3399 return ERR_INVALID_VALUE;
3400 }
3401 auto abilityRecord = Token::GetAbilityRecordByToken(token);
3402 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3403 if (!JudgeSelfCalled(abilityRecord)) {
3404 return CHECK_PERMISSION_FAILED;
3405 }
3406
3407 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3408 return ERR_WOULD_BLOCK;
3409 }
3410
3411 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3412 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3413 if (!missionListManager) {
3414 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null ownerUserId=%{public}d", ownerUserId);
3415 return ERR_INVALID_VALUE;
3416 }
3417 return missionListManager->MoveAbilityToBackground(abilityRecord);
3418 }
3419
MoveUIAbilityToBackground(const sptr<IRemoteObject> token)3420 int32_t AbilityManagerService::MoveUIAbilityToBackground(const sptr<IRemoteObject> token)
3421 {
3422 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3423 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
3424 if (!AppUtils::GetInstance().EnableMoveUIAbilityToBackgroundApi()) {
3425 return ERR_OPERATION_NOT_SUPPORTED_ON_CURRENT_DEVICE;
3426 }
3427 if (!VerificationAllToken(token)) {
3428 return ERR_INVALID_VALUE;
3429 }
3430 auto abilityRecord = Token::GetAbilityRecordByToken(token);
3431 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3432 if (!IsAppSelfCalled(abilityRecord)) {
3433 return CHECK_PERMISSION_FAILED;
3434 }
3435 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3436 TAG_LOGE(AAFwkTag::ABILITYMGR, "move ability background failed in wukong mode");
3437 return ERR_WUKONG_MODE_CANT_MOVE_STATE;
3438 }
3439 if (!abilityRecord->IsAbilityState(FOREGROUND) && !abilityRecord->IsAbilityState(FOREGROUNDING)) {
3440 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability not foregorund state");
3441 return ERR_ABILITY_NOT_FOREGROUND;
3442 }
3443 if (abilityRecord->GetAbilityInfo().type != AppExecFwk::AbilityType::PAGE) {
3444 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot background non UIAbility");
3445 return RESOLVE_CALL_ABILITY_TYPE_ERR;
3446 }
3447 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3448 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3449 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3450 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3451 return uiAbilityManager->NotifySCBToMinimizeUIAbility(abilityRecord, token);
3452 }
3453
3454 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3455 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3456 return missionListManager->MoveAbilityToBackground(abilityRecord);
3457 }
3458
TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)3459 int AbilityManagerService::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3460 {
3461 auto abilityRecord = Token::GetAbilityRecordByToken(token);
3462 if (!abilityRecord) {
3463 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
3464 return ERR_INVALID_VALUE;
3465 }
3466 auto elementName = abilityRecord->GetWant().GetElement();
3467 if (AppUtils::GetInstance().IsLauncher(elementName.GetBundleName()) &&
3468 AppUtils::GetInstance().IsLauncherAbility(elementName.GetAbilityName())) {
3469 TAG_LOGI(AAFwkTag::ABILITYMGR, "cannot terminate launcher ability");
3470 return ERR_OK;
3471 }
3472 return TerminateAbilityWithFlag(token, resultCode, resultWant, true);
3473 }
3474
TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> &token)3475 int32_t AbilityManagerService::TerminateUIServiceExtensionAbility(const sptr<IRemoteObject> &token)
3476 {
3477 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3478 if (!VerificationAllToken(token)) {
3479 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
3480 return ERR_INVALID_VALUE;
3481 }
3482
3483 if (!IsCallerSceneBoard()) {
3484 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3485 return ERR_WRONG_INTERFACE_CALL;
3486 }
3487
3488 auto abilityRecord = Token::GetAbilityRecordByToken(token);
3489 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3490
3491 auto type = abilityRecord->GetAbilityInfo().type;
3492 auto extensionAbilityType = abilityRecord->GetAbilityInfo().extensionAbilityType;
3493
3494 if (type != AppExecFwk::AbilityType::EXTENSION ||
3495 extensionAbilityType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
3496 return ERR_INVALID_VALUE;
3497 }
3498
3499 auto userId = GetValidUserId(DEFAULT_INVAL_VALUE);
3500 auto connectManager = GetConnectManagerByUserId(userId);
3501 if (!connectManager) {
3502 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
3503 return ERR_INVALID_VALUE;
3504 }
3505 return connectManager->TerminateAbility(token);
3506 }
3507
BackToCallerAbilityWithResult(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant, int64_t callerRequestCode)3508 int AbilityManagerService::BackToCallerAbilityWithResult(const sptr<IRemoteObject> &token, int resultCode,
3509 const Want *resultWant, int64_t callerRequestCode)
3510 {
3511 auto abilityRecord = Token::GetAbilityRecordByToken(token);
3512 if (!abilityRecord) {
3513 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
3514 return ERR_INVALID_VALUE;
3515 }
3516 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3517 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3518 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3519 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3520 return uiAbilityManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant,
3521 callerRequestCode);
3522 }
3523 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3524 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3525 return missionListManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant, callerRequestCode);
3526 }
3527
CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)3528 int AbilityManagerService::CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3529 {
3530 EventInfo eventInfo;
3531 SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3532 return TerminateAbilityWithFlag(token, resultCode, resultWant, false);
3533 }
3534
TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant, bool flag)3535 int AbilityManagerService::TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode,
3536 const Want *resultWant, bool flag)
3537 {
3538 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3539 TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ability begin, flag:%{public}d.", flag);
3540 if (!VerificationAllToken(token)) {
3541 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
3542 return ERR_INVALID_VALUE;
3543 }
3544
3545 auto abilityRecord = Token::GetAbilityRecordByToken(token);
3546 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3547 if (!JudgeSelfCalled(abilityRecord)) {
3548 return CHECK_PERMISSION_FAILED;
3549 }
3550
3551 if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) {
3552 TAG_LOGE(AAFwkTag::ABILITYMGR, "system ui not allow terminate");
3553 return ERR_INVALID_VALUE;
3554 }
3555
3556 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
3557 auto type = abilityRecord->GetAbilityInfo().type;
3558 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
3559 auto connectManager = GetConnectManagerByUserId(userId);
3560 if (!connectManager) {
3561 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null. userId=%{public}d", userId);
3562 return ERR_INVALID_VALUE;
3563 }
3564 return connectManager->TerminateAbility(token);
3565 }
3566
3567 if (type == AppExecFwk::AbilityType::DATA) {
3568 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot terminate, use 'ReleaseDataAbility()'");
3569 return ERR_WRONG_INTERFACE_CALL;
3570 }
3571
3572 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3573 return ERR_WOULD_BLOCK;
3574 }
3575
3576 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3577 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3578 if (missionListManager) {
3579 return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag);
3580 }
3581 TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListManager null ownerUserId=%{public}d", ownerUserId);
3582 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3583 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3584 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3585 return uiAbilityManager->CloseUIAbility(abilityRecord, resultCode, resultWant, false);
3586 }
3587 return ERR_INVALID_VALUE;
3588 }
3589
TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode, const Want *resultWant)3590 int AbilityManagerService::TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode,
3591 const Want *resultWant)
3592 {
3593 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3594 TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ui extension ability begin.");
3595 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3596 auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3597 std::shared_ptr<AbilityConnectManager> connectManager;
3598 std::shared_ptr<AbilityRecord> targetRecord;
3599 GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3600 CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3601 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3602
3603 // self terminate or caller terminate is allowed.
3604 if (!(JudgeSelfCalled(targetRecord) || (abilityRecord != nullptr && JudgeSelfCalled(abilityRecord)))) {
3605 return CHECK_PERMISSION_FAILED;
3606 }
3607
3608 auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3609 if (result != ERR_OK) {
3610 TAG_LOGE(AAFwkTag::ABILITYMGR, "judgeAbilityVisibleControl error");
3611 return result;
3612 }
3613
3614 if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3615 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot terminate except ui extension ability");
3616 return ERR_WRONG_INTERFACE_CALL;
3617 }
3618
3619 TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension persistentId: %{public}d, element: %{public}s.",
3620 extensionSessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3621 connectManager->TerminateAbilityWindowLocked(targetRecord, extensionSessionInfo);
3622 return ERR_OK;
3623 }
3624
CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)3625 int AbilityManagerService::CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
3626 {
3627 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3628 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3629 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
3630 return ERR_INVALID_VALUE;
3631 }
3632
3633 if (!IsCallerSceneBoard()) {
3634 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3635 return ERR_WRONG_INTERFACE_CALL;
3636 }
3637
3638 SetMinimizedDuringFreeInstall(sessionInfo);
3639
3640 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3641 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3642 TAG_LOGI(AAFwkTag::ABILITYMGR,
3643 "close session: %{public}d, resultCode: %{public}d", sessionInfo->persistentId, sessionInfo->resultCode);
3644 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3645 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3646 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3647 return ERR_WOULD_BLOCK;
3648 }
3649
3650 if (sessionInfo->isClearSession) {
3651 const auto &abilityInfo = abilityRecord->GetAbilityInfo();
3652 std::string abilityName = abilityInfo.name;
3653 if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
3654 abilityName += std::to_string(sessionInfo->persistentId);
3655 }
3656 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
3657 DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
3658 }
3659 EventInfo eventInfo;
3660 eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
3661 eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
3662 SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3663 eventInfo.errCode = uiAbilityManager->CloseUIAbility(abilityRecord, sessionInfo->resultCode,
3664 &(sessionInfo->want), sessionInfo->isClearSession);
3665 if (eventInfo.errCode != ERR_OK) {
3666 SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
3667 }
3668 return eventInfo.errCode;
3669 }
3670
SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)3671 int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)
3672 {
3673 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3674 if (!CheckCallerIsDmsProcess()) {
3675 TAG_LOGE(AAFwkTag::ABILITYMGR, "check processName failed");
3676 return ERR_INVALID_VALUE;
3677 }
3678 int missionId = resultWant.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
3679 resultWant.RemoveParam(DMS_MISSION_ID);
3680 if (missionId == DEFAULT_DMS_MISSION_ID) {
3681 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionId empty");
3682 return ERR_INVALID_VALUE;
3683 }
3684 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
3685 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3686 auto uiAbilityManager = GetCurrentUIAbilityManager();
3687 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3688 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
3689 } else {
3690 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
3691 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3692 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
3693 }
3694 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3695
3696 abilityRecord->SetResult(std::make_shared<AbilityResult>(requestCode, resultCode, resultWant));
3697 abilityRecord->SendResult(0, 0);
3698 return ERR_OK;
3699 }
3700
StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId, const sptr<IRemoteObject> &callerToken)3701 int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId,
3702 const sptr<IRemoteObject> &callerToken)
3703 {
3704 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3705 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3706 Want remoteWant = want;
3707 UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(remoteWant, callerToken);
3708 if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
3709 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
3710 return ERR_INVALID_VALUE;
3711 }
3712 if (AbilityUtil::IsStartFreeInstall(remoteWant)) {
3713 return freeInstallManager_ == nullptr ? ERR_INVALID_VALUE :
3714 freeInstallManager_->StartRemoteFreeInstall(remoteWant, requestCode, validUserId, callerToken);
3715 }
3716 if (remoteWant.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
3717 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: try startAbilityForResult", __func__);
3718 int32_t missionId = -1;
3719 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3720 missionId = GetMissionIdByAbilityTokenInner(callerToken);
3721 if (!missionId) {
3722 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
3723 return ERR_INVALID_VALUE;
3724 }
3725 } else {
3726 missionId = GetMissionIdByAbilityToken(callerToken);
3727 }
3728 if (missionId < 0) {
3729 return ERR_INVALID_VALUE;
3730 }
3731 remoteWant.SetParam(DMS_MISSION_ID, missionId);
3732 }
3733
3734 int32_t callerUid = IPCSkeleton::GetCallingUid();
3735 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3736 UriUtils::GetInstance().FilterUriWithPermissionDms(remoteWant, accessToken);
3737 DistributedClient dmsClient;
3738 int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken);
3739 if (result != ERR_NONE) {
3740 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityManagerService::startRemoteAbility failed, result=%{public}d", result);
3741 }
3742 return result;
3743 }
3744
CheckIsRemote(const std::string& deviceId)3745 bool AbilityManagerService::CheckIsRemote(const std::string& deviceId)
3746 {
3747 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3748 if (deviceId.empty()) {
3749 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkIsRemote:deviceId empty");
3750 return false;
3751 }
3752 std::string localDeviceId;
3753 if (!GetLocalDeviceId(localDeviceId)) {
3754 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkIsRemote:get local deviceId failed");
3755 return false;
3756 }
3757 if (localDeviceId == deviceId) {
3758 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkIsRemote:deviceId local");
3759 return false;
3760 }
3761 TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str());
3762 return true;
3763 }
3764
CheckIfOperateRemote(const Want &want)3765 bool AbilityManagerService::CheckIfOperateRemote(const Want &want)
3766 {
3767 std::string deviceId = want.GetElement().GetDeviceID();
3768 if (deviceId.empty() || want.GetElement().GetBundleName().empty() ||
3769 want.GetElement().GetAbilityName().empty()) {
3770 TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty");
3771 return false;
3772 }
3773 return CheckIsRemote(deviceId);
3774 }
3775
GetLocalDeviceId(std::string& localDeviceId)3776 bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId)
3777 {
3778 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3779 auto localNode = std::make_unique<NodeBasicInfo>();
3780 int32_t errCode = GetLocalNodeDeviceInfo(DM_PKG_NAME, localNode.get());
3781 if (errCode != ERR_OK) {
3782 TAG_LOGE(AAFwkTag::ABILITYMGR, "err=%{public}d", errCode);
3783 return false;
3784 }
3785 if (localNode != nullptr) {
3786 localDeviceId = localNode->networkId;
3787 TAG_LOGD(AAFwkTag::ABILITYMGR, "get local deviceId, deviceId = %{public}s",
3788 AnonymizeDeviceId(localDeviceId).c_str());
3789 return true;
3790 }
3791 TAG_LOGE(AAFwkTag::ABILITYMGR, "localDeviceId null");
3792 return false;
3793 }
3794
AnonymizeDeviceId(const std::string& deviceId)3795 std::string AbilityManagerService::AnonymizeDeviceId(const std::string& deviceId)
3796 {
3797 if (deviceId.length() < NON_ANONYMIZE_LENGTH) {
3798 return EMPTY_DEVICE_ID;
3799 }
3800 std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
3801 anonDeviceId.append("******");
3802 return anonDeviceId;
3803 }
3804
MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)3805 int AbilityManagerService::MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)
3806 {
3807 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3808 TAG_LOGI(AAFwkTag::ABILITYMGR, "minimize ability, fromUser:%{public}d", fromUser);
3809 if (!VerificationAllToken(token)) {
3810 return ERR_INVALID_VALUE;
3811 }
3812
3813 auto abilityRecord = Token::GetAbilityRecordByToken(token);
3814 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3815 if (!JudgeSelfCalled(abilityRecord)) {
3816 return CHECK_PERMISSION_FAILED;
3817 }
3818
3819 auto type = abilityRecord->GetAbilityInfo().type;
3820 if (type != AppExecFwk::AbilityType::PAGE) {
3821 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except page ability");
3822 return ERR_WRONG_INTERFACE_CALL;
3823 }
3824
3825 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3826 return ERR_WOULD_BLOCK;
3827 }
3828
3829 auto missionListManager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
3830 if (!missionListManager) {
3831 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null");
3832 return ERR_INVALID_VALUE;
3833 }
3834 return missionListManager->MinimizeAbility(token, fromUser);
3835 }
3836
MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, bool fromUser)3837 int AbilityManagerService::MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo,
3838 bool fromUser)
3839 {
3840 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3841 TAG_LOGD(AAFwkTag::ABILITYMGR, "Minimize ui extension ability, fromUser:%{public}d.", fromUser);
3842 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3843 auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3844 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3845 if (!JudgeSelfCalled(abilityRecord)) {
3846 return CHECK_PERMISSION_FAILED;
3847 }
3848
3849 std::shared_ptr<AbilityConnectManager> connectManager;
3850 std::shared_ptr<AbilityRecord> targetRecord;
3851 GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3852 CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3853 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3854
3855 auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3856 if (result != ERR_OK) {
3857 TAG_LOGE(AAFwkTag::ABILITYMGR, "judgeAbilityVisibleControl error");
3858 return result;
3859 }
3860
3861 if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3862 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except ui extension ability");
3863 return ERR_WRONG_INTERFACE_CALL;
3864 }
3865 extensionSessionInfo->uiExtensionComponentId = (
3866 static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
3867 static_cast<uint64_t>(extensionSessionInfo->persistentId);
3868 TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
3869 extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3870 connectManager->BackgroundAbilityWindowLocked(targetRecord, extensionSessionInfo);
3871 return ERR_OK;
3872 }
3873
SetMinimizedDuringFreeInstall(const sptr<SessionInfo> &sessionInfo)3874 void AbilityManagerService::SetMinimizedDuringFreeInstall(const sptr<SessionInfo> &sessionInfo)
3875 {
3876 if (sessionInfo == nullptr) {
3877 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
3878 return;
3879 }
3880
3881 if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
3882 return;
3883 }
3884
3885 std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
3886 if (sessionId.empty()) {
3887 return;
3888 }
3889
3890 if (freeInstallManager_ == nullptr) {
3891 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
3892 return;
3893 }
3894 FreeInstallInfo taskInfo;
3895 if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
3896 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task with sessionId=%{public}s does not exist",
3897 sessionId.c_str());
3898 return;
3899 }
3900
3901 if (taskInfo.isFreeInstallFinished) {
3902 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
3903 return;
3904 }
3905
3906 {
3907 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
3908 auto it = preStartSessionMap_.find(sessionId);
3909 if (it == preStartSessionMap_.end()) {
3910 TAG_LOGI(AAFwkTag::ABILITYMGR, "session info with sessionId=%{public}s does not exist",
3911 sessionId.c_str());
3912 return;
3913 }
3914 it->second->isMinimizedDuringFreeInstall = true;
3915 }
3916 }
3917
MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser, uint32_t sceneFlag)3918 int AbilityManagerService::MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser,
3919 uint32_t sceneFlag)
3920 {
3921 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3922 TAG_LOGI(AAFwkTag::ABILITYMGR, "called, sceneFlag:%{public}u", sceneFlag);
3923 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3924 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
3925 return ERR_INVALID_VALUE;
3926 }
3927
3928 if (!IsCallerSceneBoard()) {
3929 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
3930 return ERR_WRONG_INTERFACE_CALL;
3931 }
3932
3933 SetMinimizedDuringFreeInstall(sessionInfo);
3934
3935 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3936 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3937 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3938 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3939 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3940 return ERR_WOULD_BLOCK;
3941 }
3942 return uiAbilityManager->MinimizeUIAbility(abilityRecord, fromUser, sceneFlag);
3943 }
3944
ConnectAbility( const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)3945 int32_t AbilityManagerService::ConnectAbility(
3946 const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)
3947 {
3948 return ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::SERVICE, userId);
3949 }
3950
ConnectAbilityCommon( const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)3951 int32_t AbilityManagerService::ConnectAbilityCommon(
3952 const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
3953 AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)
3954 {
3955 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3956 TAG_LOGI(AAFwkTag::ABILITYMGR,
3957 "elementUri:%{public}s", want.GetElement().GetURI().c_str());
3958 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3959 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3960 if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE && want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
3961 TAG_LOGE(AAFwkTag::ABILITYMGR, "error to have UISERVICEHOSTPROXY_KEY");
3962 return ERR_WRONG_INTERFACE_CALL;
3963 }
3964 if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && IsCrossUserCall(userId)) {
3965 CHECK_CALLER_IS_SYSTEM_APP;
3966 }
3967 EventInfo eventInfo = BuildEventInfo(want, userId);
3968
3969 int result;
3970 #ifdef WITH_DLP
3971 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
3972 if (result != ERR_OK) {
3973 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkDlpForExtension error");
3974 eventInfo.errCode = result;
3975 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3976 return result;
3977 }
3978 #endif // WITH_DLP
3979
3980 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
3981 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
3982 shouldBlockFunc);
3983 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3984 interceptorExecuter_->DoProcess(interceptorParam);
3985 if (result != ERR_OK) {
3986 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
3987 eventInfo.errCode = result;
3988 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3989 return result;
3990 }
3991
3992 int32_t validUserId = GetValidUserId(userId);
3993
3994 if (AbilityUtil::IsStartFreeInstall(want) && freeInstallManager_ != nullptr) {
3995 std::string localDeviceId;
3996 if (!GetLocalDeviceId(localDeviceId)) {
3997 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s:get Local deviceId failed", __func__);
3998 eventInfo.errCode = ERR_INVALID_VALUE;
3999 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4000 return ERR_INVALID_VALUE;
4001 }
4002 result = freeInstallManager_->ConnectFreeInstall(want, validUserId, callerToken, localDeviceId);
4003 if (result != ERR_OK) {
4004 eventInfo.errCode = result;
4005 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4006 return result;
4007 }
4008 }
4009
4010 Want abilityWant = want;
4011 AbilityRequest abilityRequest;
4012 std::string uri = abilityWant.GetUri().ToString();
4013 bool isFileUri = (abilityWant.GetUri().GetScheme() == "file");
4014 if (!uri.empty() && !isFileUri) {
4015 // if the want include uri, it may only has uri information. it is probably a datashare extension.
4016 TAG_LOGD(AAFwkTag::ABILITYMGR,
4017 "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
4018 AppExecFwk::ExtensionAbilityInfo extensionInfo;
4019 auto bms = AbilityUtil::GetBundleManagerHelper();
4020 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4021
4022 bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4023 if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4024 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid extension ability info");
4025 eventInfo.errCode = ERR_INVALID_VALUE;
4026 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4027 return ERR_INVALID_VALUE;
4028 }
4029 abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4030 }
4031
4032 if (CheckIfOperateRemote(abilityWant)) {
4033 TAG_LOGD(AAFwkTag::ABILITYMGR, "AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility");
4034 eventInfo.errCode = ConnectRemoteAbility(abilityWant, callerToken, connect->AsObject());
4035 if (eventInfo.errCode != ERR_OK) {
4036 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4037 }
4038 return eventInfo.errCode;
4039 }
4040 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityWant, callerToken);
4041
4042 if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4043 TAG_LOGD(AAFwkTag::ABILITYMGR, "invalid Token.");
4044 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr, extensionType);
4045 if (eventInfo.errCode != ERR_OK) {
4046 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4047 }
4048 return eventInfo.errCode;
4049 }
4050 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken, extensionType, nullptr,
4051 isQueryExtensionOnly);
4052 if (eventInfo.errCode != ERR_OK) {
4053 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4054 }
4055 return eventInfo.errCode;
4056 }
4057
ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect, const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)4058 int AbilityManagerService::ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect,
4059 const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4060 {
4061 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4062 TAG_LOGD(AAFwkTag::ABILITYMGR,
4063 "Connect ui extension called, bundlename: %{public}s, ability is %{public}s, userId is %{pravite}d",
4064 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
4065 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4066 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4067 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
4068
4069 if (IsCrossUserCall(userId)) {
4070 CHECK_CALLER_IS_SYSTEM_APP;
4071 }
4072
4073 EventInfo eventInfo = BuildEventInfo(want, userId);
4074 sptr<IRemoteObject> callerToken = sessionInfo->callerToken;
4075
4076 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
4077 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectUIExtensionAbility verificationAllToken failed");
4078 eventInfo.errCode = ERR_INVALID_VALUE;
4079 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4080 return ERR_INVALID_CALLER;
4081 }
4082
4083 int result;
4084 #ifdef WITH_DLP
4085 result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
4086 if (result != ERR_OK) {
4087 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkDlpForExtension error");
4088 eventInfo.errCode = result;
4089 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4090 return result;
4091 }
4092 #endif // WITH_DLP
4093
4094 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
4095 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr,
4096 shouldBlockFunc);
4097 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
4098 interceptorExecuter_->DoProcess(interceptorParam);
4099 if (result != ERR_OK) {
4100 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
4101 eventInfo.errCode = result;
4102 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4103 return result;
4104 }
4105
4106 int32_t validUserId = GetValidUserId(userId);
4107
4108 Want abilityWant = want;
4109 AbilityRequest abilityRequest;
4110 std::string uri = abilityWant.GetUri().ToString();
4111 if (!uri.empty()) {
4112 // if the want include uri, it may only has uri information.
4113 TAG_LOGI(AAFwkTag::ABILITYMGR,
4114 "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
4115 AppExecFwk::ExtensionAbilityInfo extensionInfo;
4116 auto bms = AbilityUtil::GetBundleManagerHelper();
4117 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
4118
4119 bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
4120 if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
4121 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid extension ability info");
4122 eventInfo.errCode = ERR_INVALID_VALUE;
4123 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4124 return ERR_INVALID_VALUE;
4125 }
4126 abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
4127 }
4128
4129 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityWant, callerToken);
4130
4131 if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
4132 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s invalid Token", __func__);
4133 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr,
4134 AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4135 if (eventInfo.errCode != ERR_OK) {
4136 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4137 }
4138 return eventInfo.errCode;
4139 }
4140 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken,
4141 AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
4142 if (eventInfo.errCode != ERR_OK) {
4143 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4144 }
4145 return eventInfo.errCode;
4146 }
4147
BuildEventInfo(const Want &want, int32_t userId)4148 EventInfo AbilityManagerService::BuildEventInfo(const Want &want, int32_t userId)
4149 {
4150 EventInfo eventInfo;
4151 eventInfo.userId = userId;
4152 eventInfo.bundleName = want.GetElement().GetBundleName();
4153 eventInfo.moduleName = want.GetElement().GetModuleName();
4154 eventInfo.abilityName = want.GetElement().GetAbilityName();
4155 return eventInfo;
4156 }
4157
DisconnectAbility(sptr<IAbilityConnection> connect)4158 int AbilityManagerService::DisconnectAbility(sptr<IAbilityConnection> connect)
4159 {
4160 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4161 TAG_LOGI(AAFwkTag::ABILITYMGR, "Disconnect ability begin.");
4162 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
4163 int err = DisconnectLocalAbility(connect);
4164 if (err == ERR_OK) {
4165 return ERR_OK;
4166 }
4167 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
4168 int remoteErr = DisconnectRemoteAbility(connect->AsObject());
4169 if (remoteErr == ERR_OK) {
4170 return ERR_OK;
4171 }
4172 if (remoteErr != INVALID_PARAMETERS_ERR &&
4173 remoteErr != CONNECTION_NOT_EXIST &&
4174 err == CONNECTION_NOT_EXIST) {
4175 err = remoteErr;
4176 }
4177 TAG_LOGE(AAFwkTag::ABILITYMGR, "Disconnect ability error %{public}d", err);
4178 EventInfo eventInfo;
4179 eventInfo.errCode = err;
4180 EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
4181 return err;
4182 }
4183
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)4184 int32_t AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId,
4185 const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
4186 AppExecFwk::ExtensionAbilityType extensionType, const sptr<SessionInfo> &sessionInfo,
4187 bool isQueryExtensionOnly, sptr<UIExtensionAbilityConnectInfo> connectInfo)
4188 {
4189 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4190 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4191 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
4192 bool isEnterpriseAdmin = AAFwk::UIExtensionUtils::IsEnterpriseAdmin(extensionType);
4193 if (!isEnterpriseAdmin && !JudgeMultiUserConcurrency(userId)) {
4194 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
4195 return ERR_CROSS_USER;
4196 }
4197
4198 AbilityRequest abilityRequest;
4199 ErrCode result = ERR_OK;
4200 if (isQueryExtensionOnly ||
4201 AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4202 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, userId);
4203 } else {
4204 result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId);
4205 }
4206 abilityRequest.sessionInfo = sessionInfo;
4207
4208 Want requestWant = want;
4209 CHECK_POINTER_AND_RETURN_LOG(connect, ERR_INVALID_VALUE, "connect is nullptr");
4210 TAG_LOGD(AAFwkTag::ABILITYMGR, "requestWant SetParam success");
4211
4212 if (result != ERR_OK) {
4213 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate request error");
4214 return result;
4215 }
4216 result = CheckPermissionForUIService(extensionType, want, abilityRequest);
4217 if (result != ERR_OK) {
4218 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkPermissionForUIService failed");
4219 return result;
4220 }
4221
4222 auto abilityInfo = abilityRequest.abilityInfo;
4223 if (abilityInfo.isStageBasedModel) {
4224 bool isService = (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE);
4225 if (isService && extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
4226 TAG_LOGE(AAFwkTag::ABILITYMGR, "Service extension type, please use ConnectAbility");
4227 return ERR_WRONG_INTERFACE_CALL;
4228 }
4229 // not allow app to connect other extension by using connectServiceExtensionAbility
4230 if (callerToken && extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && !isService) {
4231 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability, type not service");
4232 return TARGET_ABILITY_NOT_SERVICE;
4233 }
4234 }
4235 int32_t validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : userId;
4236 TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
4237 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
4238
4239 result = CheckStaticCfgPermission(abilityRequest, false, -1);
4240 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
4241 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result=%{public}d", result);
4242 return ERR_STATIC_CFG_PERMISSION;
4243 }
4244
4245 AppExecFwk::ExtensionAbilityType targetExtensionType = abilityInfo.extensionAbilityType;
4246 TAG_LOGD(AAFwkTag::ABILITYMGR, "extension type %{public}d.", targetExtensionType);
4247 if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4248 if (!AAFwk::UIExtensionUtils::IsUIExtension(targetExtensionType)
4249 && targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW) {
4250 TAG_LOGE(AAFwkTag::ABILITYMGR, "UI extension, target ability not UI extension");
4251 return ERR_WRONG_INTERFACE_CALL;
4252 }
4253
4254 // Cause window has used this api, don't check it when type is window.
4255 if (targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW &&
4256 !PermissionVerification::GetInstance()->VerifyCallingPermission(
4257 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY)) {
4258 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
4259 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY);
4260 return ERR_PERMISSION_DENIED;
4261 }
4262 }
4263
4264 auto type = abilityInfo.type;
4265 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4266 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability failed, target ability not service");
4267 return TARGET_ABILITY_NOT_SERVICE;
4268 }
4269
4270 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
4271 false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
4272 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
4273 afterCheckExecuter_->DoProcess(afterCheckParam);
4274 if (result != ERR_OK) {
4275 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
4276 return result;
4277 }
4278
4279 result = CheckCallServicePermission(abilityRequest);
4280 if (result != ERR_OK) {
4281 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s checkCallServicePermission error", __func__);
4282 return result;
4283 }
4284
4285 if (!ExtensionPermissionsUtil::CheckSAPermission(targetExtensionType)) {
4286 TAG_LOGE(AAFwkTag::ABILITYMGR, "SA doesn't have target extension permission");
4287 return CHECK_PERMISSION_FAILED;
4288 }
4289
4290 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
4291 if (result != ERR_OK) {
4292 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectAbility: app data ability preloading failed, '%{public}s', %{public}d",
4293 abilityInfo.bundleName.c_str(),
4294 result);
4295 return result;
4296 }
4297
4298 auto connectManager = GetConnectManagerByUserId(validUserId);
4299 if (connectManager == nullptr) {
4300 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", validUserId);
4301 return ERR_INVALID_VALUE;
4302 }
4303
4304 SetAbilityRequestSessionInfo(abilityRequest, targetExtensionType);
4305 if (targetExtensionType != AppExecFwk::ExtensionAbilityType::REMOTE_NOTIFICATION) {
4306 // this extension type is reported in connectManager instead of here
4307 ReportEventToRSS(abilityInfo, callerToken);
4308 }
4309 UriUtils::GetInstance().CheckUriPermissionForServiceExtension(const_cast<Want &>(abilityRequest.want),
4310 abilityRequest.abilityInfo.extensionAbilityType);
4311 return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo);
4312 }
4313
ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken, const sptr<IRemoteObject> &connect)4314 int AbilityManagerService::ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken,
4315 const sptr<IRemoteObject> &connect)
4316 {
4317 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin connectAbilityRemote", __func__);
4318 UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(want, callerToken);
4319 if (AddStartControlParam(want, callerToken) != ERR_OK) {
4320 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
4321 return ERR_INVALID_VALUE;
4322 }
4323 DistributedClient dmsClient;
4324 return dmsClient.ConnectRemoteAbility(want, connect);
4325 }
4326
DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)4327 int AbilityManagerService::DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)
4328 {
4329 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4330 auto currentConnectManager = GetCurrentConnectManager();
4331 CHECK_POINTER_AND_RETURN(currentConnectManager, ERR_NO_INIT);
4332 if (currentConnectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4333 return ERR_OK;
4334 }
4335 // If current connectManager does not exist connect, then try connectManagerU0
4336 auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
4337 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4338 if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4339 return ERR_OK;
4340 }
4341
4342 auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
4343 if (userId == U0_USER_ID) {
4344 auto connectManagers = GetConnectManagers();
4345 for (auto& item : connectManagers) {
4346 if (item.second && item.second->DisconnectAbilityLocked(connect) == ERR_OK) {
4347 return ERR_OK;
4348 }
4349 }
4350 }
4351
4352 // EnterpriseAdminExtensionAbility Scene
4353 connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT);
4354 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4355 return connectManager->DisconnectAbilityLocked(connect);
4356 }
4357
DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)4358 int AbilityManagerService::DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)
4359 {
4360 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
4361 int32_t callerUid = IPCSkeleton::GetCallingUid();
4362 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4363 DistributedClient dmsClient;
4364 return dmsClient.DisconnectRemoteAbility(connect, callerUid, accessToken);
4365 }
4366
ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId, int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)4367 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
4368 int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
4369 {
4370 CHECK_CALLER_IS_SYSTEM_APP;
4371 TAG_LOGI(AAFwkTag::ABILITYMGR, "continueMission missionId: %{public}d", missionId);
4372 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4373 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4374 return CHECK_PERMISSION_FAILED;
4375 }
4376
4377 DistributedClient dmsClient;
4378 return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams);
4379 }
4380
ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo, const sptr<IRemoteObject> &callback)4381 int AbilityManagerService::ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,
4382 const sptr<IRemoteObject> &callback)
4383 {
4384 CHECK_CALLER_IS_SYSTEM_APP;
4385 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
4386 AAFWK::ContinueRadar::GetInstance().ClickIconContinue("ContinueMission");
4387 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4388 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4389 return CHECK_PERMISSION_FAILED;
4390 }
4391
4392 DistributedClient dmsClient;
4393 return dmsClient.ContinueMission(continueMissionInfo, callback);
4394 }
4395
ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)4396 int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)
4397 {
4398 TAG_LOGI(AAFwkTag::ABILITYMGR,
4399 "ContinueAbility missionId = %{public}d, version = %{public}u.", missionId, versionCode);
4400 if (!CheckCallerIsDmsProcess()) {
4401 TAG_LOGE(AAFwkTag::ABILITYMGR, "check processName failed");
4402 return ERR_INVALID_VALUE;
4403 }
4404
4405 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4406 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4407 auto uiAbilityManager = GetCurrentUIAbilityManager();
4408 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4409 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4410 } else {
4411 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4412 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4413 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4414 }
4415 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4416
4417 abilityRecord->ContinueAbility(deviceId, versionCode);
4418 return ERR_OK;
4419 }
4420
StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)4421 int AbilityManagerService::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)
4422 {
4423 TAG_LOGI(AAFwkTag::ABILITYMGR, "start continuation");
4424 if (!CheckIfOperateRemote(want)) {
4425 TAG_LOGE(AAFwkTag::ABILITYMGR, "deviceId or bundleName or abilityName empty");
4426 return ERR_INVALID_VALUE;
4427 }
4428 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4429
4430 int32_t appUid = IPCSkeleton::GetCallingUid();
4431 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4432 TAG_LOGI(AAFwkTag::ABILITYMGR,
4433 "AbilityManagerService::try startContinuation");
4434 int32_t missionId = -1;
4435 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4436 missionId = GetMissionIdByAbilityTokenInner(abilityToken);
4437 if (!missionId) {
4438 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
4439 return ERR_INVALID_VALUE;
4440 }
4441 } else {
4442 missionId = GetMissionIdByAbilityToken(abilityToken);
4443 }
4444 if (missionId < 0) {
4445 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get missionId");
4446 return ERR_INVALID_VALUE;
4447 }
4448 AAFWK::ContinueRadar::GetInstance().SaveDataRemoteWant("StartContinuation");
4449 DistributedClient dmsClient;
4450 auto result = dmsClient.StartContinuation(want, missionId, appUid, status, accessToken);
4451 if (result != ERR_OK) {
4452 TAG_LOGE(AAFwkTag::ABILITYMGR, "startContinuation failed, result=%{public}d, notify caller", result);
4453 NotifyContinuationResult(missionId, result);
4454 }
4455 return result;
4456 }
4457
NotifyCompleteContinuation(const std::string &deviceId, int32_t sessionId, bool isSuccess)4458 void AbilityManagerService::NotifyCompleteContinuation(const std::string &deviceId,
4459 int32_t sessionId, bool isSuccess)
4460 {
4461 TAG_LOGI(AAFwkTag::ABILITYMGR, "notifyCompleteContinuation");
4462 AAFWK::ContinueRadar::GetInstance().ClickIconRecvOver("NotifyCompleteContinuation");
4463 sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4464 if (samgrProxy == nullptr) {
4465 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get samgrProxy");
4466 return;
4467 }
4468 sptr<IRemoteObject> bmsProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
4469 if (bmsProxy == nullptr) {
4470 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bms from samgr");
4471 return;
4472 }
4473 auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bmsProxy);
4474 if (bundleMgr == nullptr) {
4475 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bms");
4476 return;
4477 }
4478 int32_t callerUid = IPCSkeleton::GetCallingUid();
4479 std::string callerBundleName;
4480 // reset ipc identity
4481 auto identity = IPCSkeleton::ResetCallingIdentity();
4482 bool result = bundleMgr->GetBundleNameForUid(callerUid, callerBundleName);
4483 // set ipc identity to raw
4484 IPCSkeleton::SetCallingIdentity(identity);
4485 TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName: %{public}s", callerBundleName.c_str());
4486 DistributedClient dmsClient;
4487 dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess, callerBundleName);
4488 }
4489
NotifyContinuationResult(int32_t missionId, int32_t result)4490 int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result)
4491 {
4492 TAG_LOGI(AAFwkTag::ABILITYMGR, "notify continuation result : %{public}d", result);
4493
4494 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4495 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4496 auto uiAbilityManager = GetCurrentUIAbilityManager();
4497 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4498 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4499 } else {
4500 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4501 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4502 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4503 }
4504 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4505
4506 if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
4507 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
4508 return ERR_INVALID_VALUE;
4509 }
4510 abilityRecord->NotifyContinuationResult(result);
4511 return ERR_OK;
4512 }
4513
StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)4514 int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
4515 {
4516 CHECK_CALLER_IS_SYSTEM_APP;
4517 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4518 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4519 return CHECK_PERMISSION_FAILED;
4520 }
4521 DistributedClient dmsClient;
4522 return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag);
4523 }
4524
StopSyncRemoteMissions(const std::string& devId)4525 int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId)
4526 {
4527 CHECK_CALLER_IS_SYSTEM_APP;
4528 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4529 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4530 return CHECK_PERMISSION_FAILED;
4531 }
4532 DistributedClient dmsClient;
4533 return dmsClient.StopSyncRemoteMissions(devId);
4534 }
4535
RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)4536 int AbilityManagerService::RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4537 {
4538 if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4539 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
4540 return CHECK_PERMISSION_FAILED;
4541 }
4542 return DelayedSingleton<ConnectionStateManager>::GetInstance()->RegisterObserver(observer);
4543 }
4544
UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)4545 int AbilityManagerService::UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4546 {
4547 if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4548 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
4549 return CHECK_PERMISSION_FAILED;
4550 }
4551 return DelayedSingleton<ConnectionStateManager>::GetInstance()->UnregisterObserver(observer);
4552 }
4553
4554 #ifdef WITH_DLP
GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)4555 int AbilityManagerService::GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)
4556 {
4557 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4558 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't get dlp connection infos if caller not sa");
4559 return CHECK_PERMISSION_FAILED;
4560 }
4561 DelayedSingleton<ConnectionStateManager>::GetInstance()->GetDlpConnectionInfos(infos);
4562
4563 return ERR_OK;
4564 }
4565 #endif // WITH_DLP
4566
GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)4567 int AbilityManagerService::GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)
4568 {
4569 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4570 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller no sa no connection data");
4571 return CHECK_PERMISSION_FAILED;
4572 }
4573 DelayedSingleton<ConnectionStateManager>::GetInstance()->GetConnectionData(connectionData);
4574
4575 return ERR_OK;
4576 }
4577
RegisterMissionListener(const std::string &deviceId, const sptr<IRemoteMissionListener> &listener)4578 int AbilityManagerService::RegisterMissionListener(const std::string &deviceId,
4579 const sptr<IRemoteMissionListener> &listener)
4580 {
4581 CHECK_CALLER_IS_SYSTEM_APP;
4582 std::string localDeviceId;
4583 if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4584 TAG_LOGE(AAFwkTag::ABILITYMGR, "registerMissionListener:check deviceId failed");
4585 return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4586 }
4587 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4588 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4589 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4590 return CHECK_PERMISSION_FAILED;
4591 }
4592 DistributedClient dmsClient;
4593 return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4594 }
4595
RegisterOnListener(const std::string &type, const sptr<IRemoteOnListener> &listener)4596 int AbilityManagerService::RegisterOnListener(const std::string &type,
4597 const sptr<IRemoteOnListener> &listener)
4598 {
4599 CHECK_CALLER_IS_SYSTEM_APP;
4600 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4601 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4602 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4603 return CHECK_PERMISSION_FAILED;
4604 }
4605 DistributedClient dmsClient;
4606 int32_t callingUid = IPCSkeleton::GetCallingUid();
4607 return dmsClient.RegisterOnListener(type, listener->AsObject(), callingUid);
4608 }
4609
RegisterOffListener(const std::string &type, const sptr<IRemoteOnListener> &listener)4610 int AbilityManagerService::RegisterOffListener(const std::string &type,
4611 const sptr<IRemoteOnListener> &listener)
4612 {
4613 CHECK_CALLER_IS_SYSTEM_APP;
4614 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4615 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4616 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4617 return CHECK_PERMISSION_FAILED;
4618 }
4619 DistributedClient dmsClient;
4620 int32_t callingUid = IPCSkeleton::GetCallingUid();
4621 return dmsClient.RegisterOffListener(type, listener->AsObject(), callingUid);
4622 }
4623
UnRegisterMissionListener(const std::string &deviceId, const sptr<IRemoteMissionListener> &listener)4624 int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId,
4625 const sptr<IRemoteMissionListener> &listener)
4626 {
4627 CHECK_CALLER_IS_SYSTEM_APP;
4628 std::string localDeviceId;
4629 if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4630 TAG_LOGE(AAFwkTag::ABILITYMGR, "check deviceId failed");
4631 return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4632 }
4633 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4634 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4635 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4636 return CHECK_PERMISSION_FAILED;
4637 }
4638 DistributedClient dmsClient;
4639 return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4640 }
4641
GetWantSender( const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken, int32_t uid)4642 sptr<IWantSender> AbilityManagerService::GetWantSender(
4643 const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken,
4644 int32_t uid)
4645 {
4646 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4647 auto pendingWantManager = GetCurrentPendingWantManager();
4648 CHECK_POINTER_AND_RETURN(pendingWantManager, nullptr);
4649
4650 auto bms = AbilityUtil::GetBundleManagerHelper();
4651 CHECK_POINTER_AND_RETURN(bms, nullptr);
4652
4653 int32_t callerUid = IPCSkeleton::GetCallingUid();
4654 int32_t userId = wantSenderInfo.userId;
4655 int32_t bundleMgrResult = 0;
4656
4657 if (userId < 0) {
4658 if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4659 GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4660 TAG_LOGE(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid failed uid=%{public}d", callerUid);
4661 return nullptr;
4662 }
4663 }
4664 //sa caller and has uid,no need find from bms.
4665 bool isSpecifyUidBySa = (uid != -1) && (AAFwk::PermissionVerification::GetInstance()->IsSACall());
4666
4667 int32_t appUid = 0;
4668 int32_t appIndex = 0;
4669 if (!wantSenderInfo.allWants.empty()) {
4670 AppExecFwk::BundleInfo bundleInfo;
4671 std::string bundleName = wantSenderInfo.allWants.back().want.GetElement().GetBundleName();
4672 MultiAppUtils::GetRunningMultiAppIndex(bundleName, callerUid, appIndex);
4673 if (!isSpecifyUidBySa) {
4674 bundleMgrResult = IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName,
4675 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
4676 appIndex, bundleInfo, userId));
4677 if (bundleMgrResult == ERR_OK) {
4678 appUid = bundleInfo.uid;
4679 }
4680 } else {
4681 appUid = uid;
4682 }
4683 TAG_LOGD(AAFwkTag::ABILITYMGR, "App bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), appUid);
4684 }
4685 if (!CheckSenderWantInfo(callerUid, wantSenderInfo)) {
4686 TAG_LOGE(AAFwkTag::ABILITYMGR, "check bundleName failed");
4687 return nullptr;
4688 }
4689
4690 bool isSystemApp = false;
4691 if (!wantSenderInfo.bundleName.empty() && !isSpecifyUidBySa) {
4692 AppExecFwk::BundleInfo bundleInfo;
4693 bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(wantSenderInfo.bundleName,
4694 AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
4695 if (bundleMgrResult) {
4696 isSystemApp = bundleInfo.applicationInfo.isSystemApp;
4697 }
4698 }
4699
4700 TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName = %{public}s, appIndex:%{public}d",
4701 wantSenderInfo.bundleName.c_str(), appIndex);
4702 return pendingWantManager->GetWantSender(callerUid, appUid, isSystemApp, wantSenderInfo, callerToken, appIndex);
4703 }
4704
SendWantSender(sptr<IWantSender> target, const SenderInfo &senderInfo)4705 int AbilityManagerService::SendWantSender(sptr<IWantSender> target, const SenderInfo &senderInfo)
4706 {
4707 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
4708 auto pendingWantManager = GetCurrentPendingWantManager();
4709 CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4710 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4711 return pendingWantManager->SendWantSender(target, senderInfo);
4712 }
4713
CancelWantSender(const sptr<IWantSender> &sender)4714 void AbilityManagerService::CancelWantSender(const sptr<IWantSender> &sender)
4715 {
4716 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4717 auto pendingWantManager = GetCurrentPendingWantManager();
4718 CHECK_POINTER(pendingWantManager);
4719 CHECK_POINTER(sender);
4720
4721 sptr<IRemoteObject> obj = sender->AsObject();
4722 if (!obj || obj->IsProxyObject()) {
4723 TAG_LOGE(AAFwkTag::ABILITYMGR, "obj null or proxy obj");
4724 return;
4725 }
4726
4727 auto bms = AbilityUtil::GetBundleManagerHelper();
4728 CHECK_POINTER(bms);
4729
4730 int32_t callerUid = IPCSkeleton::GetCallingUid();
4731 sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
4732
4733 int userId = -1;
4734 if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4735 GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4736 TAG_LOGE(AAFwkTag::ABILITYMGR, "getOsAccountLocalIdFromUid failed uid=%{public}d", callerUid);
4737 return;
4738 }
4739 bool isSystemApp = false;
4740 if (record->GetKey() != nullptr && !record->GetKey()->GetBundleName().empty()) {
4741 AppExecFwk::BundleInfo bundleInfo;
4742 bool bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(record->GetKey()->GetBundleName(),
4743 AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
4744 if (!bundleMgrResult) {
4745 TAG_LOGE(AAFwkTag::ABILITYMGR, "getBundleInfo fail");
4746 return;
4747 }
4748 isSystemApp = bundleInfo.applicationInfo.isSystemApp;
4749 }
4750
4751 pendingWantManager->CancelWantSender(isSystemApp, sender);
4752 }
4753
GetPendingWantUid(const sptr<IWantSender> &target)4754 int AbilityManagerService::GetPendingWantUid(const sptr<IWantSender> &target)
4755 {
4756 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
4757 auto pendingWantManager = GetCurrentPendingWantManager();
4758 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4759 if (target == nullptr) {
4760 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
4761 return -1;
4762 }
4763 return pendingWantManager->GetPendingWantUid(target);
4764 }
4765
GetPendingWantUserId(const sptr<IWantSender> &target)4766 int AbilityManagerService::GetPendingWantUserId(const sptr<IWantSender> &target)
4767 {
4768 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
4769 auto pendingWantManager = GetCurrentPendingWantManager();
4770 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4771 if (target == nullptr) {
4772 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
4773 return -1;
4774 }
4775 return pendingWantManager->GetPendingWantUserId(target);
4776 }
4777
GetPendingWantBundleName(const sptr<IWantSender> &target)4778 std::string AbilityManagerService::GetPendingWantBundleName(const sptr<IWantSender> &target)
4779 {
4780 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
4781 AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantBundleName");
4782 auto pendingWantManager = GetCurrentPendingWantManager();
4783 CHECK_POINTER_AND_RETURN(pendingWantManager, "");
4784 CHECK_POINTER_AND_RETURN(target, "");
4785 return pendingWantManager->GetPendingWantBundleName(target);
4786 }
4787
GetPendingWantCode(const sptr<IWantSender> &target)4788 int AbilityManagerService::GetPendingWantCode(const sptr<IWantSender> &target)
4789 {
4790 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin", __func__);
4791 auto pendingWantManager = GetCurrentPendingWantManager();
4792 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4793 if (target == nullptr) {
4794 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
4795 return -1;
4796 }
4797 return pendingWantManager->GetPendingWantCode(target);
4798 }
4799
GetPendingWantType(const sptr<IWantSender> &target)4800 int AbilityManagerService::GetPendingWantType(const sptr<IWantSender> &target)
4801 {
4802 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
4803 AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantType");
4804 auto pendingWantManager = GetCurrentPendingWantManager();
4805 CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4806 if (target == nullptr) {
4807 TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target null", __func__);
4808 return -1;
4809 }
4810 return pendingWantManager->GetPendingWantType(target);
4811 }
4812
RegisterCancelListener(const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)4813 void AbilityManagerService::RegisterCancelListener(const sptr<IWantSender> &sender,
4814 const sptr<IWantReceiver> &receiver)
4815 {
4816 TAG_LOGI(AAFwkTag::ABILITYMGR, "register cancel listener");
4817 auto pendingWantManager = GetCurrentPendingWantManager();
4818 CHECK_POINTER(pendingWantManager);
4819 CHECK_POINTER(sender);
4820 CHECK_POINTER(receiver);
4821 pendingWantManager->RegisterCancelListener(sender, receiver);
4822 }
4823
UnregisterCancelListener( const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)4824 void AbilityManagerService::UnregisterCancelListener(
4825 const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)
4826 {
4827 TAG_LOGI(AAFwkTag::ABILITYMGR, "unregister cancel listener");
4828 auto pendingWantManager = GetCurrentPendingWantManager();
4829 CHECK_POINTER(pendingWantManager);
4830 CHECK_POINTER(sender);
4831 CHECK_POINTER(receiver);
4832 pendingWantManager->UnregisterCancelListener(sender, receiver);
4833 }
4834
GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)4835 int AbilityManagerService::GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)
4836 {
4837 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4838 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get pending request want.");
4839 AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingRequestWant");
4840 auto pendingWantManager = GetCurrentPendingWantManager();
4841 CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4842 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4843 CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE);
4844 CHECK_CALLER_IS_SYSTEM_APP;
4845 return pendingWantManager->GetPendingRequestWant(target, want);
4846 }
4847
LockMissionForCleanup(int32_t missionId)4848 int AbilityManagerService::LockMissionForCleanup(int32_t missionId)
4849 {
4850 TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock for clean all, id=%{public}d", missionId);
4851 auto missionListManager = GetCurrentMissionListManager();
4852 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4853 CHECK_CALLER_IS_SYSTEM_APP;
4854
4855 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4856 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4857 return CHECK_PERMISSION_FAILED;
4858 }
4859 return missionListManager->SetMissionLockedState(missionId, true);
4860 }
4861
UnlockMissionForCleanup(int32_t missionId)4862 int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId)
4863 {
4864 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4865 TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock for clean all, id=%{public}d", missionId);
4866 auto missionListManager = GetCurrentMissionListManager();
4867 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4868 CHECK_CALLER_IS_SYSTEM_APP;
4869
4870 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4871 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4872 return CHECK_PERMISSION_FAILED;
4873 }
4874 return missionListManager->SetMissionLockedState(missionId, false);
4875 }
4876
SetLockedState(int32_t sessionId, bool lockedState)4877 void AbilityManagerService::SetLockedState(int32_t sessionId, bool lockedState)
4878 {
4879 TAG_LOGI(AAFwkTag::ABILITYMGR, "request lock abilityRecord, sessionId :%{public}d", sessionId);
4880 if (!IsCallerSceneBoard()) {
4881 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard, no allowed");
4882 return;
4883 }
4884 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4885 CHECK_POINTER(uiAbilityManager);
4886 auto abilityRecord = uiAbilityManager->GetAbilityRecordsById(sessionId);
4887 if (!abilityRecord) {
4888 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
4889 return;
4890 }
4891 abilityRecord->SetLockedState(lockedState);
4892 }
4893
RegisterMissionListener(const sptr<IMissionListener> &listener)4894 int AbilityManagerService::RegisterMissionListener(const sptr<IMissionListener> &listener)
4895 {
4896 TAG_LOGI(AAFwkTag::ABILITYMGR, "request registerMissionListener");
4897 auto missionListManager = GetCurrentMissionListManager();
4898 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4899 CHECK_CALLER_IS_SYSTEM_APP;
4900
4901 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4902 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4903 return CHECK_PERMISSION_FAILED;
4904 }
4905 return missionListManager->RegisterMissionListener(listener);
4906 }
4907
UnRegisterMissionListener(const sptr<IMissionListener> &listener)4908 int AbilityManagerService::UnRegisterMissionListener(const sptr<IMissionListener> &listener)
4909 {
4910 TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
4911 auto missionListManager = GetCurrentMissionListManager();
4912 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4913 CHECK_CALLER_IS_SYSTEM_APP;
4914
4915 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4916 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4917 return CHECK_PERMISSION_FAILED;
4918 }
4919 return missionListManager->UnRegisterMissionListener(listener);
4920 }
4921
GetMissionInfos(const std::string& deviceId, int32_t numMax, std::vector<MissionInfo> &missionInfos)4922 int AbilityManagerService::GetMissionInfos(const std::string& deviceId, int32_t numMax,
4923 std::vector<MissionInfo> &missionInfos)
4924 {
4925 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4926 TAG_LOGI(AAFwkTag::ABILITYMGR, "request getMissionInfos");
4927 auto missionListManager = GetCurrentMissionListManager();
4928 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4929 CHECK_CALLER_IS_SYSTEM_APP;
4930
4931 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4932 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4933 return CHECK_PERMISSION_FAILED;
4934 }
4935
4936 if (CheckIsRemote(deviceId)) {
4937 return GetRemoteMissionInfos(deviceId, numMax, missionInfos);
4938 }
4939
4940 return missionListManager->GetMissionInfos(numMax, missionInfos);
4941 }
4942
GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax, std::vector<MissionInfo> &missionInfos)4943 int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax,
4944 std::vector<MissionInfo> &missionInfos)
4945 {
4946 TAG_LOGI(AAFwkTag::ABILITYMGR, "getRemoteMissionInfos");
4947 DistributedClient dmsClient;
4948 int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos);
4949 if (result != ERR_OK) {
4950 TAG_LOGE(AAFwkTag::ABILITYMGR, "getRemoteMissionInfos failed, result=%{public}d", result);
4951 return result;
4952 }
4953 return ERR_OK;
4954 }
4955
GetMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo)4956 int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId,
4957 MissionInfo &missionInfo)
4958 {
4959 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4960 TAG_LOGI(AAFwkTag::ABILITYMGR, "request getMissionInfo, missionId:%{public}d", missionId);
4961 auto missionListManager = GetCurrentMissionListManager();
4962 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4963 CHECK_CALLER_IS_SYSTEM_APP;
4964
4965 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4966 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
4967 return CHECK_PERMISSION_FAILED;
4968 }
4969
4970 if (CheckIsRemote(deviceId)) {
4971 return GetRemoteMissionInfo(deviceId, missionId, missionInfo);
4972 }
4973
4974 return missionListManager->GetMissionInfo(missionId, missionInfo);
4975 }
4976
GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId, MissionInfo &missionInfo)4977 int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId,
4978 MissionInfo &missionInfo)
4979 {
4980 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4981 TAG_LOGI(AAFwkTag::ABILITYMGR, "getMissionInfoFromDms");
4982 std::vector<MissionInfo> missionVector;
4983 int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector);
4984 if (result != ERR_OK) {
4985 return result;
4986 }
4987 for (auto iter = missionVector.begin(); iter != missionVector.end(); iter++) {
4988 if (iter->id == missionId) {
4989 missionInfo = *iter;
4990 return ERR_OK;
4991 }
4992 }
4993 TAG_LOGW(AAFwkTag::ABILITYMGR, "missionId not found");
4994 return ERR_INVALID_VALUE;
4995 }
4996
CleanMission(int32_t missionId)4997 int AbilityManagerService::CleanMission(int32_t missionId)
4998 {
4999 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5000 TAG_LOGI(AAFwkTag::ABILITYMGR, "request cleanMission, missionId:%{public}d", missionId);
5001 auto missionListManager = GetCurrentMissionListManager();
5002 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5003 CHECK_CALLER_IS_SYSTEM_APP;
5004
5005 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5006 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5007 return CHECK_PERMISSION_FAILED;
5008 }
5009
5010 return missionListManager->ClearMission(missionId);
5011 }
5012
CleanAllMissions()5013 int AbilityManagerService::CleanAllMissions()
5014 {
5015 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5016 TAG_LOGI(AAFwkTag::ABILITYMGR, "request cleanAllMissions");
5017 auto missionListManager = GetCurrentMissionListManager();
5018 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5019 CHECK_CALLER_IS_SYSTEM_APP;
5020
5021 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5022 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5023 return CHECK_PERMISSION_FAILED;
5024 }
5025
5026 Want want;
5027 want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME);
5028 if (!IsAbilityControllerStart(want, AbilityConfig::LAUNCHER_BUNDLE_NAME)) {
5029 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", want.GetBundle().c_str());
5030 return ERR_WOULD_BLOCK;
5031 }
5032
5033 return missionListManager->ClearAllMissions();
5034 }
5035
MoveMissionToFront(int32_t missionId)5036 int AbilityManagerService::MoveMissionToFront(int32_t missionId)
5037 {
5038 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5039 TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5040 CHECK_CALLER_IS_SYSTEM_APP;
5041 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5042 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5043 return CHECK_PERMISSION_FAILED;
5044 }
5045
5046 if (!IsAbilityControllerStartById(missionId)) {
5047 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart false");
5048 return ERR_WOULD_BLOCK;
5049 }
5050
5051 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5052 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5053 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5054 return uiAbilityManager->MoveMissionToFront(missionId);
5055 }
5056
5057 auto missionListManager = GetCurrentMissionListManager();
5058 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5059 return missionListManager->MoveMissionToFront(missionId);
5060 }
5061
MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)5062 int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)
5063 {
5064 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5065 TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
5066 CHECK_CALLER_IS_SYSTEM_APP;
5067 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5068 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5069 return CHECK_PERMISSION_FAILED;
5070 }
5071
5072 if (!IsAbilityControllerStartById(missionId)) {
5073 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart false");
5074 return ERR_WOULD_BLOCK;
5075 }
5076
5077 auto options = std::make_shared<StartOptions>(startOptions);
5078 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5079 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
5080 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5081 return uiAbilityManager->MoveMissionToFront(missionId, options);
5082 }
5083
5084 auto missionListManager = GetCurrentMissionListManager();
5085 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
5086 return missionListManager->MoveMissionToFront(missionId, options);
5087 }
5088
MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)5089 int AbilityManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
5090 {
5091 CHECK_CALLER_IS_SYSTEM_APP;
5092 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5093 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5094 return CHECK_PERMISSION_FAILED;
5095 }
5096 #ifdef SUPPORT_SCREEN
5097 if (wmsHandler_) {
5098 auto ret = wmsHandler_->MoveMissionsToForeground(missionIds, topMissionId);
5099 if (ret) {
5100 TAG_LOGE(AAFwkTag::ABILITYMGR, "moveMissionsToForeground failed, missiondIds may invalid");
5101 return ERR_INVALID_VALUE;
5102 } else {
5103 return NO_ERROR;
5104 }
5105 }
5106 #endif // SUPPORT_SCREEN
5107 return ERR_NO_INIT;
5108 }
5109
MoveMissionsToBackground(const std::vector<int32_t>& missionIds, std::vector<int32_t>& result)5110 int AbilityManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
5111 std::vector<int32_t>& result)
5112 {
5113 CHECK_CALLER_IS_SYSTEM_APP;
5114 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
5115 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
5116 return CHECK_PERMISSION_FAILED;
5117 }
5118 #ifdef SUPPORT_SCREEN
5119 if (wmsHandler_) {
5120 auto ret = wmsHandler_->MoveMissionsToBackground(missionIds, result);
5121 if (ret) {
5122 TAG_LOGE(AAFwkTag::ABILITYMGR, "moveMissionsToBackground failed, missiondIds may invalid");
5123 return ERR_INVALID_VALUE;
5124 } else {
5125 return NO_ERROR;
5126 }
5127 }
5128 #endif // SUPPORT_SCREEN
5129 return ERR_NO_INIT;
5130 }
5131
GetMissionIdByToken(const sptr<IRemoteObject> &token)5132 int32_t AbilityManagerService::GetMissionIdByToken(const sptr<IRemoteObject> &token)
5133 {
5134 TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken.");
5135 auto abilityRecord = Token::GetAbilityRecordByToken(token);
5136 if (!abilityRecord) {
5137 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
5138 return ERR_INVALID_VALUE;
5139 }
5140 if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
5141 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
5142 return ERR_INVALID_VALUE;
5143 }
5144 return GetMissionIdByAbilityTokenInner(token);
5145 }
5146
IsAbilityControllerStartById(int32_t missionId)5147 bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId)
5148 {
5149 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5150 auto missionListWrap = GetMissionListWrap();
5151 if (missionListWrap == nullptr) {
5152 TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null");
5153 return true;
5154 }
5155 InnerMissionInfo innerMissionInfo;
5156 int getMission = missionListWrap->GetInnerMissionInfoById(missionId, innerMissionInfo);
5157 if (getMission != ERR_OK) {
5158 TAG_LOGE(AAFwkTag::ABILITYMGR,
5159 "cannot find mission info:%{public}d", missionId);
5160 return true;
5161 }
5162 if (!IsAbilityControllerStart(innerMissionInfo.missionInfo.want, innerMissionInfo.missionInfo.want.GetBundle())) {
5163 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s",
5164 innerMissionInfo.missionInfo.want.GetBundle().c_str());
5165 return false;
5166 }
5167 return true;
5168 }
5169
GetConnectRecordListByCallback( sptr<IAbilityConnection> callback)5170 std::list<std::shared_ptr<ConnectionRecord>> AbilityManagerService::GetConnectRecordListByCallback(
5171 sptr<IAbilityConnection> callback)
5172 {
5173 auto connectManager = GetCurrentConnectManager();
5174 CHECK_POINTER_AND_RETURN(connectManager, std::list<std::shared_ptr<ConnectionRecord>>());
5175 return connectManager->GetConnectRecordListByCallback(callback);
5176 }
5177
GenerateDataAbilityRequestByUri(const std::string& dataAbilityUri, AbilityRequest &abilityRequest, sptr<IRemoteObject> callerToken, int32_t userId)5178 bool AbilityManagerService::GenerateDataAbilityRequestByUri(const std::string& dataAbilityUri,
5179 AbilityRequest &abilityRequest, sptr<IRemoteObject> callerToken, int32_t userId)
5180 {
5181 auto bms = AbilityUtil::GetBundleManagerHelper();
5182 CHECK_POINTER_AND_RETURN(bms, false);
5183 TAG_LOGI(AAFwkTag::ABILITYMGR, "called userId %{public}d", userId);
5184 bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo));
5185 if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) {
5186 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid ability info acquiring");
5187 return false;
5188 }
5189 abilityRequest.callerToken = callerToken;
5190 return true;
5191 }
5192
AcquireDataAbility( const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)5193 sptr<IAbilityScheduler> AbilityManagerService::AcquireDataAbility(
5194 const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
5195 {
5196 auto localUri(uri);
5197 if (localUri.GetScheme() != AbilityConfig::SCHEME_DATA_ABILITY) {
5198 TAG_LOGE(AAFwkTag::ABILITYMGR, "acquire data ability invalid uri scheme");
5199 return nullptr;
5200 }
5201 std::vector<std::string> pathSegments;
5202 localUri.GetPathSegments(pathSegments);
5203 if (pathSegments.empty()) {
5204 TAG_LOGE(AAFwkTag::ABILITYMGR, "acquire data ability invalid uri path");
5205 return nullptr;
5206 }
5207
5208 auto userId = GetValidUserId(INVALID_USER_ID);
5209 AbilityRequest abilityRequest;
5210 if (!GenerateDataAbilityRequestByUri(localUri.ToString(), abilityRequest, callerToken, userId)) {
5211 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate data ability request failed");
5212 return nullptr;
5213 }
5214
5215 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5216 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5217 if (!isSaCall && CheckCallDataAbilityPermission(abilityRequest, isShellCall, isSaCall) != ERR_OK) {
5218 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid ability request info acquiring");
5219 return nullptr;
5220 }
5221
5222 TAG_LOGD(AAFwkTag::ABILITYMGR, "Query data ability info: %{public}s|%{public}s|%{public}s",
5223 abilityRequest.appInfo.name.c_str(), abilityRequest.appInfo.bundleName.c_str(),
5224 abilityRequest.abilityInfo.name.c_str());
5225
5226 if (CheckStaticCfgPermission(abilityRequest, false, -1, true, isSaCall) !=
5227 AppExecFwk::Constants::PERMISSION_GRANTED) {
5228 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission fail");
5229 return nullptr;
5230 }
5231
5232 if (!VerificationAllToken(callerToken)) {
5233 TAG_LOGI(AAFwkTag::ABILITYMGR, "verificationAllToken fail");
5234 return nullptr;
5235 }
5236
5237 if (abilityRequest.abilityInfo.applicationInfo.singleton) {
5238 userId = U0_USER_ID;
5239 }
5240
5241 std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5242 CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr);
5243 ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
5244 bool isNotHap = isSaCall || isShellCall;
5245 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
5246 return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap);
5247 }
5248
ReleaseDataAbility( sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)5249 int AbilityManagerService::ReleaseDataAbility(
5250 sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
5251 {
5252 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
5253 if (!dataAbilityScheduler || !callerToken) {
5254 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilitySchedule or callerToken null");
5255 return ERR_INVALID_VALUE;
5256 }
5257
5258 std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler);
5259 if (!dataAbilityManager) {
5260 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityScheduler absent");
5261 return ERR_INVALID_VALUE;
5262 }
5263
5264 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5265 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5266 bool isNotHap = isSaCall || isShellCall;
5267 return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isNotHap);
5268 }
5269
AttachAbilityThread( const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)5270 int AbilityManagerService::AttachAbilityThread(
5271 const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
5272 {
5273 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5274 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called", __func__);
5275 CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE);
5276 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5277 return ERR_INVALID_VALUE;
5278 }
5279 auto abilityRecord = Token::GetAbilityRecordByToken(token);
5280 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5281 if (!JudgeSelfCalled(abilityRecord)) {
5282 return CHECK_PERMISSION_FAILED;
5283 }
5284
5285 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5286 auto abilityInfo = abilityRecord->GetAbilityInfo();
5287 auto type = abilityInfo.type;
5288 // force timeout ability for test
5289 if (IsNeedTimeoutForTest(abilityInfo.name, AbilityRecord::ConvertAbilityState(AbilityState::INITIAL))) {
5290 TAG_LOGW(AAFwkTag::ABILITYMGR,
5291 "force timeout ability, state:INITIAL, ability:%{public}s", abilityInfo.name.c_str());
5292 return ERR_OK;
5293 }
5294 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5295 auto connectManager = GetConnectManagerByUserId(userId);
5296 if (!connectManager) {
5297 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
5298 return ERR_INVALID_VALUE;
5299 }
5300 return connectManager->AttachAbilityThreadLocked(scheduler, token);
5301 } else if (type == AppExecFwk::AbilityType::DATA) {
5302 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5303 if (!dataAbilityManager) {
5304 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
5305 return ERR_INVALID_VALUE;
5306 }
5307 return dataAbilityManager->AttachAbilityThread(scheduler, token);
5308 } else {
5309 FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::LOAD };
5310 std::string entry = "AbilityManagerService::AttachAbilityThread; the end of load lifecycle.";
5311 FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5312 int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5313 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5314 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5315 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5316 return uiAbilityManager->AttachAbilityThread(scheduler, token);
5317 }
5318 auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5319 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
5320 return missionListManager->AttachAbilityThread(scheduler, token);
5321 }
5322 }
5323
DumpSysInner( const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)5324 void AbilityManagerService::DumpSysInner(
5325 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5326 {
5327 std::vector<std::string> argList;
5328 SplitStr(args, " ", argList);
5329 if (argList.empty()) {
5330 return;
5331 }
5332
5333 DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5334 DumpSysStateInner(args, info, isClient, isUserID, userId);
5335 DumpSysPendingInner(args, info, isClient, isUserID, userId);
5336 DumpSysProcess(args, info, isClient, isUserID, userId);
5337 }
5338
DumpSysMissionListInner( const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)5339 void AbilityManagerService::DumpSysMissionListInner(
5340 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5341 {
5342 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5343 DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId);
5344 return;
5345 }
5346 std::shared_ptr<MissionListManagerInterface> targetManager;
5347 if (isUserID) {
5348 auto missionListManager = GetMissionListManagerByUserId(userId);
5349 if (missionListManager == nullptr) {
5350 info.push_back("error: No user found.");
5351 return;
5352 }
5353 targetManager = missionListManager;
5354 } else {
5355 targetManager = GetCurrentMissionListManager();
5356 }
5357
5358 CHECK_POINTER(targetManager);
5359
5360 std::vector<std::string> argList;
5361 SplitStr(args, " ", argList);
5362 if (argList.empty()) {
5363 return;
5364 }
5365
5366 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5367 targetManager->DumpMissionList(info, isClient, argList[1]);
5368 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5369 targetManager->DumpMissionList(info, isClient);
5370 } else {
5371 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5372 }
5373 }
5374
DumpSysMissionListInnerBySCB( const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)5375 void AbilityManagerService::DumpSysMissionListInnerBySCB(
5376 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5377 {
5378 if (!isUserID) {
5379 userId = GetUserId();
5380 }
5381
5382 std::vector<std::string> argList;
5383 SplitStr(args, " ", argList);
5384 if (argList.empty()) {
5385 return;
5386 }
5387
5388 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5389 CHECK_POINTER(uiAbilityManager);
5390 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5391 uiAbilityManager->DumpMissionList(info, isClient, argList[1]);
5392 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5393 uiAbilityManager->DumpMissionList(info, isClient);
5394 } else {
5395 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5396 }
5397 }
5398
DumpSysAbilityInner( const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)5399 void AbilityManagerService::DumpSysAbilityInner(
5400 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5401 {
5402 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5403 DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId);
5404 return;
5405 }
5406 std::shared_ptr<MissionListManagerInterface> targetManager;
5407 if (isUserID) {
5408 auto missionListManager = GetMissionListManagerByUserId(userId);
5409 if (missionListManager == nullptr) {
5410 info.push_back("error: No user found.");
5411 return;
5412 }
5413 targetManager = missionListManager;
5414 } else {
5415 targetManager = GetCurrentMissionListManager();
5416 }
5417
5418 CHECK_POINTER(targetManager);
5419
5420 std::vector<std::string> argList;
5421 SplitStr(args, " ", argList);
5422 if (argList.empty()) {
5423 return;
5424 }
5425 if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5426 TAG_LOGI(AAFwkTag::ABILITYMGR, "argList=%{public}s", argList[1].c_str());
5427 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5428 try {
5429 auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5430 targetManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5431 } catch (...) {
5432 TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5433 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5434 }
5435 } else {
5436 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5437 }
5438 }
5439
DumpSysAbilityInnerBySCB( const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)5440 void AbilityManagerService::DumpSysAbilityInnerBySCB(
5441 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5442 {
5443 if (!isUserID) {
5444 userId = GetUserId();
5445 }
5446
5447 std::vector<std::string> argList;
5448 SplitStr(args, " ", argList);
5449 if (argList.empty()) {
5450 return;
5451 }
5452 if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5453 TAG_LOGI(AAFwkTag::ABILITYMGR, "argList=%{public}s", argList[1].c_str());
5454 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5455 try {
5456 auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5457 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5458 CHECK_POINTER(uiAbilityManager);
5459 uiAbilityManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5460 } catch (...) {
5461 TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5462 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5463 }
5464 } else {
5465 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5466 }
5467 }
5468
DumpSysStateInner( const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)5469 void AbilityManagerService::DumpSysStateInner(
5470 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5471 {
5472 TAG_LOGI(AAFwkTag::ABILITYMGR, "dumpSysStateInner begin:%{public}s", args.c_str());
5473 std::shared_ptr<AbilityConnectManager> targetManager;
5474
5475 if (isUserID) {
5476 auto connectManager = GetConnectManagerByUserId(userId);
5477 if (connectManager == nullptr) {
5478 info.push_back("error: No user found.");
5479 return;
5480 }
5481 targetManager = connectManager;
5482 } else {
5483 targetManager = GetCurrentConnectManager();
5484 }
5485
5486 CHECK_POINTER(targetManager);
5487
5488 std::vector<std::string> argList;
5489 SplitStr(args, " ", argList);
5490 if (argList.empty()) {
5491 return;
5492 }
5493
5494 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5495 targetManager->DumpState(info, isClient, argList[1]);
5496 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5497 targetManager->DumpState(info, isClient);
5498 } else {
5499 TAG_LOGI(AAFwkTag::ABILITYMGR, "uri=%{public}s", argList[1].c_str());
5500 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5501 targetManager->DumpStateByUri(info, isClient, argList[1], params);
5502 }
5503 }
5504
DumpSysPendingInner( const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)5505 void AbilityManagerService::DumpSysPendingInner(
5506 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5507 {
5508 std::shared_ptr<PendingWantManager> targetManager;
5509 if (isUserID) {
5510 auto pendingWantManager = GetPendingWantManagerByUserId(userId);
5511 if (pendingWantManager == nullptr) {
5512 info.push_back("error: No user found.");
5513 return;
5514 }
5515 targetManager = pendingWantManager;
5516 } else {
5517 targetManager = GetCurrentPendingWantManager();
5518 }
5519
5520 CHECK_POINTER(targetManager);
5521
5522 std::vector<std::string> argList;
5523 SplitStr(args, " ", argList);
5524 if (argList.empty()) {
5525 return;
5526 }
5527
5528 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5529 targetManager->DumpByRecordId(info, argList[1]);
5530 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5531 targetManager->Dump(info);
5532 } else {
5533 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5534 }
5535 }
5536
DumpSysProcess( const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)5537 void AbilityManagerService::DumpSysProcess(
5538 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5539 {
5540 std::vector<std::string> argList;
5541 SplitStr(args, " ", argList);
5542 if (argList.empty()) {
5543 return;
5544 }
5545 std::vector<AppExecFwk::RunningProcessInfo> processInfos;
5546 int ret = 0;
5547 if (isUserID) {
5548 ret = GetProcessRunningInfosByUserId(processInfos, userId);
5549 } else {
5550 ret = GetProcessRunningInfos(processInfos);
5551 }
5552
5553 if (ret != ERR_OK || processInfos.size() == 0) {
5554 return;
5555 }
5556
5557 std::string dumpInfo = " AppRunningRecords:";
5558 info.push_back(dumpInfo);
5559 auto processInfoID = 0;
5560 auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false);
5561 for (const auto& processInfo : processInfos) {
5562 if (hasProcessName && argList[1] != processInfo.processName_) {
5563 continue;
5564 }
5565
5566 dumpInfo = " AppRunningRecord ID #" + std::to_string(processInfoID);
5567 processInfoID++;
5568 info.push_back(dumpInfo);
5569 dumpInfo = " process name [" + processInfo.processName_ + "]";
5570 info.push_back(dumpInfo);
5571 dumpInfo = " pid #" + std::to_string(processInfo.pid_) +
5572 " uid #" + std::to_string(processInfo.uid_);
5573 info.push_back(dumpInfo);
5574 auto appState = static_cast<AppState>(processInfo.state_);
5575 dumpInfo = " state #" + DelayedSingleton<AppScheduler>::GetInstance()->ConvertAppState(appState);
5576 info.push_back(dumpInfo);
5577 DumpUIExtensionRootHostRunningInfos(processInfo.pid_, info);
5578 DumpUIExtensionProviderRunningInfos(processInfo.pid_, info);
5579 }
5580 }
5581
DumpUIExtensionRootHostRunningInfos(pid_t pid, std::vector<std::string> &info)5582 void AbilityManagerService::DumpUIExtensionRootHostRunningInfos(pid_t pid, std::vector<std::string> &info)
5583 {
5584 auto appMgr = AppMgrUtil::GetAppMgr();
5585 if (appMgr == nullptr) {
5586 TAG_LOGW(AAFwkTag::ABILITYMGR, "get appMgr failed");
5587 return;
5588 }
5589
5590 std::vector<pid_t> hostPids;
5591 auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionRootHostPid(pid, hostPids));
5592 if (ret != ERR_OK) {
5593 TAG_LOGE(AAFwkTag::ABILITYMGR, "get root host process info faild");
5594 return;
5595 }
5596
5597 if (hostPids.size() == 0) {
5598 TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extenson root host of pid %{public}d.", pid);
5599 return;
5600 }
5601
5602 std::string temp;
5603 for (size_t i = 0; i < hostPids.size(); i++) {
5604 temp = " root caller #" + std::to_string(i);
5605 info.push_back(temp);
5606 temp = " pid #" + std::to_string(hostPids[i]);
5607 info.push_back(temp);
5608 }
5609 }
5610
DumpUIExtensionProviderRunningInfos(pid_t hostPid, std::vector<std::string> &info)5611 void AbilityManagerService::DumpUIExtensionProviderRunningInfos(pid_t hostPid, std::vector<std::string> &info)
5612 {
5613 auto appMgr = AppMgrUtil::GetAppMgr();
5614 if (appMgr == nullptr) {
5615 TAG_LOGW(AAFwkTag::ABILITYMGR, "get appMgr failed");
5616 return;
5617 }
5618
5619 std::vector<pid_t> providerPids;
5620 auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionProviderPid(hostPid, providerPids));
5621 if (ret != ERR_OK) {
5622 TAG_LOGE(AAFwkTag::ABILITYMGR, "get process info failed");
5623 return;
5624 }
5625
5626 if (providerPids.size() == 0) {
5627 TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extension provider of pid %{public}d.", hostPid);
5628 return;
5629 }
5630
5631 std::string temp;
5632 for (size_t i = 0; i < providerPids.size(); i++) {
5633 temp = " uiextension provider #" + std::to_string(i);
5634 info.push_back(temp);
5635 temp = " pid #" + std::to_string(providerPids[i]);
5636 info.push_back(temp);
5637 }
5638 }
5639
DataDumpSysStateInner( const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)5640 void AbilityManagerService::DataDumpSysStateInner(
5641 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5642 {
5643 std::shared_ptr<DataAbilityManager> targetManager;
5644 if (isUserID) {
5645 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5646 if (dataAbilityManager == nullptr) {
5647 info.push_back("error: No user found.");
5648 return;
5649 }
5650 targetManager = dataAbilityManager;
5651 } else {
5652 targetManager = GetCurrentDataAbilityManager();
5653 }
5654
5655 CHECK_POINTER(targetManager);
5656
5657 std::vector<std::string> argList;
5658 SplitStr(args, " ", argList);
5659 if (argList.empty()) {
5660 return;
5661 }
5662 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5663 targetManager->DumpSysState(info, isClient, argList[1]);
5664 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5665 targetManager->DumpSysState(info, isClient);
5666 } else {
5667 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5668 }
5669 }
5670
DumpInner(const std::string &args, std::vector<std::string> &info)5671 void AbilityManagerService::DumpInner(const std::string &args, std::vector<std::string> &info)
5672 {
5673 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5674 auto uiAbilityManager = GetCurrentUIAbilityManager();
5675 CHECK_POINTER(uiAbilityManager);
5676 uiAbilityManager->Dump(info);
5677 return;
5678 }
5679
5680 auto missionListManager = GetCurrentMissionListManager();
5681 if (missionListManager) {
5682 missionListManager->Dump(info);
5683 }
5684 }
5685
DumpMissionListInner(const std::string &args, std::vector<std::string> &info)5686 void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector<std::string> &info)
5687 {
5688 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5689 auto uiAbilityManager = GetCurrentUIAbilityManager();
5690 CHECK_POINTER(uiAbilityManager);
5691 uiAbilityManager->DumpMissionList(info, false, " ");
5692 return;
5693 }
5694 auto missionListManager = GetCurrentMissionListManager();
5695 if (missionListManager) {
5696 missionListManager->DumpMissionList(info, false, "");
5697 }
5698 }
5699
DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)5700 void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)
5701 {
5702 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5703 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5704 #ifdef SUPPORT_GRAPHICS
5705 Rosen::WindowManager::GetInstance().DumpSessionAll(info);
5706 #endif // SUPPORT_GRAPHICS
5707 return;
5708 }
5709 auto missionListManager = GetCurrentMissionListManager();
5710 if (missionListManager) {
5711 missionListManager->DumpMissionInfos(info);
5712 }
5713 }
5714
DumpMissionInner(const std::string &args, std::vector<std::string> &info)5715 void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector<std::string> &info)
5716 {
5717 std::vector<std::string> argList;
5718 SplitStr(args, " ", argList);
5719 if (argList.empty()) {
5720 return;
5721 }
5722 if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5723 info.push_back("error: invalid argument, please see 'ability dump -h'.");
5724 return;
5725 }
5726 int missionId = DEFAULT_INVAL_VALUE;
5727 (void)StrToInt(argList[1], missionId);
5728
5729 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5730 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5731 #ifdef SUPPORT_GRAPHICS
5732 Rosen::WindowManager::GetInstance().DumpSessionWithId(missionId, info);
5733 #endif // SUPPORT_GRAPHICS
5734 return;
5735 }
5736
5737 auto missionListManager = GetCurrentMissionListManager();
5738 CHECK_POINTER_LOG(missionListManager, "Current mission manager not init.");
5739 missionListManager->DumpMission(missionId, info);
5740 }
5741
DumpStateInner(const std::string &args, std::vector<std::string> &info)5742 void AbilityManagerService::DumpStateInner(const std::string &args, std::vector<std::string> &info)
5743 {
5744 auto connectManager = GetCurrentConnectManager();
5745 CHECK_POINTER_LOG(connectManager, "Current mission manager not init.");
5746 std::vector<std::string> argList;
5747 SplitStr(args, " ", argList);
5748 if (argList.empty()) {
5749 return;
5750 }
5751 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5752 connectManager->DumpState(info, false, argList[1]);
5753 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5754 connectManager->DumpState(info, false);
5755 } else {
5756 info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5757 }
5758 }
5759
DataDumpStateInner(const std::string &args, std::vector<std::string> &info)5760 void AbilityManagerService::DataDumpStateInner(const std::string &args, std::vector<std::string> &info)
5761 {
5762 auto dataAbilityManager = GetCurrentDataAbilityManager();
5763 CHECK_POINTER(dataAbilityManager);
5764 std::vector<std::string> argList;
5765 SplitStr(args, " ", argList);
5766 if (argList.empty()) {
5767 return;
5768 }
5769 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5770 dataAbilityManager->DumpState(info, argList[1]);
5771 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5772 dataAbilityManager->DumpState(info);
5773 } else {
5774 info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5775 }
5776 }
5777
DumpState(const std::string &args, std::vector<std::string> &info)5778 void AbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
5779 {
5780 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5781 auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5782 if (!isShellCall && !isHidumperServiceCall) {
5783 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
5784 return;
5785 }
5786 std::vector<std::string> argList;
5787 SplitStr(args, " ", argList);
5788 if (argList.empty()) {
5789 return;
5790 }
5791 auto key = DumpUtils::DumpMap(argList[0]);
5792 if (!key.first) {
5793 return;
5794 }
5795 switch (key.second) {
5796 case DumpUtils::KEY_DUMP_SERVICE:
5797 DumpStateInner(args, info);
5798 break;
5799 case DumpUtils::KEY_DUMP_DATA:
5800 DataDumpStateInner(args, info);
5801 break;
5802 case DumpUtils::KEY_DUMP_ALL:
5803 DumpInner(args, info);
5804 break;
5805 case DumpUtils::KEY_DUMP_MISSION:
5806 DumpMissionInner(args, info);
5807 break;
5808 case DumpUtils::KEY_DUMP_MISSION_LIST:
5809 DumpMissionListInner(args, info);
5810 break;
5811 case DumpUtils::KEY_DUMP_MISSION_INFOS:
5812 DumpMissionInfosInner(args, info);
5813 break;
5814 default:
5815 info.push_back("error: invalid argument, please see 'ability dump -h'.");
5816 break;
5817 }
5818 }
5819
DumpSysState( const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)5820 void AbilityManagerService::DumpSysState(
5821 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5822 {
5823 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
5824 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5825 auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5826 if (!isShellCall && !isHidumperServiceCall) {
5827 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
5828 return;
5829 }
5830 std::vector<std::string> argList;
5831 SplitStr(args, " ", argList);
5832 if (argList.empty()) {
5833 return;
5834 }
5835 auto key = DumpUtils::DumpsysMap(argList[0]);
5836 if (!key.first) {
5837 return;
5838 }
5839 switch (key.second) {
5840 case DumpUtils::KEY_DUMP_SYS_ALL:
5841 DumpSysInner(args, info, isClient, isUserID, userId);
5842 break;
5843 case DumpUtils::KEY_DUMP_SYS_SERVICE:
5844 DumpSysStateInner(args, info, isClient, isUserID, userId);
5845 break;
5846 case DumpUtils::KEY_DUMP_SYS_PENDING:
5847 DumpSysPendingInner(args, info, isClient, isUserID, userId);
5848 break;
5849 case DumpUtils::KEY_DUMP_SYS_PROCESS:
5850 DumpSysProcess(args, info, isClient, isUserID, userId);
5851 break;
5852 case DumpUtils::KEY_DUMP_SYS_DATA:
5853 DataDumpSysStateInner(args, info, isClient, isUserID, userId);
5854 break;
5855 case DumpUtils::KEY_DUMP_SYS_MISSION_LIST:
5856 DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5857 break;
5858 case DumpUtils::KEY_DUMP_SYS_ABILITY:
5859 DumpSysAbilityInner(args, info, isClient, isUserID, userId);
5860 break;
5861 default:
5862 info.push_back("error: invalid argument, please see 'ability dump -h'.");
5863 break;
5864 }
5865 }
5866
AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)5867 int AbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
5868 {
5869 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5870 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5871 return ERR_INVALID_VALUE;
5872 }
5873 auto abilityRecord = Token::GetAbilityRecordByToken(token);
5874 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
5875 TAG_LOGI(AAFwkTag::ABILITYMGR, "AbilityTransitionDone, ability: %{public}s, state:%{public}d",
5876 abilityRecord->GetURI().c_str(), state);
5877 if (!JudgeSelfCalled(abilityRecord)) {
5878 return CHECK_PERMISSION_FAILED;
5879 }
5880
5881 auto abilityInfo = abilityRecord->GetAbilityInfo();
5882 auto type = abilityInfo.type;
5883 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5884 // force timeout ability for test
5885 int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast<AbilityLifeCycleState>(state));
5886 bool isTerminate = abilityRecord->IsAbilityState(AbilityState::TERMINATING) && targetState == AbilityState::INITIAL;
5887 std::string tempState = isTerminate ? AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) :
5888 AbilityRecord::ConvertAbilityState(static_cast<AbilityState>(targetState));
5889 if (IsNeedTimeoutForTest(abilityInfo.name, tempState)) {
5890 TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability, state:%{public}s, ability:%{public}s",
5891 tempState.c_str(),
5892 abilityInfo.name.c_str());
5893 return ERR_OK;
5894 }
5895 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5896 auto connectManager = GetConnectManagerByUserId(userId);
5897 if (!connectManager) {
5898 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
5899 return ERR_INVALID_VALUE;
5900 }
5901 return connectManager->AbilityTransitionDone(token, state);
5902 }
5903 if (type == AppExecFwk::AbilityType::DATA) {
5904 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5905 if (!dataAbilityManager) {
5906 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
5907 return ERR_INVALID_VALUE;
5908 }
5909 return dataAbilityManager->AbilityTransitionDone(token, state);
5910 }
5911
5912 if (targetState == AbilityState::BACKGROUND) {
5913 FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::BACKGROUND };
5914 std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of background lifecycle.";
5915 FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5916 } else if (targetState != AbilityState::INITIAL) {
5917 FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::FOREGROUND };
5918 std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of foreground lifecycle."
5919 " the end of foreground lifecycle.";
5920 FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5921 }
5922
5923 int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5924 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5925 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5926 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5927 return uiAbilityManager->AbilityTransactionDone(token, state, saveData);
5928 } else {
5929 auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5930 if (!missionListManager) {
5931 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", ownerMissionUserId);
5932 return ERR_INVALID_VALUE;
5933 }
5934 return missionListManager->AbilityTransactionDone(token, state, saveData);
5935 }
5936 }
5937
AbilityWindowConfigTransitionDone( const sptr<IRemoteObject> &token, const WindowConfig &windowConfig)5938 int AbilityManagerService::AbilityWindowConfigTransitionDone(
5939 const sptr<IRemoteObject> &token, const WindowConfig &windowConfig)
5940 {
5941 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5942 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5943 return ERR_INVALID_VALUE;
5944 }
5945 auto abilityRecord = Token::GetAbilityRecordByToken(token);
5946 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record null.");
5947 if (!JudgeSelfCalled(abilityRecord)) {
5948 return CHECK_PERMISSION_FAILED;
5949 }
5950
5951 TAG_LOGI(AAFwkTag::ABILITYMGR, "lifecycle:ability:%{public}s", abilityRecord->GetURI().c_str());
5952 auto abilityInfo = abilityRecord->GetAbilityInfo();
5953 auto type = abilityInfo.extensionAbilityType;
5954 if (type != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
5955 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid type");
5956 return ERR_INVALID_VALUE;
5957 }
5958 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5959 auto connectManager = GetConnectManagerByUserId(userId);
5960 if(!connectManager) {
5961 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
5962 return ERR_INVALID_VALUE;
5963 }
5964 return connectManager->AbilityWindowConfigTransactionDone(token, windowConfig);
5965 }
5966
ScheduleConnectAbilityDone( const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)5967 int AbilityManagerService::ScheduleConnectAbilityDone(
5968 const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
5969 {
5970 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5971 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5972 if (!VerificationAllToken(token)) {
5973 return ERR_INVALID_VALUE;
5974 }
5975
5976 auto abilityRecord = Token::GetAbilityRecordByToken(token);
5977 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5978 if (!JudgeSelfCalled(abilityRecord)) {
5979 return CHECK_PERMISSION_FAILED;
5980 }
5981
5982 auto type = abilityRecord->GetAbilityInfo().type;
5983 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
5984 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability failed, target ability not service");
5985 return TARGET_ABILITY_NOT_SERVICE;
5986 }
5987 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5988 auto connectManager = GetConnectManagerByUserId(userId);
5989 if (!connectManager) {
5990 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
5991 return ERR_INVALID_VALUE;
5992 }
5993 return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject);
5994 }
5995
ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)5996 int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
5997 {
5998 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5999 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
6000 if (!VerificationAllToken(token)) {
6001 return ERR_INVALID_VALUE;
6002 }
6003
6004 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6005 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6006 if (!JudgeSelfCalled(abilityRecord)) {
6007 return CHECK_PERMISSION_FAILED;
6008 }
6009
6010 auto type = abilityRecord->GetAbilityInfo().type;
6011 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6012 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability failed, target ability not service");
6013 return TARGET_ABILITY_NOT_SERVICE;
6014 }
6015 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6016 auto connectManager = GetConnectManagerByUserId(userId);
6017 if (!connectManager) {
6018 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6019 return ERR_INVALID_VALUE;
6020 }
6021 return connectManager->ScheduleDisconnectAbilityDoneLocked(token);
6022 }
6023
ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)6024 int AbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
6025 {
6026 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6027 TAG_LOGD(AAFwkTag::ABILITYMGR, "Schedule command ability done.");
6028 if (!VerificationAllToken(token)) {
6029 return ERR_INVALID_VALUE;
6030 }
6031
6032 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6033 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6034 if (!JudgeSelfCalled(abilityRecord)) {
6035 return CHECK_PERMISSION_FAILED;
6036 }
6037 // force timeout ability for test
6038 if (IsNeedTimeoutForTest(abilityRecord->GetAbilityInfo().name, std::string("COMMAND"))) {
6039 TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability, state:COMMAND, ability: %{public}s",
6040 abilityRecord->GetAbilityInfo().name.c_str());
6041 return ERR_OK;
6042 }
6043 auto type = abilityRecord->GetAbilityInfo().type;
6044 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6045 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed, target ability not service");
6046 return TARGET_ABILITY_NOT_SERVICE;
6047 }
6048 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6049 auto connectManager = GetConnectManagerByUserId(userId);
6050 if (!connectManager) {
6051 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6052 return ERR_INVALID_VALUE;
6053 }
6054 return connectManager->ScheduleCommandAbilityDoneLocked(token);
6055 }
6056
ScheduleCommandAbilityWindowDone( const sptr<IRemoteObject> &token, const sptr<SessionInfo> &sessionInfo, WindowCommand winCmd, AbilityCommand abilityCmd)6057 int AbilityManagerService::ScheduleCommandAbilityWindowDone(
6058 const sptr<IRemoteObject> &token,
6059 const sptr<SessionInfo> &sessionInfo,
6060 WindowCommand winCmd,
6061 AbilityCommand abilityCmd)
6062 {
6063 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6064 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter.");
6065 if (!VerificationAllToken(token)) {
6066 return ERR_INVALID_VALUE;
6067 }
6068
6069 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6070 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
6071 if (!JudgeSelfCalled(abilityRecord)) {
6072 return CHECK_PERMISSION_FAILED;
6073 }
6074
6075 if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)
6076 && !UIExtensionUtils::IsWindowExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
6077 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not ui or window extension");
6078 return ERR_INVALID_VALUE;
6079 }
6080 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6081 auto connectManager = GetConnectManagerByUserId(userId);
6082 if (!connectManager) {
6083 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6084 return ERR_INVALID_VALUE;
6085 }
6086 return connectManager->ScheduleCommandAbilityWindowDone(token, sessionInfo, winCmd, abilityCmd);
6087 }
6088
OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)6089 void AbilityManagerService::OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)
6090 {
6091 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6092 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6093 CHECK_POINTER(abilityRecord);
6094 TAG_LOGI(AAFwkTag::ABILITYMGR, "OnAbilityRequestDone, bundleName: %{public}s, abilityName: %{public}s",
6095 abilityRecord->GetAbilityInfo().bundleName.c_str(), abilityRecord->GetAbilityInfo().name.c_str());
6096 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
6097
6098 auto type = abilityRecord->GetAbilityInfo().type;
6099 switch (type) {
6100 case AppExecFwk::AbilityType::DATA: {
6101 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6102 if (!dataAbilityManager) {
6103 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager null userId=%{public}d", userId);
6104 return;
6105 }
6106 dataAbilityManager->OnAbilityRequestDone(token, state);
6107 break;
6108 }
6109 case AppExecFwk::AbilityType::SERVICE:
6110 case AppExecFwk::AbilityType::EXTENSION: {
6111 auto connectManager = GetConnectManagerByUserId(userId);
6112 if (!connectManager) {
6113 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
6114 return;
6115 }
6116 connectManager->OnAbilityRequestDone(token, state);
6117 break;
6118 }
6119 default: {
6120 int32_t ownerUserId = abilityRecord->GetOwnerMissionUserId();
6121 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6122 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
6123 CHECK_POINTER(uiAbilityManager);
6124 uiAbilityManager->OnAbilityRequestDone(token, state);
6125 } else {
6126 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
6127 if (!missionListManager) {
6128 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId=%{public}d", ownerUserId);
6129 return;
6130 }
6131 missionListManager->OnAbilityRequestDone(token, state);
6132 }
6133 break;
6134 }
6135 }
6136 }
6137
OnAppStateChanged(const AppInfo &info)6138 void AbilityManagerService::OnAppStateChanged(const AppInfo &info)
6139 {
6140 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6141 auto connectManager = GetCurrentConnectManager();
6142 CHECK_POINTER_LOG(connectManager, "Connect manager not init.");
6143 connectManager->OnAppStateChanged(info);
6144 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6145 auto uiAbilityManager = GetCurrentUIAbilityManager();
6146 CHECK_POINTER(uiAbilityManager);
6147 uiAbilityManager->OnAppStateChanged(info);
6148 } else {
6149 auto missionListManager = GetCurrentMissionListManager();
6150 CHECK_POINTER_LOG(missionListManager, "Current mission list manager not init.");
6151 missionListManager->OnAppStateChanged(info);
6152 }
6153 auto dataAbilityManager = GetCurrentDataAbilityManager();
6154 CHECK_POINTER(dataAbilityManager);
6155 dataAbilityManager->OnAppStateChanged(info);
6156
6157 auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
6158 CHECK_POINTER(residentProcessMgr);
6159 residentProcessMgr->OnAppStateChanged(info);
6160 }
6161
GetEventHandler()6162 std::shared_ptr<AbilityEventHandler> AbilityManagerService::GetEventHandler()
6163 {
6164 return eventHandler_;
6165 }
6166
6167 // multi user scene
GetUserId() const6168 int32_t AbilityManagerService::GetUserId() const
6169 {
6170 if (userController_) {
6171 auto userId = userController_->GetCurrentUserId();
6172 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is %{public}d", userId);
6173 return userId;
6174 }
6175 return U0_USER_ID;
6176 }
6177
StartHighestPriorityAbility(int32_t userId, bool isBoot, bool isAppRecovery)6178 void AbilityManagerService::StartHighestPriorityAbility(int32_t userId, bool isBoot, bool isAppRecovery)
6179 {
6180 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
6181 auto bms = AbilityUtil::GetBundleManagerHelper();
6182 CHECK_POINTER(bms);
6183
6184 /* Query the highest priority ability or extension ability, and start it. usually, it is OOBE or launcher */
6185 Want want;
6186 want.AddEntity(HIGHEST_PRIORITY_ABILITY_ENTITY);
6187 AppExecFwk::AbilityInfo abilityInfo;
6188 AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
6189 int attemptNums = 0;
6190 while (!IN_PROCESS_CALL(bms->ImplicitQueryInfoByPriority(want,
6191 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId,
6192 abilityInfo, extensionAbilityInfo))) {
6193 TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting query highest priority ability info completed");
6194 ++attemptNums;
6195 if (!isBoot && attemptNums > SWITCH_ACCOUNT_TRY) {
6196 TAG_LOGE(AAFwkTag::ABILITYMGR, "query highest priority ability failed");
6197 return;
6198 }
6199 AbilityRequest abilityRequest;
6200 usleep(REPOLL_TIME_MICRO_SECONDS);
6201 }
6202
6203 if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
6204 TAG_LOGE(AAFwkTag::ABILITYMGR, "query highest priority ability failed");
6205 return;
6206 }
6207
6208 Want abilityWant; // donot use 'want' here, because the entity of 'want' is not empty
6209 if (!abilityInfo.name.empty()) {
6210 /* highest priority ability */
6211 TAG_LOGI(AAFwkTag::ABILITYMGR, "start highest priority ability bundleName:%{public}s, ability:%{public}s",
6212 abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
6213 abilityWant.SetElementName(abilityInfo.bundleName, abilityInfo.name);
6214 } else {
6215 /* highest priority extension ability */
6216 TAG_LOGI(AAFwkTag::ABILITYMGR,
6217 "start highest priority extension ability bundleName:%{public}s, ability:%{public}s",
6218 extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str());
6219 abilityWant.SetElementName(extensionAbilityInfo.bundleName, extensionAbilityInfo.name);
6220 }
6221
6222 #ifdef SUPPORT_GRAPHICS
6223 abilityWant.SetParam(NEED_STARTINGWINDOW, false);
6224 // wait BOOT_ANIMATION_STARTED to start LAUNCHER
6225 WaitBootAnimationStart();
6226 #endif
6227 if (isAppRecovery) {
6228 abilityWant.SetParam("ohos.app.logout_recovery", true);
6229 }
6230 /* note: OOBE APP need disable itself, otherwise, it will be started when restart system everytime */
6231 (void)StartAbility(abilityWant, userId, DEFAULT_INVAL_VALUE);
6232 }
6233
GenerateAbilityRequest(const Want &want, int requestCode, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)6234 int AbilityManagerService::GenerateAbilityRequest(const Want &want, int requestCode, AbilityRequest &request,
6235 const sptr<IRemoteObject> &callerToken, int32_t userId)
6236 {
6237 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6238 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6239 if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6240 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6241 (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6242 (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6243 }
6244
6245 int32_t appIndex = 0;
6246 (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
6247 if (abilityRecord != nullptr &&
6248 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName() &&
6249 abilityRecord->GetAppIndex() == appIndex) {
6250 (const_cast<Want &>(want)).SetParam(DEBUG_APP, abilityRecord->IsDebugApp());
6251 }
6252
6253 request.want = want;
6254 request.requestCode = requestCode;
6255 request.callerToken = callerToken;
6256 auto setting = AbilityStartSetting::GetEmptySetting();
6257 if (setting != nullptr) {
6258 setting->AddProperty(AbilityStartSetting::IS_START_BY_SCB_KEY, "false"); // default is false
6259 request.startSetting = std::make_shared<AbilityStartSetting>(*(setting.get()));
6260 }
6261
6262 auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6263 if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6264 int32_t appIndex = 0;
6265 if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6266 return ERR_APP_CLONE_INDEX_INVALID;
6267 }
6268 Want localWant = want;
6269 if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
6270 localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
6271 localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
6272 localWant.SetParam(Want::PARAM_RESV_CALLER_TOKEN, static_cast<int32_t>(IPCSkeleton::GetCallingTokenID()));
6273 localWant.SetParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid());
6274 }
6275 abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(localWant, userId, appIndex);
6276 }
6277 CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6278 if (abilityInfo->status != ERR_OK) {
6279 return abilityInfo->status;
6280 }
6281 request.abilityInfo = abilityInfo->abilityInfo;
6282 request.extensionProcessMode = abilityInfo->extensionProcessMode;
6283
6284 if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
6285 request.collaboratorType = CollaboratorType::RESERVE_TYPE;
6286 } else if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::OTHERS_TYPE)) {
6287 request.collaboratorType = CollaboratorType::OTHERS_TYPE;
6288 }
6289
6290 if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) {
6291 TAG_LOGI(AAFwkTag::ABILITYMGR, "stage mode, abilityInfo SERVICE type reset EXTENSION");
6292 request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
6293 }
6294
6295 if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6296 TAG_LOGE(AAFwkTag::ABILITYMGR, "get app info failed");
6297 return RESOLVE_APP_ERR;
6298 }
6299 if (want.GetIntParam(AAFwk::SCREEN_MODE_KEY, ScreenMode::IDLE_SCREEN_MODE) == ScreenMode::JUMP_SCREEN_MODE &&
6300 (request.abilityInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE ||
6301 request.abilityInfo.launchMode != AppExecFwk::LaunchMode::SINGLETON)) {
6302 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface of starting atomicService start only atomicService");
6303 return TARGET_ABILITY_NOT_SERVICE;
6304 }
6305 request.appInfo = request.abilityInfo.applicationInfo;
6306 request.uid = request.appInfo.uid;
6307 TAG_LOGD(AAFwkTag::ABILITYMGR,
6308 "GenerateAbilityRequest end, app name: %{public}s, moduleName name: %{public}s, uid: %{public}d.",
6309 request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid);
6310
6311 request.want.SetModuleName(request.abilityInfo.moduleName);
6312
6313 if (want.GetBoolParam(Want::PARAM_RESV_START_RECENT, false) &&
6314 AAFwk::PermissionVerification::GetInstance()->VerifyStartRecentAbilityPermission()) {
6315 TAG_LOGD(AAFwkTag::ABILITYMGR, "Set start recent.");
6316 request.startRecent = true;
6317 }
6318
6319 if (ModalSystemDialogUtil::CheckDebugAppNotInDeveloperMode(request.abilityInfo.applicationInfo)) {
6320 // service and extension do not show dialog.
6321 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
6322 !(request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
6323 request.abilityInfo.type == AppExecFwk::AbilityType::EXTENSION)) {
6324 ModalSystemDialogUtil::ShowDeveloperModeDialog(request.abilityInfo.bundleName, request.abilityInfo.name);
6325 }
6326 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer mode");
6327 return ERR_NOT_DEVELOPER_MODE;
6328 }
6329
6330 return ERR_OK;
6331 }
6332
GenerateExtensionAbilityRequest( const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)6333 int AbilityManagerService::GenerateExtensionAbilityRequest(
6334 const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
6335 {
6336 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6337 if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6338 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6339 (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6340 (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6341 }
6342 request.want = want;
6343 request.callerToken = callerToken;
6344 request.startSetting = nullptr;
6345
6346 auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6347 if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6348 int32_t appIndex = 0;
6349 if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6350 return ERR_APP_CLONE_INDEX_INVALID;
6351 }
6352 abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, appIndex);
6353 }
6354 CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6355 if (abilityInfo->status != ERR_OK) {
6356 return abilityInfo->status;
6357 }
6358 if (ModalSystemDialogUtil::CheckDebugAppNotInDeveloperMode(abilityInfo->abilityInfo.applicationInfo)) {
6359 TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer mode");
6360 return ERR_NOT_DEVELOPER_MODE;
6361 }
6362 auto result = InitialAbilityRequest(request, *abilityInfo);
6363 return result;
6364 }
6365
InitialAbilityRequest(AbilityRequest &request, const StartAbilityInfo &abilityInfo) const6366 int32_t AbilityManagerService::InitialAbilityRequest(AbilityRequest &request,
6367 const StartAbilityInfo &abilityInfo) const
6368 {
6369 request.abilityInfo = abilityInfo.abilityInfo;
6370 request.extensionProcessMode = abilityInfo.extensionProcessMode;
6371 if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6372 TAG_LOGE(AAFwkTag::ABILITYMGR, "get app info failed");
6373 return RESOLVE_APP_ERR;
6374 }
6375 request.appInfo = request.abilityInfo.applicationInfo;
6376 request.uid = request.appInfo.uid;
6377 TAG_LOGD(AAFwkTag::ABILITYMGR,
6378 "GenerateExtensionAbilityRequest end, app name:%{public}s, bundle name:%{public}s, uid:%{public}d, moduleName:%{public}s",
6379 request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid, request.abilityInfo.moduleName.c_str());
6380
6381 request.want.SetModuleName(request.abilityInfo.moduleName);
6382
6383 return ERR_OK;
6384 }
6385
StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)6386 int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)
6387 {
6388 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6389 TAG_LOGD(AAFwkTag::ABILITYMGR, "call.");
6390
6391 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6392 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6393 if (!isSaCall && !isShellCall) {
6394 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6395 if (abilityRecord == nullptr) {
6396 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord null");
6397 return ERR_INVALID_VALUE;
6398 }
6399 }
6400
6401 int32_t validUserId = GetValidUserId(userId);
6402 if (!JudgeMultiUserConcurrency(validUserId)) {
6403 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
6404 return ERR_CROSS_USER;
6405 }
6406
6407 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
6408 AbilityRequest abilityRequest;
6409 auto result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId);
6410 if (result != ERR_OK) {
6411 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
6412 return result;
6413 }
6414
6415 auto abilityInfo = abilityRequest.abilityInfo;
6416 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
6417 TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
6418 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
6419
6420 auto type = abilityInfo.type;
6421 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6422 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not service type");
6423 return TARGET_ABILITY_NOT_SERVICE;
6424 }
6425
6426 auto res = JudgeAbilityVisibleControl(abilityInfo);
6427 if (res != ERR_OK) {
6428 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability invisible");
6429 return res;
6430 }
6431
6432 auto connectManager = GetConnectManagerByUserId(validUserId);
6433 if (connectManager == nullptr) {
6434 return ERR_INVALID_VALUE;
6435 }
6436
6437 return connectManager->StopServiceAbility(abilityRequest);
6438 }
6439
OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)6440 void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)
6441 {
6442 CHECK_POINTER(abilityRecord);
6443 if (abilityRecord->GetToken()) {
6444 FreezeUtil::GetInstance().DeleteLifecycleEvent(abilityRecord->GetToken()->AsObject());
6445 }
6446 FreezeUtil::GetInstance().DeleteAppLifecycleEvent(abilityRecord->GetPid());
6447 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6448 if (abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6449 auto uiAbilityManager = GetUIAbilityManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6450 CHECK_POINTER(uiAbilityManager);
6451 uiAbilityManager->OnAbilityDied(abilityRecord);
6452 return;
6453 }
6454 } else {
6455 auto manager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6456 if (manager && abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6457 ReleaseAbilityTokenMap(abilityRecord->GetToken());
6458 manager->OnAbilityDied(abilityRecord, GetUserId());
6459 return;
6460 }
6461 }
6462
6463 auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
6464 if (connectManager) {
6465 connectManager->OnAbilityDied(abilityRecord, GetUserId());
6466 return;
6467 }
6468
6469 auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken());
6470 if (dataAbilityManager) {
6471 dataAbilityManager->OnAbilityDied(abilityRecord);
6472 }
6473 }
6474
OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)6475 void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
6476 {
6477 CHECK_POINTER(callRecord);
6478 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6479 auto uiAbilityManager = GetCurrentUIAbilityManager();
6480 CHECK_POINTER(uiAbilityManager);
6481 uiAbilityManager->OnCallConnectDied(callRecord);
6482 return;
6483 }
6484 auto missionListManager = GetCurrentMissionListManager();
6485 if (missionListManager) {
6486 missionListManager->OnCallConnectDied(callRecord);
6487 }
6488 }
6489
ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)6490 void AbilityManagerService::ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)
6491 {
6492 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
6493 for (auto iter = callStubTokenMap_.begin(); iter != callStubTokenMap_.end(); iter++) {
6494 if (iter->second == token) {
6495 callStubTokenMap_.erase(iter);
6496 break;
6497 }
6498 }
6499 }
6500
KillProcess(const std::string &bundleName, const bool clearPageStack)6501 int AbilityManagerService::KillProcess(const std::string &bundleName, const bool clearPageStack)
6502 {
6503 TAG_LOGI(AAFwkTag::ABILITYMGR, "Kill process, bundleName: %{public}s, clearPageStack: %{public}d",
6504 bundleName.c_str(), clearPageStack);
6505 CHECK_CALLER_IS_SYSTEM_APP;
6506 auto bms = AbilityUtil::GetBundleManagerHelper();
6507 CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED);
6508 int32_t userId = GetUserId();
6509 AppExecFwk::BundleInfo bundleInfo;
6510 if (!IN_PROCESS_CALL(
6511 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
6512 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle info when kill process failed");
6513 return GET_BUNDLE_INFO_FAILED;
6514 }
6515
6516 bool keepAliveEnable = bundleInfo.isKeepAlive;
6517 AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleName, keepAliveEnable);
6518 if (keepAliveEnable && DelayedSingleton<AppScheduler>::GetInstance()->IsMemorySizeSufficent()) {
6519 TAG_LOGE(AAFwkTag::ABILITYMGR, "no kill alive process");
6520 return KILL_PROCESS_KEEP_ALIVE;
6521 }
6522
6523 int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName, clearPageStack);
6524 if (ret != ERR_OK) {
6525 return KILL_PROCESS_FAILED;
6526 }
6527
6528 return ERR_OK;
6529 }
6530
UninstallApp(const std::string &bundleName, int32_t uid)6531 int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid)
6532 {
6533 return UninstallApp(bundleName, uid, 0);
6534 }
6535
UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex)6536 int32_t AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex)
6537 {
6538 TAG_LOGI(AAFwkTag::ABILITYMGR, "uninstall app, bundleName:%{public}s, uid=%{public}d, appIndex:%{public}d",
6539 bundleName.c_str(), uid, appIndex);
6540 return UninstallAppInner(bundleName, uid, appIndex, false, "");
6541 }
6542
UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg, int32_t appIndex)6543 int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg,
6544 int32_t appIndex)
6545 {
6546 TAG_LOGI(AAFwkTag::ABILITYMGR,
6547 "upgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg:%{public}s, appIndex:%{public}d",
6548 bundleName.c_str(), uid, exitMsg.c_str(), appIndex);
6549 return UninstallAppInner(bundleName, uid, appIndex, true, exitMsg);
6550 }
6551
UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex, const bool isUpgrade, const std::string &exitMsg)6552 int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex,
6553 const bool isUpgrade, const std::string &exitMsg)
6554 {
6555 pid_t callingPid = IPCSkeleton::GetCallingPid();
6556 pid_t pid = getprocpid();
6557 if (callingPid != pid) {
6558 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: not bundleMgr", __func__);
6559 return CHECK_PERMISSION_FAILED;
6560 }
6561
6562 if (isUpgrade) {
6563 CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
6564 AAFwk::ExitReason exitReason = { REASON_UPGRADE, exitMsg };
6565 appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
6566 } else {
6567 IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppExecFwk::AppMgrClient>::
6568 GetInstance()->SetKeepAliveEnableState(bundleName, false, uid));
6569 auto userId = uid / BASE_USER_RANGE;
6570 auto connectManager = GetConnectManagerByUserId(userId);
6571 if (connectManager) {
6572 connectManager->UninstallApp(bundleName);
6573 }
6574 }
6575
6576 CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT);
6577 subManagersHelper_->UninstallApp(bundleName, uid);
6578 int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplicationByUid(bundleName, uid, "UninstallApp");
6579 if (ret != ERR_OK) {
6580 return UNINSTALL_APP_FAILED;
6581 }
6582 if (!isUpgrade) {
6583 DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->DeleteAppExitReason(bundleName, uid,
6584 appIndex);
6585 }
6586 return ERR_OK;
6587 }
6588
PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)6589 int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)
6590 {
6591 if (bundleName.empty()) {
6592 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name preloading");
6593 return ERR_INVALID_VALUE;
6594 }
6595
6596 if (taskHandler_ == nullptr) {
6597 TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler null");
6598 return ERR_INVALID_STATE;
6599 }
6600
6601 taskHandler_->SubmitTask([weak = weak_from_this(), bundleName, userId]() {
6602 auto pthis = weak.lock();
6603 if (pthis == nullptr) {
6604 TAG_LOGE(AAFwkTag::ABILITYMGR, "pthis null");
6605 return;
6606 }
6607 pthis->PreLoadAppDataAbilitiesTask(bundleName, userId);
6608 });
6609
6610 return ERR_OK;
6611 }
6612
PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId)6613 void AbilityManagerService::PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId)
6614 {
6615 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6616 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6617 if (dataAbilityManager == nullptr) {
6618 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid data ability manager preloading");
6619 return;
6620 }
6621
6622 auto bms = AbilityUtil::GetBundleManagerHelper();
6623 CHECK_POINTER(bms);
6624
6625 AppExecFwk::BundleInfo bundleInfo;
6626 bool ret = IN_PROCESS_CALL(
6627 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
6628 if (!ret) {
6629 TAG_LOGE(AAFwkTag::ABILITYMGR,
6630 "get bundleInfo preloading failed, userId:%{public}d", userId);
6631 return;
6632 }
6633
6634 auto begin = system_clock::now();
6635 AbilityRequest dataAbilityRequest;
6636 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(dataAbilityRequest.want, nullptr);
6637 dataAbilityRequest.appInfo = bundleInfo.applicationInfo;
6638 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
6639 if (it->type != AppExecFwk::AbilityType::DATA) {
6640 continue;
6641 }
6642 if ((system_clock::now() - begin) >= DATA_ABILITY_START_TIMEOUT) {
6643 TAG_LOGE(AAFwkTag::ABILITYMGR, "app data ability preloading '%{public}s' timeout", bundleName.c_str());
6644 return;
6645 }
6646 dataAbilityRequest.abilityInfo = *it;
6647 dataAbilityRequest.uid = bundleInfo.uid;
6648 TAG_LOGD(AAFwkTag::ABILITYMGR, "App data ability preloading: '%{public}s.%{public}s'...",
6649 it->bundleName.c_str(), it->name.c_str());
6650
6651 auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false);
6652 if (dataAbility == nullptr) {
6653 TAG_LOGE(AAFwkTag::ABILITYMGR,
6654 "preload data ability failed '%{public}s.%{public}s'", it->bundleName.c_str(), it->name.c_str());
6655 return;
6656 }
6657 }
6658 }
6659
IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const6660 bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const
6661 {
6662 if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) {
6663 return false;
6664 }
6665 return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR ||
6666 info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR ||
6667 info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME);
6668 }
6669
IsSystemUI(const std::string &bundleName) const6670 bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const
6671 {
6672 return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME;
6673 }
6674
HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)6675 void AbilityManagerService::HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6676 {
6677 TAG_LOGD(AAFwkTag::ABILITYMGR, "load timeout %{public}" PRId64, abilityRecordId);
6678 if (isExtension) {
6679 auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6680 if (connectManager != nullptr) {
6681 connectManager->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6682 }
6683 return;
6684 }
6685
6686 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6687 auto uiAbilityManagers = GetUIAbilityManagers();
6688 for (auto& item : uiAbilityManagers) {
6689 if (item.second) {
6690 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6691 }
6692 }
6693 return;
6694 }
6695 auto missionListManagers = GetMissionListManagers();
6696 for (auto& item : missionListManagers) {
6697 if (item.second) {
6698 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6699 }
6700 }
6701 }
6702
HandleActiveTimeOut(int64_t abilityRecordId)6703 void AbilityManagerService::HandleActiveTimeOut(int64_t abilityRecordId)
6704 {
6705 TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle active timeout.");
6706 auto missionListManagers = GetMissionListManagers();
6707 for (auto& item : missionListManagers) {
6708 if (item.second) {
6709 item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecordId);
6710 }
6711 }
6712 }
6713
HandleInactiveTimeOut(int64_t abilityRecordId)6714 void AbilityManagerService::HandleInactiveTimeOut(int64_t abilityRecordId)
6715 {
6716 TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle inactive timeout.");
6717 auto missionListManagers = GetMissionListManagers();
6718 for (auto& item : missionListManagers) {
6719 if (item.second) {
6720 item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6721 }
6722 }
6723 auto connectManagers = GetConnectManagers();
6724 for (auto& item : connectManagers) {
6725 if (item.second) {
6726 item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6727 }
6728 }
6729 }
6730
HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)6731 void AbilityManagerService::HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6732 {
6733 TAG_LOGD(AAFwkTag::ABILITYMGR, "foreground timeout %{public}" PRId64, abilityRecordId);
6734 if (isExtension) {
6735 auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6736 if (connectManager != nullptr) {
6737 connectManager->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6738 }
6739 return;
6740 }
6741
6742 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6743 auto uiAbilityManagers = GetUIAbilityManagers();
6744 for (auto& item : uiAbilityManagers) {
6745 if (item.second) {
6746 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6747 }
6748 }
6749 return;
6750 }
6751 auto missionListManagers = GetMissionListManagers();
6752 for (auto& item : missionListManagers) {
6753 if (item.second) {
6754 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6755 }
6756 }
6757 }
6758
HandleShareDataTimeOut(int64_t uniqueId)6759 void AbilityManagerService::HandleShareDataTimeOut(int64_t uniqueId)
6760 {
6761 WantParams wantParam;
6762 int32_t ret = GetShareDataPairAndReturnData(nullptr, ERR_TIMED_OUT, uniqueId, wantParam);
6763 if (ret) {
6764 TAG_LOGE(AAFwkTag::ABILITYMGR, "acqurieShareData failed");
6765 }
6766 }
6767
GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)6768 int32_t AbilityManagerService::GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,
6769 const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
6770 {
6771 TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d, wantParam size:%{public}d",
6772 resultCode, uniqueId, wantParam.Size());
6773 {
6774 std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
6775 auto it = iAcquireShareDataMap_.find(uniqueId);
6776 if (it != iAcquireShareDataMap_.end()) {
6777 auto shareDataPair = it->second;
6778 if (abilityRecord && shareDataPair.first != abilityRecord->GetAbilityRecordId()) {
6779 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is not the abilityRecord from request");
6780 return ERR_INVALID_VALUE;
6781 }
6782 auto callback = shareDataPair.second;
6783 if (!callback) {
6784 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback object null");
6785 return ERR_INVALID_VALUE;
6786 }
6787 auto ret = callback->AcquireShareDataDone(resultCode, wantParam);
6788 iAcquireShareDataMap_.erase(it);
6789 return ret;
6790 }
6791 }
6792 TAG_LOGE(AAFwkTag::ABILITYMGR, "iAcquireShareData null");
6793 return ERR_INVALID_VALUE;
6794 }
6795
VerificationToken(const sptr<IRemoteObject> &token)6796 bool AbilityManagerService::VerificationToken(const sptr<IRemoteObject> &token)
6797 {
6798 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token");
6799 auto dataAbilityManager = GetCurrentDataAbilityManager();
6800 CHECK_POINTER_RETURN_BOOL(dataAbilityManager);
6801 auto connectManager = GetCurrentConnectManager();
6802 CHECK_POINTER_RETURN_BOOL(connectManager);
6803 auto missionListManager = GetCurrentMissionListManager();
6804 CHECK_POINTER_RETURN_BOOL(missionListManager);
6805
6806 if (missionListManager->GetAbilityRecordByToken(token)) {
6807 return true;
6808 }
6809 if (missionListManager->GetAbilityFromTerminateList(token)) {
6810 return true;
6811 }
6812
6813 if (dataAbilityManager->GetAbilityRecordByToken(token)) {
6814 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token4");
6815 return true;
6816 }
6817
6818 if (connectManager->GetExtensionByTokenFromServiceMap(token)) {
6819 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
6820 return true;
6821 }
6822
6823 if (connectManager->GetExtensionByTokenFromAbilityCache(token)) {
6824 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
6825 return true;
6826 }
6827
6828 if (connectManager->GetExtensionByTokenFromTerminatingMap(token)) {
6829 TAG_LOGI(AAFwkTag::ABILITYMGR, "verification token5");
6830 return true;
6831 }
6832
6833 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify token failed");
6834 return false;
6835 }
6836
VerificationAllToken(const sptr<IRemoteObject> &token)6837 bool AbilityManagerService::VerificationAllToken(const sptr<IRemoteObject> &token)
6838 {
6839 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6840 CHECK_POINTER_AND_RETURN(subManagersHelper_, false);
6841 return subManagersHelper_->VerificationAllToken(token);
6842 }
6843
GetCurrentDataAbilityManager()6844 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetCurrentDataAbilityManager()
6845 {
6846 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6847 return subManagersHelper_->GetCurrentDataAbilityManager();
6848 }
6849
GetDataAbilityManager( const sptr<IAbilityScheduler> &scheduler)6850 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManager(
6851 const sptr<IAbilityScheduler> &scheduler)
6852 {
6853 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6854 return subManagersHelper_->GetDataAbilityManager(scheduler);
6855 }
6856
GetDataAbilityManagerByUserId(int32_t userId)6857 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId)
6858 {
6859 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6860 return subManagersHelper_->GetDataAbilityManagerByUserId(userId);
6861 }
6862
GetDataAbilityManagerByToken( const sptr<IRemoteObject> &token)6863 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByToken(
6864 const sptr<IRemoteObject> &token)
6865 {
6866 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6867 return subManagersHelper_->GetDataAbilityManagerByToken(token);
6868 }
6869
GetConnectManagers()6870 std::unordered_map<int, std::shared_ptr<AbilityConnectManager>> AbilityManagerService::GetConnectManagers()
6871 {
6872 if (subManagersHelper_ == nullptr) {
6873 TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
6874 return std::unordered_map<int, std::shared_ptr<AbilityConnectManager>>();
6875 }
6876 return subManagersHelper_->GetConnectManagers();
6877 }
6878
GetCurrentConnectManager()6879 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetCurrentConnectManager()
6880 {
6881 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6882 return subManagersHelper_->GetCurrentConnectManager();
6883 }
6884
GetConnectManagerByUserId(int32_t userId)6885 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByUserId(int32_t userId)
6886 {
6887 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6888 return subManagersHelper_->GetConnectManagerByUserId(userId);
6889 }
6890
GetConnectManagerByToken( const sptr<IRemoteObject> &token)6891 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByToken(
6892 const sptr<IRemoteObject> &token)
6893 {
6894 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6895 return subManagersHelper_->GetConnectManagerByToken(token);
6896 }
6897
GetConnectManagerByAbilityRecordId( const int64_t &abilityRecordId)6898 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByAbilityRecordId(
6899 const int64_t &abilityRecordId)
6900 {
6901 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6902 return subManagersHelper_->GetConnectManagerByAbilityRecordId(abilityRecordId);
6903 }
6904
GetCurrentPendingWantManager()6905 std::shared_ptr<PendingWantManager> AbilityManagerService::GetCurrentPendingWantManager()
6906 {
6907 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6908 return subManagersHelper_->GetCurrentPendingWantManager();
6909 }
6910
GetPendingWantManagerByUserId(int32_t userId)6911 std::shared_ptr<PendingWantManager> AbilityManagerService::GetPendingWantManagerByUserId(int32_t userId)
6912 {
6913 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6914 return subManagersHelper_->GetPendingWantManagerByUserId(userId);
6915 }
6916
GetMissionListManagers()6917 std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>> AbilityManagerService::GetMissionListManagers()
6918 {
6919 if (subManagersHelper_ == nullptr) {
6920 TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
6921 return std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>>();
6922 }
6923 return subManagersHelper_->GetMissionListManagers();
6924 }
6925
GetCurrentMissionListManager()6926 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetCurrentMissionListManager()
6927 {
6928 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6929 return subManagersHelper_->GetCurrentMissionListManager();
6930 }
6931
GetMissionListManagerByUserId(int32_t userId)6932 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetMissionListManagerByUserId(int32_t userId)
6933 {
6934 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6935 return subManagersHelper_->GetMissionListManagerByUserId(userId);
6936 }
6937
GetMissionListWrap()6938 std::shared_ptr<MissionListWrap> AbilityManagerService::GetMissionListWrap()
6939 {
6940 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6941 return subManagersHelper_->GetMissionListWrap();
6942 }
6943
GetUIAbilityManagers()6944 std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>> AbilityManagerService::GetUIAbilityManagers()
6945 {
6946 if (subManagersHelper_ == nullptr) {
6947 TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer null");
6948 return std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>>();
6949 }
6950 return subManagersHelper_->GetUIAbilityManagers();
6951 }
6952
GetCurrentUIAbilityManager()6953 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetCurrentUIAbilityManager()
6954 {
6955 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6956 return subManagersHelper_->GetCurrentUIAbilityManager();
6957 }
6958
GetUIAbilityManagerByUserId(int32_t userId) const6959 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUserId(int32_t userId) const
6960 {
6961 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6962 return subManagersHelper_->GetUIAbilityManagerByUserId(userId);
6963 }
6964
GetUIAbilityManagerByUid(int32_t uid)6965 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUid(int32_t uid)
6966 {
6967 CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6968 return subManagersHelper_->GetUIAbilityManagerByUid(uid);
6969 }
6970
StartResidentApps(int32_t userId)6971 void AbilityManagerService::StartResidentApps(int32_t userId)
6972 {
6973 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps %{public}d", userId);
6974 ConnectServices();
6975 std::vector<AppExecFwk::BundleInfo> bundleInfos;
6976 if (!DelayedSingleton<ResidentProcessManager>::GetInstance()->GetResidentBundleInfosForUser(bundleInfos, userId)) {
6977 TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident bundleinfos failed");
6978 return;
6979 }
6980 DelayedSingleton<ResidentProcessManager>::GetInstance()->Init();
6981 TAG_LOGI(AAFwkTag::ABILITYMGR, "startResidentApps getBundleInfos size:%{public}zu", bundleInfos.size());
6982
6983 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId);
6984 if (!bundleInfos.empty()) {
6985 #ifdef SUPPORT_GRAPHICS
6986 if (userId == U0_USER_ID) {
6987 WaitBootAnimationStart();
6988 }
6989 #endif
6990 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
6991 }
6992 }
6993
StartAutoStartupApps()6994 void AbilityManagerService::StartAutoStartupApps()
6995 {
6996 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6997 if (abilityAutoStartupService_ == nullptr) {
6998 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
6999 return;
7000 }
7001 std::vector<AutoStartupInfo> infoList;
7002 int32_t result = abilityAutoStartupService_->QueryAllAutoStartupApplicationsWithoutPermission(infoList,
7003 GetUserId());
7004 if (result != ERR_OK) {
7005 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed query data");
7006 return;
7007 }
7008
7009 constexpr int retryCount = 5;
7010 RetryStartAutoStartupApps(infoList, retryCount);
7011 }
7012
RetryStartAutoStartupApps( const std::vector<AutoStartupInfo> &infoList, int32_t retryCount)7013 void AbilityManagerService::RetryStartAutoStartupApps(
7014 const std::vector<AutoStartupInfo> &infoList, int32_t retryCount)
7015 {
7016 TAG_LOGD(AAFwkTag::ABILITYMGR,
7017 "Called, retryCount: %{public}d, infoList.size:%{public}zu", retryCount, infoList.size());
7018 std::vector<AutoStartupInfo> failedList;
7019 for (auto info : infoList) {
7020 AppExecFwk::ElementName element;
7021 element.SetBundleName(info.bundleName);
7022 element.SetAbilityName(info.abilityName);
7023 element.SetModuleName(info.moduleName);
7024 Want want;
7025 want.SetElement(element);
7026 want.SetParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, true);
7027 if (info.appCloneIndex > 0 && info.appCloneIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
7028 want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, info.appCloneIndex);
7029 }
7030 if (StartAbility(want) != ERR_OK) {
7031 failedList.push_back(info);
7032 }
7033 }
7034
7035 TAG_LOGD(AAFwkTag::ABILITYMGR,
7036 "RetryCount: %{public}d, failedList.size:%{public}zu", retryCount, failedList.size());
7037 if (!failedList.empty() && retryCount > 0) {
7038 auto retryStartAutoStartupAppsTask = [aams = weak_from_this(), list = failedList, retryCount]() {
7039 auto obj = aams.lock();
7040 if (obj == nullptr) {
7041 TAG_LOGE(AAFwkTag::ABILITYMGR, "retry start auto startup app error, obj null");
7042 return;
7043 }
7044 obj->RetryStartAutoStartupApps(list, retryCount - 1);
7045 };
7046 constexpr int delaytime = 2000;
7047 taskHandler_->SubmitTask(retryStartAutoStartupAppsTask, "RetryStartAutoStartupApps", delaytime);
7048 }
7049 }
7050
SubscribeScreenUnlockedEvent()7051 void AbilityManagerService::SubscribeScreenUnlockedEvent()
7052 {
7053 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7054 // add listen screen unlocked.
7055 EventFwk::MatchingSkills matchingSkills;
7056 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
7057 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
7058 subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
7059 auto userScreenUnlockCallback = [abilityManager = weak_from_this()]() {
7060 TAG_LOGI(AAFwkTag::ABILITYMGR, "user screen unlocked.");
7061 auto abilityMgr = abilityManager.lock();
7062 if (abilityMgr == nullptr) {
7063 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
7064 return;
7065 }
7066 auto taskHandler = abilityMgr->GetTaskHandler();
7067 if (taskHandler == nullptr) {
7068 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid taskHandler pointer");
7069 return;
7070 }
7071 auto startAutoStartupAppsTask = [abilityManager]() {
7072 auto abilityMgr = abilityManager.lock();
7073 if (abilityMgr == nullptr) {
7074 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid abilityMgr pointer");
7075 return;
7076 }
7077 abilityMgr->RemoveScreenUnlockInterceptor();
7078 abilityMgr->StartAutoStartupApps();
7079 abilityMgr->UnSubscribeScreenUnlockedEvent();
7080 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartFailedResidentAbilities();
7081 };
7082 taskHandler->SubmitTask(startAutoStartupAppsTask, "StartAutoStartupApps");
7083 };
7084 screenSubscriber_ = std::make_shared<AbilityRuntime::AbilityManagerEventSubscriber>(subscribeInfo, nullptr,
7085 userScreenUnlockCallback);
7086 bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber_);
7087 if (!subResult) {
7088 constexpr int retryCount = 20;
7089 RetrySubscribeScreenUnlockedEvent(retryCount);
7090 }
7091 }
7092
UnSubscribeScreenUnlockedEvent()7093 void AbilityManagerService::UnSubscribeScreenUnlockedEvent()
7094 {
7095 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
7096 bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_);
7097 TAG_LOGD(AAFwkTag::ABILITYMGR, "Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult);
7098 }
7099
RetrySubscribeScreenUnlockedEvent(int32_t retryCount)7100 void AbilityManagerService::RetrySubscribeScreenUnlockedEvent(int32_t retryCount)
7101 {
7102 TAG_LOGD(AAFwkTag::ABILITYMGR, "RetryCount: %{public}d.", retryCount);
7103 auto retrySubscribeScreenUnlockedEventTask = [aams = weak_from_this(), screenSubscriber = screenSubscriber_,
7104 retryCount]() {
7105 bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber);
7106 auto obj = aams.lock();
7107 if (obj == nullptr) {
7108 TAG_LOGE(AAFwkTag::ABILITYMGR, "retry subscribe screen unlocked event, obj null");
7109 return;
7110 }
7111 if (!subResult && retryCount > 0) {
7112 obj->RetrySubscribeScreenUnlockedEvent(retryCount - 1);
7113 }
7114 };
7115 constexpr int delaytime = 200;
7116 taskHandler_->SubmitTask(retrySubscribeScreenUnlockedEventTask, "RetrySubscribeScreenUnlockedEvent", delaytime);
7117 }
7118
RemoveScreenUnlockInterceptor()7119 void AbilityManagerService::RemoveScreenUnlockInterceptor()
7120 {
7121 interceptorExecuter_->RemoveInterceptor("ScreenUnlock");
7122 }
7123
ConnectServices()7124 void AbilityManagerService::ConnectServices()
7125 {
7126 TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting appMgr service run completed");
7127 while (!DelayedSingleton<AppScheduler>::GetInstance()->Init(shared_from_this())) {
7128 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed init appScheduler");
7129 usleep(REPOLL_TIME_MICRO_SECONDS);
7130 }
7131 AppExceptionHandler::GetInstance().RegisterAppExceptionCallback();
7132
7133 TAG_LOGI(AAFwkTag::ABILITYMGR, "waiting bundleMgr service run completed");
7134 while (AbilityUtil::GetBundleManagerHelper() == nullptr) {
7135 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle manager helper failed");
7136 usleep(REPOLL_TIME_MICRO_SECONDS);
7137 }
7138 AbilityUtil::GetBundleManagerHelper()->ConnectTillSuccess();
7139 TAG_LOGI(AAFwkTag::ABILITYMGR, "bms success");
7140 }
7141
GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)7142 int AbilityManagerService::GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)
7143 {
7144 TAG_LOGI(AAFwkTag::ABILITYMGR, "get pending request info");
7145 auto pendingWantManager = GetCurrentPendingWantManager();
7146 CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
7147 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
7148 CHECK_POINTER_AND_RETURN(info, ERR_INVALID_VALUE);
7149 return pendingWantManager->GetWantSenderInfo(target, info);
7150 }
7151
GetAppMemorySize()7152 int AbilityManagerService::GetAppMemorySize()
7153 {
7154 TAG_LOGI(AAFwkTag::ABILITYMGR, "service getAppMemorySize start");
7155 const char *key = "const.product.arkheaplimit";
7156 const char *def = "512m";
7157 char *valueGet = nullptr;
7158 unsigned int len = 128;
7159 int ret = GetParameter(key, def, valueGet, len);
7160 int resultInt = 0;
7161 if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7162 if (valueGet == nullptr) {
7163 TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, valueGet null", __func__);
7164 return APP_MEMORY_SIZE;
7165 }
7166 int len = strlen(valueGet);
7167 for (int i = 0; i < len; i++) {
7168 if (valueGet[i] >= '0' && valueGet[i] <= '9') {
7169 resultInt *= SIZE_10;
7170 resultInt += valueGet[i] - '0';
7171 }
7172 }
7173 if (resultInt == 0) {
7174 return APP_MEMORY_SIZE;
7175 }
7176 return resultInt;
7177 }
7178 return APP_MEMORY_SIZE;
7179 }
7180
IsRamConstrainedDevice()7181 bool AbilityManagerService::IsRamConstrainedDevice()
7182 {
7183 TAG_LOGI(AAFwkTag::ABILITYMGR, "service IsRamConstrainedDevice start");
7184 const char *key = "const.product.islowram";
7185 const char *def = "0";
7186 char *valueGet = nullptr;
7187 unsigned int len = 128;
7188 int ret = GetParameter(key, def, valueGet, len);
7189 if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
7190 int value = atoi(valueGet);
7191 if (value) {
7192 return true;
7193 }
7194 return false;
7195 }
7196 return false;
7197 }
7198
GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)7199 int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)
7200 {
7201 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7202 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7203 if (!abilityRecord) {
7204 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
7205 return -1;
7206 }
7207 if (!JudgeSelfCalled(abilityRecord)) {
7208 return -1;
7209 }
7210 return GetMissionIdByAbilityTokenInner(token);
7211 }
7212
GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)7213 int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)
7214 {
7215 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7216 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7217 if (!abilityRecord) {
7218 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
7219 return -1;
7220 }
7221 auto userId = abilityRecord->GetOwnerMissionUserId();
7222 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7223 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7224 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7225 return uiAbilityManager->GetSessionIdByAbilityToken(token);
7226 }
7227 auto missionListManager = GetMissionListManagerByUserId(userId);
7228 if (!missionListManager) {
7229 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null mission userId=%{public}d", userId);
7230 return -1;
7231 }
7232 return missionListManager->GetMissionIdByAbilityToken(token);
7233 }
7234
GetAbilityTokenByMissionId(int32_t missionId)7235 sptr<IRemoteObject> AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId)
7236 {
7237 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7238 auto missionListManager = GetCurrentMissionListManager();
7239 if (!missionListManager) {
7240 return nullptr;
7241 }
7242 return missionListManager->GetAbilityTokenByMissionId(missionId);
7243 }
7244
StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken, const sptr<IRemoteObject> &connect)7245 int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken,
7246 const sptr<IRemoteObject> &connect)
7247 {
7248 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin startRemoteAbilityByCall", __func__);
7249 Want remoteWant = want;
7250 UpdateCallerInfoUtil::GetInstance().UpdateDmsCallerInfo(remoteWant, callerToken);
7251 if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
7252 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s addStartControlParam failed", __func__);
7253 return ERR_INVALID_VALUE;
7254 }
7255 int32_t missionId = -1;
7256 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7257 missionId = GetMissionIdByAbilityTokenInner(callerToken);
7258 if (!missionId) {
7259 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid missionId id");
7260 return ERR_INVALID_VALUE;
7261 }
7262 } else {
7263 missionId = GetMissionIdByAbilityToken(callerToken);
7264 }
7265 if (missionId < 0) {
7266 return ERR_INVALID_VALUE;
7267 }
7268 remoteWant.SetParam(DMS_MISSION_ID, missionId);
7269 DistributedClient dmsClient;
7270 return dmsClient.StartRemoteAbilityByCall(remoteWant, connect);
7271 }
7272
ReleaseRemoteAbility(const sptr<IRemoteObject> &connect, const AppExecFwk::ElementName &element)7273 int AbilityManagerService::ReleaseRemoteAbility(const sptr<IRemoteObject> &connect,
7274 const AppExecFwk::ElementName &element)
7275 {
7276 DistributedClient dmsClient;
7277 return dmsClient.ReleaseRemoteAbility(connect, element);
7278 }
7279
StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t accountId)7280 int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect,
7281 const sptr<IRemoteObject> &callerToken, int32_t accountId)
7282 {
7283 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
7284 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7285 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7286 if (IsCrossUserCall(accountId)) {
7287 CHECK_CALLER_IS_SYSTEM_APP;
7288 }
7289
7290 if (VerifyAccountPermission(accountId) == CHECK_PERMISSION_FAILED) {
7291 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
7292 return CHECK_PERMISSION_FAILED;
7293 }
7294
7295 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7296 if (abilityRecord && !JudgeSelfCalled(abilityRecord)) {
7297 return CHECK_PERMISSION_FAILED;
7298 }
7299
7300 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
7301 int32_t appIndex = 0;
7302 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
7303 return ERR_APP_CLONE_INDEX_INVALID;
7304 }
7305 auto checkRet = AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
7306 GetUserId(), appIndex, callerToken);
7307 if (checkRet != ERR_OK) {
7308 return checkRet;
7309 }
7310 StartAbilityInfoWrap threadLocalInfo(want, GetUserId(), appIndex, callerToken);
7311 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
7312 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), true, nullptr,
7313 shouldBlockFunc);
7314 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
7315 interceptorExecuter_->DoProcess(interceptorParam);
7316 if (result != ERR_OK) {
7317 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
7318 return result;
7319 }
7320
7321 if (CheckIfOperateRemote(want)) {
7322 TAG_LOGI(AAFwkTag::ABILITYMGR, "start remote ability by call");
7323 return StartRemoteAbilityByCall(want, callerToken, connect->AsObject());
7324 }
7325
7326 if (accountId == U0_USER_ID) {
7327 accountId = DEFAULT_INVAL_VALUE;
7328 }
7329 int32_t oriValidUserId = GetValidUserId(accountId);
7330 if (!JudgeMultiUserConcurrency(oriValidUserId)) {
7331 TAG_LOGE(AAFwkTag::ABILITYMGR, "multi-user non-concurrent unsatisfied");
7332 return ERR_CROSS_USER;
7333 }
7334
7335 AbilityRequest abilityRequest;
7336 abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
7337 abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
7338 abilityRequest.callerToken = callerToken;
7339 abilityRequest.startSetting = nullptr;
7340 abilityRequest.want = want;
7341 abilityRequest.connect = connect;
7342 result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
7343 if (result != ERR_OK) {
7344 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request error");
7345 return result;
7346 }
7347
7348 if (!abilityRequest.abilityInfo.isStageBasedModel) {
7349 TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability not stage base model");
7350 return RESOLVE_CALL_ABILITY_VERSION_ERR;
7351 }
7352
7353 result = CheckStartByCallPermission(abilityRequest);
7354 if (result != ERR_OK) {
7355 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStartByCallPermission fail, result:%{public}d", result);
7356 return result;
7357 }
7358
7359 TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityInfo.applicationInfo.singleton is %{public}s",
7360 abilityRequest.abilityInfo.applicationInfo.singleton ? "true" : "false");
7361 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
7362 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
7363 false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityRequest.abilityInfo), false, appIndex);
7364 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
7365 afterCheckExecuter_->DoProcess(afterCheckParam);
7366 if (result != ERR_OK) {
7367 TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ null or doProcess error");
7368 return result;
7369 }
7370 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7371 ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7372 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
7373 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
7374 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7375 return uiAbilityManager->ResolveLocked(abilityRequest);
7376 }
7377
7378 auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
7379 if (missionListMgr == nullptr) {
7380 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null designated user id=%{public}d", oriValidUserId);
7381 return ERR_INVALID_VALUE;
7382 }
7383 ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7384
7385 return missionListMgr->ResolveLocked(abilityRequest);
7386 }
7387
StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)7388 int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)
7389 {
7390 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7391 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
7392 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
7393 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7394 ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7395 auto uiAbilityManager = GetUIAbilityManagerByUserId(validUserId);
7396 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7397 return uiAbilityManager->ResolveLocked(abilityRequest);
7398 }
7399
7400 auto missionListMgr = GetMissionListManagerByUserId(validUserId);
7401 if (missionListMgr == nullptr) {
7402 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null designated userId=%{public}d", validUserId);
7403 return ERR_INVALID_VALUE;
7404 }
7405 ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7406
7407 return missionListMgr->ResolveLocked(abilityRequest);
7408 }
7409
ReleaseCall( const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)7410 int AbilityManagerService::ReleaseCall(
7411 const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
7412 {
7413 TAG_LOGD(AAFwkTag::ABILITYMGR, "Release called ability.");
7414
7415 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7416 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7417
7418 std::string elementName = element.GetURI();
7419 TAG_LOGD(AAFwkTag::ABILITYMGR, "try to release called ability, name: %{public}s.", elementName.c_str());
7420
7421 if (CheckIsRemote(element.GetDeviceID())) {
7422 TAG_LOGI(AAFwkTag::ABILITYMGR, "release remote ability");
7423 return ReleaseRemoteAbility(connect->AsObject(), element);
7424 }
7425
7426 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7427 auto uiAbilityManager = GetCurrentUIAbilityManager();
7428 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7429 return uiAbilityManager->ReleaseCallLocked(connect, element);
7430 }
7431 auto missionListManager = GetCurrentMissionListManager();
7432 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
7433 return missionListManager->ReleaseCallLocked(connect, element);
7434 }
7435
JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)7436 int AbilityManagerService::JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)
7437 {
7438 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
7439 if (abilityInfo.visible) {
7440 return ERR_OK;
7441 }
7442 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
7443 if (callerTokenId == abilityInfo.applicationInfo.accessTokenId ||
7444 callerTokenId == static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID())) { // foundation call is allowed
7445 return ERR_OK;
7446 }
7447 if (AccessTokenKit::VerifyAccessToken(callerTokenId,
7448 PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == AppExecFwk::Constants::PERMISSION_GRANTED) {
7449 return ERR_OK;
7450 }
7451 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken:%{private}u, targetToken:%{private}u, caller without permission",
7452 callerTokenId, abilityInfo.applicationInfo.accessTokenId);
7453 return ABILITY_VISIBLE_FALSE_DENY_REQUEST;
7454 }
7455
StartUser(int userId, sptr<IUserCallback> callback, bool isAppRecovery)7456 int AbilityManagerService::StartUser(int userId, sptr<IUserCallback> callback, bool isAppRecovery)
7457 {
7458 TAG_LOGI(AAFwkTag::ABILITYMGR, "startUser in service:%{public}d", userId);
7459 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7460 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUser permission verification failed, not account process");
7461 if (callback != nullptr) {
7462 callback->OnStartUserDone(userId, CHECK_PERMISSION_FAILED);
7463 }
7464 return CHECK_PERMISSION_FAILED;
7465 }
7466
7467 if (userController_) {
7468 userController_->StartUser(userId, callback, isAppRecovery);
7469 }
7470 return 0;
7471 }
7472
StopUser(int userId, const sptr<IUserCallback> &callback)7473 int AbilityManagerService::StopUser(int userId, const sptr<IUserCallback> &callback)
7474 {
7475 TAG_LOGI(AAFwkTag::ABILITYMGR, "stopUser in service:%{public}d", userId);
7476 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7477 TAG_LOGE(AAFwkTag::ABILITYMGR, "stopUser permission verification failed, not account process");
7478 if (callback != nullptr) {
7479 callback->OnStopUserDone(userId, CHECK_PERMISSION_FAILED);
7480 }
7481 return CHECK_PERMISSION_FAILED;
7482 }
7483
7484 auto ret = -1;
7485 if (userController_) {
7486 ret = userController_->StopUser(userId);
7487 TAG_LOGD(AAFwkTag::ABILITYMGR, "ret = %{public}d", ret);
7488 }
7489 if (callback) {
7490 callback->OnStopUserDone(userId, ret);
7491 }
7492 return 0;
7493 }
7494
LogoutUser(int32_t userId)7495 int AbilityManagerService::LogoutUser(int32_t userId)
7496 {
7497 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7498 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed, not account process");
7499 return CHECK_PERMISSION_FAILED;
7500 }
7501
7502 // Lister screen unlock for auto startup apps.
7503 if (system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) {
7504 InitInterceptorForScreenUnlock();
7505 SubscribeScreenUnlockedEvent();
7506 }
7507
7508 if (userController_) {
7509 auto ret = userController_->LogoutUser(userId);
7510 TAG_LOGD(AAFwkTag::ABILITYMGR, "logout user return = %{public}d", ret);
7511 return ret;
7512 }
7513 return ERR_OK;
7514 }
7515
OnAcceptWantResponse( const AAFwk::Want &want, const std::string &flag, int32_t requestId)7516 void AbilityManagerService::OnAcceptWantResponse(
7517 const AAFwk::Want &want, const std::string &flag, int32_t requestId)
7518 {
7519 TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
7520 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7521 auto uiAbilityManager = GetCurrentUIAbilityManager();
7522 CHECK_POINTER(uiAbilityManager);
7523 uiAbilityManager->OnAcceptWantResponse(want, flag, requestId);
7524 return;
7525 }
7526 auto missionListManager = GetCurrentMissionListManager();
7527 if (!missionListManager) {
7528 return;
7529 }
7530 missionListManager->OnAcceptWantResponse(want, flag);
7531 }
7532
OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId)7533 void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7534 {
7535 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", want.GetElement().GetURI().c_str());
7536 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7537 auto uiAbilityManager = GetCurrentUIAbilityManager();
7538 CHECK_POINTER(uiAbilityManager);
7539 uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7540 return;
7541 }
7542 auto missionListManager = GetCurrentMissionListManager();
7543 if (!missionListManager) {
7544 return;
7545 }
7546 missionListManager->OnStartSpecifiedAbilityTimeoutResponse(want);
7547 }
7548
OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag, int32_t requestId)7549 void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag,
7550 int32_t requestId)
7551 {
7552 TAG_LOGD(AAFwkTag::ABILITYMGR, "flag = %{public}s", flag.c_str());
7553 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7554 auto uiAbilityManager = GetCurrentUIAbilityManager();
7555 CHECK_POINTER(uiAbilityManager);
7556 uiAbilityManager->OnStartSpecifiedProcessResponse(want, flag, requestId);
7557 return;
7558 }
7559 }
7560
OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId)7561 void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7562 {
7563 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", want.GetElement().GetURI().c_str());
7564 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7565 auto uiAbilityManager = GetCurrentUIAbilityManager();
7566 CHECK_POINTER(uiAbilityManager);
7567 uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7568 return;
7569 }
7570 }
7571
GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)7572 int AbilityManagerService::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
7573 {
7574 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7575 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get running ability infos.");
7576 CHECK_CALLER_IS_SYSTEM_APP;
7577 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7578 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7579 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
7580 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7581 uiAbilityManager->GetAbilityRunningInfos(info, isPerm);
7582 } else {
7583 auto missionListManager = GetCurrentMissionListManager();
7584 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
7585 missionListManager->GetAbilityRunningInfos(info, isPerm);
7586 }
7587
7588 UpdateFocusState(info);
7589
7590 return ERR_OK;
7591 }
7592
UpdateFocusState(std::vector<AbilityRunningInfo> &info)7593 void AbilityManagerService::UpdateFocusState(std::vector<AbilityRunningInfo> &info)
7594 {
7595 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7596 if (info.empty()) {
7597 return;
7598 }
7599
7600 #ifdef SUPPORT_GRAPHICS
7601 sptr<IRemoteObject> token;
7602 int ret = IN_PROCESS_CALL(GetTopAbility(token));
7603 if (ret != ERR_OK || token == nullptr) {
7604 return;
7605 }
7606
7607 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7608 if (abilityRecord == nullptr) {
7609 TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
7610 return;
7611 }
7612
7613 for (auto &item : info) {
7614 if (item.uid == abilityRecord->GetUid() && item.pid == abilityRecord->GetPid() &&
7615 item.ability == abilityRecord->GetElementName()) {
7616 item.abilityState = static_cast<int>(AbilityState::ACTIVE);
7617 break;
7618 }
7619 }
7620 #endif
7621 }
7622
GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)7623 int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)
7624 {
7625 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7626 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension infos, upperLimit : %{public}d", upperLimit);
7627 CHECK_CALLER_IS_SYSTEM_APP;
7628 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7629 auto connectManager = GetCurrentConnectManager();
7630 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
7631 connectManager->GetExtensionRunningInfos(upperLimit, info, GetUserId(), isPerm);
7632 return ERR_OK;
7633 }
7634
GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)7635 int AbilityManagerService::GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)
7636 {
7637 return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfos(info);
7638 }
7639
GetProcessRunningInfosByUserId( std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)7640 int AbilityManagerService::GetProcessRunningInfosByUserId(
7641 std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)
7642 {
7643 return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfosByUserId(info, userId);
7644 }
7645
ClearUserData(int32_t userId)7646 void AbilityManagerService::ClearUserData(int32_t userId)
7647 {
7648 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7649 CHECK_POINTER(subManagersHelper_);
7650 subManagersHelper_->ClearSubManagers(userId);
7651 }
7652
RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)7653 int AbilityManagerService::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
7654 {
7655 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7656 if (!isSaCall) {
7657 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s:permission verification failed", __func__);
7658 return 0;
7659 }
7660
7661 auto missionListManager = GetCurrentMissionListManager();
7662 CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7663 missionListManager->RegisterSnapshotHandler(handler);
7664 TAG_LOGI(AAFwkTag::ABILITYMGR, "snapshot: abilityManagerService register snapshot handler success");
7665 return ERR_OK;
7666 }
7667
GetMissionSnapshot(const std::string& deviceId, int32_t missionId, MissionSnapshot& missionSnapshot, bool isLowResolution)7668 int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId,
7669 MissionSnapshot& missionSnapshot, bool isLowResolution)
7670 {
7671 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7672 CHECK_CALLER_IS_SYSTEM_APP;
7673 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
7674 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: permission verification failed", __func__);
7675 return CHECK_PERMISSION_FAILED;
7676 }
7677
7678 if (CheckIsRemote(deviceId)) {
7679 TAG_LOGI(AAFwkTag::ABILITYMGR, "get remote mission snapshot");
7680 return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot);
7681 }
7682 TAG_LOGI(AAFwkTag::ABILITYMGR, "get local mission snapshot");
7683 auto missionListManager = GetCurrentMissionListManager();
7684 CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7685 auto token = GetAbilityTokenByMissionId(missionId);
7686 bool result = missionListManager->GetMissionSnapshot(missionId, token, missionSnapshot, isLowResolution);
7687 if (!result) {
7688 return INNER_ERR;
7689 }
7690 return ERR_OK;
7691 }
7692 #ifdef SUPPORT_SCREEN
UpdateMissionSnapShot(const sptr<IRemoteObject> &token, const std::shared_ptr<Media::PixelMap> &pixelMap)7693 void AbilityManagerService::UpdateMissionSnapShot(const sptr<IRemoteObject> &token,
7694 const std::shared_ptr<Media::PixelMap> &pixelMap)
7695 {
7696 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)) {
7697 return;
7698 }
7699 auto missionListManager = GetCurrentMissionListManager();
7700 if (missionListManager) {
7701 missionListManager->UpdateSnapShot(token, pixelMap);
7702 }
7703 }
7704 #endif // SUPPORT_SCREEN
EnableRecoverAbility(const sptr<IRemoteObject>& token)7705 void AbilityManagerService::EnableRecoverAbility(const sptr<IRemoteObject>& token)
7706 {
7707 TAG_LOGD(AAFwkTag::ABILITYMGR, "Enable recovery ability.");
7708 if (token == nullptr) {
7709 return;
7710 }
7711 auto record = Token::GetAbilityRecordByToken(token);
7712 if (record == nullptr) {
7713 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::failed find abilityRecord by token", __func__);
7714 return;
7715 }
7716 if (record->IsClearMissionFlag()) {
7717 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::not allow EnableRecoverAbility before clearMission",
7718 __func__);
7719 return;
7720 }
7721
7722 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7723 auto tokenID = record->GetApplicationInfo().accessTokenId;
7724 if (callingTokenId != tokenID) {
7725 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery scheduleRecoverAbility not self, not enabled");
7726 return;
7727 }
7728 {
7729 std::lock_guard<ffrt::mutex> guard(globalLock_);
7730 auto it = appRecoveryHistory_.find(record->GetUid());
7731 if (it == appRecoveryHistory_.end()) {
7732 appRecoveryHistory_.emplace(record->GetUid(), 0);
7733 }
7734 }
7735 auto userId = record->GetOwnerMissionUserId();
7736 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7737 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7738 CHECK_POINTER(uiAbilityManager);
7739 const auto& abilityInfo = record->GetAbilityInfo();
7740 std::string abilityName = abilityInfo.name;
7741 auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
7742 if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
7743 abilityName += std::to_string(sessionId);
7744 }
7745 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->AddAbilityRecoverInfo(
7746 abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName, sessionId);
7747 } else {
7748 auto missionListMgr = GetMissionListManagerByUserId(userId);
7749 if (missionListMgr == nullptr) {
7750 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null");
7751 return;
7752 }
7753 missionListMgr->EnableRecoverAbility(record->GetMissionId());
7754 }
7755 }
7756
ScheduleClearRecoveryPageStack()7757 void AbilityManagerService::ScheduleClearRecoveryPageStack()
7758 {
7759 int32_t callerUid = IPCSkeleton::GetCallingUid();
7760 std::string bundleName;
7761 auto bms = AbilityUtil::GetBundleManagerHelper();
7762 CHECK_POINTER_IS_NULLPTR(bms);
7763
7764 if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
7765 TAG_LOGE(AAFwkTag::ABILITYMGR, "scheduleClearRecoveryPageStack get bundleName failed");
7766 return;
7767 }
7768
7769 auto tokenId = IPCSkeleton::GetCallingTokenID();
7770
7771 TAG_LOGI(AAFwkTag::ABILITYMGR,
7772 "ScheduleClearRecoveryPageStack bundleName = %{public}s, callerUid = %{public}d, tokenId = %{public}d",
7773 bundleName.c_str(), callerUid, tokenId);
7774 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
7775 DeleteAppExitReason(bundleName, tokenId);
7776 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
7777 DeleteAllRecoverInfoByTokenId(tokenId);
7778 }
7779
ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo, const std::string& abilityName, const std::string& result)7780 void AbilityManagerService::ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo,
7781 const std::string& abilityName, const std::string& result)
7782 {
7783 HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
7784 "APP_UID", appId,
7785 "VERSION_CODE", std::to_string(appInfo.versionCode),
7786 "VERSION_NAME", appInfo.versionName,
7787 "BUNDLE_NAME", appInfo.bundleName,
7788 "ABILITY_NAME", abilityName,
7789 "RECOVERY_RESULT", result);
7790 }
7791
SubmitSaveRecoveryInfo(const sptr<IRemoteObject>& token)7792 void AbilityManagerService::SubmitSaveRecoveryInfo(const sptr<IRemoteObject>& token)
7793 {
7794 if (token == nullptr) {
7795 TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo token null");
7796 return;
7797 }
7798 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7799 if (abilityRecord == nullptr) {
7800 TAG_LOGE(AAFwkTag::ABILITYMGR, "submitInfo abilityRecord null");
7801 return;
7802 }
7803 auto abilityInfo = abilityRecord->GetAbilityInfo();
7804 auto userId = abilityRecord->GetOwnerMissionUserId();
7805 auto tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
7806 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7807 if (callingTokenId != tokenId) {
7808 TAG_LOGE(AAFwkTag::ABILITYMGR, "SubmitSaveRecoveryInfo not self, not enabled");
7809 return;
7810 }
7811 std::string abilityName = abilityInfo.name;
7812 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7813 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7814 CHECK_POINTER(uiAbilityManager);
7815 auto sessionId = uiAbilityManager->GetSessionIdByAbilityToken(token);
7816 if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
7817 abilityName += std::to_string(sessionId);
7818 }
7819 } else {
7820 auto missionListMgr = GetMissionListManagerByUserId(userId);
7821 if (missionListMgr == nullptr) {
7822 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr null");
7823 return;
7824 }
7825 abilityName += std::to_string(abilityRecord->GetMissionId());
7826 }
7827 TAG_LOGI(AAFwkTag::ABILITYMGR,
7828 "submitInfo bundleName = %{public}s, moduleName = %{public}s, abilityName = %{public}s, tokenId = %{public}d",
7829 abilityInfo.bundleName.c_str(), abilityInfo.moduleName.c_str(), abilityName.c_str(), tokenId);
7830 RecoveryInfo recoveryInfo;
7831 recoveryInfo.bundleName = abilityInfo.bundleName;
7832 recoveryInfo.moduleName = abilityInfo.moduleName;
7833 recoveryInfo.abilityName = abilityName;
7834 recoveryInfo.time = time(nullptr);
7835 OHOS::AAFwk::RecoveryInfoTimer::GetInstance().SubmitSaveRecoveryInfo(recoveryInfo);
7836 }
7837
AppRecoverKill(pid_t pid, int32_t reason)7838 void AbilityManagerService::AppRecoverKill(pid_t pid, int32_t reason)
7839 {
7840 AppExecFwk::AppFaultDataBySA faultDataSA;
7841 faultDataSA.errorObject.name = "appRecovery";
7842 switch (reason) {
7843 case AppExecFwk::StateReason::CPP_CRASH:
7844 faultDataSA.faultType = AppExecFwk::FaultDataType::CPP_CRASH;
7845 break;
7846 case AppExecFwk::StateReason::JS_ERROR:
7847 faultDataSA.faultType = AppExecFwk::FaultDataType::JS_ERROR;
7848 break;
7849 case AppExecFwk::StateReason::LIFECYCLE:
7850 case AppExecFwk::StateReason::APP_FREEZE:
7851 faultDataSA.faultType = AppExecFwk::FaultDataType::APP_FREEZE;
7852 break;
7853 default:
7854 faultDataSA.faultType = AppExecFwk::FaultDataType::UNKNOWN;
7855 }
7856 faultDataSA.pid = pid;
7857 IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFaultBySA(faultDataSA));
7858 }
7859
ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)7860 void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)
7861 {
7862 if (token == nullptr) {
7863 return;
7864 }
7865 auto record = Token::GetAbilityRecordByToken(token);
7866 if (record == nullptr) {
7867 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::failed find abilityRecord by token", __func__);
7868 return;
7869 }
7870 if (!record->IsForeground() && !record->GetAbilityForegroundingFlag()) {
7871 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::recoveryAbility failed"
7872 "due background", __func__);
7873 return;
7874 }
7875
7876 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7877 auto tokenID = record->GetApplicationInfo().accessTokenId;
7878 if (callingTokenId != tokenID) {
7879 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery scheduleRecoverAbility no self, no enabled");
7880 return;
7881 }
7882
7883 AAFwk::Want curWant;
7884 {
7885 std::lock_guard<ffrt::mutex> guard(globalLock_);
7886 auto type = record->GetAbilityInfo().type;
7887 if (type != AppExecFwk::AbilityType::PAGE) {
7888 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s appRecovery::only recover for page ability", __func__);
7889 return;
7890 }
7891
7892 constexpr int64_t MIN_RECOVERY_TIME = 60;
7893 int64_t now = time(nullptr);
7894 auto it = appRecoveryHistory_.find(record->GetUid());
7895 auto appInfo = record->GetApplicationInfo();
7896 auto abilityInfo = record->GetAbilityInfo();
7897
7898 if ((it != appRecoveryHistory_.end()) &&
7899 (it->second + MIN_RECOVERY_TIME > now)) {
7900 TAG_LOGE(AAFwkTag::ABILITYMGR,
7901 "%{public}s appRecovery recover more once in one minute, kill app(%{public}d)",
7902 __func__, record->GetPid());
7903 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_WITHIN_ONE_MINUTE");
7904 AppRecoverKill(record->GetPid(), reason);
7905 return;
7906 }
7907
7908 if (want != nullptr) {
7909 TAG_LOGD(AAFwkTag::ABILITYMGR, "BundleName:%{public}s targetBundleName:%{public}s.",
7910 appInfo.bundleName.c_str(), want->GetElement().GetBundleName().c_str());
7911 if (want->GetElement().GetBundleName().empty() ||
7912 (appInfo.bundleName.compare(want->GetElement().GetBundleName()) != 0)) {
7913 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery bundleName not match, not recovery ability");
7914 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_BUNDLE_NAME_NOT_MATCH");
7915 return;
7916 }
7917 if (want->GetElement().GetAbilityName().empty()) {
7918 TAG_LOGD(AAFwkTag::ABILITYMGR, "AppRecovery recovery target ability is empty");
7919 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_TARGET_ABILITY_EMPTY");
7920 return;
7921 }
7922 auto bms = AbilityUtil::GetBundleManagerHelper();
7923 CHECK_POINTER_IS_NULLPTR(bms);
7924 AppExecFwk::BundleInfo bundleInfo;
7925 auto bundleName = want->GetElement().GetBundleName();
7926 int32_t userId = GetUserId();
7927 bool ret = IN_PROCESS_CALL(
7928 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo,
7929 userId));
7930 if (!ret) {
7931 TAG_LOGE(AAFwkTag::ABILITYMGR, "appRecovery get bundleInfo fail, not recovery");
7932 return;
7933 }
7934 bool isRestartPage = false;
7935 auto abilityName = want->GetElement().GetAbilityName();
7936 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
7937 if ((abilityName.compare(it->name) == 0) && it->type == AppExecFwk::AbilityType::PAGE) {
7938 isRestartPage = true;
7939 break;
7940 }
7941 }
7942 if (!isRestartPage) {
7943 TAG_LOGI(AAFwkTag::ABILITYMGR, "appRecovery target ability type not PAGE");
7944 ReportAppRecoverResult(record->GetUid(), appInfo, abilityName, "FAIL_TARGET_ABILITY_NOT_PAGE");
7945 return;
7946 }
7947 }
7948
7949 appRecoveryHistory_[record->GetUid()] = now;
7950 curWant = (want == nullptr) ? record->GetWant() : *want;
7951 curWant.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
7952
7953 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "SUCCESS");
7954 }
7955 RestartApp(curWant, true);
7956 }
7957
GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId, MissionSnapshot& missionSnapshot)7958 int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId,
7959 MissionSnapshot& missionSnapshot)
7960 {
7961 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7962 TAG_LOGI(AAFwkTag::ABILITYMGR, "getRemoteMissionSnapshotInfo");
7963 std::unique_ptr<MissionSnapshot> missionSnapshotPtr = std::make_unique<MissionSnapshot>();
7964 DistributedClient dmsClient;
7965 int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr);
7966 if (result != ERR_OK) {
7967 TAG_LOGE(AAFwkTag::ABILITYMGR, "getRemoteMissionSnapshotInfo failed, result=%{public}d", result);
7968 return result;
7969 }
7970 missionSnapshot = *missionSnapshotPtr;
7971 return ERR_OK;
7972 }
7973
StartSwitchUserDialog()7974 void AbilityManagerService::StartSwitchUserDialog()
7975 {
7976 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog extension ability come");
7977 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7978 TAG_LOGE(AAFwkTag::ABILITYMGR, "scene board enabled, dialog not show");
7979 return;
7980 }
7981
7982 if (userController_ == nullptr) {
7983 TAG_LOGE(AAFwkTag::ABILITYMGR, "user Controller instance null");
7984 return;
7985 }
7986 #ifdef SUPPORT_GRAPHICS
7987 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
7988 if (sysDialog == nullptr) {
7989 TAG_LOGE(AAFwkTag::ABILITYMGR, "system dialog scheduler instance null");
7990 return;
7991 }
7992
7993 Want dialogWant = sysDialog->GetSwitchUserDialogWant();
7994 StartSwitchUserDialogInner(dialogWant, userController_->GetFreezingNewUserId());
7995 #endif // SUPPORT_GRAPHICS
7996 }
7997
7998
StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)7999 void AbilityManagerService::StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)
8000 {
8001 TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog inner come");
8002 EventInfo eventInfo = BuildEventInfo(want, lastUserId);
8003 eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
8004 AbilityRequest abilityRequest;
8005 auto result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
8006 if (result != ERR_OK) {
8007 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request local error");
8008 eventInfo.errCode = result;
8009 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8010 return;
8011 }
8012
8013 auto abilityInfo = abilityRequest.abilityInfo;
8014 auto startUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
8015 result = CheckOptExtensionAbility(want, abilityRequest, startUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
8016 if (result != ERR_OK) {
8017 TAG_LOGE(AAFwkTag::ABILITYMGR, "check extensionAbility type error");
8018 eventInfo.errCode = result;
8019 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8020 return;
8021 }
8022
8023 auto connectManager = GetConnectManagerByUserId(startUserId);
8024 if (connectManager == nullptr) {
8025 CHECK_POINTER(subManagersHelper_);
8026 subManagersHelper_->InitConnectManager(startUserId, false);
8027 connectManager = GetConnectManagerByUserId(startUserId);
8028 if (connectManager == nullptr) {
8029 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", startUserId);
8030 eventInfo.errCode = ERR_INVALID_VALUE;
8031 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8032 return;
8033 }
8034 }
8035
8036 UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
8037 abilityRequest.abilityInfo.extensionAbilityType);
8038 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
8039 if (eventInfo.errCode != ERR_OK) {
8040 TAG_LOGE(AAFwkTag::ABILITYMGR, "eventInfo errCode:%{public}d", eventInfo.errCode);
8041 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
8042 }
8043 }
8044
StartFreezingScreen()8045 void AbilityManagerService::StartFreezingScreen()
8046 {
8047 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8048 #ifdef SUPPORT_GRAPHICS
8049 StartSwitchUserDialog();
8050 std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8051 IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Freeze(displayIds));
8052 #endif
8053 }
8054
StopFreezingScreen()8055 void AbilityManagerService::StopFreezingScreen()
8056 {
8057 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8058 #ifdef SUPPORT_GRAPHICS
8059 std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
8060 IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Unfreeze(displayIds));
8061 StopSwitchUserDialog();
8062 #endif
8063 }
8064
UserStarted(int32_t userId)8065 void AbilityManagerService::UserStarted(int32_t userId)
8066 {
8067 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8068 CHECK_POINTER(subManagersHelper_);
8069 subManagersHelper_->InitSubManagers(userId, false);
8070 }
8071
SwitchToUser(int32_t oldUserId, int32_t userId, sptr<IUserCallback> callback, bool isAppRecovery)8072 void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId, sptr<IUserCallback> callback,
8073 bool isAppRecovery)
8074 {
8075 TAG_LOGI(AAFwkTag::ABILITYMGR,
8076 "%{public}s, oldUserId:%{public}d, newUserId:%{public}d, isAppRecovery:%{public}d", __func__,
8077 oldUserId, userId, isAppRecovery);
8078 SwitchManagers(userId);
8079 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8080 PauseOldUser(oldUserId);
8081 ConnectServices();
8082 StartUserApps();
8083 }
8084 callback->OnStartUserDone(userId, ERR_OK);
8085 bool isBoot = oldUserId == U0_USER_ID ? true : false;
8086 StartHighestPriorityAbility(userId, isBoot, isAppRecovery);
8087 if (taskHandler_) {
8088 taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() {
8089 TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps userId:%{public}d", userId);
8090 abilityMs->StartResidentApps(userId);
8091 });
8092 }
8093 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
8094 AmsConfigurationParameter::GetInstance().MultiUserType() != 0) {
8095 TAG_LOGI(AAFwkTag::ABILITYMGR, "no need terminate old scb");
8096 return;
8097 }
8098 PauseOldConnectManager(oldUserId);
8099 }
8100
SwitchManagers(int32_t userId, bool switchUser)8101 void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser)
8102 {
8103 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId);
8104 CHECK_POINTER(subManagersHelper_);
8105 subManagersHelper_->InitSubManagers(userId, switchUser);
8106 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----end", __func__, userId);
8107 }
8108
PauseOldUser(int32_t userId)8109 void AbilityManagerService::PauseOldUser(int32_t userId)
8110 {
8111 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId);
8112 PauseOldMissionListManager(userId);
8113 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----end", __func__, userId);
8114 }
8115
PauseOldMissionListManager(int32_t userId)8116 void AbilityManagerService::PauseOldMissionListManager(int32_t userId)
8117 {
8118 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId);
8119 auto manager = GetMissionListManagerByUserId(userId);
8120 CHECK_POINTER(manager);
8121 manager->PauseManager();
8122 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId);
8123 }
8124
PauseOldConnectManager(int32_t userId)8125 void AbilityManagerService::PauseOldConnectManager(int32_t userId)
8126 {
8127 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----begin", __func__, userId);
8128 if (userId == U0_USER_ID) {
8129 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, u0 not stop, id:%{public}d-----null", __func__, userId);
8130 return;
8131 }
8132
8133 auto manager = GetConnectManagerByUserId(userId);
8134 CHECK_POINTER(manager);
8135 manager->PauseExtensions();
8136 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----end", __func__, userId);
8137 }
8138
StartUserApps()8139 void AbilityManagerService::StartUserApps()
8140 {
8141 auto missionListManager = GetCurrentMissionListManager();
8142 if (missionListManager && missionListManager->IsStarted()) {
8143 TAG_LOGI(AAFwkTag::ABILITYMGR, "missionListManager ResumeManager");
8144 missionListManager->ResumeManager();
8145 }
8146 }
8147
GetValidUserId(const int32_t userId)8148 int32_t AbilityManagerService::GetValidUserId(const int32_t userId)
8149 {
8150 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId = %{public}d.", userId);
8151 int32_t validUserId = userId;
8152
8153 if (DEFAULT_INVAL_VALUE == userId) {
8154 validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
8155 TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId = %{public}d, CallingUid = %{public}d.", validUserId,
8156 IPCSkeleton::GetCallingUid());
8157 if (validUserId == U0_USER_ID) {
8158 validUserId = GetUserId();
8159 }
8160 }
8161 return validUserId;
8162 }
8163
SetAbilityController(const sptr<IAbilityController> &abilityController, bool imAStabilityTest)8164 int AbilityManagerService::SetAbilityController(const sptr<IAbilityController> &abilityController,
8165 bool imAStabilityTest)
8166 {
8167 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest);
8168 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyControllerPerm();
8169 if (!isPerm) {
8170 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
8171 return CHECK_PERMISSION_FAILED;
8172 }
8173
8174 std::lock_guard<ffrt::mutex> guard(globalLock_);
8175 abilityController_ = abilityController;
8176 controllerIsAStabilityTest_ = imAStabilityTest;
8177 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, end", __func__);
8178 return ERR_OK;
8179 }
8180
IsRunningInStabilityTest()8181 bool AbilityManagerService::IsRunningInStabilityTest()
8182 {
8183 std::lock_guard<ffrt::mutex> guard(globalLock_);
8184 bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_;
8185 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret);
8186 return ret;
8187 }
8188
IsAbilityControllerStart(const Want &want, const std::string &bundleName)8189 bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName)
8190 {
8191 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8192 TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8193 if (abilityController_ == nullptr) {
8194 TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8195 return true;
8196 }
8197
8198 if (controllerIsAStabilityTest_) {
8199 bool isStart = abilityController_->AllowAbilityStart(want, bundleName);
8200 if (!isStart) {
8201 TAG_LOGI(AAFwkTag::ABILITYMGR,
8202 "controller starting can't start ability:%{public}s", bundleName.c_str());
8203 return false;
8204 }
8205 }
8206 return true;
8207 }
8208
IsAbilityControllerForeground(const std::string &bundleName)8209 bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName)
8210 {
8211 TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
8212 if (abilityController_ == nullptr) {
8213 TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
8214 return true;
8215 }
8216
8217 if (controllerIsAStabilityTest_) {
8218 bool isResume = abilityController_->AllowAbilityBackground(bundleName);
8219 if (!isResume) {
8220 TAG_LOGI(AAFwkTag::ABILITYMGR,
8221 "controller resuming can't terminate ability:%{public}s", bundleName.c_str());
8222 return false;
8223 }
8224 }
8225 return true;
8226 }
8227
StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)8228 int AbilityManagerService::StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)
8229 {
8230 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8231 if (observer == nullptr) {
8232 TAG_LOGE(AAFwkTag::ABILITYMGR, "observer null");
8233 return ERR_INVALID_VALUE;
8234 }
8235
8236 std::string bundleName = want.GetStringParam("-b");
8237 if (bundleName.empty()) {
8238 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name");
8239 return ERR_INVALID_VALUE;
8240 }
8241
8242 auto checkResult = AbilityUtil::CheckInstanceKey(want);
8243 if (checkResult != ERR_OK) {
8244 return checkResult;
8245 }
8246 int32_t appIndex = 0;
8247 if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex) || appIndex != 0) {
8248 TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support app clone");
8249 return ERR_NOT_SUPPORT_APP_CLONE;
8250 }
8251
8252 auto bms = AbilityUtil::GetBundleManagerHelper();
8253 CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL);
8254 AppExecFwk::BundleInfo bundleInfo;
8255 if (!IN_PROCESS_CALL(
8256 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID))) {
8257 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundleInfo by U0_USER_ID %{public}d", U0_USER_ID);
8258 int32_t userId = GetUserId();
8259 if (!IN_PROCESS_CALL(
8260 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
8261 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed get bundleInfo by userId %{public}d", userId);
8262 return GET_BUNDLE_INFO_FAILED;
8263 }
8264 }
8265
8266 bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
8267 if (isDebugApp && bundleInfo.applicationInfo.appProvisionType != AppExecFwk::Constants::APP_PROVISION_TYPE_DEBUG) {
8268 TAG_LOGE(AAFwkTag::ABILITYMGR, "release app not support debug");
8269 return ERR_NOT_IN_APP_PROVISION_MODE;
8270 }
8271
8272 return DelayedSingleton<AppScheduler>::GetInstance()->StartUserTest(want, observer, bundleInfo, GetUserId());
8273 }
8274
FinishUserTest( const std::string &msg, const int64_t &resultCode, const std::string &bundleName)8275 int AbilityManagerService::FinishUserTest(
8276 const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
8277 {
8278 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8279 if (bundleName.empty()) {
8280 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid bundle name");
8281 return ERR_INVALID_VALUE;
8282 }
8283
8284 return DelayedSingleton<AppScheduler>::GetInstance()->FinishUserTest(msg, resultCode, bundleName);
8285 }
8286
GetTopAbility(sptr<IRemoteObject> &token)8287 int AbilityManagerService::GetTopAbility(sptr<IRemoteObject> &token)
8288 {
8289 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8290 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8291 if (!isSaCall) {
8292 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
8293 return CHECK_PERMISSION_FAILED;
8294 }
8295 #ifdef SUPPORT_SCREEN
8296 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8297 Rosen::FocusChangeInfo focusChangeInfo;
8298 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
8299 token = focusChangeInfo.abilityToken_;
8300 } else {
8301 if (!wmsHandler_) {
8302 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
8303 return ERR_INVALID_VALUE;
8304 }
8305 wmsHandler_->GetFocusWindow(token);
8306 }
8307
8308 if (!token) {
8309 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
8310 return ERR_INVALID_VALUE;
8311 }
8312 #endif
8313 return ERR_OK;
8314 }
8315
DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)8316 int AbilityManagerService::DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)
8317 {
8318 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8319 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8320 auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8321 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8322 int32_t callerPid = IPCSkeleton::GetCallingPid();
8323 int32_t appPid = abilityRecord->GetPid();
8324 TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8325 if (callerPid != appPid) {
8326 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not application itself");
8327 return ERR_INVALID_VALUE;
8328 }
8329 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8330 auto sessionId = GetMissionIdByAbilityTokenInner(token);
8331 if (!sessionId) {
8332 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid session id");
8333 return ERR_INVALID_VALUE;
8334 }
8335 auto want = abilityRecord->GetWant();
8336 if (!IsAbilityControllerStart(want, want.GetBundle())) {
8337 TAG_LOGE(AAFwkTag::ABILITYMGR,
8338 "sceneBoard IsAbilityControllerStart failed:%{public}s", want.GetBundle().c_str());
8339 return ERR_WOULD_BLOCK;
8340 }
8341 return ERR_OK;
8342 }
8343 auto missionId = GetMissionIdByAbilityToken(token);
8344 if (missionId < 0) {
8345 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid mission id");
8346 return ERR_INVALID_VALUE;
8347 }
8348 return DelegatorMoveMissionToFront(missionId);
8349 }
8350
DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)8351 int AbilityManagerService::DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)
8352 {
8353 TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8354 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8355 auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8356 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8357 int32_t appPid = abilityRecord->GetPid();
8358 int32_t callerPid = IPCSkeleton::GetCallingPid();
8359 TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8360 if (callerPid != appPid) {
8361 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not application itself");
8362 return ERR_INVALID_VALUE;
8363 }
8364 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8365 return ERR_OK;
8366 }
8367 return MinimizeAbility(token, true);
8368 }
8369
DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)8370 int AbilityManagerService::DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)
8371 {
8372 TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityForeground, sceneFlag:%{public}u", flag);
8373 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8374 if (!VerificationToken(token) && !VerificationAllToken(token)) {
8375 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s token error", __func__);
8376 return ERR_INVALID_VALUE;
8377 }
8378
8379 std::lock_guard<ffrt::mutex> guard(globalLock_);
8380 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8381 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8382 if (!JudgeSelfCalled(abilityRecord)) {
8383 return CHECK_PERMISSION_FAILED;
8384 }
8385
8386 auto type = abilityRecord->GetAbilityInfo().type;
8387 if (type != AppExecFwk::AbilityType::PAGE) {
8388 TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot minimize except page ability");
8389 return ERR_WRONG_INTERFACE_CALL;
8390 }
8391
8392 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
8393 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerForeground false");
8394 return ERR_WOULD_BLOCK;
8395 }
8396
8397 auto missionListManager = GetCurrentMissionListManager();
8398 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8399 return missionListManager->DoAbilityForeground(abilityRecord, flag);
8400 }
8401
DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)8402 int AbilityManagerService::DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)
8403 {
8404 TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityBackground, sceneFlag:%{public}u", flag);
8405 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8406
8407 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8408 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8409
8410 abilityRecord->lifeCycleStateInfo_.sceneFlag = flag;
8411 int ret = MinimizeAbility(token);
8412 abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL;
8413 return ret;
8414 }
8415
DelegatorMoveMissionToFront(int32_t missionId)8416 int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId)
8417 {
8418 TAG_LOGI(AAFwkTag::ABILITYMGR, "enter missionId:%{public}d", missionId);
8419 auto missionListManager = GetCurrentMissionListManager();
8420 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8421
8422 if (!IsAbilityControllerStartById(missionId)) {
8423 TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
8424 return ERR_WOULD_BLOCK;
8425 }
8426
8427 return missionListManager->MoveMissionToFront(missionId);
8428 }
8429
JudgeMultiUserConcurrency(const int32_t userId)8430 bool AbilityManagerService::JudgeMultiUserConcurrency(const int32_t userId)
8431 {
8432 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8433 if (userId == U0_USER_ID) {
8434 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, userId is 0.", __func__);
8435 return true;
8436 }
8437
8438 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, current userId : %{public}d", userId, GetUserId());
8439
8440 // Only non-concurrent mode is supported
8441 bool concurrencyMode = CONCURRENCY_MODE_FALSE;
8442 if (!concurrencyMode) {
8443 return (userId == GetUserId());
8444 }
8445
8446 return true;
8447 }
8448
8449 #ifdef ABILITY_COMMAND_FOR_TEST
ForceTimeoutForTest(const std::string &abilityName, const std::string &state)8450 int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, const std::string &state)
8451 {
8452 if (abilityName.empty()) {
8453 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityName empty");
8454 return INVALID_DATA;
8455 }
8456 if (abilityName == "clean") {
8457 timeoutMap_.clear();
8458 return ERR_OK;
8459 }
8460 if (state != AbilityRecord::ConvertAbilityState(AbilityState::INITIAL) &&
8461 state != AbilityRecord::ConvertAbilityState(AbilityState::INACTIVE) &&
8462 state != AbilityRecord::ConvertAbilityState(AbilityState::FOREGROUND) &&
8463 state != AbilityRecord::ConvertAbilityState(AbilityState::BACKGROUND) &&
8464 state != AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) &&
8465 state != std::string("COMMAND")) {
8466 TAG_LOGE(AAFwkTag::ABILITYMGR, "lifecycle state invalid");
8467 return INVALID_DATA;
8468 }
8469 timeoutMap_.insert(std::make_pair(state, abilityName));
8470 return ERR_OK;
8471 }
8472 #endif
8473
CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo, uint32_t tokenId)8474 int AbilityManagerService::CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo,
8475 uint32_t tokenId)
8476 {
8477 if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId,
8478 PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) {
8479 return AppExecFwk::Constants::PERMISSION_GRANTED;
8480 }
8481
8482 for (const auto &permission : abilityInfo.permissions) {
8483 if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8484 AppExecFwk::Constants::PERMISSION_GRANTED) {
8485 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission:%{public}s",
8486 permission.c_str());
8487 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8488 }
8489 }
8490
8491 return AppExecFwk::Constants::PERMISSION_GRANTED;
8492 }
8493
CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId)8494 bool AbilityManagerService::CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId)
8495 {
8496 for (auto permission : skill.permissions) {
8497 if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8498 AppExecFwk::Constants::PERMISSION_GRANTED) {
8499 TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, permission:%{public}s",
8500 permission.c_str());
8501 return false;
8502 }
8503 }
8504
8505 return true;
8506 }
8507
CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest, uint32_t tokenId)8508 int AbilityManagerService::CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest,
8509 uint32_t tokenId)
8510 {
8511 auto abilityInfo = abilityRequest.abilityInfo;
8512 auto resultAbilityPermission = CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8513 if (resultAbilityPermission != AppExecFwk::Constants::PERMISSION_GRANTED) {
8514 return resultAbilityPermission;
8515 }
8516
8517 if (abilityInfo.skills.empty()) {
8518 return AppExecFwk::Constants::PERMISSION_GRANTED;
8519 }
8520 int32_t result = AppExecFwk::Constants::PERMISSION_GRANTED;
8521 for (auto skill : abilityInfo.skills) {
8522 if (skill.Match(abilityRequest.want)) {
8523 if (CheckOneSkillPermission(skill, tokenId)) {
8524 return AppExecFwk::Constants::PERMISSION_GRANTED;
8525 } else {
8526 result = AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8527 }
8528 }
8529 }
8530 return result;
8531 }
8532
CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest, bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit)8533 int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest,
8534 bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit)
8535 {
8536 auto abilityInfo = abilityRequest.abilityInfo;
8537 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8538 if (AppUtils::GetInstance().IsSupportAncoApp() &&
8539 StartAbilityUtils::IsCallFromAncoShellOrBroker(abilityRequest.callerToken)) {
8540 TAG_LOGD(AAFwkTag::ABILITYMGR,
8541 "Check static permission, name is %{public}s.", abilityInfo.name.c_str());
8542 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
8543 if (collaborator == nullptr) {
8544 TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator null");
8545 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8546 }
8547 int result = collaborator->CheckStaticCfgPermission(abilityRequest.want, isImplicit);
8548 if (result != ERR_OK) {
8549 TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker");
8550 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8551 }
8552 }
8553 if (!isData) {
8554 isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8555 }
8556 if (isSaCall) {
8557 // do not need check static config permission when start ability by SA
8558 return AppExecFwk::Constants::PERMISSION_GRANTED;
8559 }
8560
8561 uint32_t tokenId;
8562 if (isStartAsCaller) {
8563 tokenId = callerTokenId;
8564 } else {
8565 tokenId = IPCSkeleton::GetCallingTokenID();
8566 }
8567
8568 if (abilityInfo.applicationInfo.accessTokenId == tokenId) {
8569 return AppExecFwk::Constants::PERMISSION_GRANTED;
8570 }
8571
8572 if (abilityRequest.want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME) ==
8573 AppUtils::GetInstance().GetBrokerDelegateBundleName() &&
8574 abilityRequest.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
8575 return AppExecFwk::Constants::PERMISSION_GRANTED;
8576 }
8577
8578 if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
8579 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) ||
8580 (abilityInfo.type == AppExecFwk::AbilityType::DATA)) {
8581 // just need check the read permission and write permission of extension ability or data ability
8582 if (!abilityInfo.readPermission.empty()) {
8583 int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission, false);
8584 if (checkReadPermission == ERR_OK) {
8585 return AppExecFwk::Constants::PERMISSION_GRANTED;
8586 }
8587 TAG_LOGW(AAFwkTag::ABILITYMGR,
8588 "verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str());
8589 }
8590 if (!abilityInfo.writePermission.empty()) {
8591 int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission, false);
8592 if (checkWritePermission == ERR_OK) {
8593 return AppExecFwk::Constants::PERMISSION_GRANTED;
8594 }
8595 TAG_LOGW(AAFwkTag::ABILITYMGR,
8596 "verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str());
8597 }
8598
8599 if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) {
8600 // 'readPermission' and 'writePermission' take precedence over 'permission'
8601 // when 'readPermission' or 'writePermission' is not empty, no need check 'permission'
8602 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8603 }
8604 }
8605
8606 if (!isImplicit) {
8607 return CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8608 }
8609 return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId);
8610 }
8611
CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType, const Want &want, const AbilityRequest &abilityRequest)8612 int AbilityManagerService::CheckPermissionForUIService(AppExecFwk::ExtensionAbilityType extensionType,
8613 const Want &want, const AbilityRequest &abilityRequest)
8614 {
8615 AppExecFwk::ExtensionAbilityType targetExtType = abilityRequest.abilityInfo.extensionAbilityType;
8616 if (targetExtType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
8617 return ERR_OK;
8618 }
8619 if (!want.HasParameter(UISERVICEHOSTPROXY_KEY)) {
8620 TAG_LOGE(AAFwkTag::ABILITYMGR, "need UISERVICEHOSTPROXY_KEY connect UI_SERVICE");
8621 return ERR_WRONG_INTERFACE_CALL;
8622 }
8623 if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
8624 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface not support connect UI_SERVICE");
8625 return ERR_WRONG_INTERFACE_CALL;
8626 }
8627 if (!system::GetBoolParameter(ABILITYMS_ENABLE_UISERVICE, false)) {
8628 TAG_LOGE(AAFwkTag::ABILITYMGR, "ABILITYMS_ENABLE_UISERVICE false");
8629 return ERR_CAPABILITY_NOT_SUPPORT;
8630 }
8631
8632 return ERR_OK;
8633 }
8634
IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const8635 bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const
8636 {
8637 for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) {
8638 if (iter->first == state && iter->second == abilityName) {
8639 return true;
8640 }
8641 }
8642 return false;
8643 }
8644
GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)8645 bool AbilityManagerService::GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)
8646 {
8647 // note: do not use abilityInfo.uri directly, need check uri first.
8648 size_t firstSeparator = abilityInfoUri.find_first_of('/');
8649 size_t lastSeparator = abilityInfoUri.find_last_of('/');
8650 if (lastSeparator - firstSeparator != 1) {
8651 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability info uri error, uri: %{public}s", abilityInfoUri.c_str());
8652 return false;
8653 }
8654
8655 adjustUri = abilityInfoUri;
8656 adjustUri.insert(lastSeparator, "/");
8657 return true;
8658 }
8659
GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos, const std::string &mainAbility, std::string &uri)8660 bool AbilityManagerService::GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos,
8661 const std::string &mainAbility, std::string &uri)
8662 {
8663 if (abilityInfos.empty() || mainAbility.empty()) {
8664 TAG_LOGE(AAFwkTag::ABILITYMGR,
8665 "abilityInfos or mainAbility empty mainAbility:%{public}s", mainAbility.c_str());
8666 return false;
8667 }
8668
8669 std::string dataAbilityUri;
8670 for (auto abilityInfo : abilityInfos) {
8671 if (abilityInfo.type == AppExecFwk::AbilityType::DATA &&
8672 abilityInfo.name == mainAbility) {
8673 dataAbilityUri = abilityInfo.uri;
8674 TAG_LOGI(AAFwkTag::ABILITYMGR, "get data ability uri:%{public}s", dataAbilityUri.c_str());
8675 break;
8676 }
8677 }
8678
8679 return GetValidDataAbilityUri(dataAbilityUri, uri);
8680 }
8681
GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info, std::shared_ptr<AbilityRecord> &abilityRecord)8682 void AbilityManagerService::GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info,
8683 std::shared_ptr<AbilityRecord> &abilityRecord)
8684 {
8685 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8686 AbilityRunningInfo runningInfo;
8687 AppExecFwk::RunningProcessInfo processInfo;
8688
8689 runningInfo.ability = abilityRecord->GetElementName();
8690 runningInfo.startTime = abilityRecord->GetStartTime();
8691 runningInfo.abilityState = static_cast<int>(abilityRecord->GetAbilityState());
8692
8693 DelayedSingleton<AppScheduler>::GetInstance()->
8694 GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
8695 runningInfo.pid = processInfo.pid_;
8696 runningInfo.uid = processInfo.uid_;
8697 runningInfo.processName = processInfo.processName_;
8698 runningInfo.appCloneIndex = processInfo.appCloneIndex;
8699 info.emplace_back(runningInfo);
8700 }
8701
VerifyAccountPermission(int32_t userId)8702 int AbilityManagerService::VerifyAccountPermission(int32_t userId)
8703 {
8704 if ((userId < 0) || (userController_ && (userController_->GetCurrentUserId() == userId))) {
8705 return ERR_OK;
8706 }
8707 return AAFwk::PermissionVerification::GetInstance()->VerifyAccountPermission();
8708 }
8709
FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback, int32_t userId, int requestCode)8710 int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
8711 int32_t userId, int requestCode)
8712 {
8713 auto callingUid = IPCSkeleton::GetCallingUid();
8714 if (callingUid != DMS_UID) {
8715 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support DMS");
8716 return CHECK_PERMISSION_FAILED;
8717 }
8718 int32_t validUserId = GetValidUserId(userId);
8719 if (freeInstallManager_ == nullptr) {
8720 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
8721 return ERR_INVALID_VALUE;
8722 }
8723 return freeInstallManager_->FreeInstallAbilityFromRemote(want, callback, validUserId, requestCode);
8724 }
8725
GetTopAbility(bool isNeedLocalDeviceId)8726 AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId)
8727 {
8728 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8729 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
8730 AppExecFwk::ElementName elementName = {};
8731 if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
8732 auto callerPid = IPCSkeleton::GetCallingPid();
8733 AppExecFwk::RunningProcessInfo processInfo;
8734 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
8735 if (!processInfo.isTestProcess) {
8736 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't use system-api or not test process");
8737 return elementName;
8738 }
8739 }
8740 #ifdef SUPPORT_GRAPHICS
8741 sptr<IRemoteObject> token;
8742 int ret = IN_PROCESS_CALL(GetTopAbility(token));
8743 if (ret) {
8744 return elementName;
8745 }
8746 if (!token) {
8747 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
8748 return elementName;
8749 }
8750 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8751 if (abilityRecord == nullptr) {
8752 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
8753 return elementName;
8754 }
8755 elementName = abilityRecord->GetElementName();
8756 bool isDeviceEmpty = elementName.GetDeviceID().empty();
8757 std::string localDeviceId;
8758 if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
8759 elementName.SetDeviceID(localDeviceId);
8760 }
8761 #endif
8762 return elementName;
8763 }
8764
GetElementNameByToken(sptr<IRemoteObject> token, bool isNeedLocalDeviceId)8765 AppExecFwk::ElementName AbilityManagerService::GetElementNameByToken(sptr<IRemoteObject> token,
8766 bool isNeedLocalDeviceId)
8767 {
8768 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8769 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
8770 AppExecFwk::ElementName elementName = {};
8771 #ifdef SUPPORT_GRAPHICS
8772 if (!token) {
8773 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
8774 return elementName;
8775 }
8776 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8777 if (abilityRecord == nullptr) {
8778 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord null", __func__);
8779 return elementName;
8780 }
8781 elementName = abilityRecord->GetElementName();
8782 bool isDeviceEmpty = elementName.GetDeviceID().empty();
8783 std::string localDeviceId;
8784 if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
8785 elementName.SetDeviceID(localDeviceId);
8786 }
8787 #endif
8788 return elementName;
8789 }
8790
Dump(int fd, const std::vector<std::u16string>& args)8791 int AbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
8792 {
8793 TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump begin fd: %{public}d", fd);
8794 std::string result;
8795 auto errCode = Dump(args, result);
8796 int ret = dprintf(fd, "%s\n", result.c_str());
8797 if (ret < 0) {
8798 TAG_LOGE(AAFwkTag::ABILITYMGR, "dprintf error");
8799 return ERR_AAFWK_HIDUMP_ERROR;
8800 }
8801 TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump end");
8802 return errCode;
8803 }
8804
Dump(const std::vector<std::u16string>& args, std::string& result)8805 int AbilityManagerService::Dump(const std::vector<std::u16string>& args, std::string& result)
8806 {
8807 ErrCode errCode = ERR_OK;
8808 auto size = args.size();
8809 if (size == 0) {
8810 ShowHelp(result);
8811 return errCode;
8812 }
8813
8814 std::vector<std::string> argsStr;
8815 for (auto arg : args) {
8816 argsStr.emplace_back(Str16ToStr8(arg));
8817 }
8818
8819 if (argsStr[0] == "-h") {
8820 ShowHelp(result);
8821 } else {
8822 errCode = ProcessMultiParam(argsStr, result);
8823 if (errCode == ERR_AAFWK_HIDUMP_INVALID_ARGS) {
8824 ShowIllegalInfomation(result);
8825 }
8826 }
8827 return errCode;
8828 }
8829
ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)8830 ErrCode AbilityManagerService::ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)
8831 {
8832 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
8833 bool isClient = false;
8834 bool isUser = false;
8835 int userID = DEFAULT_INVAL_VALUE;
8836 std::vector<std::string>::iterator it;
8837 for (it = argsStr.begin(); it != argsStr.end();) {
8838 if (*it == ARGS_CLIENT) {
8839 isClient = true;
8840 it = argsStr.erase(it);
8841 continue;
8842 }
8843 if (*it == ARGS_USER_ID) {
8844 it = argsStr.erase(it);
8845 if (it == argsStr.end()) {
8846 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
8847 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
8848 }
8849 (void)StrToInt(*it, userID);
8850 if (userID < 0) {
8851 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
8852 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
8853 }
8854 isUser = true;
8855 it = argsStr.erase(it);
8856 continue;
8857 }
8858 it++;
8859 }
8860 std::string cmd;
8861 for (unsigned int i = 0; i < argsStr.size(); i++) {
8862 cmd.append(argsStr[i]);
8863 if (i != argsStr.size() - 1) {
8864 cmd.append(" ");
8865 }
8866 }
8867 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, isClient:%{public}d, userID:%{public}d, cmd:%{public}s",
8868 __func__, isClient, userID, cmd.c_str());
8869
8870 std::vector<std::string> dumpResults;
8871 DumpSysState(cmd, dumpResults, isClient, isUser, userID);
8872 for (auto it : dumpResults) {
8873 result += it + "\n";
8874 }
8875 return ERR_OK;
8876 }
8877
ShowHelp(std::string& result)8878 void AbilityManagerService::ShowHelp(std::string& result)
8879 {
8880 result.append("Usage:\n")
8881 .append("-h ")
8882 .append("help text for the tool\n")
8883 .append("-a [-c | -u {UserId}] ")
8884 .append("dump all ability infomation in the system or all ability infomation of client/UserId\n")
8885 .append("-l ")
8886 .append("dump all mission list information in the system\n")
8887 .append("-i {AbilityRecordId} ")
8888 .append("dump an ability infomation by ability record id\n")
8889 .append("-e ")
8890 .append("dump all extension infomation in the system(FA: ServiceAbilityRecords, Stage: ExtensionRecords)\n")
8891 .append("-p [PendingWantRecordId] ")
8892 .append("dump all pendingwant record infomation in the system\n")
8893 .append("-r ")
8894 .append("dump all process in the system\n")
8895 .append("-d ")
8896 .append("dump all data ability infomation in the system");
8897 }
8898
ShowIllegalInfomation(std::string& result)8899 void AbilityManagerService::ShowIllegalInfomation(std::string& result)
8900 {
8901 result.append(ILLEGAL_INFOMATION);
8902 }
8903
DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)8904 int AbilityManagerService::DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)
8905 {
8906 TAG_LOGD(AAFwkTag::ABILITYMGR, "dumpAbilityInfoDone begin");
8907 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8908 if (abilityRecord == nullptr) {
8909 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
8910 return ERR_INVALID_VALUE;
8911 }
8912 if (!JudgeSelfCalled(abilityRecord)) {
8913 return CHECK_PERMISSION_FAILED;
8914 }
8915 abilityRecord->DumpAbilityInfoDone(infos);
8916 return ERR_OK;
8917 }
8918
SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)8919 int AbilityManagerService::SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)
8920 {
8921 TAG_LOGD(AAFwkTag::ABILITYMGR, "SetMissionContinueState begin. State: %{public}d", state);
8922
8923 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8924
8925 int32_t missionId = GetMissionIdByAbilityToken(token);
8926 if (missionId == -1) {
8927 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed state:%{public}d", state);
8928 return ERR_INVALID_VALUE;
8929 }
8930
8931 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8932 if (!abilityRecord) {
8933 TAG_LOGE(AAFwkTag::ABILITYMGR,
8934 "no such ability record missionId:%{public}d, state:%{public}d",
8935 missionId, state);
8936 return -1;
8937 }
8938
8939 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8940 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
8941 if (callingTokenId != tokenID) {
8942 TAG_LOGE(AAFwkTag::ABILITYMGR,
8943 "setMissionContinueState not self, not enabled. missionId:%{public}d, state:%{public}d",
8944 missionId, state);
8945 return -1;
8946 }
8947
8948 auto userId = abilityRecord->GetOwnerMissionUserId();
8949 auto missionListManager = GetMissionListManagerByUserId(userId);
8950 if (!missionListManager) {
8951 TAG_LOGE(AAFwkTag::ABILITYMGR, "find missionListManager failed missionId:%{public}d, state:%{public}d",
8952 missionId, state);
8953 return -1;
8954 }
8955
8956 auto setResult = missionListManager->SetMissionContinueState(token, missionId, state);
8957 if (setResult != ERR_OK) {
8958 TAG_LOGE(AAFwkTag::ABILITYMGR,
8959 "missionListManager set failed, result:%{public}d, missionId:%{public}d, state:%{public}d",
8960 setResult, missionId, state);
8961 return setResult;
8962 }
8963
8964 DistributedClient dmsClient;
8965 auto result = dmsClient.SetMissionContinueState(missionId, state);
8966 if (result != ERR_OK) {
8967 TAG_LOGE(AAFwkTag::ABILITYMGR,
8968 "Notify DMS client failed, result: %{public}d. Mission id: %{public}d, state: %{public}d",
8969 result, missionId, state);
8970 }
8971
8972 TAG_LOGD(AAFwkTag::ABILITYMGR,
8973 "SetMissionContinueState end. Mission id: %{public}d, state: %{public}d", missionId, state);
8974 return ERR_OK;
8975 }
8976
8977 #ifdef SUPPORT_SCREEN
SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)8978 int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
8979 {
8980 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8981 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8982 if (!abilityRecord) {
8983 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
8984 return -1;
8985 }
8986
8987 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8988 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
8989 if (callingTokenId != tokenID) {
8990 TAG_LOGE(AAFwkTag::ABILITYMGR, "setMissionLabel not self, not enabled");
8991 return -1;
8992 }
8993
8994 auto userId = abilityRecord->GetOwnerMissionUserId();
8995 auto missionListManager = GetMissionListManagerByUserId(userId);
8996 if (!missionListManager) {
8997 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager find failed when set mission label");
8998 return -1;
8999 }
9000
9001 return missionListManager->SetMissionLabel(token, label);
9002 }
9003
SetMissionIcon(const sptr<IRemoteObject> &token, const std::shared_ptr<OHOS::Media::PixelMap> &icon)9004 int AbilityManagerService::SetMissionIcon(const sptr<IRemoteObject> &token,
9005 const std::shared_ptr<OHOS::Media::PixelMap> &icon)
9006 {
9007 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
9008 CHECK_CALLER_IS_SYSTEM_APP;
9009 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9010 if (!abilityRecord) {
9011 TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
9012 return -1;
9013 }
9014
9015 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9016 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9017 if (callingTokenId != tokenID) {
9018 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self, not enable set mission icon");
9019 return -1;
9020 }
9021
9022 auto userId = abilityRecord->GetOwnerMissionUserId();
9023 auto missionListManager = GetMissionListManagerByUserId(userId);
9024 if (!missionListManager) {
9025 TAG_LOGE(AAFwkTag::ABILITYMGR, "find missionListManager failed");
9026 return -1;
9027 }
9028
9029 return missionListManager->SetMissionIcon(token, icon);
9030 }
9031
RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler, bool animationEnabled)9032 int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler,
9033 bool animationEnabled)
9034 {
9035 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9036 if (!isSaCall) {
9037 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
9038 return CHECK_PERMISSION_FAILED;
9039 }
9040 wmsHandler_ = handler;
9041 isAnimationEnabled_ = animationEnabled;
9042 TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s: WMS handler registered successfully.", __func__);
9043 return ERR_OK;
9044 }
9045
GetWMSHandler() const9046 sptr<IWindowManagerServiceHandler> AbilityManagerService::GetWMSHandler() const
9047 {
9048 return wmsHandler_;
9049 }
9050
CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)9051 void AbilityManagerService::CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)
9052 {
9053 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9054 if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
9055 TAG_LOGE(AAFwkTag::ABILITYMGR, "not foundation call");
9056 return;
9057 }
9058 auto abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
9059 CHECK_POINTER(abilityRecord);
9060
9061 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
9062 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
9063 CHECK_POINTER(missionListManager);
9064 missionListManager->CompleteFirstFrameDrawing(abilityToken);
9065 }
9066
CompleteFirstFrameDrawing(int32_t sessionId)9067 void AbilityManagerService::CompleteFirstFrameDrawing(int32_t sessionId)
9068 {
9069 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
9070 if (!IsCallerSceneBoard()) {
9071 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sceneboard called, not allowed");
9072 return;
9073 }
9074 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
9075 CHECK_POINTER(uiAbilityManager);
9076 uiAbilityManager->CompleteFirstFrameDrawing(sessionId);
9077 }
9078
ShowPickerDialog( const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)9079 int32_t AbilityManagerService::ShowPickerDialog(
9080 const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)
9081 {
9082 AAFwk::Want newWant = want;
9083 std::string sharePickerBundleName =
9084 OHOS::system::GetParameter(SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME);
9085 std::string sharePickerAbilityName =
9086 OHOS::system::GetParameter(SHARE_PICKER_DIALOG_ABILITY_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME);
9087 newWant.SetElementName(sharePickerBundleName, sharePickerAbilityName);
9088 newWant.SetParam(TOKEN_KEY, callerToken);
9089 // note: clear actions
9090 newWant.SetAction("");
9091 return IN_PROCESS_CALL(StartAbility(newWant, DEFAULT_INVAL_VALUE, userId));
9092 }
9093
CheckWindowMode(int32_t windowMode, const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const9094 bool AbilityManagerService::CheckWindowMode(int32_t windowMode,
9095 const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const
9096 {
9097 TAG_LOGI(AAFwkTag::ABILITYMGR, "window mode:%{public}d", windowMode);
9098 if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED) {
9099 return true;
9100 }
9101
9102 auto bmsWindowMode = WindowOptionsUtils::WindowModeMap(windowMode);
9103 if (bmsWindowMode.first) {
9104 for (const auto& mode : windowModes) {
9105 if (mode == bmsWindowMode.second) {
9106 return true;
9107 }
9108 }
9109 }
9110 return false;
9111 }
9112
PrepareTerminateAbility(const sptr<IRemoteObject> &token, sptr<IPrepareTerminateCallback> &callback)9113 int AbilityManagerService::PrepareTerminateAbility(const sptr<IRemoteObject> &token,
9114 sptr<IPrepareTerminateCallback> &callback)
9115 {
9116 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
9117 if (callback == nullptr) {
9118 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback null");
9119 return ERR_INVALID_VALUE;
9120 }
9121 if (!CheckPrepareTerminateEnable()) {
9122 callback->DoPrepareTerminate();
9123 return ERR_INVALID_VALUE;
9124 }
9125
9126 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9127 if (abilityRecord == nullptr) {
9128 TAG_LOGE(AAFwkTag::ABILITYMGR, "record null");
9129 callback->DoPrepareTerminate();
9130 return ERR_INVALID_VALUE;
9131 }
9132
9133 if (!JudgeSelfCalled(abilityRecord)) {
9134 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self call");
9135 callback->DoPrepareTerminate();
9136 return CHECK_PERMISSION_FAILED;
9137 }
9138
9139 auto type = abilityRecord->GetAbilityInfo().type;
9140 if (type != AppExecFwk::AbilityType::PAGE) {
9141 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support PAGE");
9142 callback->DoPrepareTerminate();
9143 return RESOLVE_CALL_ABILITY_TYPE_ERR;
9144 }
9145
9146 auto timeoutTask = [&callback]() {
9147 callback->DoPrepareTerminate();
9148 };
9149 if (taskHandler_) {
9150 taskHandler_->SubmitTask(timeoutTask, "PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()),
9151 GlobalConstant::PREPARE_TERMINATE_TIMEOUT_TIME);
9152 }
9153
9154 bool res = abilityRecord->PrepareTerminateAbility();
9155 if (!res) {
9156 callback->DoPrepareTerminate();
9157 }
9158 if (taskHandler_) {
9159 taskHandler_->CancelTask("PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()));
9160 }
9161 return ERR_OK;
9162 }
9163
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)9164 void AbilityManagerService::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9165 {
9166 TAG_LOGI(AAFwkTag::ABILITYMGR, "handle focused event");
9167 auto missionListManager = GetCurrentMissionListManager();
9168 CHECK_POINTER(missionListManager);
9169
9170 int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9171 missionListManager->NotifyMissionFocused(missionId);
9172 }
9173
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)9174 void AbilityManagerService::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9175 {
9176 TAG_LOGI(AAFwkTag::ABILITYMGR, "handle unfocused event");
9177 auto missionListManager = GetCurrentMissionListManager();
9178 CHECK_POINTER(missionListManager);
9179
9180 int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9181 missionListManager->NotifyMissionUnfocused(missionId);
9182 }
9183
InitFocusListener()9184 void AbilityManagerService::InitFocusListener()
9185 {
9186 TAG_LOGI(AAFwkTag::ABILITYMGR, "init ability focus listener");
9187 if (focusListener_) {
9188 return;
9189 }
9190
9191 focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
9192 auto registerTask = [innerService = shared_from_this()]() {
9193 if (innerService) {
9194 TAG_LOGI(AAFwkTag::ABILITYMGR, "registerFocusListener task");
9195 innerService->RegisterFocusListener();
9196 }
9197 };
9198 if (taskHandler_) {
9199 taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
9200 }
9201 }
9202
RegisterFocusListener()9203 void AbilityManagerService::RegisterFocusListener()
9204 {
9205 TAG_LOGI(AAFwkTag::ABILITYMGR, "register focus listener");
9206 if (!focusListener_) {
9207 TAG_LOGE(AAFwkTag::ABILITYMGR, "no listener obj");
9208 return;
9209 }
9210 Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
9211 TAG_LOGI(AAFwkTag::ABILITYMGR, "register focus listener success");
9212 }
9213
InitPrepareTerminateConfig()9214 void AbilityManagerService::InitPrepareTerminateConfig()
9215 {
9216 char value[PREPARE_TERMINATE_ENABLE_SIZE] = "false";
9217 int retSysParam = GetParameter(PREPARE_TERMINATE_ENABLE_PARAMETER, "false", value, PREPARE_TERMINATE_ENABLE_SIZE);
9218 TAG_LOGI(AAFwkTag::ABILITYMGR,
9219 "checkPrepareTerminateEnable, %{public}s value=%{public}s", PREPARE_TERMINATE_ENABLE_PARAMETER,
9220 value);
9221 if (retSysParam > 0 && !std::strcmp(value, "true")) {
9222 isPrepareTerminateEnable_ = true;
9223 }
9224 }
9225
RegisterAbilityFirstFrameStateObserver( const sptr<IAbilityFirstFrameStateObserver> &observer, const std::string &targetBundleName)9226 int AbilityManagerService::RegisterAbilityFirstFrameStateObserver(
9227 const sptr<IAbilityFirstFrameStateObserver> &observer, const std::string &targetBundleName)
9228 {
9229 return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9230 RegisterAbilityFirstFrameStateObserver(observer, targetBundleName);
9231 }
9232
UnregisterAbilityFirstFrameStateObserver( const sptr<IAbilityFirstFrameStateObserver> &observer)9233 int AbilityManagerService::UnregisterAbilityFirstFrameStateObserver(
9234 const sptr<IAbilityFirstFrameStateObserver> &observer)
9235 {
9236 return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9237 UnregisterAbilityFirstFrameStateObserver(observer);
9238 }
9239
GetAnimationFlag()9240 bool AbilityManagerService::GetAnimationFlag()
9241 {
9242 return isAnimationEnabled_;
9243 }
9244
9245 #endif
9246
CheckCallServicePermission(const AbilityRequest &abilityRequest)9247 int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest)
9248 {
9249 if (abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()) ==
9250 AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
9251 abilityRequest.want.GetElement().GetBundleName() == AppUtils::GetInstance().GetBrokerDelegateBundleName()) {
9252 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9253 if (collaborator != nullptr) {
9254 TAG_LOGI(AAFwkTag::ABILITYMGR, "Collaborator CheckCallAbilityPermission");
9255 return collaborator->CheckCallAbilityPermission(abilityRequest.want);
9256 }
9257 }
9258 if (abilityRequest.abilityInfo.isStageBasedModel) {
9259 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9260 TAG_LOGD(AAFwkTag::ABILITYMGR, "extensionType is %{public}d.", static_cast<int>(extensionType));
9261 if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE ||
9262 extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
9263 extensionType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9264 return CheckCallServiceExtensionPermission(abilityRequest);
9265 } else {
9266 return CheckCallOtherExtensionPermission(abilityRequest);
9267 }
9268 } else {
9269 return CheckCallServiceAbilityPermission(abilityRequest);
9270 }
9271 }
9272
CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)9273 int AbilityManagerService::CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)
9274 {
9275 abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo;
9276 abilityRequest.uid = abilityRequest.appInfo.uid;
9277 if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) {
9278 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app info acquiring");
9279 return ERR_INVALID_VALUE;
9280 }
9281 if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) {
9282 TAG_LOGE(AAFwkTag::ABILITYMGR, "BMS query result not data ability");
9283 return ERR_WRONG_INTERFACE_CALL;
9284 }
9285
9286 AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest,
9287 true, isShell, isSACall);
9288 if (isShell) {
9289 verificationInfo.isBackgroundCall = true;
9290 }
9291 if (!isShell && IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall, true) != ERR_OK) {
9292 return ERR_INVALID_VALUE;
9293 }
9294 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallDataAbilityPermission(verificationInfo,
9295 isShell);
9296 if (result != ERR_OK) {
9297 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start DataAbility permission");
9298 return result;
9299 }
9300
9301 return ERR_OK;
9302 }
9303
CreateVerificationInfo( const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)9304 AAFwk::PermissionVerification::VerificationInfo AbilityManagerService::CreateVerificationInfo(
9305 const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)
9306 {
9307 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9308 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9309 verificationInfo.visible = abilityRequest.abilityInfo.visible;
9310 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9311 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call ServiceAbility or DataAbility, target bundleName: %{public}s.",
9312 abilityRequest.appInfo.bundleName.c_str());
9313 if (whiteListassociatedWakeUpFlag_ &&
9314 abilityRequest.appInfo.bundleName == BUNDLE_NAME_SETTINGSDATA) {
9315 TAG_LOGD(AAFwkTag::ABILITYMGR,
9316 "Call ServiceAbility or DataAbility, target bundle in white-list, allow associatedWakeUp.");
9317 verificationInfo.associatedWakeUp = true;
9318 } else {
9319 verificationInfo.associatedWakeUp = abilityRequest.appInfo.associatedWakeUp;
9320 }
9321 if (!isData) {
9322 isSA = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9323 isShell = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
9324 }
9325 if (isSA || isShell) {
9326 return verificationInfo;
9327 }
9328 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9329 if (callerAbility) {
9330 verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9331 }
9332
9333 return verificationInfo;
9334 }
9335
CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)9336 int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)
9337 {
9338 TAG_LOGD(AAFwkTag::ABILITYMGR, "begin");
9339
9340 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9341 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9342 verificationInfo.visible = abilityRequest.abilityInfo.visible;
9343 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9344 verificationInfo.isBackgroundCall = false;
9345 if (isParamStartAbilityEnable_) {
9346 bool stopContinuousTaskFlag = ShouldPreventStartAbility(abilityRequest);
9347 if (stopContinuousTaskFlag) {
9348 TAG_LOGE(AAFwkTag::ABILITYMGR, "no have permission to start ServiceExtension");
9349 return CHECK_PERMISSION_FAILED;
9350 }
9351 }
9352
9353 if (abilityRequest.abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
9354 TAG_LOGE(AAFwkTag::ABILITYMGR, "background startup UI_SERVICE");
9355 verificationInfo.isBackgroundCall = true;
9356 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9357 if (callerAbility) {
9358 verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9359 }
9360 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9361 TAG_LOGE(AAFwkTag::ABILITYMGR, "not background startup UI_SERVICE");
9362 return ERR_INVALID_VALUE;
9363 }
9364 }
9365
9366 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo);
9367 if (result != ERR_OK) {
9368 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceExtension or sataShareExtension permission");
9369 }
9370 return result;
9371 }
9372
CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)9373 int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)
9374 {
9375 if (IPCSkeleton::GetCallingUid() != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
9376 AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9377 return ERR_OK;
9378 }
9379 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9380 TAG_LOGD(AAFwkTag::ABILITYMGR, "OtherExtension type: %{public}d.", static_cast<int32_t>(extensionType));
9381 if (system::GetBoolParameter(DEVELOPER_MODE_STATE, false) &&
9382 PermissionVerification::GetInstance()->VerifyShellStartExtensionType(static_cast<int32_t>(extensionType))) {
9383 TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckCallOtherExtensionPermission, allow aa start with debug mode.");
9384 return ERR_OK;
9385 }
9386 if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) {
9387 CHECK_CALLER_IS_SYSTEM_APP;
9388 return ERR_OK;
9389 }
9390 if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) {
9391 return ERR_OK;
9392 }
9393 if (extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD ||
9394 extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART) {
9395 if (!abilityRequest.appInfo.isSystemApp) {
9396 TAG_LOGE(AAFwkTag::ABILITYMGR, "application requesting call isn't system application");
9397 return CHECK_PERMISSION_FAILED;
9398 }
9399 std::string jsonDataStr = abilityRequest.want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY);
9400 AbilityBase::ViewData viewData;
9401 viewData.FromJsonString(jsonDataStr.c_str());
9402 if (!CheckCallingTokenId(viewData.bundleName)) {
9403 TAG_LOGE(AAFwkTag::ABILITYMGR, "no %{public}s called, no allowed", viewData.bundleName.c_str());
9404 return ERR_WRONG_INTERFACE_CALL;
9405 }
9406 return ERR_OK;
9407 }
9408 if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
9409 return CheckUIExtensionPermission(abilityRequest);
9410 }
9411 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
9412 return ERR_OK;
9413 }
9414 if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION) {
9415 return CheckFileAccessExtensionPermission(abilityRequest);
9416 }
9417 if (extensionType == AppExecFwk::ExtensionAbilityType::CALLER_INFO_QUERY) {
9418 return CheckCallerInfoQueryExtensionPermission(abilityRequest);
9419 }
9420 TAG_LOGE(AAFwkTag::ABILITYMGR, "not SA, can't start other extension");
9421 return CHECK_PERMISSION_FAILED;
9422 }
9423
CheckCallerInfoQueryExtensionPermission(const AbilityRequest &abilityRequest)9424 int AbilityManagerService::CheckCallerInfoQueryExtensionPermission(const AbilityRequest &abilityRequest)
9425 {
9426 auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9427 PermissionConstants::PERMISSION_GET_TELEPHONY_STATE);
9428 if (!ret) {
9429 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny for callerInfoQueryExtension");
9430 return CHECK_PERMISSION_FAILED;
9431 }
9432 TAG_LOGI(AAFwkTag::ABILITYMGR, "check permission success");
9433 return ERR_OK;
9434 }
9435
CheckFileAccessExtensionPermission(const AbilityRequest &abilityRequest)9436 int AbilityManagerService::CheckFileAccessExtensionPermission(const AbilityRequest &abilityRequest)
9437 {
9438 auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9439 PermissionConstants::PERMISSION_FILE_ACCESS_MANAGER);
9440 if (!ret) {
9441 return CHECK_PERMISSION_FAILED;
9442 }
9443 TAG_LOGD(AAFwkTag::ABILITYMGR, "Temporary, FILEACCESS_EXTENSION use serviceExtension start-up rule.");
9444 return CheckCallServiceExtensionPermission(abilityRequest);
9445 }
9446
CheckUIExtensionPermission(const AbilityRequest &abilityRequest)9447 int AbilityManagerService::CheckUIExtensionPermission(const AbilityRequest &abilityRequest)
9448 {
9449 if (abilityRequest.want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
9450 // If started by embedded atomic service, allow it.
9451 return ERR_OK;
9452 }
9453
9454 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9455 if (AAFwk::UIExtensionUtils::IsSystemUIExtension(extensionType)) {
9456 auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9457 if (callerRecord == nullptr) {
9458 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid caller");
9459 return NO_FOUND_ABILITY_BY_CALLER;
9460 }
9461
9462 if (!abilityRequest.appInfo.isSystemApp) {
9463 TAG_LOGE(AAFwkTag::ABILITYMGR, "bundle %{public}s want start or caller bundle %{public}s "
9464 "isn't system app, type %{public}d not allowed", abilityRequest.appInfo.bundleName.c_str(),
9465 callerRecord->GetApplicationInfo().bundleName.c_str(), extensionType);
9466 return CHECK_PERMISSION_FAILED;
9467 }
9468 }
9469
9470 if (AAFwk::UIExtensionUtils::IsSystemCallerNeeded(extensionType)) {
9471 auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9472 if (callerRecord == nullptr) {
9473 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid caller");
9474 return NO_FOUND_ABILITY_BY_CALLER;
9475 }
9476
9477 if (!callerRecord->GetApplicationInfo().isSystemApp
9478 && !AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9479 TAG_LOGE(AAFwkTag::ABILITYMGR,
9480 "bundle %{public}s want start but caller bundle %{public}s "
9481 "isn't system app, type %{public}d not allowed",
9482 abilityRequest.appInfo.bundleName.c_str(), callerRecord->GetApplicationInfo().bundleName.c_str(),
9483 extensionType);
9484 return CHECK_PERMISSION_FAILED;
9485 }
9486 }
9487
9488 if (!CheckUIExtensionCallerIsForeground(abilityRequest)) {
9489 return CHECK_PERMISSION_FAILED;
9490 }
9491
9492 if (!CheckUIExtensionCallerPidByHostWindowId(abilityRequest)) {
9493 return ERR_INVALID_CALLER;
9494 }
9495
9496 return ERR_OK;
9497 }
9498
CheckUIExtensionCallerIsForeground(const AbilityRequest &abilityRequest)9499 bool AbilityManagerService::CheckUIExtensionCallerIsForeground(const AbilityRequest &abilityRequest)
9500 {
9501 if (!CheckUIExtensionCallerIsUIAbility(abilityRequest)) {
9502 // Check only if the caller is uiability, if caller is not a uiability, don't check.
9503 return true;
9504 }
9505
9506 bool isBackgroundCall = true;
9507 auto ret = IsCallFromBackground(abilityRequest, isBackgroundCall);
9508 if (ret != ERR_OK) {
9509 TAG_LOGE(AAFwkTag::UI_EXT, "start uea when background");
9510 return false;
9511 }
9512
9513 if (!isBackgroundCall) {
9514 return true;
9515 }
9516
9517 auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9518 if (callerAbility != nullptr) {
9519 if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9520 auto tokenId = callerAbility->GetApplicationInfo().accessTokenId;
9521 bool isFocused = false;
9522 if (CheckUIExtensionIsFocused(tokenId, isFocused) == ERR_OK && isFocused) {
9523 TAG_LOGD(AAFwkTag::ABILITYMGR, "Root caller is foreground");
9524 return true;
9525 }
9526 }
9527
9528 if (callerAbility->IsSceneBoard()) {
9529 return true;
9530 }
9531 }
9532
9533 if (PermissionVerification::GetInstance()->VerifyCallingPermission(
9534 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
9535 return true;
9536 }
9537
9538 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller app not foreground, can't start %{public}s",
9539 abilityRequest.want.GetElement().GetURI().c_str());
9540 return false;
9541 }
9542
CheckUIExtensionCallerIsUIAbility(const AbilityRequest &abilityRequest)9543 bool AbilityManagerService::CheckUIExtensionCallerIsUIAbility(const AbilityRequest &abilityRequest)
9544 {
9545 auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9546 if (callerAbility == nullptr) {
9547 TAG_LOGE(AAFwkTag::UI_EXT, "caller ability invalid");
9548 return false;
9549 }
9550
9551 if (callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9552 return true;
9553 }
9554
9555 if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9556 callerAbility = GetUIExtensionRootCaller(abilityRequest.callerToken, abilityRequest.userId);
9557 if (callerAbility != nullptr && callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9558 return true;
9559 }
9560 }
9561
9562 return false;
9563 }
9564
CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest &abilityRequest)9565 bool AbilityManagerService::CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest &abilityRequest)
9566 {
9567 #ifdef SUPPORT_SCREEN
9568 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9569 return true;
9570 }
9571
9572 auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9573 CHECK_POINTER_AND_RETURN(callerAbility, false);
9574 if (callerAbility->IsSceneBoard()) {
9575 return true;
9576 }
9577
9578 auto sessionInfo = abilityRequest.sessionInfo;
9579 CHECK_POINTER_AND_RETURN(sessionInfo, false);
9580 auto hostWindowId = sessionInfo->hostWindowId;
9581 auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
9582 CHECK_POINTER_AND_RETURN(sceneSessionManager, false);
9583 pid_t hostPid = 0;
9584 // If host window id is scb, it will return with error.
9585 auto ret = sceneSessionManager->CheckWindowId(hostWindowId, hostPid);
9586 TAG_LOGD(AAFwkTag::UI_EXT, "get pid %{public}d by windowId %{public}d", hostPid, hostWindowId);
9587 if (hostPid != 0 && callerAbility->GetPid() == hostPid) {
9588 return true;
9589 }
9590
9591 if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9592 TAG_LOGD(AAFwkTag::UI_EXT, "caller is nested uiextability");
9593 auto connectManager = GetCurrentConnectManager();
9594 CHECK_POINTER_AND_RETURN(connectManager, false);
9595 bool matched = false;
9596 std::list<sptr<IRemoteObject>> callerList;
9597 connectManager->GetUIExtensionCallerTokenList(callerAbility, callerList);
9598 for (auto &item : callerList) {
9599 auto ability = AAFwk::Token::GetAbilityRecordByToken(item);
9600 if (ability == nullptr) {
9601 TAG_LOGW(AAFwkTag::UI_EXT, "wrong ability");
9602 continue;
9603 }
9604
9605 if ((hostPid != 0 && ability->GetPid() == hostPid) || ability->IsSceneBoard()) {
9606 matched = true;
9607 return true;
9608 }
9609 }
9610 if (!matched) {
9611 TAG_LOGE(AAFwkTag::UI_EXT, "Check nested uiextability failed");
9612 }
9613 }
9614
9615 TAG_LOGE(AAFwkTag::UI_EXT, "check pid %{public}d fail, got %{public}d actual %{public}d",
9616 hostWindowId, hostPid, callerAbility->GetPid());
9617 return false;
9618 #else
9619 return true;
9620 #endif // SUPPORT_SCREEN
9621 }
9622
CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)9623 int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)
9624 {
9625 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9626 AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest);
9627 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9628 return ERR_INVALID_VALUE;
9629 }
9630
9631 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceAbilityPermission(verificationInfo);
9632 if (result != ERR_OK) {
9633 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceAbility permission");
9634 }
9635 return result;
9636 }
9637
CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId, bool isCallByShortcut)9638 int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId,
9639 bool isCallByShortcut)
9640 {
9641 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9642 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9643
9644 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9645 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9646 verificationInfo.visible = abilityRequest.abilityInfo.visible;
9647 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9648 verificationInfo.specifyTokenId = specifyTokenId;
9649 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9650 return ERR_INVALID_VALUE;
9651 }
9652
9653 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission(
9654 verificationInfo, isCallByShortcut);
9655 if (result != ERR_OK) {
9656 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start pageAbility(FA) or ability(Stage) permission");
9657 }
9658 return result;
9659 }
9660
CheckStartByCallPermission(const AbilityRequest &abilityRequest)9661 int AbilityManagerService::CheckStartByCallPermission(const AbilityRequest &abilityRequest)
9662 {
9663 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9664 // check whether the target ability is page type and not specified mode.
9665 if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::PAGE ||
9666 abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
9667 TAG_LOGE(AAFwkTag::ABILITYMGR, "called ability not common ability");
9668 return RESOLVE_CALL_ABILITY_TYPE_ERR;
9669 }
9670
9671 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9672 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9673 verificationInfo.visible = abilityRequest.abilityInfo.visible;
9674 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9675 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9676 return ERR_INVALID_VALUE;
9677 }
9678
9679 if (AAFwk::PermissionVerification::GetInstance()->CheckStartByCallPermission(verificationInfo) != ERR_OK) {
9680 TAG_LOGE(AAFwkTag::ABILITYMGR, "without startAbilityByCall permission");
9681 return RESOLVE_CALL_NO_PERMISSIONS;
9682 }
9683 TAG_LOGD(AAFwkTag::ABILITYMGR, "caller has permission to resolve the call proxy of common ability");
9684 return ERR_OK;
9685 }
9686
IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall, bool isData)9687 int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall,
9688 bool isData)
9689 {
9690 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9691 if (!isData && AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
9692 isBackgroundCall = true;
9693 return ERR_OK;
9694 }
9695
9696 if (!isData && (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
9697 AbilityUtil::IsStartFreeInstall(abilityRequest.want))) {
9698 isBackgroundCall = false;
9699 return ERR_OK;
9700 }
9701
9702 AppExecFwk::RunningProcessInfo processInfo;
9703 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9704 if (callerAbility && callerAbility->GetAbilityInfo().bundleName == BUNDLE_NAME_DIALOG) {
9705 callerAbility = callerAbility->GetCallerRecord();
9706 }
9707 if (callerAbility) {
9708 if (callerAbility->IsForeground() || callerAbility->GetAbilityForegroundingFlag()) {
9709 isBackgroundCall = false;
9710 return ERR_OK;
9711 }
9712 // CallerAbility is not foreground, so check process state
9713 DelayedSingleton<AppScheduler>::GetInstance()->
9714 GetRunningProcessInfoByToken(callerAbility->GetToken(), processInfo);
9715 if (IsDelegatorCall(processInfo, abilityRequest)) {
9716 TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
9717 isBackgroundCall = false;
9718 return ERR_OK;
9719 }
9720 auto abilityState = callerAbility->GetAbilityState();
9721 if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING ||
9722 // If uiability or uiextensionability ability state is foreground when terminate,
9723 // it will move to background firstly. So if startAbility in onBackground() lifecycle,
9724 // the actual ability state may be had changed to terminating from background or backgrounding.
9725 abilityState == AbilityState::TERMINATING) {
9726 return ERR_OK;
9727 }
9728 } else {
9729 auto callerPid = IPCSkeleton::GetCallingPid();
9730 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
9731 if (processInfo.processName_.empty()) {
9732 TAG_LOGD(AAFwkTag::ABILITYMGR, "Can not find caller application by callerPid: %{private}d.", callerPid);
9733 if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9734 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
9735 TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller has PERMISSION_START_ABILITIES_FROM_BACKGROUND, PASS.");
9736 isBackgroundCall = false;
9737 return ERR_OK;
9738 }
9739 TAG_LOGE(AAFwkTag::ABILITYMGR, "without PERMISSION_START_ABILITIES_FROM_BACKGROUND, REJECT");
9740 return ERR_INVALID_VALUE;
9741 }
9742 }
9743 return SetBackgroundCall(processInfo, abilityRequest, isBackgroundCall);
9744 }
9745
SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest, bool &isBackgroundCall) const9746 int32_t AbilityManagerService::SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo,
9747 const AbilityRequest &abilityRequest, bool &isBackgroundCall) const
9748 {
9749 if (IsDelegatorCall(processInfo, abilityRequest)) {
9750 TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
9751 isBackgroundCall = false;
9752 return ERR_OK;
9753 }
9754
9755 if (backgroundJudgeFlag_) {
9756 isBackgroundCall = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND &&
9757 !processInfo.isFocused && !processInfo.isAbilityForegrounding;
9758 } else {
9759 isBackgroundCall = !processInfo.isFocused;
9760 if (!processInfo.isFocused && processInfo.state_ == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) {
9761 // Allow background startup within 1 second after application startup if state is FOREGROUND
9762 int64_t aliveTime = AbilityUtil::SystemTimeMillis() - processInfo.startTimeMillis_;
9763 isBackgroundCall = aliveTime > APP_ALIVE_TIME_MS;
9764 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process %{public}s is alive %{public}s ms.",
9765 processInfo.processName_.c_str(), std::to_string(aliveTime).c_str());
9766 }
9767 }
9768 TAG_LOGD(AAFwkTag::ABILITYMGR,
9769 "backgroundJudgeFlag: %{public}d, isBackgroundCall: %{public}d, callerAppState: %{public}d.",
9770 static_cast<int32_t>(backgroundJudgeFlag_),
9771 static_cast<int32_t>(isBackgroundCall),
9772 static_cast<int32_t>(processInfo.state_));
9773
9774 return ERR_OK;
9775 }
9776
IsTargetPermission(const Want &want) const9777 bool AbilityManagerService::IsTargetPermission(const Want &want) const
9778 {
9779 if (want.GetElement().GetBundleName() == PERMISSIONMGR_BUNDLE_NAME &&
9780 want.GetElement().GetAbilityName() == PERMISSIONMGR_ABILITY_NAME) {
9781 return true;
9782 }
9783
9784 return false;
9785 }
9786
IsDelegatorCall( const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest) const9787 inline bool AbilityManagerService::IsDelegatorCall(
9788 const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest) const
9789 {
9790 /* To make sure the AbilityDelegator is not counterfeited
9791 * 1. The caller-process must be test-process
9792 * 2. The callerToken must be nullptr
9793 */
9794 if (processInfo.isTestProcess &&
9795 !abilityRequest.callerToken && abilityRequest.want.GetBoolParam(IS_DELEGATOR_CALL, false)) {
9796 return true;
9797 }
9798 return false;
9799 }
9800
CheckNewRuleSwitchState(const std::string ¶m)9801 bool AbilityManagerService::CheckNewRuleSwitchState(const std::string ¶m)
9802 {
9803 char value[NEW_RULE_VALUE_SIZE] = "false";
9804 int retSysParam = GetParameter(param.c_str(), "false", value, NEW_RULE_VALUE_SIZE);
9805 TAG_LOGI(AAFwkTag::ABILITYMGR, "checkNewRuleSwitchState, %{public}s value: %{public}s", param.c_str(), value);
9806 if (retSysParam > 0 && !std::strcmp(value, "true")) {
9807 return true;
9808 }
9809 return false;
9810 }
9811
GetStartUpNewRuleFlag() const9812 bool AbilityManagerService::GetStartUpNewRuleFlag() const
9813 {
9814 return startUpNewRule_;
9815 }
9816
CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)9817 void AbilityManagerService::CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)
9818 {
9819 {
9820 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
9821 callStubTokenMap_[callStub] = token;
9822 }
9823 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9824 CHECK_POINTER(abilityRecord);
9825 if (!JudgeSelfCalled(abilityRecord)) {
9826 return;
9827 }
9828
9829 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9830 auto uiAbilityManager = GetCurrentUIAbilityManager();
9831 CHECK_POINTER(uiAbilityManager);
9832 uiAbilityManager->CallRequestDone(abilityRecord, callStub);
9833 return;
9834 }
9835
9836 auto missionListManager = GetCurrentMissionListManager();
9837 CHECK_POINTER(missionListManager);
9838 missionListManager->CallRequestDone(abilityRecord, callStub);
9839 }
9840
GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)9841 void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)
9842 {
9843 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
9844 auto it = callStubTokenMap_.find(callStub);
9845 if (it == callStubTokenMap_.end()) {
9846 token = nullptr;
9847 return;
9848 }
9849 token = callStubTokenMap_[callStub];
9850 }
9851
AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)9852 int AbilityManagerService::AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)
9853 {
9854 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9855 if (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
9856 AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
9857 return ERR_OK;
9858 }
9859 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
9860 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
9861 int32_t apiVersion = abilityRecord->GetApplicationInfo().apiTargetVersion;
9862 want.SetParam(DMS_API_VERSION, apiVersion);
9863 bool isCallerBackground = true;
9864 AppExecFwk::RunningProcessInfo processInfo;
9865 DelayedSingleton<AppScheduler>::GetInstance()->
9866 GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
9867 if (backgroundJudgeFlag_) {
9868 isCallerBackground = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND;
9869 } else {
9870 isCallerBackground = !processInfo.isFocused;
9871 }
9872 want.SetParam(DMS_IS_CALLER_BACKGROUND, isCallerBackground);
9873 return ERR_OK;
9874 }
9875
9876 #ifdef WITH_DLP
CheckDlpForExtension( const Want &want, const sptr<IRemoteObject> &callerToken, int32_t userId, EventInfo &eventInfo, const EventName &eventName)9877 int AbilityManagerService::CheckDlpForExtension(
9878 const Want &want, const sptr<IRemoteObject> &callerToken,
9879 int32_t userId, EventInfo &eventInfo, const EventName &eventName)
9880 {
9881 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9882 // check if form frs
9883 auto callingUid = IPCSkeleton::GetCallingUid();
9884 std::string bundleName = want.GetBundle();
9885 if (callingUid == FOUNDATION_UID && FRS_BUNDLE_NAME == bundleName) {
9886 return ERR_OK;
9887 }
9888
9889 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
9890 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
9891 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
9892 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verify failed");
9893 eventInfo.errCode = CHECK_PERMISSION_FAILED;
9894 EventReport::SendExtensionEvent(eventName, HiSysEventType::FAULT, eventInfo);
9895 return CHECK_PERMISSION_FAILED;
9896 }
9897 return ERR_OK;
9898 }
9899 #endif // WITH_DLP
9900
JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)9901 bool AbilityManagerService::JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
9902 {
9903 if (IPCSkeleton::GetCallingPid() == getprocpid()) {
9904 return true;
9905 }
9906
9907 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9908 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9909 if (callingTokenId != tokenID) {
9910 TAG_LOGE(AAFwkTag::ABILITYMGR, "no self, no enabled");
9911 return false;
9912 }
9913
9914 return true;
9915 }
9916
IsAppSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)9917 bool AbilityManagerService::IsAppSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
9918 {
9919 CHECK_POINTER_RETURN_BOOL(abilityRecord);
9920 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9921 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9922 if (callingTokenId != tokenID) {
9923 TAG_LOGE(AAFwkTag::ABILITYMGR, "not app self called");
9924 return false;
9925 }
9926 return true;
9927 }
9928
GetFocusAbility()9929 std::shared_ptr<AbilityRecord> AbilityManagerService::GetFocusAbility()
9930 {
9931 #ifdef SUPPORT_SCREEN
9932 sptr<IRemoteObject> token;
9933 if (!wmsHandler_) {
9934 TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ null");
9935 return nullptr;
9936 }
9937
9938 wmsHandler_->GetFocusWindow(token);
9939 if (!token) {
9940 TAG_LOGE(AAFwkTag::ABILITYMGR, "token null");
9941 return nullptr;
9942 }
9943
9944 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9945 if (!abilityRecord) {
9946 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
9947 }
9948 return abilityRecord;
9949 #endif
9950
9951 return nullptr;
9952 }
9953
CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)9954 int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)
9955 {
9956 sptr<IRemoteObject> token;
9957 auto ret = GetTopAbility(token);
9958 if (ret != ERR_OK) {
9959 TAG_LOGE(AAFwkTag::ABILITYMGR, "getTopAbility failed");
9960 return ret;
9961 }
9962
9963 auto topAbility = Token::GetAbilityRecordByToken(token);
9964 if (topAbility != nullptr) {
9965 TAG_LOGD(AAFwkTag::ABILITYMGR, "top ability: %{public}s, pid: %{public}d, tokenId: %{public}d",
9966 topAbility->GetWant().GetElement().GetURI().c_str(), topAbility->GetPid(),
9967 topAbility->GetApplicationInfo().accessTokenId);
9968 }
9969
9970 bool focused = false;
9971 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
9972 auto connectManager = GetConnectManagerByUserId(userId);
9973 if (connectManager) {
9974 focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
9975 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
9976 } else {
9977 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:%{public}d", userId);
9978 }
9979 if (!focused && userId != U0_USER_ID) {
9980 TAG_LOGD(AAFwkTag::ABILITYMGR, "Check connectManager in user0");
9981 connectManager = GetConnectManagerByUserId(U0_USER_ID);
9982 if (connectManager) {
9983 focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
9984 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
9985 } else {
9986 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId: 0");
9987 }
9988 }
9989 isFocused = focused;
9990 TAG_LOGD(AAFwkTag::ABILITYMGR, "isFocused: %{public}d", isFocused);
9991 return ERR_OK;
9992 }
9993
AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken, const sptr<AbilityRuntime::IFreeInstallObserver> &observer)9994 int AbilityManagerService::AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken,
9995 const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
9996 {
9997 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9998 if (freeInstallManager_ == nullptr) {
9999 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
10000 return ERR_INVALID_VALUE;
10001 }
10002 return freeInstallManager_->AddFreeInstallObserver(callerToken, observer);
10003 }
10004
IsValidMissionIds( const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)10005 int32_t AbilityManagerService::IsValidMissionIds(
10006 const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)
10007 {
10008 auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
10009 auto missionlistMgr = GetMissionListManagerByUserId(userId);
10010 if (missionlistMgr == nullptr) {
10011 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionlistMgr null");
10012 return ERR_INVALID_VALUE;
10013 }
10014
10015 return missionlistMgr->IsValidMissionIds(missionIds, results);
10016 }
10017
VerifyPermission(const std::string &permission, int pid, int uid)10018 int AbilityManagerService::VerifyPermission(const std::string &permission, int pid, int uid)
10019 {
10020 TAG_LOGI(AAFwkTag::ABILITYMGR, "permission=%{public}s, pid=%{public}d, uid=%{public}d",
10021 permission.c_str(),
10022 pid,
10023 uid);
10024 if (permission.empty()) {
10025 TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission permission invalid");
10026 return CHECK_PERMISSION_FAILED;
10027 }
10028
10029 auto bms = AbilityUtil::GetBundleManagerHelper();
10030 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
10031
10032 std::string bundleName;
10033 if (IN_PROCESS_CALL(bms->GetNameForUid(uid, bundleName)) != ERR_OK) {
10034 TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission get bundle name failed");
10035 return CHECK_PERMISSION_FAILED;
10036 }
10037
10038 int account = -1;
10039 DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, account);
10040 AppExecFwk::ApplicationInfo appInfo;
10041 if (!IN_PROCESS_CALL(bms->GetApplicationInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
10042 account, appInfo))) {
10043 TAG_LOGE(AAFwkTag::ABILITYMGR, "verifyPermission get application info failed");
10044 return CHECK_PERMISSION_FAILED;
10045 }
10046
10047 int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false);
10048 if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
10049 TAG_LOGE(AAFwkTag::ABILITYMGR, "PERMISSION_DENIED");
10050 return CHECK_PERMISSION_FAILED;
10051 }
10052
10053 return ERR_OK;
10054 }
10055
AcquireShareData( const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)10056 int32_t AbilityManagerService::AcquireShareData(
10057 const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)
10058 {
10059 TAG_LOGD(AAFwkTag::ABILITYMGR, "missionId is %{public}d.", missionId);
10060 CHECK_CALLER_IS_SYSTEM_APP;
10061 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
10062 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10063 auto uiAbilityManager = GetCurrentUIAbilityManager();
10064 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10065 abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
10066 } else {
10067 auto missionListManager = GetCurrentMissionListManager();
10068 CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
10069 abilityRecord = missionListManager->GetAbilityRecordByMissionId(missionId);
10070 }
10071 if (!abilityRecord) {
10072 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord null");
10073 return ERR_INVALID_VALUE;
10074 }
10075 std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
10076 uniqueId_ = (uniqueId_ == INT_MAX) ? 0 : (uniqueId_ + 1);
10077 std::pair<int64_t, const sptr<IAcquireShareDataCallback>> shareDataPair =
10078 std::make_pair(abilityRecord->GetAbilityRecordId(), shareData);
10079 iAcquireShareDataMap_.emplace(uniqueId_, shareDataPair);
10080 abilityRecord->ShareData(uniqueId_);
10081 return ERR_OK;
10082 }
10083
ShareDataDone( const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)10084 int32_t AbilityManagerService::ShareDataDone(
10085 const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
10086 {
10087 TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d", resultCode, uniqueId);
10088 if (!VerificationAllToken(token)) {
10089 return ERR_INVALID_VALUE;
10090 }
10091 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10092 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record is nullptr.");
10093 if (!JudgeSelfCalled(abilityRecord)) {
10094 return CHECK_PERMISSION_FAILED;
10095 }
10096 CHECK_POINTER_AND_RETURN_LOG(eventHandler_, ERR_INVALID_VALUE, "fail to get abilityEventHandler.");
10097 eventHandler_->RemoveEvent(SHAREDATA_TIMEOUT_MSG, uniqueId);
10098 return GetShareDataPairAndReturnData(abilityRecord, resultCode, uniqueId, wantParam);
10099 }
10100
NotifySaveAsResult(const Want &want, int resultCode, int requestCode)10101 int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCode, int requestCode)
10102 {
10103 TAG_LOGD(AAFwkTag::ABILITYMGR, "requestCode is %{public}d.", requestCode);
10104 CHECK_CALLER_IS_SYSTEM_APP;
10105 #ifdef WITH_DLP
10106 //caller check
10107 if (!DlpUtils::CheckCallerIsDlpManager(AbilityUtil::GetBundleManagerHelper())) {
10108 TAG_LOGW(AAFwkTag::ABILITYMGR, "caller check failed");
10109 return CHECK_PERMISSION_FAILED;
10110 }
10111 #endif // WITH_DLP
10112 auto checkResult = AbilityUtil::CheckInstanceKey(want);
10113 if (checkResult != ERR_OK) {
10114 return checkResult;
10115 }
10116
10117 for (const auto &item : startAbilityChain_) {
10118 if (item.second->GetHandlerName() == StartAbilitySandboxSavefile::handlerName_) {
10119 auto savefileHandler = (StartAbilitySandboxSavefile*)(item.second.get());
10120 savefileHandler->HandleResult(want, resultCode, requestCode);
10121 break;
10122 }
10123 }
10124 return ERR_OK;
10125 }
10126
SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)10127 void AbilityManagerService::SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)
10128 {
10129 if (!IsCallerSceneBoard()) {
10130 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10131 return;
10132 }
10133 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10134 CHECK_POINTER(uiAbilityManager);
10135 uiAbilityManager->SetRootSceneSession(rootSceneSession);
10136 }
10137
CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isColdStart)10138 void AbilityManagerService::CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isColdStart)
10139 {
10140 if (!IsCallerSceneBoard()) {
10141 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10142 return;
10143 }
10144 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10145 CHECK_POINTER(uiAbilityManager);
10146 uiAbilityManager->CallUIAbilityBySCB(sessionInfo, isColdStart);
10147 }
10148
SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)10149 int32_t AbilityManagerService::SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)
10150 {
10151 if (!IsCallerSceneBoard()) {
10152 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10153 return ERR_WRONG_INTERFACE_CALL;
10154 }
10155
10156 TAG_LOGI(AAFwkTag::ABILITYMGR, "call setSessionManagerService of WMS");
10157 auto ret = Rosen::MockSessionManagerService::GetInstance().SetSessionManagerService(sessionManagerService);
10158 if (ret) {
10159 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10160 return ERR_OK;
10161 }
10162 TAG_LOGE(AAFwkTag::ABILITYMGR, "SMS setSessionManagerService return false");
10163 return ERR_OK;
10164 }
10165
CheckPrepareTerminateEnable()10166 bool AbilityManagerService::CheckPrepareTerminateEnable()
10167 {
10168 if (!isPrepareTerminateEnable_) {
10169 TAG_LOGD(AAFwkTag::ABILITYMGR, "Only support PC.");
10170 return false;
10171 }
10172 if (!AAFwk::PermissionVerification::GetInstance()->VerifyPrepareTerminatePermission()) {
10173 TAG_LOGD(AAFwkTag::ABILITYMGR, "failed, please apply permission ohos.permission.PREPARE_APP_TERMINATE");
10174 return false;
10175 }
10176 return true;
10177 }
10178
StartSpecifiedAbilityBySCB(const Want &want)10179 void AbilityManagerService::StartSpecifiedAbilityBySCB(const Want &want)
10180 {
10181 if (!IsCallerSceneBoard()) {
10182 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10183 return;
10184 }
10185 int32_t appIndex = 0;
10186 if (!StartAbilityUtils::GetAppIndex(want, nullptr, appIndex)) {
10187 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid app clone index");
10188 }
10189 (void)AbilityPermissionUtil::GetInstance().CheckMultiInstanceAndAppClone(const_cast<Want &>(want),
10190 GetUserId(), appIndex, nullptr);
10191 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10192 CHECK_POINTER(uiAbilityManager);
10193 uiAbilityManager->StartSpecifiedAbilityBySCB(want);
10194 }
10195
RegisterIAbilityManagerCollaborator( int32_t type, const sptr<IAbilityManagerCollaborator> &impl)10196 int32_t AbilityManagerService::RegisterIAbilityManagerCollaborator(
10197 int32_t type, const sptr<IAbilityManagerCollaborator> &impl)
10198 {
10199 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10200 auto callingUid = IPCSkeleton::GetCallingUid();
10201 if (!isSaCall || (callingUid != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
10202 callingUid != AppUtils::GetInstance().GetCollaboratorBrokerReserveUID())) {
10203 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
10204 return CHECK_PERMISSION_FAILED;
10205 }
10206 if (!CheckCollaboratorType(type)) {
10207 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator register failed, invalid type");
10208 return ERR_INVALID_VALUE;
10209 }
10210 {
10211 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10212 collaboratorMap_[type] = impl;
10213 }
10214 return ERR_OK;
10215 }
10216
UnregisterIAbilityManagerCollaborator(int32_t type)10217 int32_t AbilityManagerService::UnregisterIAbilityManagerCollaborator(int32_t type)
10218 {
10219 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10220 auto callingUid = IPCSkeleton::GetCallingUid();
10221 if (!isSaCall || (callingUid != AppUtils::GetInstance().GetCollaboratorBrokerUID() &&
10222 callingUid != AppUtils::GetInstance().GetCollaboratorBrokerReserveUID())) {
10223 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
10224 return CHECK_PERMISSION_FAILED;
10225 }
10226 if (!CheckCollaboratorType(type)) {
10227 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator unregister failed, invalid type");
10228 return ERR_INVALID_VALUE;
10229 }
10230 {
10231 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10232 collaboratorMap_.erase(type);
10233 }
10234 return ERR_OK;
10235 }
10236
GetCollaborator(int32_t type)10237 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetCollaborator(int32_t type)
10238 {
10239 if (!CheckCollaboratorType(type)) {
10240 return nullptr;
10241 }
10242 {
10243 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10244 auto it = collaboratorMap_.find(type);
10245 if (it != collaboratorMap_.end()) {
10246 return it->second;
10247 }
10248 }
10249 return nullptr;
10250 }
10251
CheckCollaboratorType(int32_t type)10252 bool AbilityManagerService::CheckCollaboratorType(int32_t type)
10253 {
10254 if (type != CollaboratorType::RESERVE_TYPE && type != CollaboratorType::OTHERS_TYPE) {
10255 return false;
10256 }
10257 return true;
10258 }
10259
GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo, std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility)10260 void AbilityManagerService::GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo,
10261 std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility)
10262 {
10263 targetAbility = nullptr;
10264 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10265 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId=%{public}d", userId);
10266 connectManager = GetConnectManagerByUserId(userId);
10267 if (connectManager) {
10268 targetAbility = connectManager->GetUIExtensionBySessionInfo(sessionInfo);
10269 } else {
10270 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:%{public}d", userId);
10271 }
10272 if (targetAbility == nullptr && userId != U0_USER_ID) {
10273 TAG_LOGD(AAFwkTag::ABILITYMGR, "try to find UIExtension in user0");
10274 connectManager = GetConnectManagerByUserId(U0_USER_ID);
10275 if (connectManager) {
10276 targetAbility = connectManager->GetUIExtensionBySessionInfo(sessionInfo);
10277 } else {
10278 TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager null, userId:0");
10279 }
10280 }
10281 }
10282
RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)10283 int32_t AbilityManagerService::RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)
10284 {
10285 if (!IsCallerSceneBoard()) {
10286 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10287 return ERR_WRONG_INTERFACE_CALL;
10288 }
10289 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10290 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10291 return uiAbilityManager->RegisterStatusBarDelegate(delegate);
10292 }
10293
KillProcessWithPrepareTerminate(const std::vector<int32_t>& pids)10294 int32_t AbilityManagerService::KillProcessWithPrepareTerminate(const std::vector<int32_t>& pids)
10295 {
10296 if (!IsCallerSceneBoard()) {
10297 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10298 return ERR_WRONG_INTERFACE_CALL;
10299 }
10300 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10301 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10302 return uiAbilityManager->TryPrepareTerminateByPids(pids);
10303 }
10304
RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)10305 int32_t AbilityManagerService::RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10306 {
10307 if (abilityAutoStartupService_ == nullptr) {
10308 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10309 return ERR_NO_INIT;
10310 }
10311 return abilityAutoStartupService_->RegisterAutoStartupSystemCallback(callback);
10312 }
10313
UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)10314 int32_t AbilityManagerService::UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10315 {
10316 if (abilityAutoStartupService_ == nullptr) {
10317 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10318 return ERR_NO_INIT;
10319 }
10320 return abilityAutoStartupService_->UnregisterAutoStartupSystemCallback(callback);
10321 }
10322
SetApplicationAutoStartup(const AutoStartupInfo &info)10323 int32_t AbilityManagerService::SetApplicationAutoStartup(const AutoStartupInfo &info)
10324 {
10325 if (abilityAutoStartupService_ == nullptr) {
10326 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10327 return ERR_NO_INIT;
10328 }
10329 return abilityAutoStartupService_->SetApplicationAutoStartup(info);
10330 }
10331
CancelApplicationAutoStartup(const AutoStartupInfo &info)10332 int32_t AbilityManagerService::CancelApplicationAutoStartup(const AutoStartupInfo &info)
10333 {
10334 if (abilityAutoStartupService_ == nullptr) {
10335 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10336 return ERR_NO_INIT;
10337 }
10338 return abilityAutoStartupService_->CancelApplicationAutoStartup(info);
10339 }
10340
QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)10341 int32_t AbilityManagerService::QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)
10342 {
10343 if (abilityAutoStartupService_ == nullptr) {
10344 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10345 return ERR_NO_INIT;
10346 }
10347 return abilityAutoStartupService_->QueryAllAutoStartupApplications(infoList, GetUserId());
10348 }
10349
PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)10350 int AbilityManagerService::PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)
10351 {
10352 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10353 TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
10354 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
10355 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
10356 return ERR_INVALID_VALUE;
10357 }
10358
10359 if (!IsCallerSceneBoard()) {
10360 TAG_LOGE(AAFwkTag::ABILITYMGR, "not sceneboard called, not allowed");
10361 return ERR_WRONG_INTERFACE_CALL;
10362 }
10363
10364 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10365 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10366 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
10367 isTerminate = uiAbilityManager->PrepareTerminateAbility(abilityRecord);
10368
10369 return ERR_OK;
10370 }
10371
RegisterSessionHandler(const sptr<IRemoteObject> &object)10372 int AbilityManagerService::RegisterSessionHandler(const sptr<IRemoteObject> &object)
10373 {
10374 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
10375 if (!IsCallerSceneBoard()) {
10376 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
10377 return ERR_WRONG_INTERFACE_CALL;
10378 }
10379 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10380 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10381 sptr<ISessionHandler> handler = iface_cast<ISessionHandler>(object);
10382 uiAbilityManager->SetSessionHandler(handler);
10383 return ERR_OK;
10384 }
10385
CheckUserIdActive(int32_t userId)10386 bool AbilityManagerService::CheckUserIdActive(int32_t userId)
10387 {
10388 std::vector<int32_t> osActiveAccountIds;
10389 auto ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
10390 QueryActiveOsAccountIds(osActiveAccountIds);
10391 if (ret != ERR_OK) {
10392 TAG_LOGE(AAFwkTag::ABILITYMGR, "queryActiveOsAccountIds failed");
10393 return false;
10394 }
10395 if (osActiveAccountIds.empty()) {
10396 TAG_LOGE(AAFwkTag::ABILITYMGR, "queryActiveOsAccountIds empty");
10397 return false;
10398 }
10399 auto iter = std::find(osActiveAccountIds.begin(), osActiveAccountIds.end(), userId);
10400 if (iter == osActiveAccountIds.end()) {
10401 return false;
10402 }
10403 return true;
10404 }
10405
CheckProcessOptions(const Want &want, const StartOptions &startOptions, int32_t userId)10406 int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const StartOptions &startOptions, int32_t userId)
10407 {
10408 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10409 if (startOptions.processOptions == nullptr ||
10410 !ProcessOptions::IsValidProcessMode(startOptions.processOptions->processMode)) {
10411 return ERR_OK;
10412 }
10413
10414 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability with process options");
10415 bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
10416 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
10417 TAG_LOGE(AAFwkTag::ABILITYMGR, "not support process options");
10418 return ERR_CAPABILITY_NOT_SUPPORT;
10419 }
10420
10421 auto element = want.GetElement();
10422 if (element.GetAbilityName().empty() || want.GetAction().compare(ACTION_CHOOSE) == 0) {
10423 TAG_LOGE(AAFwkTag::ABILITYMGR, "not allow implicit start");
10424 return ERR_NOT_ALLOW_IMPLICIT_START;
10425 }
10426
10427 int32_t appIndex = 0;
10428 appIndex = !AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex) ? 0 : appIndex;
10429 bool isStartupVisibilityHide =
10430 (startOptions.processOptions->startupVisibility == StartupVisibility::STARTUP_HIDE);
10431 bool hasStartBackgroundAbilityPermission = PermissionVerification::GetInstance()->
10432 VerifyStartUIAbilityToHiddenPermission();
10433 bool canStartupHide = (ProcessOptions::IsNoAttachmentMode(startOptions.processOptions->processMode) &&
10434 isStartupVisibilityHide && hasStartBackgroundAbilityPermission);
10435 if (!CheckCallingTokenId(element.GetBundleName(), userId, appIndex) &&
10436 !canStartupHide) {
10437 TAG_LOGE(AAFwkTag::ABILITYMGR, "not self application and has no start background ability permission");
10438 return ERR_NOT_SELF_APPLICATION;
10439 }
10440
10441 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10442 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10443
10444 if ((ProcessOptions::IsAttachToStatusBarMode(startOptions.processOptions->processMode) &&
10445 !uiAbilityManager->IsCallerInStatusBar()) && !canStartupHide) {
10446 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not in status bar in attch status bar mode and "
10447 "has no start background ability permission");
10448 return ERR_START_OPTIONS_CHECK_FAILED;
10449 }
10450
10451 auto abilityRecords = uiAbilityManager->GetAbilityRecordsByName(element);
10452 if (!abilityRecords.empty() && abilityRecords[0] &&
10453 abilityRecords[0]->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::STANDARD &&
10454 abilityRecords[0]->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::SPECIFIED) {
10455 TAG_LOGE(AAFwkTag::ABILITYMGR, "if not STANDARD or SPECIFIED mode, repeated starts not allowed");
10456 return ERR_ABILITY_ALREADY_RUNNING;
10457 }
10458
10459 return ERR_OK;
10460 }
10461
RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10462 int32_t AbilityManagerService::RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10463 {
10464 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10465 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10466 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
10467 return CHECK_PERMISSION_FAILED;
10468 }
10469 return DelayedSingleton<AppScheduler>::GetInstance()->RegisterAppDebugListener(listener);
10470 }
10471
UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10472 int32_t AbilityManagerService::UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10473 {
10474 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10475 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10476 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
10477 return CHECK_PERMISSION_FAILED;
10478 }
10479 return DelayedSingleton<AppScheduler>::GetInstance()->UnregisterAppDebugListener(listener);
10480 }
10481
ConnectInitAbilityDebugDeal()10482 std::shared_ptr<AbilityDebugDeal> AbilityManagerService::ConnectInitAbilityDebugDeal()
10483 {
10484 if (abilityDebugDeal_ != nullptr) {
10485 return abilityDebugDeal_;
10486 }
10487
10488 std::unique_lock<ffrt::mutex> lock(abilityDebugDealLock_);
10489 if (abilityDebugDeal_ != nullptr) {
10490 return abilityDebugDeal_;
10491 }
10492
10493 TAG_LOGD(AAFwkTag::ABILITYMGR, "Creat ability debug deal object.");
10494 abilityDebugDeal_ = std::make_shared<AbilityDebugDeal>();
10495 if (abilityDebugDeal_ == nullptr) {
10496 TAG_LOGE(AAFwkTag::ABILITYMGR, "creat ability debug deal object failed");
10497 return nullptr;
10498 }
10499
10500 abilityDebugDeal_->RegisterAbilityDebugResponse();
10501 return abilityDebugDeal_;
10502 }
10503
AttachAppDebug(const std::string &bundleName)10504 int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName)
10505 {
10506 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10507 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10508 TAG_LOGE(AAFwkTag::ABILITYMGR, "developer Mode false");
10509 return ERR_NOT_DEVELOPER_MODE;
10510 }
10511
10512 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10513 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10514 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
10515 return CHECK_PERMISSION_FAILED;
10516 }
10517
10518 int32_t err = ERR_OK;
10519 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10520 if ((err = StartAbilityUtils::CheckAppProvisionMode(bundleName, userId)) != ERR_OK) {
10521 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckAppProvisionMode returns errcode=%{public}d", err);
10522 return err;
10523 }
10524
10525 ConnectInitAbilityDebugDeal();
10526 return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->AttachAppDebug(bundleName));
10527 }
10528
DetachAppDebug(const std::string &bundleName)10529 int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName)
10530 {
10531 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10532 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10533 TAG_LOGE(AAFwkTag::ABILITYMGR, "developer Mode false");
10534 return ERR_NOT_DEVELOPER_MODE;
10535 }
10536
10537 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10538 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10539 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
10540 return CHECK_PERMISSION_FAILED;
10541 }
10542
10543 int32_t err = ERR_OK;
10544 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10545 if ((err = StartAbilityUtils::CheckAppProvisionMode(bundleName, userId)) != ERR_OK) {
10546 TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckAppProvisionMode returns errcode=%{public}d", err);
10547 return err;
10548 }
10549
10550 return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->DetachAppDebug(bundleName));
10551 }
10552
ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam ¶m)10553 int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken,
10554 const InsightIntentExecuteParam ¶m)
10555 {
10556 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10557 auto paramPtr = std::make_shared<InsightIntentExecuteParam>(param);
10558 int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateParam(key, callerToken,
10559 paramPtr);
10560 if (ret != ERR_OK) {
10561 return ret;
10562 }
10563
10564 Want want;
10565 ret = InsightIntentExecuteManager::GenerateWant(paramPtr, want);
10566 if (ret != ERR_OK) {
10567 return ret;
10568 }
10569
10570 switch (param.executeMode_) {
10571 case AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND:
10572 TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_FOREGROUND.");
10573 ret = StartAbilityWithInsightIntent(want);
10574 break;
10575 case AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND: {
10576 TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_BACKGROUND.");
10577 ret = StartAbilityByCallWithInsightIntent(want, callerToken, param);
10578 break;
10579 }
10580 case AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY:
10581 TAG_LOGW(AAFwkTag::ABILITYMGR, "executeMode UI_EXTENSION_ABILITY not supported");
10582 ret = ERR_INVALID_OPERATION;
10583 break;
10584 case AppExecFwk::ExecuteMode::SERVICE_EXTENSION_ABILITY:
10585 TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode SERVICE_EXTENSION_ABILITY.");
10586 ret = StartExtensionAbilityWithInsightIntent(want, AppExecFwk::ExtensionAbilityType::SERVICE);
10587 break;
10588 default:
10589 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid executeMode");
10590 ret = ERR_INVALID_OPERATION;
10591 break;
10592 }
10593 if (ret == START_ABILITY_WAITING) {
10594 TAG_LOGD(AAFwkTag::ABILITYMGR, "Top ability is foregrounding. The intent will be queued for execution");
10595 ret = ERR_OK;
10596 }
10597 if (ret != ERR_OK) {
10598 DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->RemoveExecuteIntent(paramPtr->insightIntentId_);
10599 }
10600
10601 TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteIntent done, ret: %{public}d.", ret);
10602 return ret;
10603 }
10604
IsAbilityStarted(AbilityRequest &abilityRequest, std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)10605 bool AbilityManagerService::IsAbilityStarted(AbilityRequest &abilityRequest,
10606 std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)
10607 {
10608 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10609 TAG_LOGI(AAFwkTag::ABILITYMGR, "scene board enable");
10610 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
10611 CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
10612 return uiAbilityManager->IsAbilityStarted(abilityRequest, targetRecord);
10613 }
10614
10615 auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10616 if (missionListMgr == nullptr) {
10617 return false;
10618 }
10619 return missionListMgr->IsAbilityStarted(abilityRequest, targetRecord);
10620 }
10621
OnExecuteIntent(AbilityRequest &abilityRequest, std::shared_ptr<AbilityRecord> &targetRecord)10622 int32_t AbilityManagerService::OnExecuteIntent(AbilityRequest &abilityRequest,
10623 std::shared_ptr<AbilityRecord> &targetRecord)
10624 {
10625 TAG_LOGI(AAFwkTag::ABILITYMGR, "onExecuteIntent");
10626 if (targetRecord == nullptr || targetRecord->GetScheduler() == nullptr) {
10627 return ERR_INVALID_VALUE;
10628 }
10629 targetRecord->GetScheduler()->OnExecuteIntent(abilityRequest.want);
10630
10631 return ERR_OK;
10632 }
10633
StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)10634 int32_t AbilityManagerService::StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)
10635 {
10636 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10637 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
10638 if (startWithAccount || IsCrossUserCall(userId)) {
10639 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
10640 CHECK_CALLER_IS_SYSTEM_APP;
10641 }
10642 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
10643 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
10644 EventInfo eventInfo = BuildEventInfo(want, userId);
10645 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
10646 int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
10647 if (ret != ERR_OK) {
10648 eventInfo.errCode = ret;
10649 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
10650 }
10651 return ret;
10652 }
10653
StartExtensionAbilityWithInsightIntent(const Want &want, AppExecFwk::ExtensionAbilityType extensionType)10654 int32_t AbilityManagerService::StartExtensionAbilityWithInsightIntent(const Want &want,
10655 AppExecFwk::ExtensionAbilityType extensionType)
10656 {
10657 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10658 return StartExtensionAbilityInner(want, nullptr, DEFAULT_INVAL_VALUE, extensionType, true);
10659 }
10660
StartAbilityByCallWithInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam ¶m)10661 int32_t AbilityManagerService::StartAbilityByCallWithInsightIntent(const Want &want,
10662 const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam ¶m)
10663 {
10664 TAG_LOGI(AAFwkTag::ABILITYMGR, "call startAbilityByCallWithInsightIntent");
10665 sptr<IAbilityConnection> connect = sptr<AbilityBackgroundConnection>::MakeSptr();
10666 if (connect == nullptr) {
10667 TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid connect");
10668 return ERR_INVALID_VALUE;
10669 }
10670
10671 AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
10672 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
10673 AbilityRequest abilityRequest;
10674 abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
10675 abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
10676 abilityRequest.callerToken = callerToken;
10677 abilityRequest.startSetting = nullptr;
10678 abilityRequest.want = want;
10679 abilityRequest.connect = connect;
10680 int32_t result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
10681 if (result != ERR_OK) {
10682 TAG_LOGE(AAFwkTag::ABILITYMGR, "generate ability request error");
10683 return result;
10684 }
10685 std::shared_ptr<AbilityRecord> targetRecord;
10686 int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
10687 auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10688 if (IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId)) {
10689 TAG_LOGI(AAFwkTag::ABILITYMGR, "ability has already started");
10690 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
10691 result = OnExecuteIntent(abilityRequest, targetRecord);
10692 } else {
10693 result = StartAbilityByCall(want, connect, callerToken);
10694 }
10695
10696 TAG_LOGI(AAFwkTag::ABILITYMGR, "startAbilityByCallWithInsightIntent %{public}d", result);
10697 return result;
10698 }
10699
IsAbilityControllerStart(const Want &want)10700 bool AbilityManagerService::IsAbilityControllerStart(const Want &want)
10701 {
10702 auto callingUid = IPCSkeleton::GetCallingUid();
10703 bool isBrokerCall = (callingUid == AppUtils::GetInstance().GetCollaboratorBrokerUID() ||
10704 callingUid == AppUtils::GetInstance().GetCollaboratorBrokerReserveUID());
10705 if (isBrokerCall) {
10706 return IsAbilityControllerStart(want, want.GetBundle());
10707 }
10708 TAG_LOGE(AAFwkTag::ABILITYMGR, "interface only support broker");
10709 return true;
10710 }
10711
ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId, const InsightIntentExecuteResult &result)10712 int32_t AbilityManagerService::ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId,
10713 const InsightIntentExecuteResult &result)
10714 {
10715 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10716 auto abilityRecord = Token::GetAbilityRecordByToken(token);
10717 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
10718 if (!JudgeSelfCalled(abilityRecord)) {
10719 return CHECK_PERMISSION_FAILED;
10720 }
10721
10722 // check send by same bundleName.
10723 std::string bundleNameStored = "";
10724 auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetBundleName(intentId, bundleNameStored);
10725 if (ret != ERR_OK) {
10726 TAG_LOGE(AAFwkTag::ABILITYMGR, "matched bundleName failed, intentId:%{public}" PRIu64"", intentId);
10727 return ERR_INVALID_VALUE;
10728 }
10729
10730 std::string bundleName = abilityRecord->GetAbilityInfo().bundleName;
10731 if (bundleNameStored != bundleName) {
10732 TAG_LOGE(AAFwkTag::ABILITYMGR,
10733 "bundleName %{public}s and %{public}s mismatch", bundleName.c_str(), bundleNameStored.c_str());
10734 return ERR_INVALID_VALUE;
10735 }
10736
10737 return DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
10738 intentId, result.innerErr, result);
10739 }
10740
SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)10741 int32_t AbilityManagerService::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
10742 {
10743 if (abilityAutoStartupService_ == nullptr) {
10744 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10745 return ERR_NO_INIT;
10746 }
10747 return abilityAutoStartupService_->SetApplicationAutoStartupByEDM(info, flag);
10748 }
10749
CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)10750 int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
10751 {
10752 if (abilityAutoStartupService_ == nullptr) {
10753 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ null");
10754 return ERR_NO_INIT;
10755 }
10756 return abilityAutoStartupService_->CancelApplicationAutoStartupByEDM(info, flag);
10757 }
10758
GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)10759 int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)
10760 {
10761 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10762 CHECK_CALLER_IS_SYSTEM_APP;
10763 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
10764 if (!isPerm) {
10765 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
10766 return CHECK_PERMISSION_FAILED;
10767 }
10768
10769 std::vector<AbilityRunningInfo> abilityRunningInfos;
10770 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10771 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10772 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10773 uiAbilityManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
10774 } else {
10775 auto missionListManager = GetCurrentMissionListManager();
10776 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NULL_OBJECT);
10777 missionListManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
10778 }
10779
10780 for (auto &info : abilityRunningInfos) {
10781 if (info.abilityState != AbilityState::FOREGROUND) {
10782 continue;
10783 }
10784
10785 AppExecFwk::AbilityStateData abilityData;
10786 abilityData.bundleName = info.ability.GetBundleName();
10787 abilityData.moduleName = info.ability.GetModuleName();
10788 abilityData.abilityName = info.ability.GetAbilityName();
10789 abilityData.abilityState = info.abilityState;
10790 abilityData.pid = info.pid;
10791 abilityData.uid = info.uid;
10792 abilityData.abilityType = static_cast<int32_t>(AppExecFwk::AbilityType::PAGE);
10793 abilityData.appCloneIndex = info.appCloneIndex;
10794 AppExecFwk::ApplicationInfo appInfo;
10795 if (!StartAbilityUtils::GetApplicationInfo(abilityData.bundleName, GetUserId(), appInfo)) {
10796 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't get applicationInfo through bundleName");
10797 } else if (appInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
10798 abilityData.isAtomicService = true;
10799 }
10800 list.push_back(abilityData);
10801 }
10802 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get foreground ui abilities end, list.size = %{public}zu.", list.size());
10803 return ERR_OK;
10804 }
10805
NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)10806 void AbilityManagerService::NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)
10807 {
10808 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
10809 if (collaborator == nullptr) {
10810 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator getCollaborator null");
10811 return;
10812 }
10813 collaborator->UpdateConfiguration(config, userId);
10814 }
10815
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)10816 void AbilityManagerService::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
10817 {
10818 if (userController_ == nullptr) {
10819 TAG_LOGE(AAFwkTag::ABILITYMGR, "userController_ null");
10820 return;
10821 }
10822 auto currentUser = userController_->GetCurrentUserId();
10823 std::vector<AppExecFwk::BundleInfo> bundleInfosForU0;
10824 std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
10825 for (const auto &item: bundleInfos) {
10826 auto user = item.uid / BASE_USER_RANGE;
10827 if (user == U0_USER_ID) {
10828 bundleInfosForU0.push_back(item);
10829 } else if (user == currentUser) {
10830 bundleInfosForCurrentUser.push_back(item);
10831 }
10832 }
10833
10834 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
10835 bundleInfosForU0, U0_USER_ID);
10836 if (!bundleInfosForU0.empty()) {
10837 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForU0);
10838 }
10839
10840 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
10841 bundleInfosForCurrentUser, currentUser);
10842 if (!bundleInfosForCurrentUser.empty()) {
10843 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForCurrentUser);
10844 }
10845 }
10846
NotifyAppPreCache(int32_t pid, int32_t userId)10847 void AbilityManagerService::NotifyAppPreCache(int32_t pid, int32_t userId)
10848 {
10849 ForceTerminateServiceExtensionByPid(pid, userId);
10850 }
10851
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens)10852 void AbilityManagerService::OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens)
10853 {
10854 std::shared_ptr<AbilityRecord> abilityRecord;
10855 for (auto &token : abilityTokens) {
10856 abilityRecord = Token::GetAbilityRecordByToken(token);
10857 if (abilityRecord == nullptr) {
10858 continue;
10859 }
10860 TAG_LOGI(AAFwkTag::ABILITYMGR, "app onRemoteDied, ability:%{public}s, app:%{public}s",
10861 abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
10862 abilityRecord->OnProcessDied();
10863 }
10864 }
10865
OpenFile(const Uri& uri, uint32_t flag)10866 int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag)
10867 {
10868 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
10869 if (!IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission(
10870 uri, flag, accessTokenId))) {
10871 TAG_LOGE(AAFwkTag::ABILITYMGR, "premission check failed");
10872 return -1;
10873 }
10874 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
10875 if (collaborator == nullptr) {
10876 TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator getCollaborator null");
10877 return ERR_COLLABORATOR_NOT_REGISTER;
10878 }
10879 return collaborator->OpenFile(uri, flag);
10880 }
10881 #ifdef SUPPORT_SCREEN
GetDialogSessionInfo(const std::string &dialogSessionId, sptr<DialogSessionInfo> &dialogSessionInfo)10882 int AbilityManagerService::GetDialogSessionInfo(const std::string &dialogSessionId,
10883 sptr<DialogSessionInfo> &dialogSessionInfo)
10884 {
10885 CHECK_CALLER_IS_SYSTEM_APP;
10886 dialogSessionInfo = DialogSessionManager::GetInstance().GetDialogSessionInfo(dialogSessionId);
10887 if (dialogSessionInfo) {
10888 TAG_LOGD(AAFwkTag::ABILITYMGR, "success");
10889 return ERR_OK;
10890 }
10891 TAG_LOGD(AAFwkTag::ABILITYMGR, "fail");
10892 return INNER_ERR;
10893 }
10894
SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed)10895 int AbilityManagerService::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed)
10896 {
10897 CHECK_CALLER_IS_SYSTEM_APP;
10898 return DialogSessionManager::GetInstance().SendDialogResult(want, dialogSessionId, isAllowed);
10899 }
10900
CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId, const std::string &replaceWantString)10901 int AbilityManagerService::CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId,
10902 const std::string &replaceWantString)
10903 {
10904 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
10905 return implicitStartProcessor_->ImplicitStartAbility(request, userId, 0, replaceWantString, true);
10906 }
10907 #endif // SUPPORT_SCREEN
RemoveSelectorIdentity(int32_t tokenId)10908 void AbilityManagerService::RemoveSelectorIdentity(int32_t tokenId)
10909 {
10910 CHECK_POINTER(implicitStartProcessor_);
10911 implicitStartProcessor_->RemoveIdentity(tokenId);
10912 }
10913
SetTargetCloneIndexInSameBundle(const Want &want, sptr<IRemoteObject> callerToken)10914 void AbilityManagerService::SetTargetCloneIndexInSameBundle(const Want &want, sptr<IRemoteObject> callerToken)
10915 {
10916 auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
10917 CHECK_POINTER(callerRecord);
10918 if (callerRecord->GetAbilityInfo().bundleName != want.GetElement().GetBundleName()) {
10919 TAG_LOGD(AAFwkTag::ABILITYMGR, "not the same bundle");
10920 return;
10921 }
10922 if (want.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY)) {
10923 TAG_LOGD(AAFwkTag::ABILITYMGR, "want with app clone index.");
10924 return;
10925 }
10926 int32_t appIndex = callerRecord->GetApplicationInfo().appIndex;
10927 if (appIndex >= 0 && appIndex < AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
10928 (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
10929 }
10930 }
10931
RemoveLauncherDeathRecipient(int32_t userId)10932 void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId)
10933 {
10934 auto connectManager = GetConnectManagerByUserId(userId);
10935 if (connectManager == nullptr) {
10936 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager null userId=%{public}d", userId);
10937 return;
10938 }
10939 connectManager->RemoveLauncherDeathRecipient();
10940 }
10941
GenerateEmbeddableUIAbilityRequest( const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)10942 int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest(
10943 const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
10944 {
10945 int32_t screenMode = want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
10946 int32_t result = ERR_OK;
10947 if (screenMode == AAFwk::EMBEDDED_FULL_SCREEN_MODE) {
10948 result = GenerateAbilityRequest(want, -1, request, callerToken, userId);
10949 request.abilityInfo.isModuleJson = true;
10950 request.abilityInfo.isStageBasedModel = true;
10951 request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
10952 request.abilityInfo.extensionAbilityType = AppExecFwk::ExtensionAbilityType::UI;
10953 struct timespec time = {0, 0};
10954 clock_gettime(CLOCK_MONOTONIC, &time);
10955 int64_t times = static_cast<int64_t>(time.tv_sec);
10956 request.abilityInfo.process = request.abilityInfo.bundleName + PROCESS_SUFFIX + std::to_string(times);
10957 } else {
10958 result = GenerateExtensionAbilityRequest(want, request, callerToken, userId);
10959 }
10960 return result;
10961 }
10962
CheckDebugAssertPermission()10963 int32_t AbilityManagerService::CheckDebugAssertPermission()
10964 {
10965 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10966 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10967 if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
10968 TAG_LOGE(AAFwkTag::ABILITYMGR, "assert fault product dialog not enabled");
10969 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
10970 }
10971 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10972 TAG_LOGE(AAFwkTag::ABILITYMGR, "developer mode false");
10973 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
10974 }
10975
10976 auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
10977 CHECK_POINTER_AND_RETURN(bundleMgr, ERR_INVALID_VALUE);
10978 int32_t flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
10979 AppExecFwk::BundleInfo bundleInfo;
10980 auto ret = bundleMgr->GetBundleInfoForSelf(flags, bundleInfo);
10981 if (ret != ERR_OK) {
10982 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle info failed");
10983 return ret;
10984 }
10985 if (!bundleInfo.applicationInfo.debug) {
10986 TAG_LOGE(AAFwkTag::ABILITYMGR, "non-debug version app");
10987 return ERR_INVALID_VALUE;
10988 }
10989 return ERR_OK;
10990 }
10991
CloseAssertDialog(const std::string &assertSessionId)10992 void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId)
10993 {
10994 TAG_LOGD(AAFwkTag::ABILITYMGR, "Close assert fault dialog begin.");
10995 auto validUserId = GetUserId();
10996 auto connectManager = GetConnectManagerByUserId(validUserId);
10997 if (connectManager == nullptr) {
10998 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId: %{public}d", validUserId);
10999 return;
11000 }
11001
11002 connectManager->CloseAssertDialog(assertSessionId);
11003 }
11004
SetResidentProcessEnabled(const std::string &bundleName, bool enable)11005 int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable)
11006 {
11007 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11008 if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) {
11009 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
11010 return ERR_NOT_SYSTEM_APP;
11011 }
11012
11013 auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
11014 if (residentProcessManager == nullptr) {
11015 TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident proces mgr null");
11016 return INNER_ERR;
11017 }
11018
11019 std::string callerName;
11020 int32_t uid = 0;
11021 auto callerPid = IPCSkeleton::GetCallingPid();
11022 DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
11023 if (callerName.empty()) {
11024 TAG_LOGE(AAFwkTag::ABILITYMGR, "obtain caller name failed");
11025 return INNER_ERR;
11026 }
11027
11028 return residentProcessManager->SetResidentProcessEnabled(bundleName, callerName, enable);
11029 }
11030
RequestAssertFaultDialog( const sptr<IRemoteObject> &callback, const AAFwk::WantParams &wantParams)11031 int32_t AbilityManagerService::RequestAssertFaultDialog(
11032 const sptr<IRemoteObject> &callback, const AAFwk::WantParams &wantParams)
11033 {
11034 TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog begin.");
11035 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11036 auto checkRet = CheckDebugAssertPermission();
11037 if (checkRet != ERR_OK) {
11038 TAG_LOGE(AAFwkTag::ABILITYMGR, "check debug assert permission error");
11039 return checkRet;
11040 }
11041 sptr<IRemoteObject> remoteCallback = callback;
11042 if (remoteCallback == nullptr) {
11043 TAG_LOGE(AAFwkTag::ABILITYMGR, "params remote callback null");
11044 return ERR_INVALID_VALUE;
11045 }
11046 auto debugDeal = ConnectInitAbilityDebugDeal();
11047 Want want;
11048 #ifdef SUPPORT_SCREEN
11049 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
11050 if (sysDialog == nullptr || debugDeal == nullptr) {
11051 TAG_LOGE(AAFwkTag::ABILITYMGR, "sysDialog or debugDeal null");
11052 return ERR_INVALID_VALUE;
11053 }
11054 if (!sysDialog->GetAssertFaultDialogWant(want)) {
11055 TAG_LOGE(AAFwkTag::ABILITYMGR, "get assert fault dialog want failed");
11056 return ERR_INVALID_VALUE;
11057 }
11058 #endif // SUPPORT_SCREEN
11059 uint64_t assertFaultSessionId = reinterpret_cast<uint64_t>(remoteCallback.GetRefPtr());
11060 want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, std::to_string(assertFaultSessionId));
11061 want.SetParam(ASSERT_FAULT_DETAIL, wantParams.GetStringParam(ASSERT_FAULT_DETAIL));
11062 auto &connection = AbilityRuntime::ModalSystemAssertUIExtension::GetInstance();
11063 want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
11064 if (!IN_PROCESS_CALL(connection.CreateModalUIExtension(want))) {
11065 TAG_LOGE(AAFwkTag::ABILITYMGR, "create modal ui extension failed");
11066 return ERR_INVALID_VALUE;
11067 }
11068 auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11069 if (callbackDeathMgr == nullptr) {
11070 TAG_LOGE(AAFwkTag::ABILITYMGR, "get callback death manager instance null");
11071 return ERR_INVALID_VALUE;
11072 }
11073 auto callbackTask = [weak = weak_from_this()] (const std::string &assertSessionId) {
11074 auto abilityMgr = weak.lock();
11075 if (abilityMgr == nullptr) {
11076 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability manager instance null");
11077 return;
11078 }
11079 abilityMgr->CloseAssertDialog(assertSessionId);
11080 };
11081 callbackDeathMgr->AddAssertFaultCallback(remoteCallback, callbackTask);
11082 TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog end.");
11083 return ERR_OK;
11084 }
11085
NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus)11086 int32_t AbilityManagerService::NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus)
11087 {
11088 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11089 if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
11090 TAG_LOGE(AAFwkTag::ABILITYMGR, "assert fault dialog product not enabled");
11091 return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
11092 }
11093
11094 CHECK_CALLER_IS_SYSTEM_APP;
11095 auto permissionSA = PermissionVerification::GetInstance();
11096 if (permissionSA == nullptr) {
11097 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification instance null");
11098 return ERR_INVALID_VALUE;
11099 }
11100 if (!permissionSA->VerifyCallingPermission(PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT)) {
11101 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
11102 PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT);
11103 return ERR_PERMISSION_DENIED;
11104 }
11105
11106 auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
11107 if (callbackDeathMgr == nullptr) {
11108 TAG_LOGE(AAFwkTag::ABILITYMGR, "get callback death manager instance null");
11109 return ERR_INVALID_VALUE;
11110 }
11111 callbackDeathMgr->CallAssertFaultCallback(assertFaultSessionId, userStatus);
11112 return ERR_OK;
11113 }
11114
UpdateSessionInfoBySCB(std::list<SessionInfo> &sessionInfos, int32_t userId, std::vector<int32_t> &sessionIds)11115 int32_t AbilityManagerService::UpdateSessionInfoBySCB(std::list<SessionInfo> &sessionInfos, int32_t userId,
11116 std::vector<int32_t> &sessionIds)
11117 {
11118 if (!IsCallerSceneBoard()) {
11119 TAG_LOGE(AAFwkTag::ABILITYMGR, "no sceneboard called, no allowed");
11120 return ERR_WRONG_INTERFACE_CALL;
11121 }
11122 TAG_LOGI(AAFwkTag::ABILITYMGR, "sceneboard being restored");
11123 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11124 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11125 return uiAbilityManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds);
11126 }
11127
CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)11128 bool AbilityManagerService::CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)
11129 {
11130 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
11131 auto bms = AbilityUtil::GetBundleManagerHelper();
11132 CHECK_POINTER_AND_RETURN(bms, false);
11133
11134 std::string bundleName;
11135 if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
11136 TAG_LOGE(AAFwkTag::ABILITYMGR, "get bundle name failed");
11137 return false;
11138 }
11139 if (wantSenderInfo.bundleName != bundleName) {
11140 TAG_LOGE(AAFwkTag::ABILITYMGR, "wantSender bundleName check failed");
11141 return false;
11142 }
11143 }
11144 return true;
11145 }
11146
CheckCallerIsDmsProcess()11147 bool AbilityManagerService::CheckCallerIsDmsProcess()
11148 {
11149 Security::AccessToken::NativeTokenInfo nativeTokenInfo;
11150 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
11151 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
11152 int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
11153 if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
11154 result != ERR_OK || nativeTokenInfo.processName != DMS_PROCESS_NAME) {
11155 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not dms");
11156 return false;
11157 }
11158 return true;
11159 }
11160
WaitBootAnimationStart()11161 void AbilityManagerService::WaitBootAnimationStart()
11162 {
11163 char value[BOOTEVENT_BOOT_ANIMATION_READY_SIZE] = "";
11164 int32_t ret = GetParameter(BOOTEVENT_BOOT_ANIMATION_READY, "", value,
11165 BOOTEVENT_BOOT_ANIMATION_READY_SIZE);
11166 if (ret > 0 && !std::strcmp(value, "false")) {
11167 // Get new param success and new param is not ready, wait the new param.
11168 WaitParameter(BOOTEVENT_BOOT_ANIMATION_READY, "true",
11169 AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11170 } else if (ret <= 0 || !std::strcmp(value, "")) {
11171 // Get new param failed or new param is not set, wait the old param.
11172 WaitParameter(BOOTEVENT_BOOT_ANIMATION_STARTED, "true",
11173 AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11174 }
11175 // other, the animation is ready, not wait.
11176 }
11177
GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token, UIExtensionHostInfo &hostInfo, int32_t userId)11178 int32_t AbilityManagerService::GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,
11179 UIExtensionHostInfo &hostInfo, int32_t userId)
11180 {
11181 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11182 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11183 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11184
11185 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11186 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
11187 return ERR_PERMISSION_DENIED;
11188 }
11189
11190 auto callerRecord = GetUIExtensionRootCaller(token, userId);
11191 if (callerRecord == nullptr) {
11192 TAG_LOGE(AAFwkTag::UI_EXT, "get root host info failed");
11193 return ERR_INVALID_VALUE;
11194 }
11195
11196 hostInfo.elementName_ = callerRecord->GetElementName();
11197 TAG_LOGD(AAFwkTag::UI_EXT, "uri: %{public}s.", hostInfo.elementName_.GetURI().c_str());
11198 return ERR_OK;
11199 }
11200
GetUIExtensionRootCaller(const sptr<IRemoteObject> token, int32_t userId)11201 std::shared_ptr<AbilityRecord> AbilityManagerService::GetUIExtensionRootCaller(const sptr<IRemoteObject> token,
11202 int32_t userId)
11203 {
11204 auto validUserId = GetValidUserId(userId);
11205 auto connectManager = GetConnectManagerByUserId(validUserId);
11206 if (connectManager == nullptr) {
11207 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId:%{public}d", validUserId);
11208 return nullptr;
11209 }
11210
11211 auto callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11212 if (callerRecord == nullptr && validUserId != U0_USER_ID) {
11213 connectManager = GetConnectManagerByUserId(U0_USER_ID);
11214 if (connectManager == nullptr) {
11215 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId: %{public}d", U0_USER_ID);
11216 return nullptr;
11217 }
11218 callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11219 }
11220
11221 return callerRecord;
11222 }
11223
GetUIExtensionSessionInfo(const sptr<IRemoteObject> token, UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId)11224 int32_t AbilityManagerService::GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,
11225 UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId)
11226 {
11227 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11228 TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11229 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11230
11231 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11232 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission deny");
11233 return ERR_PERMISSION_DENIED;
11234 }
11235
11236 auto validUserId = GetValidUserId(userId);
11237 auto connectManager = GetConnectManagerByUserId(validUserId);
11238 if (connectManager == nullptr) {
11239 TAG_LOGE(AAFwkTag::ABILITYMGR, "manager null, userId:%{public}d", validUserId);
11240 return ERR_INVALID_VALUE;
11241 }
11242
11243 auto ret = connectManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo);
11244 if (ret != ERR_OK) {
11245 TAG_LOGE(AAFwkTag::ABILITYMGR, "get ui extension session info failed");
11246 return ret;
11247 }
11248
11249 return ERR_OK;
11250 }
11251
RestartApp(const AAFwk::Want &want, bool isAppRecovery)11252 int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want, bool isAppRecovery)
11253 {
11254 TAG_LOGI(AAFwkTag::ABILITYMGR, "RestartApp, isAppRecovery: %{public}d", isAppRecovery);
11255 auto appIndex = WantUtils::GetAppIndex(want);
11256 int result = CheckRestartAppWant(want, appIndex);
11257 if (result != ERR_OK) {
11258 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkRestartAppWant error");
11259 return result;
11260 }
11261
11262 int32_t callerUid = IPCSkeleton::GetCallingUid();
11263 int64_t now = time(nullptr);
11264 if (!isAppRecovery && RestartAppManager::GetInstance().IsRestartAppFrequent(callerUid, now)) {
11265 return AAFwk::ERR_RESTART_APP_FREQUENT;
11266 }
11267
11268 bool isForegroundToRestartApp = RestartAppManager::GetInstance().IsForegroundToRestartApp();
11269 if (!isForegroundToRestartApp) {
11270 TAG_LOGE(AAFwkTag::ABILITYMGR, "restartApp, isForegroundToRestartApp failed");
11271 return AAFwk::NOT_TOP_ABILITY;
11272 }
11273
11274 int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11275 result = SignRestartAppFlag(userId, callerUid, isAppRecovery);
11276 if (result != ERR_OK) {
11277 TAG_LOGE(AAFwkTag::ABILITYMGR, "signRestartAppFlag error");
11278 return result;
11279 }
11280 result = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->KillApplicationSelf(false, "RestartApp");
11281 if (result != ERR_OK) {
11282 TAG_LOGE(AAFwkTag::ABILITYMGR, "killApplicationSelf error");
11283 return result;
11284 }
11285
11286 TAG_LOGD(AAFwkTag::ABILITYMGR, "restartApp, without checkCallAbilityPermission.");
11287 (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
11288 result = StartAbilityWrap(want, nullptr,
11289 DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, 0, isForegroundToRestartApp);
11290 if (result != ERR_OK) {
11291 TAG_LOGE(AAFwkTag::ABILITYMGR, "startAbility error");
11292 return result;
11293 }
11294 if (!isAppRecovery) {
11295 RestartAppManager::GetInstance().AddRestartAppHistory(callerUid, now);
11296 }
11297 return result;
11298 }
11299
CheckRestartAppWant(const AAFwk::Want &want, int32_t appIndex)11300 int32_t AbilityManagerService::CheckRestartAppWant(const AAFwk::Want &want, int32_t appIndex)
11301 {
11302 std::string bundleName = want.GetElement().GetBundleName();
11303 auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11304 if (!CheckCallingTokenId(bundleName, userId, appIndex)) {
11305 TAG_LOGE(AAFwkTag::ABILITYMGR, "no itself called, no allowed");
11306 return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11307 }
11308
11309 auto bms = AbilityUtil::GetBundleManagerHelper();
11310 CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
11311 auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
11312 AppExecFwk::AbilityInfo abilityInfo;
11313 auto queryResult = IN_PROCESS_CALL(
11314 bms->QueryCloneAbilityInfo(want.GetElement(), abilityInfoFlag, appIndex, abilityInfo, userId));
11315 if (queryResult != ERR_OK || abilityInfo.name.empty() || abilityInfo.bundleName.empty() ||
11316 abilityInfo.type != AbilityType::PAGE) {
11317 TAG_LOGE(AAFwkTag::ABILITYMGR, "ability invalid or not UIAbility");
11318 return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11319 }
11320 return ERR_OK;
11321 }
11322
SignRestartAppFlag(int32_t userId, int32_t uid, bool isAppRecovery)11323 int32_t AbilityManagerService::SignRestartAppFlag(int32_t userId, int32_t uid, bool isAppRecovery)
11324 {
11325 auto appMgr = AppMgrUtil::GetAppMgr();
11326 if (appMgr == nullptr) {
11327 TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
11328 return ERR_INVALID_VALUE;
11329 }
11330 auto ret = IN_PROCESS_CALL(appMgr->SignRestartAppFlag(uid));
11331 if (ret != ERR_OK) {
11332 TAG_LOGE(AAFwkTag::ABILITYMGR, "appMgr signRestartAppFlag error");
11333 return ret;
11334 }
11335
11336 auto connectManager = GetConnectManagerByUserId(userId);
11337 connectManager->SignRestartAppFlag(uid);
11338 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11339 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
11340 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11341 uiAbilityManager->SignRestartAppFlag(uid, isAppRecovery);
11342 return ERR_OK;
11343 }
11344 auto missionListManager = GetMissionListManagerByUserId(userId);
11345 if (missionListManager == nullptr) {
11346 TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager null userId:%{public}d", userId);
11347 return ERR_INVALID_VALUE;
11348 }
11349 missionListManager->SignRestartAppFlag(uid);
11350 return ERR_OK;
11351 }
11352
IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken, const std::string &appId)11353 bool AbilityManagerService::IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken, const std::string &appId)
11354 {
11355 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11356 if (!AppUtils::GetInstance().IsLaunchEmbededUIAbility()) {
11357 TAG_LOGE(AAFwkTag::ABILITYMGR, "device type not allowd");
11358 return false;
11359 }
11360 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
11361 auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
11362 if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
11363 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not hap");
11364 return false;
11365 }
11366 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11367 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11368 auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
11369 if (callerAbility == nullptr) {
11370 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller invalid");
11371 return false;
11372 }
11373 if (callerAbility->GetApplicationInfo().accessTokenId != accessTokenId) {
11374 TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken don't belong caller");
11375 return false;
11376 }
11377 if (!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag()) {
11378 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not foreground");
11379 return false;
11380 }
11381 std::string bundleName = ATOMIC_SERVICE_PREFIX + appId;
11382 Want want;
11383 want.SetBundle(bundleName);
11384 want.SetParam("send_to_erms_embedded", 1);
11385 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(want, callerToken);
11386 int32_t ret = freeInstallManager_->StartFreeInstall(want, GetUserId(), 0, callerToken, false);
11387 if (ret != ERR_OK) {
11388 TAG_LOGE(AAFwkTag::ABILITYMGR, "target not allowed free install");
11389 return false;
11390 }
11391 want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
11392 auto erms = std::make_shared<EcologicalRuleInterceptor>();
11393 return erms->DoProcess(want, GetUserId());
11394 }
11395
ShouldPreventStartAbility(const AbilityRequest &abilityRequest)11396 bool AbilityManagerService::ShouldPreventStartAbility(const AbilityRequest &abilityRequest)
11397 {
11398 std::shared_ptr<AbilityRecord> abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11399 if (abilityRecord == nullptr) {
11400 TAG_LOGD(AAFwkTag::ABILITYMGR, "No matched token pass");
11401 return false;
11402 }
11403 auto abilityInfo = abilityRequest.abilityInfo;
11404 auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
11405 PrintStartAbilityInfo(callerAbilityInfo, abilityInfo);
11406 if (abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD < API12) {
11407 TAG_LOGD(AAFwkTag::ABILITYMGR, "API version %{public}d pass",
11408 abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD);
11409 return false;
11410 }
11411 bool continuousFlag = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
11412 if(!IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->
11413 IsProcessContainsOnlyUIAbility(abilityRecord->GetPid()))) {
11414 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has other extension except UIAbility, pass");
11415 return false;
11416 }
11417 if (abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::DATASHARE &&
11418 abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
11419 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process did not call service or datashare extension Pass");
11420 return false;
11421 }
11422 if (abilityInfo.applicationInfo.uid == IPCSkeleton::GetCallingUid()) {
11423 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in same bundle Pass");
11424 return false;
11425 }
11426 if (callerAbilityInfo.type != AppExecFwk::AbilityType::PAGE) {
11427 TAG_LOGD(AAFwkTag::ABILITYMGR, "Is not UI Ability Pass");
11428 return false;
11429 }
11430 if (abilityRecord->GetAbilityState() != AAFwk::AbilityState::BACKGROUND) {
11431 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is not on background Pass");
11432 return false;
11433 }
11434 if (continuousFlag) {
11435 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has continuous task Pass");
11436 return false;
11437 }
11438 if (IsInWhiteList(callerAbilityInfo.bundleName, abilityInfo.bundleName, abilityInfo.name)) {
11439 TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in white list Pass");
11440 return false;
11441 }
11442 TAG_LOGE(AAFwkTag::ABILITYMGR, "without start serviceExtension %{public}s permission",
11443 abilityRecord->GetURI().c_str());
11444 ReportPreventStartAbilityResult(callerAbilityInfo, abilityInfo);
11445 return true;
11446 }
11447
PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo, AppExecFwk::AbilityInfo calledInfo)11448 void AbilityManagerService::PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo, AppExecFwk::AbilityInfo calledInfo)
11449 {
11450 TAG_LOGD(AAFwkTag::ABILITYMGR, "calledAbilityInfo toString: "
11451 "calledUid is: %{public}d, "
11452 "name is: %{public}s, "
11453 "bundleName is: %{public}s, "
11454 "type is: %{public}d, "
11455 "extensionAbilityType is: %{public}d, "
11456 "moduleName is: %{public}s, "
11457 "applicationName is: %{public}s",
11458 calledInfo.applicationInfo.uid,
11459 calledInfo.name.c_str(),
11460 calledInfo.bundleName.c_str(),
11461 static_cast<int32_t>(calledInfo.type),
11462 static_cast<int32_t>(calledInfo.extensionAbilityType),
11463 calledInfo.moduleName.c_str(),
11464 calledInfo.applicationName.c_str());
11465
11466
11467 TAG_LOGD(AAFwkTag::ABILITYMGR, "callerAbilityInfo toString: "
11468 "callerUid is: %{public}d, "
11469 "callerPid is: %{public}d, "
11470 "name is: %{public}s, "
11471 "bundleName is: %{public}s, "
11472 "type is: %{public}d, "
11473 "extensionAbilityType is: %{public}d, "
11474 "moduleName is: %{public}s, "
11475 "applicationName is: %{public}s",
11476 IPCSkeleton::GetCallingUid(),
11477 IPCSkeleton::GetCallingPid(),
11478 callerInfo.name.c_str(),
11479 callerInfo.bundleName.c_str(),
11480 static_cast<int32_t>(callerInfo.type),
11481 static_cast<int32_t>(callerInfo.extensionAbilityType),
11482 callerInfo.moduleName.c_str(),
11483 callerInfo.applicationName.c_str());
11484 }
11485
ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo, const AppExecFwk::AbilityInfo &abilityInfo)11486 void AbilityManagerService::ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo,
11487 const AppExecFwk::AbilityInfo &abilityInfo)
11488 {
11489 int32_t callerUid = IPCSkeleton::GetCallingUid();
11490 int32_t callerPid = IPCSkeleton::GetCallingPid();
11491 int32_t extensionAbilityType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
11492 TAG_LOGD(AAFwkTag::ABILITYMGR,
11493 "Prevent start ability debug log CALLER_BUNDLE_NAME %{public}s CALLEE_BUNDLE_NAME"
11494 "%{public}s ABILITY_NAME %{public}s",
11495 callerAbilityInfo.bundleName.c_str(), abilityInfo.name.c_str(), abilityInfo.name.c_str());
11496 HiSysEventWrite(HiSysEvent::Domain::AAFWK, "PREVENT_START_ABILITY", HiSysEvent::EventType::BEHAVIOR,
11497 "CALLER_UID", callerUid,
11498 "CALLER_PID", callerPid,
11499 "CALLER_PROCESS_NAME", callerAbilityInfo.process,
11500 "CALLER_BUNDLE_NAME", callerAbilityInfo.bundleName,
11501 "CALLEE_BUNDLE_NAME", abilityInfo.bundleName,
11502 "CALLEE_PROCESS_NAME", abilityInfo.process,
11503 "EXTENSION_ABILITY_TYPE", extensionAbilityType,
11504 "ABILITY_NAME", abilityInfo.name);
11505 }
11506
IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName, const std::string &calleeAbilityName)11507 bool AbilityManagerService::IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName,
11508 const std::string &calleeAbilityName)
11509 {
11510 std::lock_guard<std::mutex> locker(whiteListMutex_);
11511 std::map<std::string, std::list<std::string>>::iterator iter = whiteListMap_.find(callerBundleName);
11512 std::string uri = calleeBundleName + "/" + calleeAbilityName;
11513 if (iter != whiteListMap_.end()) {
11514 if (std::find(std::begin(iter->second), std::end(iter->second), uri) != std::end(iter->second)) {
11515 return true;
11516 }
11517 }
11518 std::list<std::string>::iterator it = std::find(exportWhiteList_.begin(), exportWhiteList_.end(), uri);
11519 if (it != exportWhiteList_.end()) {
11520 return true;
11521 }
11522 return false;
11523 }
11524
ParseJsonFromBoot(const std::string &relativePath)11525 bool AbilityManagerService::ParseJsonFromBoot(const std::string &relativePath)
11526 {
11527 nlohmann::json jsonObj;
11528 std::string absolutePath = GetConfigFileAbsolutePath(relativePath);
11529 if (ParseJsonValueFromFile(jsonObj, absolutePath) != ERR_OK) {
11530 return false;
11531 }
11532 std::lock_guard<std::mutex> locker(whiteListMutex_);
11533 nlohmann::json whiteListJsonList = jsonObj[WHITE_LIST];
11534 for (const auto& [key, value] : whiteListJsonList.items()) {
11535 if (!value.is_array()) {
11536 continue;
11537 }
11538 whiteListMap_.emplace(key, std::list<std::string>());
11539 for (const auto& it : value) {
11540 if (it.is_string()) {
11541 whiteListMap_[key].push_back(it);
11542 }
11543 }
11544 }
11545 if (!jsonObj.contains("exposed_white_list")) {
11546 return false;
11547 }
11548 nlohmann::json exportWhiteJsonList = jsonObj["exposed_white_list"];
11549 for (const auto& it : exportWhiteJsonList) {
11550 if (it.is_string()) {
11551 exportWhiteList_.push_back(it);
11552 }
11553 }
11554 return true;
11555 }
11556
GetConfigFileAbsolutePath(const std::string &relativePath)11557 std::string AbilityManagerService::GetConfigFileAbsolutePath(const std::string &relativePath)
11558 {
11559 if (relativePath.empty()) {
11560 TAG_LOGE(AAFwkTag::ABILITYMGR, "relativePath empty");
11561 return "";
11562 }
11563 char buf[PATH_MAX];
11564 char *tmpPath = GetOneCfgFile(relativePath.c_str(), buf, PATH_MAX);
11565 char absolutePath[PATH_MAX] = {0};
11566 if (!tmpPath || strlen(tmpPath) > PATH_MAX || !realpath(tmpPath, absolutePath)) {
11567 TAG_LOGE(AAFwkTag::ABILITYMGR, "get file fail");
11568 return "";
11569 }
11570 return std::string(absolutePath);
11571 }
11572
ParseJsonValueFromFile(nlohmann::json &value, const std::string &filePath)11573 int32_t AbilityManagerService::ParseJsonValueFromFile(nlohmann::json &value, const std::string &filePath)
11574 {
11575 std::ifstream fin;
11576 std::string realPath;
11577 if (!ConvertFullPath(filePath, realPath)) {
11578 TAG_LOGE(AAFwkTag::ABILITYMGR, "get real path failed");
11579 return ERR_INVALID_VALUE;
11580 }
11581 fin.open(realPath, std::ios::in);
11582 if (!fin.is_open()) {
11583 TAG_LOGE(AAFwkTag::ABILITYMGR, "can't open file %{private}s", realPath.c_str());
11584 return ERR_INVALID_VALUE;
11585 }
11586 char buffer[MAX_BUFFER];
11587 std::ostringstream os;
11588 while (fin.getline(buffer, MAX_BUFFER)) {
11589 os << buffer;
11590 }
11591 const std::string data = os.str();
11592 value = nlohmann::json::parse(data, nullptr, false);
11593 if (value.is_discarded()) {
11594 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed due data discarded");
11595 return ERR_INVALID_VALUE;
11596 }
11597 return ERR_OK;
11598 }
11599
ConvertFullPath(const std::string& partialPath, std::string& fullPath)11600 bool AbilityManagerService::ConvertFullPath(const std::string& partialPath, std::string& fullPath)
11601 {
11602 if (partialPath.empty() || partialPath.length() >= PATH_MAX) {
11603 return false;
11604 }
11605 char tmpPath[PATH_MAX] = {0};
11606 if (realpath(partialPath.c_str(), tmpPath) == nullptr) {
11607 return false;
11608 }
11609 fullPath = tmpPath;
11610 return true;
11611 }
11612
StartShortcut(const Want &want, const StartOptions &startOptions)11613 int32_t AbilityManagerService::StartShortcut(const Want &want, const StartOptions &startOptions)
11614 {
11615 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11616 if (!PermissionVerification::GetInstance()->IsSystemAppCall()) {
11617 TAG_LOGE(AAFwkTag::ABILITYMGR, "non-system app calling system api");
11618 return ERR_NOT_SYSTEM_APP;
11619 }
11620 if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
11621 PermissionConstants::PERMISSION_START_SHORTCUT)) {
11622 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission %{public}s verification failed",
11623 PermissionConstants::PERMISSION_START_SHORTCUT);
11624 return ERR_PERMISSION_DENIED;
11625 }
11626 AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
11627 return StartUIAbilityForOptionWrap(want, startOptions, nullptr, false, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE,
11628 0, false, true);
11629 }
11630
GetAbilityStateByPersistentId(int32_t persistentId, bool &state)11631 int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentId, bool &state)
11632 {
11633 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11634 if (!CheckCallerIsDmsProcess()) {
11635 TAG_LOGE(AAFwkTag::ABILITYMGR, "getAbilityStateByPersistentId, caller not dms");
11636 return ERR_PERMISSION_DENIED;
11637 }
11638
11639 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11640 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11641 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11642 return uiAbilityManager->GetAbilityStateByPersistentId(persistentId, state);
11643 }
11644 TAG_LOGE(AAFwkTag::ABILITYMGR, "getAbilityStateByPersistentId, mission without persistent id");
11645 return INNER_ERR;
11646 }
11647
TransferAbilityResultForExtension(const sptr<IRemoteObject> &callerToken, int32_t resultCode, const Want &want)11648 int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptr<IRemoteObject> &callerToken,
11649 int32_t resultCode, const Want &want)
11650 {
11651 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11652 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
11653 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
11654 if (!JudgeSelfCalled(abilityRecord)) {
11655 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller mismatch");
11656 return ERR_INVALID_VALUE;
11657 }
11658 auto type = abilityRecord->GetAbilityInfo().type;
11659 if (type != AppExecFwk::AbilityType::EXTENSION) {
11660 TAG_LOGE(AAFwkTag::ABILITYMGR, "type not uiextension");
11661 return ERR_INVALID_VALUE;
11662 }
11663 // save result to caller AbilityRecord.
11664 Want* newWant = const_cast<Want*>(&want);
11665 newWant->RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
11666 abilityRecord->SaveResultToCallers(resultCode, newWant);
11667 abilityRecord->SendResultToCallers();
11668 return ERR_OK;
11669 }
11670
NotifyFrozenProcessByRSS(const std::vector<int32_t> &pidList, int32_t uid)11671 void AbilityManagerService::NotifyFrozenProcessByRSS(const std::vector<int32_t> &pidList, int32_t uid)
11672 {
11673 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(RSS_PROCESS_NAME)) {
11674 TAG_LOGE(AAFwkTag::ABILITYMGR, "caller not RSS");
11675 return;
11676 }
11677 auto userId = uid / BASE_USER_RANGE;
11678 auto connectManager = GetConnectManagerByUserId(userId);
11679 CHECK_POINTER_LOG(connectManager, "can't find user connect manager");
11680 connectManager->HandleProcessFrozen(pidList, uid);
11681 }
11682
HandleRestartResidentProcessDependedOnWeb()11683 void AbilityManagerService::HandleRestartResidentProcessDependedOnWeb()
11684 {
11685 TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
11686 auto appMgr = AppMgrUtil::GetAppMgr();
11687 CHECK_POINTER_LOG(appMgr, "get appMgr fail");
11688 appMgr->RestartResidentProcessDependedOnWeb();
11689 }
11690
PreStartMission(const std::string& bundleName, const std::string& moduleName, const std::string& abilityName, const std::string& startTime)11691 int32_t AbilityManagerService::PreStartMission(const std::string& bundleName, const std::string& moduleName,
11692 const std::string& abilityName, const std::string& startTime)
11693 {
11694 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
11695 CHECK_CALLER_IS_SYSTEM_APP;
11696
11697 if (!PermissionVerification::GetInstance()->VerifyPreStartAtomicServicePermission()) {
11698 TAG_LOGE(AAFwkTag::ABILITYMGR, "calling user not ag");
11699 return ERR_PERMISSION_DENIED;
11700 }
11701
11702 if (!freeInstallManager_) {
11703 TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
11704 return ERR_INVALID_VALUE;
11705 }
11706
11707 FreeInstallInfo taskInfo;
11708 if (!freeInstallManager_->GetFreeInstallTaskInfo(bundleName, abilityName, startTime, taskInfo)) {
11709 TAG_LOGE(AAFwkTag::ABILITYMGR,
11710 "failed find free install task info:bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
11711 bundleName.c_str(), abilityName.c_str(), startTime.c_str());
11712 return ERR_FREE_INSTALL_TASK_NOT_EXIST;
11713 }
11714
11715 if (taskInfo.isFreeInstallFinished) {
11716 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install finished");
11717 if (!taskInfo.isInstalled) {
11718 TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
11719 taskInfo.resultCode);
11720 } else {
11721 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeded");
11722 }
11723 // if free install is already finished then either the window is opened (on success)
11724 // or the user is informed of the error (on failure).
11725 return taskInfo.resultCode;
11726 }
11727
11728 return PreStartInner(taskInfo);
11729 }
11730
PreStartInner(const FreeInstallInfo& taskInfo)11731 int32_t AbilityManagerService::PreStartInner(const FreeInstallInfo& taskInfo)
11732 {
11733 TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11734
11735 const Want& want = taskInfo.want;
11736 sptr<IRemoteObject> callerToken = taskInfo.callerToken;
11737
11738 EventInfo eventInfo = BuildEventInfo(want, taskInfo.userId);
11739 SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
11740
11741 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
11742 eventInfo.errCode = ERR_INVALID_VALUE;
11743 SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
11744 return ERR_INVALID_CALLER;
11745 }
11746
11747 int32_t oriValidUserId = GetValidUserId(taskInfo.userId);
11748
11749 int32_t appIndex = 0;
11750 StartAbilityInfoWrap threadLocalInfo(want, oriValidUserId,
11751 StartAbilityUtils::GetAppIndex(want, callerToken, appIndex), callerToken);
11752
11753 AbilityRequest abilityRequest = {
11754 .want = want,
11755 .requestCode = taskInfo.requestCode,
11756 .callerToken = callerToken,
11757 .startSetting = nullptr
11758 };
11759
11760 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
11761 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
11762
11763 // sceneboard
11764 abilityRequest.userId = oriValidUserId;
11765 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
11766 std::string sessionId = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
11767 std::chrono::system_clock::now().time_since_epoch()).count());
11768 abilityRequest.want.SetParam(KEY_SESSION_ID, sessionId);
11769 auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
11770 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11771 sptr<SessionInfo> sessionInfo = nullptr;
11772 auto errCode = uiAbilityManager->NotifySCBToPreStartUIAbility(abilityRequest, sessionInfo);
11773 if (errCode != ERR_OK) {
11774 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed notify sceneboard pre-start uiability");
11775 return errCode;
11776 }
11777 freeInstallManager_->SetFreeInstallTaskSessionId(taskInfo.want.GetElement().GetBundleName(),
11778 taskInfo.want.GetElement().GetAbilityName(),
11779 taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), sessionId);
11780
11781 freeInstallManager_->SetPreStartMissionCallStatus(taskInfo.want.GetElement().GetBundleName(),
11782 taskInfo.want.GetElement().GetAbilityName(),
11783 taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME),
11784 true);
11785 return ERR_OK;
11786 }
11787
StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo)11788 int32_t AbilityManagerService::StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo)
11789 {
11790 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11791 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
11792 if (!taskInfo.isFreeInstallFinished || !taskInfo.isInstalled) {
11793 TAG_LOGE(AAFwkTag::ABILITYMGR, "free install not finished or failed");
11794 return ERR_INVALID_VALUE;
11795 }
11796 if (!taskInfo.isStartUIAbilityBySCBCalled) {
11797 TAG_LOGI(AAFwkTag::ABILITYMGR, "free install finished, startUIAbilityBySCB not called");
11798 return ERR_OK;
11799 }
11800
11801 const auto& want = taskInfo.want;
11802 auto sessionId = want.GetStringParam(KEY_SESSION_ID);
11803 if (sessionId.empty()) {
11804 TAG_LOGE(AAFwkTag::ABILITYMGR, "session id empty");
11805 return ERR_INVALID_VALUE;
11806 }
11807 auto bundleName = want.GetElement().GetBundleName();
11808 auto abilityName = want.GetElement().GetAbilityName();
11809 auto startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME);
11810 TAG_LOGI(AAFwkTag::ABILITYMGR, "call"
11811 "sessionId=%{public}s,bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
11812 sessionId.c_str(), bundleName.c_str(), abilityName.c_str(), startTime.c_str());
11813 sptr<SessionInfo> sessionInfo = nullptr;
11814 {
11815 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
11816 auto it = preStartSessionMap_.find(sessionId);
11817 if (it == preStartSessionMap_.end()) {
11818 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed find session info with sessionId=%{public}s",
11819 sessionId.c_str());
11820 return ERR_INVALID_VALUE;
11821 }
11822 sessionInfo = it->second;
11823 (sessionInfo->want).SetElement(want.GetElement());
11824 }
11825
11826 if (sessionInfo == nullptr || sessionInfo->isMinimizedDuringFreeInstall) {
11827 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr or ability is already minimized");
11828 RemovePreStartSession(sessionId);
11829 return ERR_INVALID_VALUE;
11830 }
11831
11832 int errCode = ERR_OK;
11833 bool isColdStart = true;
11834 if ((errCode = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, 0, isColdStart)) != ERR_OK) {
11835 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUIAbilityByPreInstallInner failed,errCode=%{public}d", errCode);
11836 }
11837 RemovePreStartSession(sessionId);
11838 return errCode;
11839 }
11840
11841 // StartUIAbilityByPreInstallInner is called when free install task is already finished
StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo, uint32_t specifyTokenId, uint32_t sceneFlag, bool &isColdStart)11842 int AbilityManagerService::StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo, uint32_t specifyTokenId,
11843 uint32_t sceneFlag, bool &isColdStart)
11844 {
11845 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
11846 auto callerToken = sessionInfo->callerToken;
11847 const auto& want = sessionInfo->want;
11848 const auto userId = sessionInfo->userId;
11849 const auto requestCode = sessionInfo->requestCode;
11850 bool isStartAsCaller = false;
11851
11852 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
11853 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
11854 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
11855 if (!isSpecificSA) {
11856 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s verificationAllToken failed", __func__);
11857 return ERR_INVALID_CALLER;
11858 }
11859 TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: caller specific system ability", __func__);
11860 }
11861
11862 int32_t oriValidUserId = GetValidUserId(userId);
11863 int32_t validUserId = oriValidUserId;
11864
11865 int32_t appIndex = 0;
11866 if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
11867 TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s GetAppIndex failed", __func__);
11868 return ERR_APP_CLONE_INDEX_INVALID;
11869 }
11870 StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
11871 auto shouldBlockFunc = [aams = shared_from_this()]() { return aams->ShouldBlockAllAppStart(); };
11872 AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
11873 true, nullptr, shouldBlockFunc);
11874 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
11875 interceptorExecuter_->DoProcess(interceptorParam);
11876 if (result != ERR_OK) {
11877 TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ null or doProcess error");
11878 return result;
11879 }
11880
11881 AbilityRequest abilityRequest;
11882 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
11883 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
11884 std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
11885
11886 if (result != ERR_OK) {
11887 TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error");
11888 return result;
11889 }
11890
11891 if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
11892 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
11893 } else if (!isStartAsCaller) {
11894 TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
11895 UpdateCallerInfoUtil::GetInstance().UpdateCallerInfo(abilityRequest.want, callerToken);
11896 } else if (callerBundleName == BUNDLE_NAME_DIALOG) {
11897 #ifdef SUPPORT_SCREEN
11898 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
11899 implicitStartProcessor_->ResetCallingIdentityAsCaller(
11900 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), true);
11901 #endif // SUPPORT_SCREEN
11902 }
11903
11904 auto abilityInfo = abilityRequest.abilityInfo;
11905 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
11906 TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
11907 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
11908
11909 result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
11910 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false);
11911 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
11912 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkStaticCfgPermission error, result:%{public}d", result);
11913 return ERR_STATIC_CFG_PERMISSION;
11914 }
11915
11916 result = CheckCallPermission(want, abilityInfo, abilityRequest, false,
11917 false, specifyTokenId, callerBundleName);
11918 if (result != ERR_OK) {
11919 TAG_LOGE(AAFwkTag::ABILITYMGR, "checkCallPermission error, result:%{public}d", result);
11920 return result;
11921 }
11922
11923 Want newWant = abilityRequest.want;
11924 AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
11925 true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
11926 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
11927 afterCheckExecuter_->DoProcess(afterCheckParam);
11928 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
11929 newWant.RemoveParam("queryWantFromErms");
11930 if (result != ERR_OK && isReplaceWantExist == false) {
11931 TAG_LOGE(AAFwkTag::ABILITYMGR, "doProcess failed or replaceWant absent");
11932 return result;
11933 }
11934 #ifdef SUPPORT_SCREEN
11935 if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
11936 return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
11937 }
11938 if (result == ERR_OK &&
11939 DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
11940 TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
11941 return CreateCloneSelectorDialog(abilityRequest, GetUserId());
11942 }
11943 #endif // SUPPORT_SCREEN
11944
11945 if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
11946 abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
11947 return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
11948 }
11949
11950 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
11951 TAG_LOGE(AAFwkTag::ABILITYMGR, "isAbilityControllerStart failed:%{public}s", abilityInfo.bundleName.c_str());
11952 return ERR_WOULD_BLOCK;
11953 }
11954
11955 abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
11956 if (specifyTokenId > 0) {
11957 TAG_LOGD(AAFwkTag::ABILITYMGR, "set specifyTokenId, the specifyTokenId is %{public}d", specifyTokenId);
11958 abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
11959 abilityRequest.specifyTokenId = specifyTokenId;
11960 }
11961 abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
11962
11963 auto uiAbilityManager = GetCurrentUIAbilityManager();
11964 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11965
11966 return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
11967 }
11968
NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode, const std::string& reason)11969 void AbilityManagerService::NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode,
11970 const std::string& reason)
11971 {
11972 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
11973 sptr<SessionInfo> sessionInfo = nullptr;
11974 {
11975 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
11976 auto it = preStartSessionMap_.find(sessionId);
11977 if (it == preStartSessionMap_.end()) {
11978 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed find session info with sessionId=%{public}s",
11979 sessionId.c_str());
11980 return;
11981 }
11982 sessionInfo = it->second;
11983 preStartSessionMap_.erase(it);
11984 }
11985 if (sessionInfo == nullptr) {
11986 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
11987 return;
11988 }
11989 auto uiAbilityManager = GetCurrentUIAbilityManager();
11990 CHECK_POINTER(uiAbilityManager);
11991 return uiAbilityManager->NotifySCBToHandleAtomicServiceException(sessionInfo, errCode, reason);
11992 }
11993
RemovePreStartSession(const std::string& sessionId)11994 void AbilityManagerService::RemovePreStartSession(const std::string& sessionId)
11995 {
11996 std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
11997 preStartSessionMap_.erase(sessionId);
11998 }
11999
OpenLink(const Want& want, sptr<IRemoteObject> callerToken, int32_t userId, int requestCode)12000 ErrCode AbilityManagerService::OpenLink(const Want& want, sptr<IRemoteObject> callerToken,
12001 int32_t userId, int requestCode)
12002 {
12003 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12004 AbilityUtil::RemoveInstanceKey(const_cast<Want &>(want));
12005 std::string callerBundleName;
12006 Want convertedWant = want;
12007 if (!WantUtils::IsAtomicServiceUrl(want) ||
12008 WantUtils::GetCallerBundleName(callerBundleName) != ERR_OK) {
12009 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
12010 int retCode = StartAbility(want, callerToken, userId, requestCode);
12011 CHECK_RET_RETURN_RET(retCode, "startAbility failed");
12012 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12013 }
12014
12015 TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName=%{public}s", callerBundleName.c_str());
12016 convertedWant.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
12017 if (WantUtils::ConvertToExplicitWant(convertedWant) != ERR_OK ||
12018 freeInstallManager_ == nullptr) {
12019 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
12020 int retCode = StartAbility(want, callerToken, userId, requestCode);
12021 CHECK_RET_RETURN_RET(retCode, "startAbility failed");
12022 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12023 }
12024
12025 convertedWant.AddFlags(Want::FLAG_INSTALL_ON_DEMAND);
12026 TAG_LOGD(AAFwkTag::ABILITYMGR, "convertedWant=%{private}s", convertedWant.ToString().c_str());
12027 ErrCode retCode = freeInstallManager_->StartFreeInstall(convertedWant, GetValidUserId(userId),
12028 requestCode, callerToken, true, 0, true, std::make_shared<Want>(want));
12029 if (retCode != ERR_OK) {
12030 TAG_LOGW(AAFwkTag::ABILITYMGR, "startFreeInstall returns errCode=%{public}d", retCode);
12031 if (retCode == NOT_TOP_ABILITY) {
12032 TAG_LOGE(AAFwkTag::ABILITYMGR, "start from background not allowed");
12033 return retCode;
12034 }
12035 TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default");
12036 retCode = StartAbility(want, callerToken, userId, requestCode);
12037 CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
12038 return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
12039 }
12040 return ERR_OK;
12041 }
12042
CleanUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)12043 int32_t AbilityManagerService::CleanUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
12044 {
12045 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12046 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
12047 TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo invalid");
12048 return ERR_INVALID_VALUE;
12049 }
12050
12051 if (!IsCallerSceneBoard()) {
12052 TAG_LOGE(AAFwkTag::ABILITYMGR, "only support sceneboard call");
12053 return ERR_WRONG_INTERFACE_CALL;
12054 }
12055
12056 SetMinimizedDuringFreeInstall(sessionInfo);
12057
12058 auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12059 CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12060 TAG_LOGI(AAFwkTag::ABILITYMGR, "user request clean session: %{public}d", sessionInfo->persistentId);
12061 auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
12062 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
12063 int32_t errCode = uiAbilityManager->CleanUIAbility(abilityRecord);
12064 ReportCleanSession(sessionInfo, abilityRecord, errCode);
12065 return errCode;
12066 }
12067
ForceTerminateServiceExtensionByPid(int32_t pid, int32_t userId)12068 void AbilityManagerService::ForceTerminateServiceExtensionByPid(int32_t pid, int32_t userId)
12069 {
12070 std::vector<sptr<IRemoteObject>> tokens;
12071 IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppScheduler>::GetInstance()->GetAbilityRecordsByProcessID(
12072 pid, tokens));
12073 auto connectManager = GetConnectManagerByUserId(userId);
12074 if (connectManager) {
12075 for (const auto& token : tokens) {
12076 auto abilityRecord = Token::GetAbilityRecordByToken(token);
12077 if (abilityRecord &&
12078 abilityRecord->GetAbilityInfo().extensionAbilityType ==
12079 AppExecFwk::ExtensionAbilityType::SERVICE) {
12080 TAG_LOGI(AAFwkTag::ABILITYMGR, "app ForceTerminateServiceExtensionByPid, pid is %{public}d", pid);
12081 connectManager->TerminateAbility(token);
12082 }
12083 }
12084 }
12085 }
12086
ReportCleanSession(const sptr<SessionInfo> &sessionInfo, const std::shared_ptr<AbilityRecord> &abilityRecord, int32_t errCode)12087 void AbilityManagerService::ReportCleanSession(const sptr<SessionInfo> &sessionInfo,
12088 const std::shared_ptr<AbilityRecord> &abilityRecord, int32_t errCode)
12089 {
12090 if (!sessionInfo || !abilityRecord) {
12091 return;
12092 }
12093
12094 const auto &abilityInfo = abilityRecord->GetAbilityInfo();
12095 std::string abilityName = abilityInfo.name;
12096 if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
12097 abilityName += std::to_string(sessionInfo->persistentId);
12098 }
12099 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
12100 DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
12101
12102 EventInfo eventInfo;
12103 eventInfo.errCode = errCode;
12104 eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
12105 eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
12106 SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12107 if (eventInfo.errCode != ERR_OK) {
12108 SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
12109 }
12110 }
12111
SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo& abilityInfo, const Want& want, uint32_t specifyTokenId)12112 void AbilityManagerService::SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo& abilityInfo,
12113 const Want& want, uint32_t specifyTokenId)
12114 {
12115 if (abilityInfo.type != AppExecFwk::AbilityType::EXTENSION ||
12116 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
12117 return;
12118 }
12119 EventInfo eventInfo;
12120 eventInfo.bundleName = abilityInfo.bundleName;
12121 eventInfo.moduleName = abilityInfo.moduleName;
12122 eventInfo.abilityName = abilityInfo.name;
12123 eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
12124 if (specifyTokenId > 0) {
12125 // come from want agent or form
12126 Security::AccessToken::HapTokenInfo hapInfo;
12127 if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(specifyTokenId, hapInfo) == ERR_OK) {
12128 eventInfo.callerBundleName = hapInfo.bundleName;
12129 }
12130 } else {
12131 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
12132 if (eventInfo.callerBundleName.empty()) {
12133 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
12134 }
12135 }
12136 TAG_LOGI(AAFwkTag::ABILITYMGR,
12137 "SendStartAbilityOtherExtensionEvent, bundleName:%{public}s, extensionAbilityType:%{public}d",
12138 eventInfo.bundleName.c_str(), eventInfo.extensionType);
12139 EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
12140 }
12141
SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest, AppExecFwk::ExtensionAbilityType extensionType)12142 void AbilityManagerService::SetAbilityRequestSessionInfo(AbilityRequest &abilityRequest,
12143 AppExecFwk::ExtensionAbilityType extensionType)
12144 {
12145 TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
12146 if (extensionType != AppExecFwk::ExtensionAbilityType::UI_SERVICE) {
12147 return;
12148 }
12149
12150 abilityRequest.want.RemoveParam(WANT_PARAMS_HOST_WINDOW_ID_KEY);
12151 auto callerAbilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
12152 CHECK_POINTER_LOG(callerAbilityRecord, "callerAbilityRecord is nullptr");
12153 sptr<SessionInfo> callerSessionInfo = callerAbilityRecord->GetSessionInfo();
12154 CHECK_POINTER_LOG(callerSessionInfo, "callerSessionInfo is nullptr");
12155
12156 if (callerAbilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
12157 TAG_LOGI(AAFwkTag::ABILITYMGR, "UIAbility Caller");
12158 abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, callerSessionInfo->persistentId);
12159 } else if (AAFwk::UIExtensionUtils::IsUIExtension(callerAbilityRecord->GetAbilityInfo().extensionAbilityType)) {
12160 int32_t mainWindowId = -1;
12161 auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().
12162 GetSceneSessionManagerLiteProxy();
12163 CHECK_POINTER_LOG(sceneSessionManager, "sceneSessionManager is nullptr");
12164 auto err = sceneSessionManager->GetRootMainWindowId(static_cast<int32_t>(callerSessionInfo->hostWindowId),mainWindowId);
12165 TAG_LOGI(AAFwkTag::ABILITYMGR, "callerSessionInfo->hostWindowId = %{public}d, mainWindowId = %{public}d, err = %{public}d",
12166 callerSessionInfo->hostWindowId, mainWindowId, err);
12167 abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, mainWindowId);
12168 } else {
12169 abilityRequest.want.SetParam(WANT_PARAMS_HOST_WINDOW_ID_KEY, 0);
12170 }
12171 }
12172
TerminateMission(int32_t missionId)12173 int32_t AbilityManagerService::TerminateMission(int32_t missionId)
12174 {
12175 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12176 TAG_LOGI(AAFwkTag::ABILITYMGR, "terminateMission call");
12177 auto missionListManager = GetCurrentMissionListManager();
12178 CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
12179 CHECK_CALLER_IS_SYSTEM_APP;
12180
12181 if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
12182 PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
12183 TAG_LOGE(AAFwkTag::ABILITYMGR, "permission verification failed");
12184 return CHECK_PERMISSION_FAILED;
12185 }
12186
12187 return missionListManager->ClearMission(missionId);
12188 }
12189
BlockAllAppStart(bool flag)12190 int32_t AbilityManagerService::BlockAllAppStart(bool flag)
12191 {
12192 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12193 TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
12194
12195 if (!AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
12196 TAG_LOGE(AAFwkTag::ABILITYMGR, "not supported device");
12197 return ERR_PERMISSION_DENIED;
12198 }
12199
12200 if (!PermissionVerification::GetInstance()->VerifyBlockAllAppStartPermission()) {
12201 TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
12202 return ERR_PERMISSION_DENIED;
12203 }
12204
12205 std::unique_lock<ffrt::mutex> lock(shouldBlockAllAppStartMutex_);
12206 shouldBlockAllAppStart_ = flag;
12207 return ERR_OK;
12208 }
12209
ShouldBlockAllAppStart()12210 bool AbilityManagerService::ShouldBlockAllAppStart()
12211 {
12212 if (!AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
12213 return false;
12214 }
12215
12216 std::unique_lock<ffrt::mutex> lock(shouldBlockAllAppStartMutex_);
12217 return shouldBlockAllAppStart_;
12218 }
12219
UpdateAssociateConfigList(const std::map<std::string, std::list<std::string>>& configs, const std::list<std::string>& exportConfigs, int32_t flag)12220 int32_t AbilityManagerService::UpdateAssociateConfigList(const std::map<std::string, std::list<std::string>>& configs,
12221 const std::list<std::string>& exportConfigs, int32_t flag)
12222 {
12223 if (IPCSkeleton::GetCallingUid() != RESOURCE_SCHEDULE_UID) {
12224 TAG_LOGE(AAFwkTag::ABILITYMGR, "Update associate config, current process not rss process");
12225 return CHECK_PERMISSION_FAILED;
12226 }
12227 std::lock_guard<std::mutex> locker(whiteListMutex_);
12228 if (flag == UPDATE_CONFIG_FLAG_COVER) {
12229 whiteListMap_ = configs;
12230 exportWhiteList_ = exportConfigs;
12231 } else if (flag == UPDATE_CONFIG_FLAG_APPEND) {
12232 for (const auto& config : configs) {
12233 for (const auto& item : config.second) {
12234 whiteListMap_[config.first].push_back(item);
12235 }
12236 }
12237 for (const auto& config : exportConfigs) {
12238 exportWhiteList_.push_back(config);
12239 }
12240 }
12241 return ERR_OK;
12242 }
12243
EnableListForSCBRecovery(int32_t userId) const12244 void AbilityManagerService::EnableListForSCBRecovery(int32_t userId) const
12245 {
12246 auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
12247 CHECK_POINTER_LOG(uiAbilityManager, "UIAbilityMgr not exist.");
12248 uiAbilityManager->EnableListForSCBRecovery();
12249 }
12250
UpdateKeepAliveEnableState(const std::string &bundleName, const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId)12251 int32_t AbilityManagerService::UpdateKeepAliveEnableState(const std::string &bundleName,
12252 const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId)
12253 {
12254 auto connectManager = GetConnectManagerByUserId(userId);
12255 CHECK_POINTER_AND_RETURN(connectManager, ERR_NULL_OBJECT);
12256 int32_t ret = connectManager->UpdateKeepAliveEnableState(bundleName, moduleName, mainElement, updateEnable);
12257 if (ret != ERR_OK) {
12258 TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateKeepAliveEnableState failed, err:%{public}d", ret);
12259 }
12260 return ret;
12261 }
12262 } // namespace AAFwk
12263 } // namespace OHOS
12264