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 <atomic>
19 #include <chrono>
20 #include <csignal>
21 #include <cstdlib>
22 #include <fstream>
23 #include <functional>
24 #include <getopt.h>
25 #include <memory>
26 #include <mutex>
27 #include <nlohmann/json.hpp>
28 #include <string>
29 #include <thread>
30 #include <unistd.h>
31 #include <unordered_set>
32
33 #include "ability_background_connection.h"
34 #include "ability_debug_deal.h"
35 #include "ability_info.h"
36 #include "ability_interceptor.h"
37 #include "ability_manager_errors.h"
38 #include "ability_util.h"
39 #include "accesstoken_kit.h"
40 #include "app_utils.h"
41 #include "app_exit_reason_data_manager.h"
42 #include "application_util.h"
43 #include "bundle_mgr_client.h"
44 #include "common_event_manager.h"
45 #include "common_event_support.h"
46 #include "connection_state_manager.h"
47 #include "display_manager.h"
48 #include "distributed_client.h"
49 #include "dlp_utils.h"
50 #include "errors.h"
51 #include "extension_config.h"
52 #include "freeze_util.h"
53 #include "hilog_wrapper.h"
54 #include "hisysevent.h"
55 #include "hitrace_meter.h"
56 #include "if_system_ability_manager.h"
57 #include "in_process_call_wrapper.h"
58 #include "insight_intent_execute_callback_proxy.h"
59 #include "insight_intent_execute_manager.h"
60 #include "ipc_skeleton.h"
61 #include "ipc_types.h"
62 #include "iservice_registry.h"
63 #include "itest_observer.h"
64 #include "mission_info.h"
65 #include "mission_info_mgr.h"
66 #include "mock_session_manager_service.h"
67 #include "modal_system_ui_extension.h"
68 #include "os_account_manager_wrapper.h"
69 #include "modal_system_ui_extension.h"
70 #include "parameters.h"
71 #include "permission_constants.h"
72 #include "recovery_param.h"
73 #include "sa_mgr_client.h"
74 #include "scene_board_judgement.h"
75 #include "session_info.h"
76 #include "softbus_bus_center.h"
77 #include "start_ability_handler/start_ability_sandbox_savefile.h"
78 #include "start_options.h"
79 #include "string_ex.h"
80 #include "string_wrapper.h"
81 #include "system_ability_definition.h"
82 #include "system_ability_token_callback.h"
83 #include "extension_record_manager.h"
84 #include "ui_extension_utils.h"
85 #include "uri_permission_manager_client.h"
86 #include "view_data.h"
87 #include "xcollie/watchdog.h"
88 #ifdef SUPPORT_GRAPHICS
89 #include "dialog_session_record.h"
90 #include "application_anr_listener.h"
91 #include "input_manager.h"
92 #endif
93
94 #ifdef EFFICIENCY_MANAGER_ENABLE
95 #include "suspend_manager_client.h"
96 #include "process_frozen_state_observer.h"
97 #endif // EFFICIENCY_MANAGER_ENABLE
98
99 #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE
100 #include "res_sched_client.h"
101 #include "res_type.h"
102 #endif // RESOURCE_SCHEDULE_SERVICE_ENABLE
103
104 using OHOS::AppExecFwk::ElementName;
105 using OHOS::Security::AccessToken::AccessTokenKit;
106
107 namespace OHOS {
108 using AbilityRuntime::FreezeUtil;
109 namespace AAFwk {
110 using AutoStartupInfo = AbilityRuntime::AutoStartupInfo;
111 namespace {
112 #define CHECK_CALLER_IS_SYSTEM_APP \
113 if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
114 HILOG_ERROR("The caller is not system-app, can not use system-api"); \
115 return ERR_NOT_SYSTEM_APP; \
116 }
117
118 const std::string ARGS_USER_ID = "-u";
119 const std::string ARGS_CLIENT = "-c";
120 const std::string ILLEGAL_INFOMATION = "The arguments are illegal and you can enter '-h' for help.";
121
122 constexpr int32_t NEW_RULE_VALUE_SIZE = 6;
123 constexpr int64_t APP_ALIVE_TIME_MS = 1000; // Allow background startup within 1 second after application startup
124 constexpr int32_t REGISTER_FOCUS_DELAY = 5000;
125 constexpr size_t OFFSET = 32;
126 const std::string IS_DELEGATOR_CALL = "isDelegatorCall";
127 // Startup rule switch
128 const std::string COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
129 const std::string NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI = "component.startup.newRules.except.LauncherSystemUI";
130 const std::string BACKGROUND_JUDGE_FLAG = "component.startup.backgroundJudge.flag";
131 const std::string WHITE_LIST_ASS_WAKEUP_FLAG = "component.startup.whitelist.associatedWakeUp";
132 // White list app
133 const std::string BUNDLE_NAME_SETTINGSDATA = "com.ohos.settingsdata";
134 const std::string BUNDLE_NAME_SCENEBOARD = "com.ohos.sceneboard";
135 // Support prepare terminate
136 constexpr int32_t PREPARE_TERMINATE_ENABLE_SIZE = 6;
137 const char* PREPARE_TERMINATE_ENABLE_PARAMETER = "persist.sys.prepare_terminate";
138 const std::string DLP_BUNDLE_NAME = "com.ohos.dlpmanager";
139 // UIExtension type
140 const std::string UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType";
141 const std::string UIEXTENSION_TARGET_TYPE_KEY = "ability.want.params.uiExtensionTargetType";
142 const std::string SYSTEM_SHARE = "share";
143 const std::string SYSTEM_SHARE_TYPE = "sysPicker/share";
144 // Share picker params
145 constexpr char SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY[] = "const.system.sharePicker.bundleName";
146 constexpr char SHARE_PICKER_DIALOG_ABILITY_NAME_KEY[] = "const.system.sharePicker.abilityName";
147 constexpr char SHARE_PICKER_UIEXTENSION_NAME_KEY[] = "const.system.sharePicker.UIExtensionAbilityName";
148 constexpr char SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME[] = "com.ohos.sharepickerdialog";
149 constexpr char SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME[] = "PickerDialog";
150 constexpr char TOKEN_KEY[] = "ohos.ability.params.token";
151 // Developer mode param
152 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
153 // Broker params key
154 const std::string KEY_VISIBLE_ID = "ohos.anco.param.visible";
155 const std::string START_ABILITY_TYPE = "ABILITY_INNER_START_WITH_ACCOUNT";
156 const std::string SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant";
157 const std::string SHELL_ASSISTANT_ABILITYNAME = "MainAbility";
158 const std::string AMS_DIALOG_BUNDLENAME = "com.ohos.amsdialog";
159 const std::string STR_PHONE = "phone";
160
161 const std::string DEBUG_APP = "debugApp";
162 const std::string AUTO_FILL_PASSWORD_TPYE = "autoFill/password";
163 constexpr size_t INDEX_ZERO = 0;
164 constexpr size_t INDEX_ONE = 1;
165 constexpr size_t INDEX_TWO = 2;
166 constexpr size_t ARGC_THREE = 3;
167 constexpr static char WANT_PARAMS_VIEW_DATA_KEY[] = "ohos.ability.params.viewData";
168
169 constexpr int32_t FOUNDATION_UID = 5523;
170 const std::string FRS_BUNDLE_NAME = "com.ohos.formrenderservice";
171 const std::string FOUNDATION_PROCESS_NAME = "foundation";
172
173 const std::unordered_set<std::string> WHITE_LIST_ASS_WAKEUP_SET = { BUNDLE_NAME_SETTINGSDATA };
174 std::atomic<bool> g_isDmsAlive = false;
175
CheckCallerIsDlpManager(const std::shared_ptr<AppExecFwk::BundleMgrHelper> & bundleManager)176 bool CheckCallerIsDlpManager(const std::shared_ptr<AppExecFwk::BundleMgrHelper> &bundleManager)
177 {
178 if (!bundleManager) {
179 return false;
180 }
181
182 std::string bundleName;
183 auto callerUid = IPCSkeleton::GetCallingUid();
184 if (IN_PROCESS_CALL(bundleManager->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
185 HILOG_WARN("Get Bundle Name failed.");
186 return false;
187 }
188 if (bundleName != DLP_BUNDLE_NAME) {
189 HILOG_WARN("Wrong Caller.");
190 return false;
191 }
192 return true;
193 }
194 } // namespace
195
196 using namespace std::chrono;
197 using namespace std::chrono_literals;
198 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
199 using namespace BackgroundTaskMgr;
200 #endif
201 const bool CONCURRENCY_MODE_FALSE = false;
202 const int32_t MAIN_USER_ID = 100;
203 constexpr auto DATA_ABILITY_START_TIMEOUT = 5s;
204 constexpr int32_t NON_ANONYMIZE_LENGTH = 6;
205 constexpr uint32_t SCENE_FLAG_NORMAL = 0;
206 const int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20;
207 const int32_t SWITCH_ACCOUNT_TRY = 3;
208 #ifdef ABILITY_COMMAND_FOR_TEST
209 const int32_t BLOCK_AMS_SERVICE_TIME = 65;
210 #endif
211 const std::string EMPTY_DEVICE_ID = "";
212 const int32_t APP_MEMORY_SIZE = 512;
213 const int32_t GET_PARAMETER_INCORRECT = -9;
214 const int32_t GET_PARAMETER_OTHER = -1;
215 const int32_t SIZE_10 = 10;
216 const int32_t HIDUMPER_SERVICE_UID = 1212;
217 const int32_t ACCOUNT_MGR_SERVICE_UID = 3058;
218 const int32_t BROKER_UID = 5557;
219 const int32_t BROKER_RESERVE_UID = 5005;
220 const int32_t DMS_UID = 5522;
221 const int32_t PREPARE_TERMINATE_TIMEOUT_MULTIPLE = 10;
222 const int32_t BOOTEVENT_COMPLETED_DELAY_TIME = 1000;
223 constexpr int32_t BOOTEVENT_BOOT_ANIMATION_READY_SIZE = 6;
224 const std::string BUNDLE_NAME_KEY = "bundleName";
225 const std::string DM_PKG_NAME = "ohos.distributedhardware.devicemanager";
226 const std::string ACTION_CHOOSE = "ohos.want.action.select";
227 const std::string HIGHEST_PRIORITY_ABILITY_ENTITY = "flag.home.intent.from.system";
228 const std::string DMS_API_VERSION = "dmsApiVersion";
229 const std::string DMS_IS_CALLER_BACKGROUND = "dmsIsCallerBackGround";
230 const std::string DMS_PROCESS_NAME = "distributedsched";
231 const std::string DMS_MISSION_ID = "dmsMissionId";
232 const std::string DLP_INDEX = "ohos.dlp.params.index";
233 const std::string BOOTEVENT_APPFWK_READY = "bootevent.appfwk.ready";
234 const std::string BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed";
235 const std::string BOOTEVENT_BOOT_ANIMATION_STARTED = "bootevent.bootanimation.started";
236 const std::string BOOTEVENT_BOOT_ANIMATION_READY = "bootevent.bootanimation.ready";
237 const std::string NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
238 const std::string PERMISSIONMGR_BUNDLE_NAME = "com.ohos.permissionmanager";
239 const std::string PERMISSIONMGR_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility";
240 const std::string IS_CALL_BY_SCB = "isCallBySCB";
241 const std::string PROCESS_SUFFIX = "embeddable";
242 const int DEFAULT_DMS_MISSION_ID = -1;
243 const std::map<std::string, AbilityManagerService::DumpKey> AbilityManagerService::dumpMap = {
244 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--all", KEY_DUMP_ALL),
245 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-a", KEY_DUMP_ALL),
246 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--stack-list", KEY_DUMP_STACK_LIST),
247 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-l", KEY_DUMP_STACK_LIST),
248 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--stack", KEY_DUMP_STACK),
249 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-s", KEY_DUMP_STACK),
250 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--mission", KEY_DUMP_MISSION),
251 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-m", KEY_DUMP_MISSION),
252 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--top", KEY_DUMP_TOP_ABILITY),
253 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-t", KEY_DUMP_TOP_ABILITY),
254 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--waiting-queue", KEY_DUMP_WAIT_QUEUE),
255 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-w", KEY_DUMP_WAIT_QUEUE),
256 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--serv", KEY_DUMP_SERVICE),
257 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-e", KEY_DUMP_SERVICE),
258 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--data", KEY_DUMP_DATA),
259 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-d", KEY_DUMP_DATA),
260 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-focus", KEY_DUMP_FOCUS_ABILITY),
261 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-f", KEY_DUMP_FOCUS_ABILITY),
262 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--win-mode", KEY_DUMP_WINDOW_MODE),
263 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-z", KEY_DUMP_WINDOW_MODE),
264 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--mission-list", KEY_DUMP_MISSION_LIST),
265 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-L", KEY_DUMP_MISSION_LIST),
266 std::map<std::string, AbilityManagerService::DumpKey>::value_type("--mission-infos", KEY_DUMP_MISSION_INFOS),
267 std::map<std::string, AbilityManagerService::DumpKey>::value_type("-S", KEY_DUMP_MISSION_INFOS),
268 };
269
270 const std::map<std::string, AbilityManagerService::DumpsysKey> AbilityManagerService::dumpsysMap = {
271 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("--all", KEY_DUMPSYS_ALL),
272 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("-a", KEY_DUMPSYS_ALL),
273 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("--mission-list", KEY_DUMPSYS_MISSION_LIST),
274 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("-l", KEY_DUMPSYS_MISSION_LIST),
275 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("--ability", KEY_DUMPSYS_ABILITY),
276 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("-i", KEY_DUMPSYS_ABILITY),
277 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("--extension", KEY_DUMPSYS_SERVICE),
278 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("-e", KEY_DUMPSYS_SERVICE),
279 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("--pending", KEY_DUMPSYS_PENDING),
280 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("-p", KEY_DUMPSYS_PENDING),
281 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("--process", KEY_DUMPSYS_PROCESS),
282 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("-r", KEY_DUMPSYS_PROCESS),
283 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("--data", KEY_DUMPSYS_DATA),
284 std::map<std::string, AbilityManagerService::DumpsysKey>::value_type("-d", KEY_DUMPSYS_DATA),
285 };
286
287 const std::map<int32_t, AppExecFwk::SupportWindowMode> AbilityManagerService::windowModeMap = {
288 std::map<int32_t, AppExecFwk::SupportWindowMode>::value_type(MULTI_WINDOW_DISPLAY_FULLSCREEN,
289 AppExecFwk::SupportWindowMode::FULLSCREEN),
290 std::map<int32_t, AppExecFwk::SupportWindowMode>::value_type(MULTI_WINDOW_DISPLAY_PRIMARY,
291 AppExecFwk::SupportWindowMode::SPLIT),
292 std::map<int32_t, AppExecFwk::SupportWindowMode>::value_type(MULTI_WINDOW_DISPLAY_SECONDARY,
293 AppExecFwk::SupportWindowMode::SPLIT),
294 std::map<int32_t, AppExecFwk::SupportWindowMode>::value_type(MULTI_WINDOW_DISPLAY_FLOATING,
295 AppExecFwk::SupportWindowMode::FLOATING),
296 };
297
298 const bool REGISTER_RESULT =
299 SystemAbility::MakeAndRegisterAbility(DelayedSingleton<AbilityManagerService>::GetInstance().get());
300 sptr<AbilityManagerService> AbilityManagerService::instance_;
301
AbilityManagerService()302 AbilityManagerService::AbilityManagerService()
303 : SystemAbility(ABILITY_MGR_SERVICE_ID, true),
304 state_(ServiceRunningState::STATE_NOT_START),
305 bundleMgrHelper_(nullptr)
306 {
307 DumpFuncInit();
308 DumpSysFuncInit();
309 }
310
~AbilityManagerService()311 AbilityManagerService::~AbilityManagerService()
312 {}
313
OnStart()314 void AbilityManagerService::OnStart()
315 {
316 if (state_ == ServiceRunningState::STATE_RUNNING) {
317 HILOG_INFO("AMS has already started.");
318 return;
319 }
320 HILOG_INFO("AMS starting.");
321 if (!Init()) {
322 HILOG_ERROR("Failed to init AMS.");
323 return;
324 }
325 state_ = ServiceRunningState::STATE_RUNNING;
326 /* Publish service maybe failed, so we need call this function at the last,
327 * so it can't affect the TDD test program */
328 instance_ = DelayedSingleton<AbilityManagerService>::GetInstance().get();
329 if (instance_ == nullptr) {
330 HILOG_ERROR("AMS enter OnStart, but instance_ is nullptr!");
331 return;
332 }
333 bool ret = Publish(instance_);
334 if (!ret) {
335 HILOG_ERROR("Publish AMS failed!");
336 return;
337 }
338
339 SetParameter(BOOTEVENT_APPFWK_READY.c_str(), "true");
340 AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
341 AddSystemAbilityListener(DISTRIBUTED_SCHED_SA_ID);
342 AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
343 HILOG_INFO("AMS start success.");
344 }
345
Init()346 bool AbilityManagerService::Init()
347 {
348 HiviewDFX::Watchdog::GetInstance().InitFfrtWatchdog(); // For ffrt watchdog available in foundation
349 taskHandler_ = TaskHandlerWrap::CreateQueueHandler(AbilityConfig::NAME_ABILITY_MGR_SERVICE);
350 eventHandler_ = std::make_shared<AbilityEventHandler>(taskHandler_, weak_from_this());
351 freeInstallManager_ = std::make_shared<FreeInstallManager>(weak_from_this());
352 CHECK_POINTER_RETURN_BOOL(freeInstallManager_);
353
354 // init user controller.
355 userController_ = std::make_shared<UserController>();
356 userController_->Init();
357
358 InitConnectManager(MAIN_USER_ID, true);
359 InitDataAbilityManager(MAIN_USER_ID, true);
360 InitPendWantManager(MAIN_USER_ID, true);
361 systemDataAbilityManager_ = std::make_shared<DataAbilityManager>();
362
363 AmsConfigurationParameter::GetInstance().Parse();
364 HILOG_INFO("ams config parse");
365 std::string deviceType = OHOS::system::GetDeviceType();
366 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
367 uiAbilityLifecycleManager_ = std::make_shared<UIAbilityLifecycleManager>();
368 uiAbilityLifecycleManager_->SetDevice(deviceType);
369 } else {
370 InitMissionListManager(MAIN_USER_ID, true);
371 }
372 SwitchManagers(U0_USER_ID, false);
373 #ifdef SUPPORT_GRAPHICS
374 auto anrListenerTask = []() {
375 auto anrListener = std::make_shared<ApplicationAnrListener>();
376 MMI::InputManager::GetInstance()->SetAnrObserver(anrListener);
377 };
378 taskHandler_->SubmitTask(anrListenerTask, "AnrListenerTask");
379 DelayedSingleton<SystemDialogScheduler>::GetInstance()->SetDeviceType(deviceType);
380 implicitStartProcessor_ = std::make_shared<ImplicitStartProcessor>();
381 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
382 InitFocusListener();
383 }
384 #endif
385
386 DelayedSingleton<ConnectionStateManager>::GetInstance()->Init(taskHandler_);
387
388 InitInterceptor();
389 InitStartAbilityChain();
390
391 abilityAutoStartupService_ = std::make_shared<AbilityRuntime::AbilityAutoStartupService>();
392
393 dialogSessionRecord_ = std::make_shared<DialogSessionRecord>();
394
395 InitPushTask();
396
397 SubscribeScreenUnlockedEvent();
398 HILOG_INFO("Init success.");
399 return true;
400 }
401
InitInterceptor()402 void AbilityManagerService::InitInterceptor()
403 {
404 interceptorExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
405 interceptorExecuter_->AddInterceptor(std::make_shared<CrowdTestInterceptor>());
406 interceptorExecuter_->AddInterceptor(std::make_shared<ControlInterceptor>());
407 afterCheckExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
408 afterCheckExecuter_->AddInterceptor(std::make_shared<DisposedRuleInterceptor>());
409 afterCheckExecuter_->AddInterceptor(std::make_shared<EcologicalRuleInterceptor>());
410 afterCheckExecuter_->SetTaskHandler(taskHandler_);
411 bool isAppJumpEnabled = OHOS::system::GetBoolParameter(
412 OHOS::AppExecFwk::PARAMETER_APP_JUMP_INTERCEPTOR_ENABLE, false);
413 if (isAppJumpEnabled) {
414 HILOG_INFO("App jump intercetor enabled, add AbilityJumpInterceptor to Executer");
415 interceptorExecuter_->AddInterceptor(std::make_shared<AbilityJumpInterceptor>());
416 }
417 }
418
InitPushTask()419 void AbilityManagerService::InitPushTask()
420 {
421 if (taskHandler_ == nullptr) {
422 HILOG_ERROR("taskHandler_ is nullptr.");
423 return;
424 }
425 auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(); };
426 taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps");
427
428 auto initStartupFlagTask = [aams = shared_from_this()]() { aams->InitStartupFlag(); };
429 taskHandler_->SubmitTask(initStartupFlagTask, "InitStartupFlag");
430
431 auto initPrepareTerminateConfigTask = [aams = shared_from_this()]() { aams->InitPrepareTerminateConfig(); };
432 taskHandler_->SubmitTask(initPrepareTerminateConfigTask, "InitPrepareTerminateConfig");
433
434 RegisterSuspendObserver();
435
436 auto initExtensionConfigTask = []() {
437 DelayedSingleton<ExtensionConfig>::GetInstance()->LoadExtensionConfiguration();
438 };
439 taskHandler_->SubmitTask(initExtensionConfigTask, "InitExtensionConfigTask");
440
441 auto bootCompletedTask = [handler = taskHandler_]() {
442 if (ApplicationUtil::IsBootCompleted()) {
443 auto task = []() {
444 ApplicationUtil::AppFwkBootEventCallback(BOOTEVENT_BOOT_COMPLETED.c_str(), "true", nullptr);
445 };
446 handler->SubmitTask(task, "BootCompletedDelayTask", BOOTEVENT_COMPLETED_DELAY_TIME);
447 } else {
448 WatchParameter(BOOTEVENT_BOOT_COMPLETED.c_str(), ApplicationUtil::AppFwkBootEventCallback, nullptr);
449 }
450 };
451 taskHandler_->SubmitTask(bootCompletedTask, "BootCompletedTask");
452 }
453
InitStartupFlag()454 void AbilityManagerService::InitStartupFlag()
455 {
456 startUpNewRule_ = CheckNewRuleSwitchState(COMPONENT_STARTUP_NEW_RULES);
457 newRuleExceptLauncherSystemUI_ = CheckNewRuleSwitchState(NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI);
458 backgroundJudgeFlag_ = CheckNewRuleSwitchState(BACKGROUND_JUDGE_FLAG);
459 whiteListassociatedWakeUpFlag_ = CheckNewRuleSwitchState(WHITE_LIST_ASS_WAKEUP_FLAG);
460 }
461
InitStartAbilityChain()462 void AbilityManagerService::InitStartAbilityChain()
463 {
464 auto startSandboxSaveFile = std::make_shared<StartAbilitySandboxSavefile>();
465 startAbilityChain_.emplace(startSandboxSaveFile->GetPriority(), startSandboxSaveFile);
466 }
467
OnStop()468 void AbilityManagerService::OnStop()
469 {
470 HILOG_INFO("Stop AMS.");
471 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
472 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
473 if (bgtaskObserver_) {
474 int ret = BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver_);
475 if (ret != ERR_OK) {
476 HILOG_ERROR("unsubscribe bgtask failed, err:%{public}d.", ret);
477 }
478 }
479 #endif
480 if (abilityBundleEventCallback_) {
481 auto bms = GetBundleManager();
482 if (bms) {
483 bool ret = IN_PROCESS_CALL(bms->UnregisterBundleEventCallback(abilityBundleEventCallback_));
484 if (ret != ERR_OK) {
485 HILOG_ERROR("unsubscribe bundle event callback failed, err:%{public}d.", ret);
486 }
487 }
488 }
489 eventHandler_.reset();
490 taskHandler_.reset();
491 state_ = ServiceRunningState::STATE_NOT_START;
492 }
493
QueryServiceState() const494 ServiceRunningState AbilityManagerService::QueryServiceState() const
495 {
496 return state_;
497 }
498
StartAbility(const Want & want,int32_t userId,int requestCode)499 int AbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode)
500 {
501 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
502 if (want.GetBoolParam(DEBUG_APP, false) && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
503 HILOG_ERROR("Developer Mode is false.");
504 return ERR_NOT_DEVELOPER_MODE;
505 }
506 HILOG_DEBUG("coldStart:%{public}d", want.GetBoolParam("coldStart", false));
507 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
508 if (startWithAccount || IsCrossUserCall(userId)) {
509 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
510 CHECK_CALLER_IS_SYSTEM_APP;
511 }
512 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
513 EventInfo eventInfo = BuildEventInfo(want, userId);
514 EventReport::SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
515 int32_t ret = StartAbilityWrap(want, nullptr, requestCode, userId);
516 if (ret != ERR_OK) {
517 eventInfo.errCode = ret;
518 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
519 }
520 return ret;
521 }
522
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)523 int AbilityManagerService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
524 int32_t userId, int requestCode)
525 {
526 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
527 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
528 if (startWithAccount || IsCrossUserCall(userId)) {
529 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
530 CHECK_CALLER_IS_SYSTEM_APP;
531 }
532 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
533 auto flags = want.GetFlags();
534 EventInfo eventInfo = BuildEventInfo(want, userId);
535 EventReport::SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
536 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
537 HILOG_ERROR("StartAbility with continuation flags is not allowed!");
538 eventInfo.errCode = ERR_INVALID_VALUE;
539 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
540 return ERR_INVALID_CONTINUATION_FLAG;
541 }
542
543 HILOG_INFO("Start ability come, ability is %{public}s, userId is %{public}d",
544 want.GetElement().GetAbilityName().c_str(), userId);
545
546 int32_t ret = StartAbilityWrap(want, callerToken, requestCode, userId);
547 if (ret != ERR_OK) {
548 eventInfo.errCode = ret;
549 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
550 }
551 return ret;
552 }
553
StartAbilityByInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,uint64_t intentId,int32_t userId)554 int32_t AbilityManagerService::StartAbilityByInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken,
555 uint64_t intentId, int32_t userId)
556 {
557 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
558 std::string bundleNameFromWant = want.GetElement().GetBundleName();
559 std::string bundleNameFromIntentMgr = "";
560 if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->
561 GetBundleName(intentId, bundleNameFromIntentMgr) != ERR_OK) {
562 HILOG_ERROR("no such bundle matched intentId");
563 return ERR_INVALID_VALUE;
564 }
565 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
566 if (abilityRecord == nullptr) {
567 HILOG_ERROR("no such bundle matched token");
568 return ERR_INVALID_VALUE;
569 }
570 std::string bundleNameFromAbilityRecord = abilityRecord->GetAbilityInfo().bundleName;
571 if (!bundleNameFromWant.empty() && bundleNameFromWant == bundleNameFromIntentMgr &&
572 bundleNameFromWant == bundleNameFromAbilityRecord) {
573 HILOG_INFO("bundleName match");
574 return StartAbility(want, callerToken, userId, -1);
575 }
576 HILOG_ERROR("bundleName not match");
577 return ERR_INSIGHT_INTENT_START_INVALID_COMPONENT;
578 }
579
StartAbilityByUIContentSession(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)580 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const sptr<IRemoteObject> &callerToken,
581 const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
582 {
583 if (!callerToken || !sessionInfo) {
584 HILOG_ERROR("callerToken or sessionInfo is nullptr");
585 return ERR_INVALID_VALUE;
586 }
587 sptr<IRemoteObject> token;
588 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
589 Rosen::FocusChangeInfo focusChangeInfo;
590 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
591 token = focusChangeInfo.abilityToken_;
592 } else {
593 if (!wmsHandler_) {
594 HILOG_ERROR("wmsHandler_ is nullptr.");
595 return ERR_INVALID_VALUE;
596 }
597 wmsHandler_->GetFocusWindow(token);
598 }
599
600 if (!token) {
601 HILOG_ERROR("token is nullptr");
602 return ERR_INVALID_VALUE;
603 }
604
605 if (token != sessionInfo->callerToken) {
606 HILOG_ERROR("callerToken is not equal to top ablity token");
607 return NOT_TOP_ABILITY;
608 }
609 return StartAbility(want, callerToken, userId, requestCode);
610 }
611
StartAbilityByUIContentSession(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)612 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const StartOptions &startOptions,
613 const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
614 {
615 if (!callerToken || !sessionInfo) {
616 HILOG_ERROR("callerToken or sessionInfo is nullptr");
617 return ERR_INVALID_VALUE;
618 }
619 sptr<IRemoteObject> token;
620 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
621 Rosen::FocusChangeInfo focusChangeInfo;
622 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
623 token = focusChangeInfo.abilityToken_;
624 } else {
625 if (!wmsHandler_) {
626 HILOG_ERROR("wmsHandler_ is nullptr.");
627 return ERR_INVALID_VALUE;
628 }
629 wmsHandler_->GetFocusWindow(token);
630 }
631
632 if (!token) {
633 HILOG_ERROR("token is nullptr");
634 return ERR_INVALID_VALUE;
635 }
636
637 if (token != sessionInfo->callerToken) {
638 HILOG_ERROR("callerToken is not equal to top ablity token");
639 return NOT_TOP_ABILITY;
640 }
641 return StartAbility(want, startOptions, callerToken, userId, requestCode);
642 }
643
StartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSoureToken,int32_t userId,int requestCode,bool isSendDialogResult)644 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
645 sptr<IRemoteObject> asCallerSoureToken, int32_t userId, int requestCode, bool isSendDialogResult)
646 {
647 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
648 CHECK_CALLER_IS_SYSTEM_APP;
649 auto flags = want.GetFlags();
650 EventInfo eventInfo = BuildEventInfo(want, userId);
651 EventReport::SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
652 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
653 HILOG_ERROR("StartAbility with continuation flags is not allowed!");
654 eventInfo.errCode = ERR_INVALID_VALUE;
655 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
656 return ERR_INVALID_CONTINUATION_FLAG;
657 }
658
659 AAFwk::Want newWant = want;
660 if (asCallerSoureToken != nullptr) {
661 HILOG_DEBUG("Start as caller, UpdateCallerInfo");
662 UpdateAsCallerSourceInfo(newWant, asCallerSoureToken);
663 }
664
665 HILOG_INFO("Start ability come, ability is %{public}s, userId is %{public}d",
666 want.GetElement().GetAbilityName().c_str(), userId);
667 std::string callerPkg;
668 std::string targetPkg;
669 if (AbilityUtil::CheckJumpInterceptorWant(newWant, callerPkg, targetPkg)) {
670 HILOG_INFO("the call is from interceptor dialog, callerPkg:%{public}s, targetPkg:%{public}s",
671 callerPkg.c_str(), targetPkg.c_str());
672 AbilityUtil::AddAbilityJumpRuleToBms(callerPkg, targetPkg, GetUserId());
673 }
674 int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, userId, true, isSendDialogResult);
675 if (ret != ERR_OK) {
676 eventInfo.errCode = ret;
677 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
678 }
679 return ret;
680 }
681
StartAbilityPublicPrechainCheck(StartAbilityParams & params)682 int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams ¶ms)
683 {
684 // 1. CheckCallerToken
685 if (params.callerToken != nullptr && !VerificationAllToken(params.callerToken)) {
686 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
687 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
688 if (!isSpecificSA) {
689 HILOG_ERROR("%{public}s VerificationAllToken failed.", __func__);
690 return ERR_INVALID_CALLER;
691 }
692 HILOG_INFO("%{public}s: Caller is specific system ability.", __func__);
693 }
694
695 // 2. validUserId, multi-user
696 if (!JudgeMultiUserConcurrency(params.GetValidUserId())) {
697 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
698 return ERR_CROSS_USER;
699 }
700
701 return ERR_OK;
702 }
703
StartAbilityPrechainInterceptor(StartAbilityParams & params)704 int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams ¶ms)
705 {
706 auto interceptorResult = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
707 interceptorExecuter_->DoProcess(params.want, params.requestCode, GetUserId(), true);
708 if (interceptorResult != ERR_OK) {
709 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
710 return interceptorResult;
711 }
712
713 return ERR_OK;
714 }
715
StartAbilityInChain(StartAbilityParams & params,int & result)716 bool AbilityManagerService::StartAbilityInChain(StartAbilityParams ¶ms, int &result)
717 {
718 std::shared_ptr<StartAbilityHandler> reqHandler;
719 for (const auto &item : startAbilityChain_) {
720 if (item.second->MatchStartRequest(params)) {
721 reqHandler = item.second;
722 break;
723 }
724 }
725
726 if (!reqHandler) {
727 return false;
728 }
729
730 result = StartAbilityPublicPrechainCheck(params);
731 if (result != ERR_OK) {
732 return true;
733 }
734 result = StartAbilityPrechainInterceptor(params);
735 if (result != ERR_OK) {
736 return true;
737 }
738 result = reqHandler->HandleStartRequest(params);
739 return true;
740 }
741
StartAbilityWrap(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId,bool isStartAsCaller,bool isSendDialogResult)742 int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr<IRemoteObject> &callerToken,
743 int requestCode, int32_t userId, bool isStartAsCaller, bool isSendDialogResult)
744 {
745 StartAbilityParams startParams(const_cast<Want &>(want));
746 startParams.callerToken = callerToken;
747 startParams.userId = userId;
748 startParams.requestCode = requestCode;
749 startParams.isStartAsCaller = isStartAsCaller;
750 startParams.SetValidUserId(GetValidUserId(userId));
751
752 int result = ERR_OK;
753 if (StartAbilityInChain(startParams, result)) {
754 return result;
755 }
756
757 return StartAbilityInner(want, callerToken, requestCode, userId, isStartAsCaller, isSendDialogResult);
758 }
759
StartAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId,bool isStartAsCaller,bool isSendDialogResult)760 int AbilityManagerService::StartAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
761 int requestCode, int32_t userId, bool isStartAsCaller, bool isSendDialogResult)
762 {
763 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
764 {
765 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
766 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
767 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
768 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
769 HILOG_ERROR("%{public}s: Permission verification failed.", __func__);
770 return CHECK_PERMISSION_FAILED;
771 }
772
773 if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
774 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
775 return StartExtensionAbilityInner(want, callerToken, userId,
776 AppExecFwk::ExtensionAbilityType::SERVICE, false);
777 }
778 }
779
780 std::string dialogSessionId = want.GetStringParam("dialogSessionId");
781 isSendDialogResult = false;
782 if (!dialogSessionId.empty() && dialogSessionRecord_->GetDialogCallerInfo(dialogSessionId) != nullptr) {
783 isSendDialogResult = true;
784 dialogSessionRecord_->ClearDialogContext(dialogSessionId);
785 }
786 if (callerToken != nullptr && !VerificationAllToken(callerToken) && !isSendDialogResult) {
787 auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
788 CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
789 if (!isSpecificSA) {
790 HILOG_ERROR("%{public}s VerificationAllToken failed.", __func__);
791 return ERR_INVALID_CALLER;
792 }
793 HILOG_INFO("%{public}s: Caller is specific system ability.", __func__);
794 }
795
796 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
797 interceptorExecuter_->DoProcess(want, requestCode, GetUserId(), true);
798 if (result != ERR_OK) {
799 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
800 return result;
801 }
802
803 int32_t oriValidUserId = GetValidUserId(userId);
804 int32_t validUserId = oriValidUserId;
805
806 if (callerToken != nullptr && CheckIfOperateRemote(want)) {
807 HILOG_INFO("try to StartRemoteAbility");
808 return StartRemoteAbility(want, requestCode, validUserId, callerToken);
809 }
810
811 if (!JudgeMultiUserConcurrency(validUserId)) {
812 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
813 return ERR_CROSS_USER;
814 }
815
816 AbilityRequest abilityRequest;
817 #ifdef SUPPORT_GRAPHICS
818 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
819 abilityRequest.Voluation(want, requestCode, callerToken);
820 if (!isStartAsCaller) {
821 HILOG_DEBUG("do not start as caller, UpdateCallerInfo");
822 UpdateCallerInfo(abilityRequest.want, callerToken);
823 }
824 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
825 return implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
826 }
827 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
828 return ShowPickerDialog(want, validUserId, callerToken);
829 }
830 #endif
831 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
832 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
833 std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
834 std::string callerAbilityName = abilityRecord ? abilityRecord->GetAbilityInfo().name : "";
835 bool selfFreeInstallEnable = (result == RESOLVE_ABILITY_ERR && want.GetElement().GetModuleName() != "" &&
836 want.GetElement().GetBundleName() == callerBundleName);
837 bool isStartFreeInstallByWant = AbilityUtil::IsStartFreeInstall(want);
838 if (isStartFreeInstallByWant || selfFreeInstallEnable) {
839 if (freeInstallManager_ == nullptr) {
840 return ERR_INVALID_VALUE;
841 }
842 Want localWant = want;
843 if (!localWant.GetDeviceId().empty()) {
844 localWant.SetDeviceId("");
845 }
846 if (!isStartAsCaller) {
847 HILOG_DEBUG("do not start as caller, UpdateCallerInfo");
848 UpdateCallerInfo(localWant, callerToken);
849 }
850
851 if (isStartFreeInstallByWant) {
852 return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true);
853 }
854 int32_t ret = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, false);
855 if (ret == ERR_OK) {
856 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
857 }
858 }
859
860 if (result != ERR_OK) {
861 HILOG_ERROR("Generate ability request local error.");
862 return result;
863 }
864
865 if (!isStartAsCaller) {
866 HILOG_DEBUG("do not start as caller, UpdateCallerInfo");
867 UpdateCallerInfo(abilityRequest.want, callerToken);
868 } else if (callerBundleName == AMS_DIALOG_BUNDLENAME ||
869 (isSendDialogResult && want.GetBoolParam("isSelector", false))) {
870 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
871 implicitStartProcessor_->ResetCallingIdentityAsCaller(abilityRequest.want.GetIntParam(
872 Want::PARAM_RESV_CALLER_TOKEN, 0));
873 }
874
875 auto abilityInfo = abilityRequest.abilityInfo;
876 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
877 HILOG_DEBUG("userId is : %{public}d, singleton is : %{public}d",
878 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
879
880 result = CheckStaticCfgPermission(abilityInfo, isStartAsCaller,
881 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0));
882 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
883 HILOG_ERROR("CheckStaticCfgPermission error, result is %{public}d.", result);
884 return ERR_STATIC_CFG_PERMISSION;
885 }
886
887 auto type = abilityInfo.type;
888 if (type == AppExecFwk::AbilityType::DATA) {
889 HILOG_ERROR("Cannot start data ability by start ability.");
890 return ERR_WRONG_INTERFACE_CALL;
891 } else if (type == AppExecFwk::AbilityType::EXTENSION) {
892 auto isSACall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
893 auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall();
894 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
895 auto isToPermissionMgr = IsTargetPermission(want);
896 if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) {
897 HILOG_ERROR("Cannot start extension by start ability, use startServiceExtensionAbility.");
898 return ERR_WRONG_INTERFACE_CALL;
899 }
900 result = CheckCallServicePermission(abilityRequest);
901 if (result != ERR_OK) {
902 HILOG_ERROR("Check permission failed");
903 return result;
904 }
905 } else if (type == AppExecFwk::AbilityType::SERVICE) {
906 HILOG_DEBUG("Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
907 result = CheckCallServicePermission(abilityRequest);
908 if (result != ERR_OK) {
909 HILOG_ERROR("Check permission failed");
910 return result;
911 }
912 } else if ((callerBundleName == SHELL_ASSISTANT_BUNDLENAME && OHOS::system::GetDeviceType() == STR_PHONE) ||
913 IPCSkeleton::GetCallingUid() == BROKER_UID) {
914 // temp add for broker, remove when delete issacall
915 if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) {
916 HILOG_DEBUG("Check permission failed");
917 return CHECK_PERMISSION_FAILED;
918 }
919 HILOG_DEBUG("Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
920 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
921 if (collaborator == nullptr) {
922 HILOG_ERROR("Collaborator is nullptr.");
923 return CHECK_PERMISSION_FAILED;
924 }
925 result = collaborator->CheckCallAbilityPermission(abilityRequest.want);
926 if (result != ERR_OK) {
927 HILOG_ERROR("Check permission failed from broker.");
928 return CHECK_PERMISSION_FAILED;
929 }
930 } else if (!isSendDialogResult || want.GetBoolParam("isSelector", false)) {
931 HILOG_DEBUG("Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
932 result = CheckCallAbilityPermission(abilityRequest);
933 if (result != ERR_OK) {
934 HILOG_ERROR("Check permission failed");
935 return result;
936 }
937 }
938
939 Want newWant = abilityRequest.want;
940 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
941 afterCheckExecuter_->DoProcess(newWant, requestCode, GetUserId(), true, callerToken);
942 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
943 newWant.RemoveParam("queryWantFromErms");
944 if (result != ERR_OK && isReplaceWantExist == false) {
945 HILOG_ERROR("DoProcess failed or replaceWant not exist");
946 return result;
947 }
948 if (result != ERR_OK && isReplaceWantExist && !isSendDialogResult &&
949 callerBundleName != AMS_DIALOG_BUNDLENAME) {
950 std::string dialogSessionId;
951 std::vector<DialogAppInfo> dialogAppInfos(1);
952 if (GenerateDialogSessionRecord(abilityRequest, GetUserId(), dialogSessionId, dialogAppInfos, false)) {
953 HILOG_DEBUG("create dialog by ui extension");
954 return CreateModalDialog(newWant, callerToken, dialogSessionId);
955 }
956 HILOG_ERROR("create dialog by ui extension failed");
957 return INNER_ERR;
958 }
959
960 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
961 HILOG_DEBUG("PreLoadAppDataAbilities:%{public}s.", abilityInfo.bundleName.c_str());
962 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
963 if (result != ERR_OK) {
964 HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d.",
965 abilityInfo.bundleName.c_str(), result);
966 return result;
967 }
968 }
969
970 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
971 auto connectManager = GetConnectManagerByUserId(validUserId);
972 if (!connectManager) {
973 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", validUserId);
974 return ERR_INVALID_VALUE;
975 }
976 HILOG_DEBUG("Start service or extension, name is %{public}s.", abilityInfo.name.c_str());
977 ReportEventToSuspendManager(abilityInfo);
978 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
979 return connectManager->StartAbility(abilityRequest);
980 }
981
982 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
983 HILOG_ERROR("IsAbilityControllerStart failed: %{public}s.", abilityInfo.bundleName.c_str());
984 return ERR_WOULD_BLOCK;
985 }
986 // sceneboard
987 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
988 ReportEventToSuspendManager(abilityInfo);
989 abilityRequest.userId = oriValidUserId;
990 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
991 return uiAbilityLifecycleManager_->NotifySCBToStartUIAbility(abilityRequest, oriValidUserId);
992 }
993 auto missionListManager = GetListManagerByUserId(oriValidUserId);
994 if (missionListManager == nullptr) {
995 HILOG_ERROR("missionListManager is nullptr. userId=%{public}d", validUserId);
996 return ERR_INVALID_VALUE;
997 }
998 ReportAbilitStartInfoToRSS(abilityInfo);
999 ReportEventToSuspendManager(abilityInfo);
1000 HILOG_DEBUG("Start ability, name is %{public}s.", abilityInfo.name.c_str());
1001 return missionListManager->StartAbility(abilityRequest);
1002 }
1003
StartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1004 int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1005 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1006 {
1007 if (want.GetBoolParam(DEBUG_APP, false) && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
1008 HILOG_ERROR("Developer Mode is false.");
1009 return ERR_NOT_DEVELOPER_MODE;
1010 }
1011 StartAbilityParams startParams(const_cast<Want &>(want));
1012 startParams.callerToken = callerToken;
1013 startParams.userId = userId;
1014 startParams.requestCode = requestCode;
1015 startParams.SetValidUserId(GetValidUserId(userId));
1016
1017 int result = ERR_OK;
1018 if (StartAbilityInChain(startParams, result)) {
1019 return result;
1020 }
1021
1022 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1023 HILOG_DEBUG("Start ability setting.");
1024 if (IsCrossUserCall(userId)) {
1025 CHECK_CALLER_IS_SYSTEM_APP;
1026 }
1027 EventInfo eventInfo = BuildEventInfo(want, userId);
1028 EventReport::SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1029
1030 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1031 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1032 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1033 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1034 eventInfo.errCode = CHECK_PERMISSION_FAILED;
1035 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1036 return CHECK_PERMISSION_FAILED;
1037 }
1038
1039 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1040 eventInfo.errCode = ERR_INVALID_VALUE;
1041 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1042 return ERR_INVALID_CALLER;
1043 }
1044
1045 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1046 interceptorExecuter_->DoProcess(want, requestCode, GetUserId(), true);
1047 if (result != ERR_OK) {
1048 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
1049 eventInfo.errCode = result;
1050 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1051 return result;
1052 }
1053
1054 int32_t oriValidUserId = GetValidUserId(userId);
1055 int32_t validUserId = oriValidUserId;
1056
1057 if (AbilityUtil::IsStartFreeInstall(want)) {
1058 if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1059 HILOG_ERROR("can not start remote free install");
1060 return ERR_INVALID_VALUE;
1061 }
1062 Want localWant = want;
1063 UpdateCallerInfo(localWant, callerToken);
1064 return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true);
1065 }
1066
1067 if (!JudgeMultiUserConcurrency(validUserId)) {
1068 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
1069 eventInfo.errCode = ERR_INVALID_VALUE;
1070 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1071 return ERR_CROSS_USER;
1072 }
1073
1074 AbilityRequest abilityRequest;
1075 #ifdef SUPPORT_GRAPHICS
1076 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1077 abilityRequest.Voluation(
1078 want, requestCode, callerToken, std::make_shared<AbilityStartSetting>(abilityStartSetting));
1079 abilityRequest.callType = AbilityCallType::START_SETTINGS_TYPE;
1080 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1081 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1082 if (result != ERR_OK) {
1083 HILOG_ERROR("implicit start ability error.");
1084 eventInfo.errCode = result;
1085 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1086 }
1087 return result;
1088 }
1089 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1090 return ShowPickerDialog(want, validUserId, callerToken);
1091 }
1092 #endif
1093 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1094 if (result != ERR_OK) {
1095 HILOG_ERROR("Generate ability request local error.");
1096 eventInfo.errCode = result;
1097 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1098 return result;
1099 }
1100
1101 auto abilityInfo = abilityRequest.abilityInfo;
1102 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1103 HILOG_DEBUG("userId : %{public}d, singleton is : %{public}d",
1104 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1105
1106 result = CheckStaticCfgPermission(abilityInfo, false, -1);
1107 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1108 HILOG_ERROR("CheckStaticCfgPermission error, result is %{public}d.", result);
1109 eventInfo.errCode = result;
1110 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1111 return ERR_STATIC_CFG_PERMISSION;
1112 }
1113 result = CheckCallAbilityPermission(abilityRequest);
1114 if (result != ERR_OK) {
1115 HILOG_ERROR("%{public}s CheckCallAbilityPermission error.", __func__);
1116 eventInfo.errCode = result;
1117 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1118 return result;
1119 }
1120
1121 abilityRequest.startSetting = std::make_shared<AbilityStartSetting>(abilityStartSetting);
1122
1123 if (abilityInfo.type == AppExecFwk::AbilityType::DATA) {
1124 HILOG_ERROR("Cannot start data ability, use 'AcquireDataAbility()' instead.");
1125 eventInfo.errCode = ERR_INVALID_VALUE;
1126 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1127 return ERR_WRONG_INTERFACE_CALL;
1128 }
1129
1130 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1131 afterCheckExecuter_->DoProcess(abilityRequest.want, requestCode, GetUserId(), true, callerToken);
1132 if (result != ERR_OK) {
1133 HILOG_ERROR("afterCheckExecuter_ is nullptr or DoProcess return error.");
1134 return result;
1135 }
1136
1137 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1138 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1139 if (result != ERR_OK) {
1140 HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
1141 abilityInfo.bundleName.c_str(),
1142 result);
1143 eventInfo.errCode = result;
1144 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1145 return result;
1146 }
1147 }
1148 #ifdef SUPPORT_GRAPHICS
1149 if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1150 HILOG_ERROR("Only support for page type ability.");
1151 eventInfo.errCode = ERR_INVALID_VALUE;
1152 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1153 return ERR_WRONG_INTERFACE_CALL;
1154 }
1155 #endif
1156 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1157 eventInfo.errCode = ERR_WOULD_BLOCK;
1158 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1159 return ERR_WOULD_BLOCK;
1160 }
1161 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1162 UpdateCallerInfo(abilityRequest.want, callerToken);
1163 abilityRequest.userId = oriValidUserId;
1164 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1165 return uiAbilityLifecycleManager_->NotifySCBToStartUIAbility(abilityRequest, oriValidUserId);
1166 }
1167 auto missionListManager = GetListManagerByUserId(oriValidUserId);
1168 if (missionListManager == nullptr) {
1169 HILOG_ERROR("missionListManager is Null. userId=%{public}d", validUserId);
1170 eventInfo.errCode = ERR_INVALID_VALUE;
1171 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1172 return ERR_INVALID_VALUE;
1173 }
1174 UpdateCallerInfo(abilityRequest.want, callerToken);
1175 auto ret = missionListManager->StartAbility(abilityRequest);
1176 if (ret != ERR_OK) {
1177 eventInfo.errCode = ret;
1178 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1179 }
1180 return ret;
1181 }
1182
StartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1183 int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions,
1184 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1185 {
1186 HILOG_DEBUG("Start ability with startOptions.");
1187 return StartAbilityForOptionWrap(want, startOptions, callerToken, userId, requestCode, false);
1188 }
1189
StartAbilityAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSoureToken,int32_t userId,int requestCode)1190 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOptions &startOptions,
1191 const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSoureToken,
1192 int32_t userId, int requestCode)
1193 {
1194 HILOG_DEBUG("Start ability as caller with startOptions.");
1195 CHECK_CALLER_IS_SYSTEM_APP;
1196
1197 AAFwk::Want newWant = want;
1198 if (asCallerSoureToken != nullptr) {
1199 HILOG_DEBUG("start as caller, UpdateCallerInfo");
1200 UpdateAsCallerSourceInfo(newWant, asCallerSoureToken);
1201 }
1202
1203 return StartAbilityForOptionWrap(newWant, startOptions, callerToken, userId, requestCode, true);
1204 }
1205
StartAbilityForOptionWrap(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode,bool isStartAsCaller)1206 int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const StartOptions &startOptions,
1207 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isStartAsCaller)
1208 {
1209 StartAbilityParams startParams(const_cast<Want &>(want));
1210 startParams.callerToken = callerToken;
1211 startParams.userId = userId;
1212 startParams.requestCode = requestCode;
1213 startParams.isStartAsCaller = isStartAsCaller;
1214 startParams.startOptions = &startOptions;
1215 startParams.SetValidUserId(GetValidUserId(userId));
1216
1217 int result = ERR_OK;
1218 if (StartAbilityInChain(startParams, result)) {
1219 return result;
1220 }
1221
1222 return StartAbilityForOptionInner(want, startOptions, callerToken, userId, requestCode, isStartAsCaller);
1223 }
1224
StartAbilityForOptionInner(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode,bool isStartAsCaller)1225 int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const StartOptions &startOptions,
1226 const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isStartAsCaller)
1227 {
1228 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1229 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
1230 if (startWithAccount || IsCrossUserCall(userId)) {
1231 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
1232 CHECK_CALLER_IS_SYSTEM_APP;
1233 }
1234 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1235 EventInfo eventInfo = BuildEventInfo(want, userId);
1236 EventReport::SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1237
1238 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1239 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1240 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1241 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
1242 eventInfo.errCode = CHECK_PERMISSION_FAILED;
1243 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1244 return CHECK_PERMISSION_FAILED;
1245 }
1246
1247 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1248 eventInfo.errCode = ERR_INVALID_VALUE;
1249 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1250 return ERR_INVALID_CALLER;
1251 }
1252
1253 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1254 interceptorExecuter_->DoProcess(want, requestCode, GetUserId(), true);
1255 if (result != ERR_OK) {
1256 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
1257 eventInfo.errCode = result;
1258 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1259 return result;
1260 }
1261
1262 int32_t oriValidUserId = GetValidUserId(userId);
1263 int32_t validUserId = oriValidUserId;
1264
1265 if (AbilityUtil::IsStartFreeInstall(want)) {
1266 if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1267 HILOG_ERROR("can not start remote free install");
1268 return ERR_INVALID_VALUE;
1269 }
1270 Want localWant = want;
1271 if (!isStartAsCaller) {
1272 HILOG_DEBUG("do not start as caller, UpdateCallerInfo");
1273 UpdateCallerInfo(localWant, callerToken);
1274 }
1275 return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true);
1276 }
1277 if (!JudgeMultiUserConcurrency(validUserId)) {
1278 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
1279 eventInfo.errCode = ERR_INVALID_VALUE;
1280 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1281 return ERR_CROSS_USER;
1282 }
1283
1284 AbilityRequest abilityRequest;
1285 #ifdef SUPPORT_GRAPHICS
1286 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1287 abilityRequest.Voluation(want, requestCode, callerToken);
1288 if (startOptions.GetDisplayID() == 0) {
1289 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1290 static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1291 } else {
1292 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1293 }
1294 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_MODE, startOptions.GetWindowMode());
1295 if (AppUtils::GetInstance().JudgePCDevice()) {
1296 if (startOptions.windowLeftUsed_) {
1297 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_LEFT, startOptions.GetWindowLeft());
1298 }
1299 if (startOptions.windowTopUsed_) {
1300 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_TOP, startOptions.GetWindowTop());
1301 }
1302 if (startOptions.windowWidthUsed_) {
1303 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_HEIGHT, startOptions.GetWindowWidth());
1304 }
1305 if (startOptions.windowHeightUsed_) {
1306 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_WIDTH, startOptions.GetWindowHeight());
1307 }
1308 bool withAnimation = startOptions.GetWithAnimation();
1309 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1310 if (!withAnimation && abilityRecord != nullptr &&
1311 abilityRecord->GetAbilityInfo().bundleName == abilityRequest.want.GetBundle()) {
1312 abilityRequest.want.SetParam(Want::PARAM_RESV_WITH_ANIMATION, withAnimation);
1313 }
1314 }
1315 abilityRequest.callType = AbilityCallType::START_OPTIONS_TYPE;
1316 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1317 if (!isStartAsCaller) {
1318 HILOG_DEBUG("do not start as caller, UpdateCallerInfo");
1319 UpdateCallerInfo(abilityRequest.want, callerToken);
1320 }
1321 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1322 if (result != ERR_OK) {
1323 HILOG_ERROR("implicit start ability error.");
1324 eventInfo.errCode = result;
1325 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1326 }
1327 return result;
1328 }
1329 if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1330 return ShowPickerDialog(want, validUserId, callerToken);
1331 }
1332 #endif
1333 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1334 if (result != ERR_OK) {
1335 HILOG_ERROR("Generate ability request local error.");
1336 eventInfo.errCode = result;
1337 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1338 return result;
1339 }
1340
1341 if (!isStartAsCaller) {
1342 HILOG_DEBUG("do not start as caller, UpdateCallerInfo");
1343 UpdateCallerInfo(abilityRequest.want, callerToken);
1344 }
1345 auto abilityInfo = abilityRequest.abilityInfo;
1346 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1347 HILOG_DEBUG("userId : %{public}d, singleton is : %{public}d",
1348 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1349
1350 result = CheckStaticCfgPermission(abilityInfo, isStartAsCaller,
1351 abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0));
1352 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1353 HILOG_ERROR("CheckStaticCfgPermission error, result is %{public}d.", result);
1354 eventInfo.errCode = result;
1355 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1356 return ERR_STATIC_CFG_PERMISSION;
1357 }
1358 result = CheckCallAbilityPermission(abilityRequest);
1359 if (result != ERR_OK) {
1360 HILOG_ERROR("%{public}s CheckCallAbilityPermission error.", __func__);
1361 eventInfo.errCode = result;
1362 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1363 return result;
1364 }
1365
1366 if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1367 HILOG_ERROR("Only support for page type ability.");
1368 eventInfo.errCode = ERR_INVALID_VALUE;
1369 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1370 return ERR_INVALID_VALUE;
1371 }
1372
1373 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1374 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1375 if (result != ERR_OK) {
1376 HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
1377 abilityInfo.bundleName.c_str(),
1378 result);
1379 eventInfo.errCode = result;
1380 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1381 return result;
1382 }
1383 }
1384
1385 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1386 eventInfo.errCode = ERR_WOULD_BLOCK;
1387 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1388 return ERR_WOULD_BLOCK;
1389 }
1390 #ifdef SUPPORT_GRAPHICS
1391 if (abilityInfo.isStageBasedModel && !CheckWindowMode(startOptions.GetWindowMode(), abilityInfo.windowModes)) {
1392 return ERR_AAFWK_INVALID_WINDOW_MODE;
1393 }
1394 #endif
1395 if (startOptions.GetDisplayID() == 0) {
1396 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1397 static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1398 } else {
1399 abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1400 }
1401 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_MODE, startOptions.GetWindowMode());
1402 if (AppUtils::GetInstance().JudgePCDevice()) {
1403 if (startOptions.windowLeftUsed_) {
1404 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_LEFT, startOptions.GetWindowLeft());
1405 }
1406 if (startOptions.windowTopUsed_) {
1407 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_TOP, startOptions.GetWindowTop());
1408 }
1409 if (startOptions.windowHeightUsed_) {
1410 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_HEIGHT, startOptions.GetWindowHeight());
1411 }
1412 if (startOptions.windowWidthUsed_) {
1413 abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_WIDTH, startOptions.GetWindowWidth());
1414 }
1415 bool withAnimation = startOptions.GetWithAnimation();
1416 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1417 if (!withAnimation && abilityRecord != nullptr &&
1418 abilityRecord->GetAbilityInfo().bundleName == abilityRequest.want.GetBundle()) {
1419 abilityRequest.want.SetParam(Want::PARAM_RESV_WITH_ANIMATION, withAnimation);
1420 }
1421 }
1422
1423 Want newWant = abilityRequest.want;
1424 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1425 afterCheckExecuter_->DoProcess(newWant, requestCode, GetUserId(), true, callerToken);
1426 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1427 newWant.RemoveParam("queryWantFromErms");
1428 if (result != ERR_OK && isReplaceWantExist == false) {
1429 HILOG_ERROR("DoProcess failed or replaceWant not exist");
1430 return result;
1431 }
1432 if (result != ERR_OK && isReplaceWantExist) {
1433 std::string dialogSessionId;
1434 std::vector<DialogAppInfo> dialogAppInfos(1);
1435 if (GenerateDialogSessionRecord(abilityRequest, GetUserId(), dialogSessionId, dialogAppInfos, false)) {
1436 HILOG_DEBUG("create dialog by ui extension");
1437 return CreateModalDialog(newWant, callerToken, dialogSessionId);
1438 }
1439 HILOG_ERROR("create dialog by ui extension failed");
1440 return INNER_ERR;
1441 }
1442
1443 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1444 abilityRequest.userId = oriValidUserId;
1445 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1446 return uiAbilityLifecycleManager_->NotifySCBToStartUIAbility(abilityRequest, oriValidUserId);
1447 }
1448 auto missionListManager = GetListManagerByUserId(oriValidUserId);
1449 if (missionListManager == nullptr) {
1450 HILOG_ERROR("missionListManager is Null. userId=%{public}d", oriValidUserId);
1451 eventInfo.errCode = ERR_INVALID_VALUE;
1452 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1453 return ERR_INVALID_VALUE;
1454 }
1455
1456 auto ret = missionListManager->StartAbility(abilityRequest);
1457 if (ret != ERR_OK) {
1458 eventInfo.errCode = ret;
1459 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1460 }
1461 return ret;
1462 }
1463
RequestDialogService(const Want & want,const sptr<IRemoteObject> & callerToken)1464 int32_t AbilityManagerService::RequestDialogService(const Want &want, const sptr<IRemoteObject> &callerToken)
1465 {
1466 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1467 auto flags = want.GetFlags();
1468 if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
1469 HILOG_ERROR("RequestDialogService with continuation flags is not allowed!");
1470 return ERR_INVALID_CONTINUATION_FLAG;
1471 }
1472
1473 HILOG_INFO("request dialog service, target is %{public}s", want.GetElement().GetURI().c_str());
1474 return RequestDialogServiceInner(want, callerToken, -1, -1);
1475 }
1476
ReportDrawnCompleted(const sptr<IRemoteObject> & callerToken)1477 int32_t AbilityManagerService::ReportDrawnCompleted(const sptr<IRemoteObject> &callerToken)
1478 {
1479 HILOG_DEBUG("called.");
1480 if (callerToken == nullptr) {
1481 HILOG_ERROR("callerToken is nullptr");
1482 return INNER_ERR;
1483 }
1484
1485 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1486 if (abilityRecord == nullptr) {
1487 HILOG_ERROR("abilityRecord is nullptr");
1488 return INNER_ERR;
1489 }
1490 auto abilityInfo = abilityRecord->GetAbilityInfo();
1491
1492 EventInfo eventInfo;
1493 eventInfo.userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
1494 eventInfo.pid = IPCSkeleton::GetCallingPid();
1495 eventInfo.bundleName = abilityInfo.bundleName;
1496 eventInfo.moduleName = abilityInfo.moduleName;
1497 eventInfo.abilityName = abilityInfo.name;
1498 EventReport::SendAppEvent(EventName::DRAWN_COMPLETED, HiSysEventType::BEHAVIOR, eventInfo);
1499 return ERR_OK;
1500 }
1501
RequestDialogServiceInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1502 int32_t AbilityManagerService::RequestDialogServiceInner(const Want &want, const sptr<IRemoteObject> &callerToken,
1503 int requestCode, int32_t userId)
1504 {
1505 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1506 if (callerToken == nullptr || !VerificationAllToken(callerToken)) {
1507 HILOG_WARN("caller is invalid.");
1508 return ERR_INVALID_CALLER;
1509 }
1510
1511 {
1512 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1513 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1514 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1515 HILOG_ERROR("%{public}s: Permission verification failed.", __func__);
1516 return CHECK_PERMISSION_FAILED;
1517 }
1518
1519 if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1520 HILOG_ERROR("Cannot handle dlp by RequestDialogService.");
1521 return ERR_WRONG_INTERFACE_CALL;
1522 }
1523 }
1524
1525 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1526 interceptorExecuter_->DoProcess(want, requestCode, GetUserId(), true);
1527 if (result != ERR_OK) {
1528 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
1529 return result;
1530 }
1531
1532 int32_t oriValidUserId = GetValidUserId(userId);
1533 int32_t validUserId = oriValidUserId;
1534 if (!JudgeMultiUserConcurrency(validUserId)) {
1535 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
1536 return ERR_CROSS_USER;
1537 }
1538
1539 AbilityRequest abilityRequest;
1540 result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1541 if (result != ERR_OK) {
1542 HILOG_ERROR("Generate ability request local error when RequestDialogService.");
1543 return result;
1544 }
1545 UpdateCallerInfo(abilityRequest.want, callerToken);
1546
1547 auto abilityInfo = abilityRequest.abilityInfo;
1548 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1549 HILOG_DEBUG("userId is : %{public}d, singleton is : %{public}d",
1550 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1551
1552 result = CheckStaticCfgPermission(abilityInfo, false, -1);
1553 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1554 HILOG_ERROR("CheckStaticCfgPermission error, result is %{public}d.", result);
1555 return ERR_STATIC_CFG_PERMISSION;
1556 }
1557
1558 auto type = abilityInfo.type;
1559 if (type == AppExecFwk::AbilityType::PAGE) {
1560 result = CheckCallAbilityPermission(abilityRequest);
1561 if (result != ERR_OK) {
1562 HILOG_ERROR("Check permission failed");
1563 return result;
1564 }
1565 } else if (type == AppExecFwk::AbilityType::EXTENSION &&
1566 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
1567 HILOG_DEBUG("Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
1568 result = CheckCallServicePermission(abilityRequest);
1569 if (result != ERR_OK) {
1570 HILOG_ERROR("Check permission failed");
1571 return result;
1572 }
1573 } else {
1574 HILOG_ERROR("RequestDialogService do not support other component.");
1575 return ERR_WRONG_INTERFACE_CALL;
1576 }
1577
1578 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1579 afterCheckExecuter_->DoProcess(abilityRequest.want, requestCode, GetUserId(), true, callerToken);
1580 if (result != ERR_OK) {
1581 HILOG_ERROR("afterCheckExecuter_ is nullptr or DoProcess return error.");
1582 return result;
1583 }
1584
1585 if (type == AppExecFwk::AbilityType::EXTENSION) {
1586 auto connectManager = GetConnectManagerByUserId(validUserId);
1587 if (!connectManager) {
1588 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", validUserId);
1589 return ERR_INVALID_VALUE;
1590 }
1591 HILOG_DEBUG("request dialog service, start service extension,name is %{public}s.", abilityInfo.name.c_str());
1592 ReportEventToSuspendManager(abilityInfo);
1593 return connectManager->StartAbility(abilityRequest);
1594 }
1595
1596 if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1597 HILOG_ERROR("IsAbilityControllerStart failed : %{public}s.", abilityInfo.bundleName.c_str());
1598 return ERR_WOULD_BLOCK;
1599 }
1600 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1601 ReportEventToSuspendManager(abilityInfo);
1602 abilityRequest.userId = oriValidUserId;
1603 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1604 return uiAbilityLifecycleManager_->NotifySCBToStartUIAbility(abilityRequest, oriValidUserId);
1605 }
1606 auto missionListManager = GetListManagerByUserId(oriValidUserId);
1607 if (missionListManager == nullptr) {
1608 HILOG_ERROR("missionListManager is nullptr. userId:%{public}d", validUserId);
1609 return ERR_INVALID_VALUE;
1610 }
1611 ReportAbilitStartInfoToRSS(abilityInfo);
1612 ReportEventToSuspendManager(abilityInfo);
1613 HILOG_DEBUG("RequestDialogService, start ability, name is %{public}s.", abilityInfo.name.c_str());
1614 return missionListManager->StartAbility(abilityRequest);
1615 }
1616
StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo)1617 int AbilityManagerService::StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo)
1618 {
1619 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1620 HILOG_DEBUG("Call.");
1621 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
1622 HILOG_ERROR("sessionInfo is nullptr");
1623 return ERR_INVALID_VALUE;
1624 }
1625
1626 if (sessionInfo->userId == DEFAULT_INVAL_VALUE) {
1627 sessionInfo->userId = GetUserId();
1628 } else if (sessionInfo->userId != GetUserId()) {
1629 HILOG_ERROR("this userId is not valid");
1630 return ERR_CROSS_USER;
1631 }
1632
1633 auto currentUserId = GetUserId();
1634 EventInfo eventInfo = BuildEventInfo(sessionInfo->want, currentUserId);
1635 EventReport::SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1636
1637 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
1638 HILOG_ERROR("Not sceneboard called, not allowed.");
1639 return ERR_WRONG_INTERFACE_CALL;
1640 }
1641
1642 auto requestCode = sessionInfo->requestCode;
1643 if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
1644 HILOG_DEBUG("interceptorExecuter_ called.");
1645 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1646 interceptorExecuter_->DoProcess(sessionInfo->want, requestCode, currentUserId, true);
1647 if (result != ERR_OK) {
1648 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
1649 eventInfo.errCode = result;
1650 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1651 return result;
1652 }
1653 }
1654
1655 AbilityRequest abilityRequest;
1656 auto result = GenerateAbilityRequest(sessionInfo->want, requestCode, abilityRequest,
1657 sessionInfo->callerToken, currentUserId);
1658 if (result != ERR_OK) {
1659 HILOG_ERROR("Generate ability request local error.");
1660 return result;
1661 }
1662 abilityRequest.collaboratorType = sessionInfo->collaboratorType;
1663
1664 auto abilityInfo = abilityRequest.abilityInfo;
1665 if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall() &&
1666 abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1667 HILOG_ERROR("Only support for page type ability.");
1668 return ERR_INVALID_VALUE;
1669 }
1670
1671 if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
1672 HILOG_DEBUG("afterCheckExecuter_ called.");
1673 Want newWant = abilityRequest.want;
1674 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1675 afterCheckExecuter_->DoProcess(newWant, requestCode, GetUserId(), true, sessionInfo->callerToken);
1676 bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1677 newWant.RemoveParam("queryWantFromErms");
1678 if (result != ERR_OK) {
1679 if (isReplaceWantExist == false) {
1680 HILOG_ERROR("DoProcess failed or replaceWant not exist");
1681 return result;
1682 }
1683 auto systemUIExtension = std::make_shared<OHOS::Rosen::ModalSystemUiExtension>();
1684 return systemUIExtension->CreateModalUIExtension(newWant) ?
1685 ERR_ECOLOGICAL_CONTROL_STATUS : INNER_ERR;
1686 }
1687 }
1688
1689 if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1690 result = PreLoadAppDataAbilities(abilityInfo.bundleName, currentUserId);
1691 if (result != ERR_OK) {
1692 HILOG_ERROR("StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
1693 abilityInfo.bundleName.c_str(), result);
1694 return result;
1695 }
1696 }
1697
1698 if (uiAbilityLifecycleManager_ == nullptr) {
1699 HILOG_ERROR("uiAbilityLifecycleManager_ is nullptr");
1700 return ERR_INVALID_VALUE;
1701 }
1702 ReportAbilitStartInfoToRSS(abilityInfo);
1703 ReportAbilitAssociatedStartInfoToRSS(abilityInfo, static_cast<int64_t>(
1704 ResourceSchedule::ResType::AssociatedStartType::SCB_START_ABILITY), sessionInfo->callerToken);
1705 return uiAbilityLifecycleManager_->StartUIAbility(abilityRequest, sessionInfo);
1706 }
1707
CheckCallingTokenId(const std::string & bundleName)1708 bool AbilityManagerService::CheckCallingTokenId(const std::string &bundleName)
1709 {
1710 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1711 auto bms = GetBundleManager();
1712 if (bms == nullptr) {
1713 HILOG_ERROR("bms is invalid.");
1714 return false;
1715 }
1716 AppExecFwk::ApplicationInfo appInfo;
1717 IN_PROCESS_CALL_WITHOUT_RET(bms->GetApplicationInfo(bundleName,
1718 AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, GetUserId(), appInfo));
1719 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
1720 if (accessTokenId != appInfo.accessTokenId) {
1721 HILOG_ERROR("Permission verification failed");
1722 return false;
1723 }
1724 return true;
1725 }
1726
IsBackgroundTaskUid(const int uid)1727 bool AbilityManagerService::IsBackgroundTaskUid(const int uid)
1728 {
1729 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
1730 std::lock_guard<ffrt::mutex> lock(bgtaskObserverMutex_);
1731 if (bgtaskObserver_) {
1732 return bgtaskObserver_->IsBackgroundTaskUid(uid);
1733 }
1734 return false;
1735 #else
1736 return false;
1737 #endif
1738 }
1739
IsDmsAlive() const1740 bool AbilityManagerService::IsDmsAlive() const
1741 {
1742 return g_isDmsAlive.load();
1743 }
1744
AppUpgradeCompleted(const std::string & bundleName,int32_t uid)1745 void AbilityManagerService::AppUpgradeCompleted(const std::string &bundleName, int32_t uid)
1746 {
1747 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
1748 HILOG_ERROR("Not sa call");
1749 return;
1750 }
1751
1752 auto bms = GetBundleManager();
1753 CHECK_POINTER(bms);
1754 auto userId = uid / BASE_USER_RANGE;
1755
1756 AppExecFwk::BundleInfo bundleInfo;
1757 if (!IN_PROCESS_CALL(
1758 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId))) {
1759 HILOG_ERROR("Failed to get bundle info.");
1760 return;
1761 }
1762
1763 RecordAppExitReasonAtUpgrade(bundleInfo);
1764
1765 if (userId != U0_USER_ID) {
1766 HILOG_ERROR("Application upgrade for non U0 users.");
1767 return;
1768 }
1769
1770 if (!bundleInfo.isKeepAlive) {
1771 HILOG_WARN("Not a resident application.");
1772 return;
1773 }
1774
1775 std::vector<AppExecFwk::BundleInfo> bundleInfos = { bundleInfo };
1776 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos);
1777
1778 if (!bundleInfos.empty()) {
1779 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
1780 }
1781 }
1782
RecordAppExitReason(Reason exitReason)1783 int32_t AbilityManagerService::RecordAppExitReason(Reason exitReason)
1784 {
1785 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !currentMissionListManager_) {
1786 HILOG_ERROR("currentMissionListManager_ is null.");
1787 return ERR_NULL_OBJECT;
1788 }
1789
1790 auto bms = GetBundleManager();
1791 CHECK_POINTER_AND_RETURN(bms, ERR_NULL_OBJECT);
1792
1793 std::string bundleName;
1794 int32_t callerUid = IPCSkeleton::GetCallingUid();
1795 if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
1796 HILOG_ERROR("Get Bundle Name failed.");
1797 return ERR_INVALID_VALUE;
1798 }
1799
1800 std::vector<std::string> abilityList;
1801 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1802 uiAbilityLifecycleManager_->GetActiveAbilityList(bundleName, abilityList);
1803 } else {
1804 currentMissionListManager_->GetActiveAbilityList(bundleName, abilityList);
1805 }
1806
1807 return DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->SetAppExitReason(
1808 bundleName, abilityList, exitReason);
1809 }
1810
ForceExitApp(const int32_t pid,Reason exitReason)1811 int32_t AbilityManagerService::ForceExitApp(const int32_t pid, Reason exitReason)
1812 {
1813 if (exitReason < REASON_UNKNOWN || exitReason > REASON_UPGRADE) {
1814 HILOG_ERROR("Force exit reason invalid.");
1815 return ERR_INVALID_VALUE;
1816 }
1817
1818 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
1819 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
1820 HILOG_ERROR("Not sa or shell call");
1821 return ERR_PERMISSION_DENIED;
1822 }
1823
1824 std::string bundleName;
1825 int32_t uid;
1826 DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(pid, bundleName, uid);
1827 if (bundleName.empty()) {
1828 HILOG_ERROR("Get bundle name by pid failed.");
1829 return ERR_INVALID_VALUE;
1830 }
1831
1832 int32_t targetUserId = uid / BASE_USER_RANGE;
1833 std::vector<std::string> abilityLists;
1834 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1835 uiAbilityLifecycleManager_->GetActiveAbilityList(bundleName, abilityLists, targetUserId);
1836 } else if (targetUserId == U0_USER_ID) {
1837 std::lock_guard lock(managersMutex_);
1838 for (auto item: missionListManagers_) {
1839 if (item.second) {
1840 std::vector<std::string> abilityList;
1841 item.second->GetActiveAbilityList(bundleName, abilityList);
1842 if (!abilityList.empty()) {
1843 abilityLists.insert(abilityLists.end(), abilityList.begin(), abilityList.end());
1844 }
1845 }
1846 }
1847 } else {
1848 auto listManager = GetListManagerByUserId(targetUserId);
1849 if (listManager) {
1850 listManager->GetActiveAbilityList(bundleName, abilityLists);
1851 }
1852 }
1853
1854 int32_t result = DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->SetAppExitReason(
1855 bundleName, abilityLists, exitReason);
1856
1857 DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName);
1858
1859 return result;
1860 }
1861
GetConfiguration(AppExecFwk::Configuration & config)1862 int32_t AbilityManagerService::GetConfiguration(AppExecFwk::Configuration& config)
1863 {
1864 auto appMgr = GetAppMgr();
1865 if (appMgr == nullptr) {
1866 HILOG_WARN("GetAppMgr failed");
1867 return -1;
1868 }
1869
1870 return appMgr->GetConfiguration(config);
1871 }
1872
GetAppMgr()1873 OHOS::sptr<OHOS::AppExecFwk::IAppMgr> AbilityManagerService::GetAppMgr()
1874 {
1875 if (appMgr_) {
1876 return appMgr_;
1877 }
1878
1879 OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
1880 OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
1881 if (!systemAbilityManager) {
1882 return nullptr;
1883 }
1884 OHOS::sptr<OHOS::IRemoteObject> object = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID);
1885 appMgr_ = OHOS::iface_cast<OHOS::AppExecFwk::IAppMgr>(object);
1886 return appMgr_;
1887 }
1888
CheckOptExtensionAbility(const Want & want,AbilityRequest & abilityRequest,int32_t validUserId,AppExecFwk::ExtensionAbilityType extensionType)1889 int AbilityManagerService::CheckOptExtensionAbility(const Want &want, AbilityRequest &abilityRequest,
1890 int32_t validUserId, AppExecFwk::ExtensionAbilityType extensionType)
1891 {
1892 auto abilityInfo = abilityRequest.abilityInfo;
1893 auto type = abilityInfo.type;
1894 if (type != AppExecFwk::AbilityType::EXTENSION) {
1895 HILOG_ERROR("Not extension ability, not allowed.");
1896 return ERR_WRONG_INTERFACE_CALL;
1897 }
1898 if (extensionType != AppExecFwk::ExtensionAbilityType::UNSPECIFIED &&
1899 extensionType != abilityInfo.extensionAbilityType) {
1900 HILOG_ERROR("Extension ability type not match, set type: %{public}d, real type: %{public}d",
1901 static_cast<int32_t>(extensionType), static_cast<int32_t>(abilityInfo.extensionAbilityType));
1902 return ERR_WRONG_INTERFACE_CALL;
1903 }
1904
1905 auto result = CheckStaticCfgPermission(abilityInfo, false, -1);
1906 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1907 HILOG_ERROR("CheckStaticCfgPermission error, result is %{public}d.", result);
1908 return ERR_STATIC_CFG_PERMISSION;
1909 }
1910
1911 if (extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
1912 extensionType == AppExecFwk::ExtensionAbilityType::SERVICE) {
1913 result = CheckCallServiceExtensionPermission(abilityRequest);
1914 if (result != ERR_OK) {
1915 return result;
1916 }
1917 } else {
1918 result = CheckCallOtherExtensionPermission(abilityRequest);
1919 if (result != ERR_OK) {
1920 return result;
1921 }
1922 }
1923
1924 UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
1925 return ERR_OK;
1926 }
1927
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)1928 void AbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
1929 {
1930 HILOG_INFO("systemAbilityId: %{public}d add", systemAbilityId);
1931 switch (systemAbilityId) {
1932 case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
1933 SubscribeBackgroundTask();
1934 break;
1935 }
1936 case DISTRIBUTED_SCHED_SA_ID: {
1937 g_isDmsAlive.store(true);
1938 break;
1939 }
1940 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
1941 SubscribeBundleEventCallback();
1942 break;
1943 }
1944 default:
1945 break;
1946 }
1947 }
1948
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)1949 void AbilityManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
1950 {
1951 HILOG_INFO("systemAbilityId: %{public}d remove", systemAbilityId);
1952 switch (systemAbilityId) {
1953 case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
1954 UnSubscribeBackgroundTask();
1955 break;
1956 }
1957 case DISTRIBUTED_SCHED_SA_ID: {
1958 g_isDmsAlive.store(false);
1959 break;
1960 }
1961 case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
1962 UnsubscribeBundleEventCallback();
1963 break;
1964 }
1965 default:
1966 break;
1967 }
1968 }
1969
SubscribeBackgroundTask()1970 void AbilityManagerService::SubscribeBackgroundTask()
1971 {
1972 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
1973 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
1974 if (!bgtaskObserver_) {
1975 bgtaskObserver_ = std::make_shared<BackgroundTaskObserver>();
1976 }
1977 int ret = BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver_);
1978 if (ret != ERR_OK) {
1979 HILOG_ERROR("%{public}s failed, err:%{public}d.", __func__, ret);
1980 return;
1981 }
1982 bgtaskObserver_->GetContinuousTaskApps();
1983 HILOG_INFO("%{public}s success.", __func__);
1984 #endif
1985 }
1986
UnSubscribeBackgroundTask()1987 void AbilityManagerService::UnSubscribeBackgroundTask()
1988 {
1989 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
1990 std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
1991 if (!bgtaskObserver_) {
1992 return;
1993 }
1994 HILOG_INFO("%{public}s success.", __func__);
1995 #endif
1996 }
1997
SubscribeBundleEventCallback()1998 void AbilityManagerService::SubscribeBundleEventCallback()
1999 {
2000 HILOG_DEBUG("SubscribeBundleEventCallback to receive hap updates.");
2001 if (abilityBundleEventCallback_) {
2002 return;
2003 }
2004
2005 // Register abilityBundleEventCallback to receive hap updates
2006 abilityBundleEventCallback_ =
2007 new (std::nothrow) AbilityBundleEventCallback(taskHandler_, abilityAutoStartupService_);
2008 auto bms = GetBundleManager();
2009 if (bms) {
2010 bool ret = IN_PROCESS_CALL(bms->RegisterBundleEventCallback(abilityBundleEventCallback_));
2011 if (!ret) {
2012 HILOG_ERROR("RegisterBundleEventCallback failed!");
2013 }
2014 } else {
2015 HILOG_ERROR("Get BundleManager failed!");
2016 }
2017 HILOG_DEBUG("SubscribeBundleEventCallback success.");
2018 }
2019
UnsubscribeBundleEventCallback()2020 void AbilityManagerService::UnsubscribeBundleEventCallback()
2021 {
2022 if (!abilityBundleEventCallback_) {
2023 return;
2024 }
2025 abilityBundleEventCallback_ = nullptr;
2026 HILOG_DEBUG("UnsubscribeBundleEventCallback success.");
2027 }
2028
ReportAbilitStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo)2029 void AbilityManagerService::ReportAbilitStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo)
2030 {
2031 #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE
2032 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2033 if (abilityInfo.type == AppExecFwk::AbilityType::PAGE &&
2034 abilityInfo.launchMode != AppExecFwk::LaunchMode::SPECIFIED) {
2035 std::vector<AppExecFwk::RunningProcessInfo> runningProcessInfos;
2036 if (IN_PROCESS_CALL(GetProcessRunningInfos(runningProcessInfos)) != ERR_OK) {
2037 return;
2038 }
2039 bool isColdStart = true;
2040 int32_t pid = 0;
2041 for (auto const &info : runningProcessInfos) {
2042 if (info.uid_ == abilityInfo.applicationInfo.uid) {
2043 isColdStart = false;
2044 pid = info.pid_;
2045 break;
2046 }
2047 }
2048 std::unordered_map<std::string, std::string> eventParams {
2049 { "name", "ability_start" },
2050 { "uid", std::to_string(abilityInfo.applicationInfo.uid) },
2051 { "bundleName", abilityInfo.applicationInfo.bundleName },
2052 { "abilityName", abilityInfo.name },
2053 { "pid", std::to_string(pid) }
2054 };
2055 ResourceSchedule::ResSchedClient::GetInstance().ReportData(
2056 ResourceSchedule::ResType::RES_TYPE_APP_ABILITY_START, isColdStart ? 1 : 0, eventParams);
2057 }
2058 #endif
2059 }
2060
ReportAbilitAssociatedStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo,int64_t type,const sptr<IRemoteObject> & callerToken)2061 void AbilityManagerService::ReportAbilitAssociatedStartInfoToRSS(
2062 const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr<IRemoteObject> &callerToken)
2063 {
2064 #ifdef RESOURCE_SCHEDULE_SERVICE_ENABLE
2065 if (callerToken == nullptr) {
2066 HILOG_WARN("associated start caller token is nullptr");
2067 return;
2068 }
2069
2070 auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2071 if (callerAbility == nullptr) {
2072 HILOG_WARN("associated start caller ability is nullptr");
2073 return;
2074 }
2075 int32_t callerUid = callerAbility->GetUid();
2076 int32_t callerPid = callerAbility->GetPid();
2077 std::unordered_map<std::string, std::string> eventParams {
2078 { "name", "associated_start" },
2079 { "caller_uid", std::to_string(callerUid) },
2080 { "caller_pid", std::to_string(callerPid) },
2081 { "callee_uid", std::to_string(abilityInfo.applicationInfo.uid) },
2082 { "callee_bundle_name", abilityInfo.applicationInfo.bundleName }
2083 };
2084 ResourceSchedule::ResSchedClient::GetInstance().ReportData(
2085 ResourceSchedule::ResType::RES_TYPE_APP_ASSOCIATED_START, type, eventParams);
2086 #endif
2087 }
2088
ReportEventToSuspendManager(const AppExecFwk::AbilityInfo & abilityInfo)2089 void AbilityManagerService::ReportEventToSuspendManager(const AppExecFwk::AbilityInfo &abilityInfo)
2090 {
2091 #ifdef EFFICIENCY_MANAGER_ENABLE
2092 std::string reason = (abilityInfo.type == AppExecFwk::AbilityType::PAGE) ?
2093 "THAW_BY_START_PAGE_ABILITY" : "THAW_BY_START_NOT_PAGE_ABILITY";
2094 SuspendManager::SuspendManagerClient::GetInstance().ThawOneApplication(
2095 abilityInfo.applicationInfo.uid,
2096 abilityInfo.applicationInfo.bundleName, reason);
2097 #endif // EFFICIENCY_MANAGER_ENABLE
2098 }
2099
RegisterSuspendObserver()2100 void AbilityManagerService::RegisterSuspendObserver()
2101 {
2102 #ifdef EFFICIENCY_MANAGER_ENABLE
2103 if (!taskHandler_) {
2104 HILOG_ERROR("taskhandler null");
2105 return;
2106 }
2107 taskHandler_->SubmitTask([taskHandler = taskHandler_]() {
2108 ProcessFrozenStateObserver::RegisterSuspendObserver(taskHandler);
2109 });
2110 #endif // EFFICIENCY_MANAGER_ENABLE
2111 }
2112
StartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2113 int AbilityManagerService::StartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2114 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2115 {
2116 InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2117 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
2118 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false);
2119 }
2120 return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true);
2121 }
2122
RequestModalUIExtension(const Want & want)2123 int AbilityManagerService::RequestModalUIExtension(const Want &want)
2124 {
2125 CHECK_CALLER_IS_SYSTEM_APP;
2126 return RequestModalUIExtensionInner(want);
2127 }
2128
RequestModalUIExtensionInner(const Want & want)2129 int AbilityManagerService::RequestModalUIExtensionInner(const Want &want)
2130 {
2131 sptr<IRemoteObject> token = nullptr;
2132 int ret = IN_PROCESS_CALL(GetTopAbility(token));
2133 if (ret != ERR_OK || token == nullptr) {
2134 HILOG_ERROR("token is nullptr.");
2135 return ERR_INVALID_VALUE;
2136 }
2137
2138 // Gets the record corresponding to the current focus appliaction
2139 auto record = Token::GetAbilityRecordByToken(token);
2140 if (!record) {
2141 HILOG_ERROR("Record is nullptr.");
2142 return ERR_INVALID_VALUE;
2143 }
2144
2145 // Gets the abilityName, bundleName, modulename corresponding to the current focus appliaction
2146 EventInfo focusInfo;
2147 focusInfo.bundleName = record->GetAbilityInfo().bundleName;
2148
2149 // Gets the abilityName, bundleName, modulename corresponding to the caller appliaction
2150 EventInfo callerInfo;
2151 callerInfo.bundleName = want.GetParams().GetStringParam("bundleName");
2152 HILOG_INFO("focusbundlname: %{public}s, callerbundlname: %{public}s.",
2153 focusInfo.bundleName.c_str(), callerInfo.bundleName.c_str());
2154
2155 // Compare
2156 if (record->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
2157 focusInfo.bundleName == callerInfo.bundleName) {
2158 HILOG_DEBUG("CreateModalUIExtension is called!");
2159 return record->CreateModalUIExtension(want);
2160 }
2161
2162 HILOG_DEBUG("Window Modal System Create UIExtension is called!");
2163 auto connection = std::make_shared<Rosen::ModalSystemUiExtension>();
2164 return connection->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR;
2165 }
2166
StartExtensionAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType,bool checkSystemCaller)2167 int AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
2168 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller)
2169 {
2170 HILOG_DEBUG("Start extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
2171 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
2172 if (checkSystemCaller) {
2173 CHECK_CALLER_IS_SYSTEM_APP;
2174 }
2175 EventInfo eventInfo = BuildEventInfo(want, userId);
2176 eventInfo.extensionType = static_cast<int32_t>(extensionType);
2177 EventReport::SendExtensionEvent(EventName::START_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
2178
2179 auto result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::START_EXTENSION_ERROR);
2180 if (result != ERR_OK) {
2181 HILOG_ERROR("CheckDlpForExtension error.");
2182 return result;
2183 }
2184
2185 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2186 HILOG_ERROR("%{public}s VerificationAllToken failed.", __func__);
2187 eventInfo.errCode = ERR_INVALID_VALUE;
2188 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2189 return ERR_INVALID_CALLER;
2190 }
2191
2192 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2193 interceptorExecuter_->DoProcess(want, 0, GetUserId(), false);
2194 if (result != ERR_OK) {
2195 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
2196 eventInfo.errCode = result;
2197 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2198 return result;
2199 }
2200
2201 int32_t validUserId = GetValidUserId(userId);
2202 if (!JudgeMultiUserConcurrency(validUserId)) {
2203 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
2204 eventInfo.errCode = ERR_INVALID_VALUE;
2205 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2206 return ERR_CROSS_USER;
2207 }
2208
2209 AbilityRequest abilityRequest;
2210 #ifdef SUPPORT_GRAPHICS
2211 if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
2212 abilityRequest.Voluation(want, DEFAULT_INVAL_VALUE, callerToken);
2213 abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
2214 abilityRequest.extensionType = extensionType;
2215 CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
2216 result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
2217 if (result != ERR_OK) {
2218 HILOG_ERROR("implicit start ability error.");
2219 eventInfo.errCode = result;
2220 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2221 }
2222 return result;
2223 }
2224 #endif
2225 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2226 if (result != ERR_OK) {
2227 HILOG_ERROR("Generate ability request local error.");
2228 eventInfo.errCode = result;
2229 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2230 return result;
2231 }
2232
2233 auto abilityInfo = abilityRequest.abilityInfo;
2234 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2235 HILOG_DEBUG("userId is : %{public}d, singleton is : %{public}d",
2236 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2237
2238 result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
2239 if (result != ERR_OK) {
2240 HILOG_ERROR("CheckOptExtensionAbility error.");
2241 eventInfo.errCode = result;
2242 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2243 return result;
2244 }
2245
2246 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2247 afterCheckExecuter_->DoProcess(abilityRequest.want, 0, GetUserId(), false, callerToken);
2248 if (result != ERR_OK) {
2249 HILOG_ERROR("afterCheckExecuter_ is nullptr or DoProcess return error.");
2250 return result;
2251 }
2252
2253 auto connectManager = GetConnectManagerByUserId(validUserId);
2254 if (!connectManager) {
2255 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", validUserId);
2256 eventInfo.errCode = ERR_INVALID_VALUE;
2257 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2258 return ERR_INVALID_VALUE;
2259 }
2260 UpdateCallerInfo(abilityRequest.want, callerToken);
2261 HILOG_DEBUG("Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
2262 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
2263 if (eventInfo.errCode != ERR_OK) {
2264 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2265 }
2266 ReportAbilitAssociatedStartInfoToRSS(abilityRequest.abilityInfo, static_cast<int64_t>(
2267 ResourceSchedule::ResType::AssociatedStartType::EXTENSION_START_ABILITY), callerToken);
2268 return eventInfo.errCode;
2269 }
2270
SetPickerElementName(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)2271 void AbilityManagerService::SetPickerElementName(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
2272 {
2273 CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
2274 std::string targetType = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TARGET_TYPE_KEY);
2275 if (extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
2276 extensionSessionInfo->want.GetElement().GetAbilityName().empty() && !targetType.empty()) {
2277 std::string abilityName;
2278 std::string bundleName;
2279 std::string pickerType;
2280 std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
2281 auto pickerMap = AmsConfigurationParameter::GetInstance().GetPickerMap();
2282 auto it = pickerMap.find(targetType);
2283 if (it == pickerMap.end()) {
2284 HILOG_ERROR("can not find the targetType: %{public}s", targetType.c_str());
2285 return;
2286 }
2287 pickerType = it->second;
2288 auto bms = GetBundleManager();
2289 CHECK_POINTER(bms);
2290 int32_t validUserId = GetValidUserId(userId);
2291 HILOG_INFO("targetType: %{public}s, pickerType: %{public}s, userId: %{public}d",
2292 targetType.c_str(), pickerType.c_str(), validUserId);
2293 auto ret = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfosOnlyWithTypeName(pickerType,
2294 static_cast<int32_t>(AppExecFwk::GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION),
2295 validUserId,
2296 extensionInfos));
2297 if (ret != ERR_OK) {
2298 HILOG_ERROR("QueryExtensionAbilityInfosOnlyWithTypeName failed");
2299 return;
2300 }
2301 abilityName = extensionInfos[0].name;
2302 bundleName = extensionInfos[0].bundleName;
2303 HILOG_INFO("abilityName: %{public}s, bundleName: %{public}s", abilityName.c_str(), bundleName.c_str());
2304 extensionSessionInfo->want.SetElementName(bundleName, abilityName);
2305 WantParams ¶meters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
2306 parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box(pickerType));
2307 extensionSessionInfo->want.SetParams(parameters);
2308 }
2309 }
2310
SetAutoFillElementName(const sptr<SessionInfo> & extensionSessionInfo)2311 void AbilityManagerService::SetAutoFillElementName(const sptr<SessionInfo> &extensionSessionInfo)
2312 {
2313 HILOG_DEBUG("Called.");
2314 CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
2315 if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) != AUTO_FILL_PASSWORD_TPYE) {
2316 return;
2317 }
2318 std::vector<std::string> argList;
2319 SplitStr(KEY_AUTO_FILL_ABILITY, "/", argList);
2320 if (argList.size() != ARGC_THREE) {
2321 HILOG_ERROR("Parse auto fill extension element name failed.");
2322 return;
2323 }
2324 extensionSessionInfo->want.SetElementName(argList[INDEX_ZERO], argList[INDEX_TWO]);
2325 extensionSessionInfo->want.SetModuleName(argList[INDEX_ONE]);
2326 }
2327
StartUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)2328 int AbilityManagerService::StartUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
2329 {
2330 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2331 HILOG_DEBUG("Start ui extension ability come");
2332 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
2333 SetPickerElementName(extensionSessionInfo, userId);
2334 SetAutoFillElementName(extensionSessionInfo);
2335 std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY);
2336 AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ?
2337 AppExecFwk::ExtensionAbilityType::UI : AppExecFwk::ConvertToExtensionAbilityType(extensionTypeStr);
2338 EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, userId);
2339 eventInfo.extensionType = static_cast<int32_t>(extensionType);
2340 EventReport::SendExtensionEvent(EventName::START_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
2341
2342 if (InsightIntentExecuteParam::IsInsightIntentExecute(extensionSessionInfo->want)) {
2343 int32_t result = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateWant(
2344 extensionSessionInfo->want, AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY);
2345 if (result != ERR_OK) {
2346 return result;
2347 }
2348 }
2349
2350 sptr<IRemoteObject> callerToken = extensionSessionInfo->callerToken;
2351
2352 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, extensionSessionInfo->want) ||
2353 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
2354 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, extensionSessionInfo->want)) {
2355 HILOG_ERROR("StartUIExtensionAbility: Permission verification failed.");
2356 eventInfo.errCode = CHECK_PERMISSION_FAILED;
2357 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2358 return CHECK_PERMISSION_FAILED;
2359 }
2360
2361 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2362 HILOG_ERROR("StartUIExtensionAbility VerificationAllToken failed.");
2363 eventInfo.errCode = ERR_INVALID_VALUE;
2364 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2365 return ERR_INVALID_CALLER;
2366 }
2367
2368 auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
2369 if (callerRecord == nullptr || !JudgeSelfCalled(callerRecord)) {
2370 HILOG_ERROR("invalid callerToken.");
2371 eventInfo.errCode = ERR_INVALID_VALUE;
2372 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2373 return ERR_INVALID_CALLER;
2374 }
2375
2376 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2377 interceptorExecuter_->DoProcess(extensionSessionInfo->want, 0, GetUserId(), false);
2378 if (result != ERR_OK) {
2379 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
2380 eventInfo.errCode = result;
2381 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2382 return result;
2383 }
2384
2385 int32_t validUserId = GetValidUserId(userId);
2386 if (!JudgeMultiUserConcurrency(validUserId)) {
2387 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
2388 eventInfo.errCode = ERR_INVALID_VALUE;
2389 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2390 return ERR_INVALID_VALUE;
2391 }
2392
2393 if (ImplicitStartProcessor::IsImplicitStartAction(extensionSessionInfo->want)) {
2394 HILOG_ERROR("UI extension ability donot support implicit start.");
2395 eventInfo.errCode = ERR_INVALID_VALUE;
2396 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2397 return ERR_INVALID_VALUE;
2398 }
2399
2400 AbilityRequest abilityRequest;
2401 abilityRequest.Voluation(extensionSessionInfo->want, DEFAULT_INVAL_VALUE, callerToken);
2402 abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
2403 abilityRequest.sessionInfo = extensionSessionInfo;
2404 result = GenerateEmbeddableUIAbilityRequest(extensionSessionInfo->want, abilityRequest, callerToken, validUserId);
2405 CHECK_POINTER_AND_RETURN(abilityRequest.sessionInfo, ERR_INVALID_VALUE);
2406 abilityRequest.sessionInfo->uiExtensionComponentId = (
2407 static_cast<uint64_t>(callerRecord->GetRecordId()) << OFFSET) |
2408 static_cast<uint64_t>(abilityRequest.sessionInfo->persistentId);
2409 HILOG_DEBUG("UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
2410 abilityRequest.sessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
2411 if (result != ERR_OK) {
2412 HILOG_ERROR("Generate ability request local error.");
2413 eventInfo.errCode = result;
2414 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2415 return result;
2416 }
2417 abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
2418
2419 auto abilityInfo = abilityRequest.abilityInfo;
2420 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2421 HILOG_DEBUG("userId is : %{public}d, singleton is : %{public}d",
2422 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2423
2424 result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType);
2425 if (result != ERR_OK) {
2426 HILOG_ERROR("CheckOptExtensionAbility error.");
2427 eventInfo.errCode = result;
2428 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2429 return result;
2430 }
2431
2432 sptr<IRemoteObject> parentToken = extensionSessionInfo->parentToken;
2433 if (parentToken && parentToken != callerToken) {
2434 UpdateCallerInfoFromToken(abilityRequest.want, parentToken);
2435 }
2436
2437 result = JudgeAbilityVisibleControl(abilityInfo);
2438 if (result != ERR_OK) {
2439 HILOG_ERROR("JudgeAbilityVisibleControl error.");
2440 eventInfo.errCode = result;
2441 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2442 return result;
2443 }
2444
2445 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2446 afterCheckExecuter_->DoProcess(abilityRequest.want, 0, GetUserId(), false, callerToken);
2447 if (result != ERR_OK) {
2448 HILOG_ERROR("afterCheckExecuter_ is nullptr or DoProcess return error.");
2449 return result;
2450 }
2451
2452 auto connectManager = GetConnectManagerByUserId(validUserId);
2453 if (!connectManager) {
2454 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", validUserId);
2455 eventInfo.errCode = ERR_INVALID_VALUE;
2456 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2457 return ERR_INVALID_VALUE;
2458 }
2459 HILOG_INFO("Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
2460 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
2461 if (eventInfo.errCode != ERR_OK) {
2462 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2463 }
2464 return eventInfo.errCode;
2465 }
2466
StopExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2467 int AbilityManagerService::StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2468 int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2469 {
2470 HILOG_INFO("Stop extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
2471 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
2472 if (extensionType != AppExecFwk::ExtensionAbilityType::VPN) {
2473 CHECK_CALLER_IS_SYSTEM_APP;
2474 }
2475 EventInfo eventInfo = BuildEventInfo(want, userId);
2476 eventInfo.extensionType = static_cast<int32_t>(extensionType);
2477 EventReport::SendExtensionEvent(EventName::STOP_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
2478
2479 auto result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::STOP_EXTENSION_ERROR);
2480 if (result != ERR_OK) {
2481 HILOG_ERROR("CheckDlpForExtension error.");
2482 return result;
2483 }
2484
2485 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2486 HILOG_ERROR("%{public}s VerificationAllToken failed.", __func__);
2487 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
2488 HILOG_ERROR("VerificationAllToken failed.");
2489 eventInfo.errCode = ERR_INVALID_VALUE;
2490 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2491 return ERR_INVALID_CALLER;
2492 }
2493 HILOG_DEBUG("Caller is specific system ability.");
2494 }
2495
2496 int32_t validUserId = GetValidUserId(userId);
2497 if (!JudgeMultiUserConcurrency(validUserId)) {
2498 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
2499 eventInfo.errCode = ERR_INVALID_VALUE;
2500 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2501 return ERR_CROSS_USER;
2502 }
2503
2504 if (callerToken != nullptr && CheckIfOperateRemote(want)) {
2505 auto callerUid = IPCSkeleton::GetCallingUid();
2506 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
2507 DistributedClient dmsClient;
2508 return dmsClient.StopRemoteExtensionAbility(want, callerUid, accessToken, eventInfo.extensionType);
2509 }
2510
2511 AbilityRequest abilityRequest;
2512 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2513 if (result != ERR_OK) {
2514 HILOG_ERROR("Generate ability request local error.");
2515 eventInfo.errCode = result;
2516 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2517 return result;
2518 }
2519
2520 auto abilityInfo = abilityRequest.abilityInfo;
2521 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2522 HILOG_DEBUG("userId is : %{public}d, singleton is : %{public}d",
2523 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2524
2525 result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
2526 if (result != ERR_OK) {
2527 HILOG_ERROR("CheckOptExtensionAbility error.");
2528 eventInfo.errCode = result;
2529 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2530 return result;
2531 }
2532
2533 auto connectManager = GetConnectManagerByUserId(validUserId);
2534 if (!connectManager) {
2535 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", validUserId);
2536 eventInfo.errCode = ERR_INVALID_VALUE;
2537 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2538 return ERR_INVALID_VALUE;
2539 }
2540 HILOG_INFO("Stop extension begin, name is %{public}s.", abilityInfo.name.c_str());
2541 eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
2542 if (eventInfo.errCode != ERR_OK) {
2543 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2544 }
2545 return eventInfo.errCode;
2546 }
2547
StopSwitchUserDialog()2548 void AbilityManagerService::StopSwitchUserDialog()
2549 {
2550 HILOG_DEBUG("Stop switch user dialog extension ability come");
2551 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2552 HILOG_ERROR("Scene board enabled.");
2553 return;
2554 }
2555
2556 if (userController_ == nullptr || userController_->GetFreezingNewUserId() == DEFAULT_INVAL_VALUE) {
2557 HILOG_ERROR("Get last userId error.");
2558 return;
2559 }
2560
2561 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
2562 if (sysDialog == nullptr) {
2563 HILOG_ERROR("System dialog scheduler instance is nullptr.");
2564 return;
2565 }
2566
2567 if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
2568 HILOG_ERROR("The caller is not system-app, can not use system-api");
2569 return;
2570 }
2571
2572 Want stopWant = sysDialog->GetSwitchUserDialogWant();
2573 StopSwitchUserDialogInner(stopWant, userController_->GetFreezingNewUserId());
2574 userController_->SetFreezingNewUserId(DEFAULT_INVAL_VALUE);
2575 return;
2576 }
2577
StopSwitchUserDialogInner(const Want & want,const int32_t lastUserId)2578 void AbilityManagerService::StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)
2579 {
2580 HILOG_DEBUG("Stop switch user dialog inner come");
2581 EventInfo eventInfo = BuildEventInfo(want, lastUserId);
2582 eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
2583 EventReport::SendExtensionEvent(EventName::STOP_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
2584 AbilityRequest abilityRequest;
2585 auto result =
2586 GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
2587 if (result != ERR_OK) {
2588 HILOG_ERROR("Generate ability request local error.");
2589 eventInfo.errCode = result;
2590 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2591 return;
2592 }
2593
2594 auto abilityInfo = abilityRequest.abilityInfo;
2595 auto stopUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
2596 result = CheckOptExtensionAbility(want, abilityRequest, stopUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
2597 if (result != ERR_OK) {
2598 HILOG_ERROR("Check extensionAbility type error.");
2599 eventInfo.errCode = result;
2600 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2601 return;
2602 }
2603
2604 auto connectManager = GetConnectManagerByUserId(stopUserId);
2605 if (connectManager == nullptr) {
2606 HILOG_ERROR("ConnectManager is nullptr. userId:%{public}d", stopUserId);
2607 eventInfo.errCode = ERR_INVALID_VALUE;
2608 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2609 return;
2610 }
2611
2612 eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
2613 if (eventInfo.errCode != ERR_OK) {
2614 HILOG_ERROR("EventInfo errCode is %{public}d", eventInfo.errCode);
2615 EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2616 }
2617 }
2618
MoveAbilityToBackground(const sptr<IRemoteObject> & token)2619 int AbilityManagerService::MoveAbilityToBackground(const sptr<IRemoteObject> &token)
2620 {
2621 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2622 HILOG_DEBUG("Move ability to background begin");
2623 if (!VerificationAllToken(token)) {
2624 return ERR_INVALID_VALUE;
2625 }
2626 auto abilityRecord = Token::GetAbilityRecordByToken(token);
2627 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2628 if (!JudgeSelfCalled(abilityRecord)) {
2629 return CHECK_PERMISSION_FAILED;
2630 }
2631
2632 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
2633 return ERR_WOULD_BLOCK;
2634 }
2635
2636 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
2637 auto missionListManager = GetListManagerByUserId(ownerUserId);
2638 if (!missionListManager) {
2639 HILOG_ERROR("missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
2640 return ERR_INVALID_VALUE;
2641 }
2642 return missionListManager->MoveAbilityToBackground(abilityRecord);
2643 }
2644
TerminateAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)2645 int AbilityManagerService::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
2646 {
2647 auto abilityRecord = Token::GetAbilityRecordByToken(token);
2648 if (!abilityRecord) {
2649 HILOG_ERROR("abilityRecord is Null.");
2650 return ERR_INVALID_VALUE;
2651 }
2652 return TerminateAbilityWithFlag(token, resultCode, resultWant, true);
2653 }
2654
CloseAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)2655 int AbilityManagerService::CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
2656 {
2657 EventInfo eventInfo;
2658 EventReport::SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
2659 return TerminateAbilityWithFlag(token, resultCode, resultWant, false);
2660 }
2661
TerminateAbilityWithFlag(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,bool flag)2662 int AbilityManagerService::TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode,
2663 const Want *resultWant, bool flag)
2664 {
2665 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2666 HILOG_DEBUG("Terminate ability begin, flag:%{public}d.", flag);
2667 if (!VerificationAllToken(token)) {
2668 HILOG_ERROR("%{public}s VerificationAllToken failed.", __func__);
2669 return ERR_INVALID_VALUE;
2670 }
2671
2672 auto abilityRecord = Token::GetAbilityRecordByToken(token);
2673 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2674 if (!JudgeSelfCalled(abilityRecord)) {
2675 return CHECK_PERMISSION_FAILED;
2676 }
2677
2678 if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) {
2679 HILOG_ERROR("System ui not allow terminate.");
2680 return ERR_INVALID_VALUE;
2681 }
2682
2683 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
2684 auto type = abilityRecord->GetAbilityInfo().type;
2685 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
2686 auto connectManager = GetConnectManagerByUserId(userId);
2687 if (!connectManager) {
2688 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
2689 return ERR_INVALID_VALUE;
2690 }
2691 return connectManager->TerminateAbility(token);
2692 }
2693
2694 if (type == AppExecFwk::AbilityType::DATA) {
2695 HILOG_ERROR("Cannot terminate data ability, use 'ReleaseDataAbility()' instead.");
2696 return ERR_WRONG_INTERFACE_CALL;
2697 }
2698
2699 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
2700 return ERR_WOULD_BLOCK;
2701 }
2702
2703 auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
2704 auto missionListManager = GetListManagerByUserId(ownerUserId);
2705 if (missionListManager) {
2706 return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag);
2707 }
2708 HILOG_WARN("missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
2709 if (uiAbilityLifecycleManager_ && Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2710 return uiAbilityLifecycleManager_->CloseUIAbility(abilityRecord, resultCode, resultWant, false);
2711 }
2712 return ERR_INVALID_VALUE;
2713 }
2714
TerminateUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int resultCode,const Want * resultWant)2715 int AbilityManagerService::TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode,
2716 const Want *resultWant)
2717 {
2718 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2719 HILOG_DEBUG("Terminate ui extension ability begin.");
2720 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
2721 auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
2722 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2723 std::shared_ptr<AbilityConnectManager> connectManager;
2724 std::shared_ptr<AbilityRecord> targetRecord;
2725 GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
2726 CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
2727 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
2728
2729 if (!JudgeSelfCalled(targetRecord) && !JudgeSelfCalled(abilityRecord)) {
2730 return CHECK_PERMISSION_FAILED;
2731 }
2732
2733 auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
2734 if (result != ERR_OK) {
2735 HILOG_ERROR("JudgeAbilityVisibleControl error.");
2736 return result;
2737 }
2738
2739 if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
2740 HILOG_ERROR("Cannot terminate except ui extension ability.");
2741 return ERR_WRONG_INTERFACE_CALL;
2742 }
2743 extensionSessionInfo->uiExtensionComponentId = (
2744 static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
2745 static_cast<uint64_t>(extensionSessionInfo->persistentId);
2746 HILOG_DEBUG("UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
2747 extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
2748 connectManager->TerminateAbilityWindowLocked(targetRecord, extensionSessionInfo);
2749 return ERR_OK;
2750 }
2751
CloseUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)2752 int AbilityManagerService::CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
2753 {
2754 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2755 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
2756 HILOG_ERROR("sessionInfo is nullptr");
2757 return ERR_INVALID_VALUE;
2758 }
2759
2760 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
2761 HILOG_ERROR("Not sceneboard called, not allowed.");
2762 return ERR_WRONG_INTERFACE_CALL;
2763 }
2764
2765 if (!uiAbilityLifecycleManager_) {
2766 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
2767 return ERR_INVALID_VALUE;
2768 }
2769 HILOG_INFO("close session: %{public}d, resultCode: %{public}d", sessionInfo->persistentId, sessionInfo->resultCode);
2770 auto abilityRecord = uiAbilityLifecycleManager_->GetUIAbilityRecordBySessionInfo(sessionInfo);
2771 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2772 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
2773 return ERR_WOULD_BLOCK;
2774 }
2775
2776 if (sessionInfo->isClearSession) {
2777 const auto &abilityInfo = abilityRecord->GetAbilityInfo();
2778 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
2779 DeleteAbilityRecoverInfo(abilityInfo.bundleName, abilityInfo.moduleName, abilityInfo.name);
2780 }
2781
2782 EventInfo eventInfo;
2783 eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
2784 eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
2785 EventReport::SendAbilityEvent(EventName::CLOSE_UI_ABILITY_BY_SCB, HiSysEventType::BEHAVIOR, eventInfo);
2786 eventInfo.errCode = uiAbilityLifecycleManager_->CloseUIAbility(abilityRecord, sessionInfo->resultCode,
2787 &(sessionInfo->want), sessionInfo->isClearSession);
2788 if (eventInfo.errCode != ERR_OK) {
2789 EventReport::SendAbilityEvent(EventName::CLOSE_UI_ABILITY_BY_SCB_ERROR, HiSysEventType::FAULT, eventInfo);
2790 }
2791 return eventInfo.errCode;
2792 }
2793
SendResultToAbility(int32_t requestCode,int32_t resultCode,Want & resultWant)2794 int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)
2795 {
2796 HILOG_INFO("%{public}s", __func__);
2797 if (!CheckCallerIsDmsProcess()) {
2798 HILOG_ERROR("Check processName failed");
2799 return ERR_INVALID_VALUE;
2800 }
2801 int missionId = resultWant.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
2802 resultWant.RemoveParam(DMS_MISSION_ID);
2803 if (missionId == DEFAULT_DMS_MISSION_ID) {
2804 HILOG_ERROR("MissionId is empty");
2805 return ERR_INVALID_VALUE;
2806 }
2807 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
2808 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2809 abilityRecord = uiAbilityLifecycleManager_->GetAbilityRecordsById(missionId);
2810 } else {
2811 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
2812 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
2813 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
2814 }
2815 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2816
2817 abilityRecord->SetResult(std::make_shared<AbilityResult>(requestCode, resultCode, resultWant));
2818 abilityRecord->SendResult(0, 0);
2819 return ERR_OK;
2820 }
2821
StartRemoteAbility(const Want & want,int requestCode,int32_t validUserId,const sptr<IRemoteObject> & callerToken)2822 int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId,
2823 const sptr<IRemoteObject> &callerToken)
2824 {
2825 HILOG_INFO("%{public}s", __func__);
2826 Want remoteWant = want;
2827 if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
2828 HILOG_ERROR("%{public}s AddStartControlParam failed.", __func__);
2829 return ERR_INVALID_VALUE;
2830 }
2831 if (AbilityUtil::IsStartFreeInstall(remoteWant)) {
2832 return freeInstallManager_ == nullptr ? ERR_INVALID_VALUE :
2833 freeInstallManager_->StartRemoteFreeInstall(remoteWant, requestCode, validUserId, callerToken);
2834 }
2835 if (remoteWant.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
2836 HILOG_INFO("%{public}s: try to StartAbilityForResult", __func__);
2837 int32_t missionId = -1;
2838 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
2839 missionId = uiAbilityLifecycleManager_->GetSessionIdByAbilityToken(callerToken);
2840 if (!missionId) {
2841 HILOG_ERROR("Invalid missionId id.");
2842 return ERR_INVALID_VALUE;
2843 }
2844 } else {
2845 missionId = GetMissionIdByAbilityToken(callerToken);
2846 }
2847 if (missionId < 0) {
2848 return ERR_INVALID_VALUE;
2849 }
2850 remoteWant.SetParam(DMS_MISSION_ID, missionId);
2851 }
2852
2853 int32_t callerUid = IPCSkeleton::GetCallingUid();
2854 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
2855 DistributedClient dmsClient;
2856 HILOG_DEBUG("get callerUid = %d, AccessTokenID = %u", callerUid, accessToken);
2857 int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken);
2858 if (result != ERR_NONE) {
2859 HILOG_ERROR("AbilityManagerService::StartRemoteAbility failed, result = %{public}d", result);
2860 }
2861 return result;
2862 }
2863
CheckIsRemote(const std::string & deviceId)2864 bool AbilityManagerService::CheckIsRemote(const std::string& deviceId)
2865 {
2866 if (deviceId.empty()) {
2867 HILOG_INFO("CheckIsRemote: deviceId is empty.");
2868 return false;
2869 }
2870 std::string localDeviceId;
2871 if (!GetLocalDeviceId(localDeviceId)) {
2872 HILOG_ERROR("CheckIsRemote: get local deviceId failed");
2873 return false;
2874 }
2875 if (localDeviceId == deviceId) {
2876 HILOG_INFO("CheckIsRemote: deviceId is local.");
2877 return false;
2878 }
2879 HILOG_DEBUG("CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str());
2880 return true;
2881 }
2882
CheckIfOperateRemote(const Want & want)2883 bool AbilityManagerService::CheckIfOperateRemote(const Want &want)
2884 {
2885 std::string deviceId = want.GetElement().GetDeviceID();
2886 if (deviceId.empty() || want.GetElement().GetBundleName().empty() ||
2887 want.GetElement().GetAbilityName().empty()) {
2888 HILOG_DEBUG("CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty");
2889 return false;
2890 }
2891 return CheckIsRemote(deviceId);
2892 }
2893
GetLocalDeviceId(std::string & localDeviceId)2894 bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId)
2895 {
2896 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2897 auto localNode = std::make_unique<NodeBasicInfo>();
2898 int32_t errCode = GetLocalNodeDeviceInfo(DM_PKG_NAME.c_str(), localNode.get());
2899 if (errCode != ERR_OK) {
2900 HILOG_ERROR("AbilityManagerService::GetLocalNodeDeviceInfo errCode = %{public}d", errCode);
2901 return false;
2902 }
2903 if (localNode != nullptr) {
2904 localDeviceId = localNode->networkId;
2905 HILOG_DEBUG("get local deviceId, deviceId = %{public}s",
2906 AnonymizeDeviceId(localDeviceId).c_str());
2907 return true;
2908 }
2909 HILOG_ERROR("AbilityManagerService::GetLocalDeviceId localDeviceId null");
2910 return false;
2911 }
2912
AnonymizeDeviceId(const std::string & deviceId)2913 std::string AbilityManagerService::AnonymizeDeviceId(const std::string& deviceId)
2914 {
2915 if (deviceId.length() < NON_ANONYMIZE_LENGTH) {
2916 return EMPTY_DEVICE_ID;
2917 }
2918 std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
2919 anonDeviceId.append("******");
2920 return anonDeviceId;
2921 }
2922
MinimizeAbility(const sptr<IRemoteObject> & token,bool fromUser)2923 int AbilityManagerService::MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)
2924 {
2925 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2926 HILOG_INFO("Minimize ability, fromUser:%{public}d.", fromUser);
2927 if (!VerificationAllToken(token)) {
2928 return ERR_INVALID_VALUE;
2929 }
2930
2931 auto abilityRecord = Token::GetAbilityRecordByToken(token);
2932 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2933 if (!JudgeSelfCalled(abilityRecord)) {
2934 return CHECK_PERMISSION_FAILED;
2935 }
2936
2937 auto type = abilityRecord->GetAbilityInfo().type;
2938 if (type != AppExecFwk::AbilityType::PAGE) {
2939 HILOG_ERROR("Cannot minimize except page ability.");
2940 return ERR_WRONG_INTERFACE_CALL;
2941 }
2942
2943 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
2944 return ERR_WOULD_BLOCK;
2945 }
2946
2947 auto missionListManager = GetListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
2948 if (!missionListManager) {
2949 HILOG_ERROR("missionListManager is Null.");
2950 return ERR_INVALID_VALUE;
2951 }
2952 return missionListManager->MinimizeAbility(token, fromUser);
2953 }
2954
MinimizeUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,bool fromUser)2955 int AbilityManagerService::MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo,
2956 bool fromUser)
2957 {
2958 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2959 HILOG_DEBUG("Minimize ui extension ability, fromUser:%{public}d.", fromUser);
2960 CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
2961 auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
2962 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
2963 if (!JudgeSelfCalled(abilityRecord)) {
2964 return CHECK_PERMISSION_FAILED;
2965 }
2966
2967 std::shared_ptr<AbilityConnectManager> connectManager;
2968 std::shared_ptr<AbilityRecord> targetRecord;
2969 GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
2970 CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
2971 CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
2972
2973 auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
2974 if (result != ERR_OK) {
2975 HILOG_ERROR("JudgeAbilityVisibleControl error.");
2976 return result;
2977 }
2978
2979 if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
2980 HILOG_ERROR("Cannot minimize except ui extension ability.");
2981 return ERR_WRONG_INTERFACE_CALL;
2982 }
2983 extensionSessionInfo->uiExtensionComponentId = (
2984 static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
2985 static_cast<uint64_t>(extensionSessionInfo->persistentId);
2986 HILOG_DEBUG("UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
2987 extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
2988 connectManager->BackgroundAbilityWindowLocked(targetRecord, extensionSessionInfo);
2989 return ERR_OK;
2990 }
2991
MinimizeUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool fromUser)2992 int AbilityManagerService::MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser)
2993 {
2994 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2995 HILOG_DEBUG("call");
2996 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
2997 HILOG_ERROR("sessionInfo is nullptr");
2998 return ERR_INVALID_VALUE;
2999 }
3000
3001 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
3002 HILOG_ERROR("Not sceneboard called, not allowed.");
3003 return ERR_WRONG_INTERFACE_CALL;
3004 }
3005
3006 if (!uiAbilityLifecycleManager_) {
3007 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
3008 return ERR_INVALID_VALUE;
3009 }
3010 auto abilityRecord = uiAbilityLifecycleManager_->GetUIAbilityRecordBySessionInfo(sessionInfo);
3011 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3012 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3013 return ERR_WOULD_BLOCK;
3014 }
3015
3016 return uiAbilityLifecycleManager_->MinimizeUIAbility(abilityRecord, fromUser);
3017 }
3018
ConnectAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t userId)3019 int AbilityManagerService::ConnectAbility(
3020 const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)
3021 {
3022 return ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::SERVICE, userId);
3023 }
3024
ConnectAbilityCommon(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,AppExecFwk::ExtensionAbilityType extensionType,int32_t userId,bool isQueryExtensionOnly)3025 int AbilityManagerService::ConnectAbilityCommon(
3026 const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
3027 AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)
3028 {
3029 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3030 HILOG_INFO("Connect ability called, element uri: %{public}s.", want.GetElement().GetURI().c_str());
3031 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3032 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3033 if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && IsCrossUserCall(userId)) {
3034 CHECK_CALLER_IS_SYSTEM_APP;
3035 }
3036 EventInfo eventInfo = BuildEventInfo(want, userId);
3037 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
3038
3039 auto result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
3040 if (result != ERR_OK) {
3041 HILOG_ERROR("CheckDlpForExtension error.");
3042 eventInfo.errCode = result;
3043 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3044 return result;
3045 }
3046
3047 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3048 interceptorExecuter_->DoProcess(want, 0, GetUserId(), false);
3049 if (result != ERR_OK) {
3050 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
3051 eventInfo.errCode = result;
3052 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3053 return result;
3054 }
3055
3056 int32_t validUserId = GetValidUserId(userId);
3057
3058 if (AbilityUtil::IsStartFreeInstall(want) && freeInstallManager_ != nullptr) {
3059 std::string localDeviceId;
3060 if (!GetLocalDeviceId(localDeviceId)) {
3061 HILOG_ERROR("%{public}s: Get Local DeviceId failed", __func__);
3062 eventInfo.errCode = ERR_INVALID_VALUE;
3063 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3064 return ERR_INVALID_VALUE;
3065 }
3066 result = freeInstallManager_->ConnectFreeInstall(want, validUserId, callerToken, localDeviceId);
3067 if (result != ERR_OK) {
3068 eventInfo.errCode = result;
3069 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3070 return result;
3071 }
3072 }
3073
3074 Want abilityWant = want;
3075 AbilityRequest abilityRequest;
3076 std::string uri = abilityWant.GetUri().ToString();
3077 if (!uri.empty()) {
3078 // if the want include uri, it may only has uri information. it is probably a datashare extension.
3079 HILOG_DEBUG("%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
3080 AppExecFwk::ExtensionAbilityInfo extensionInfo;
3081 auto bms = GetBundleManager();
3082 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3083
3084 abilityWant.SetParam("abilityConnectionObj", connect->AsObject());
3085 abilityWant.RemoveParam("abilityConnectionObj");
3086
3087 bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
3088 if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
3089 HILOG_ERROR("Invalid extension ability info.");
3090 eventInfo.errCode = ERR_INVALID_VALUE;
3091 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3092 return ERR_INVALID_VALUE;
3093 }
3094 abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
3095 }
3096
3097 if (CheckIfOperateRemote(abilityWant)) {
3098 HILOG_DEBUG("AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility");
3099 eventInfo.errCode = ConnectRemoteAbility(abilityWant, callerToken, connect->AsObject());
3100 if (eventInfo.errCode != ERR_OK) {
3101 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3102 }
3103 return eventInfo.errCode;
3104 }
3105 UpdateCallerInfo(abilityWant, callerToken);
3106
3107 if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
3108 HILOG_DEBUG("invalid Token.");
3109 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr, extensionType);
3110 if (eventInfo.errCode != ERR_OK) {
3111 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3112 }
3113 return eventInfo.errCode;
3114 }
3115 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken, extensionType, nullptr,
3116 isQueryExtensionOnly);
3117 if (eventInfo.errCode != ERR_OK) {
3118 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3119 }
3120 return eventInfo.errCode;
3121 }
3122
ConnectUIExtensionAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<SessionInfo> & sessionInfo,int32_t userId,sptr<UIExtensionAbilityConnectInfo> connectInfo)3123 int AbilityManagerService::ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect,
3124 const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)
3125 {
3126 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3127 HILOG_DEBUG("Connect ui extension called, bundlename: %{public}s, ability is %{public}s, userId is %{pravite}d",
3128 want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3129 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3130 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3131 CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
3132
3133 if (IsCrossUserCall(userId)) {
3134 CHECK_CALLER_IS_SYSTEM_APP;
3135 }
3136
3137 EventInfo eventInfo = BuildEventInfo(want, userId);
3138 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
3139 sptr<IRemoteObject> callerToken = sessionInfo->callerToken;
3140
3141 if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3142 HILOG_ERROR("ConnectUIExtensionAbility VerificationAllToken failed.");
3143 eventInfo.errCode = ERR_INVALID_VALUE;
3144 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3145 return ERR_INVALID_CALLER;
3146 }
3147
3148 auto result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
3149 if (result != ERR_OK) {
3150 HILOG_ERROR("CheckDlpForExtension error.");
3151 eventInfo.errCode = result;
3152 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3153 return result;
3154 }
3155
3156 result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3157 interceptorExecuter_->DoProcess(want, 0, GetUserId(), false);
3158 if (result != ERR_OK) {
3159 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
3160 eventInfo.errCode = result;
3161 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3162 return result;
3163 }
3164
3165 int32_t validUserId = GetValidUserId(userId);
3166
3167 Want abilityWant = want;
3168 AbilityRequest abilityRequest;
3169 std::string uri = abilityWant.GetUri().ToString();
3170 if (!uri.empty()) {
3171 // if the want include uri, it may only has uri information.
3172 HILOG_INFO("%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
3173 AppExecFwk::ExtensionAbilityInfo extensionInfo;
3174 auto bms = GetBundleManager();
3175 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3176
3177 abilityWant.SetParam("abilityConnectionObj", connect->AsObject());
3178 abilityWant.RemoveParam("abilityConnectionObj");
3179
3180 bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
3181 if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
3182 HILOG_ERROR("Invalid extension ability info.");
3183 eventInfo.errCode = ERR_INVALID_VALUE;
3184 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3185 return ERR_INVALID_VALUE;
3186 }
3187 abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
3188 }
3189
3190 UpdateCallerInfo(abilityWant, callerToken);
3191
3192 if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
3193 HILOG_INFO("%{public}s invalid Token.", __func__);
3194 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr,
3195 AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
3196 if (eventInfo.errCode != ERR_OK) {
3197 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3198 }
3199 return eventInfo.errCode;
3200 }
3201 eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken,
3202 AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
3203 if (eventInfo.errCode != ERR_OK) {
3204 EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3205 }
3206 return eventInfo.errCode;
3207 }
3208
BuildEventInfo(const Want & want,int32_t userId)3209 EventInfo AbilityManagerService::BuildEventInfo(const Want &want, int32_t userId)
3210 {
3211 EventInfo eventInfo;
3212 eventInfo.userId = userId;
3213 eventInfo.bundleName = want.GetElement().GetBundleName();
3214 eventInfo.moduleName = want.GetElement().GetModuleName();
3215 eventInfo.abilityName = want.GetElement().GetAbilityName();
3216 return eventInfo;
3217 }
3218
DisconnectAbility(sptr<IAbilityConnection> connect)3219 int AbilityManagerService::DisconnectAbility(sptr<IAbilityConnection> connect)
3220 {
3221 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3222 HILOG_DEBUG("Disconnect ability begin.");
3223 EventInfo eventInfo;
3224 EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
3225 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3226 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3227
3228 if (ERR_OK != DisconnectLocalAbility(connect) &&
3229 ERR_OK != DisconnectRemoteAbility(connect->AsObject())) {
3230 eventInfo.errCode = INNER_ERR;
3231 EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3232 }
3233 return ERR_OK;
3234 }
3235
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)3236 int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId,
3237 const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
3238 AppExecFwk::ExtensionAbilityType extensionType, const sptr<SessionInfo> &sessionInfo,
3239 bool isQueryExtensionOnly, sptr<UIExtensionAbilityConnectInfo> connectInfo)
3240 {
3241 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3242 HILOG_DEBUG("called");
3243 bool isEnterpriseAdmin = AAFwk::UIExtensionUtils::IsEnterpriseAdmin(extensionType);
3244 if (!isEnterpriseAdmin && !JudgeMultiUserConcurrency(userId)) {
3245 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
3246 return ERR_CROSS_USER;
3247 }
3248
3249 AbilityRequest abilityRequest;
3250 ErrCode result = ERR_OK;
3251 if (isQueryExtensionOnly ||
3252 AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
3253 result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, userId);
3254 } else {
3255 result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId);
3256 }
3257 abilityRequest.sessionInfo = sessionInfo;
3258
3259 Want requestWant = want;
3260 CHECK_POINTER_AND_RETURN_LOG(connect, ERR_INVALID_VALUE, "connect is nullptr");
3261 CHECK_POINTER_AND_RETURN_LOG(connect->AsObject(), ERR_INVALID_VALUE, "abilityConnectionObj is nullptr");
3262 requestWant.SetParam("abilityConnectionObj", connect->AsObject());
3263 HILOG_DEBUG("requestWant SetParam success");
3264
3265 if (result != ERR_OK) {
3266 HILOG_ERROR("Generate ability request error.");
3267 return result;
3268 }
3269
3270 if (abilityRequest.abilityInfo.isStageBasedModel) {
3271 bool isService =
3272 (abilityRequest.abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE);
3273 if (isService && extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
3274 HILOG_ERROR("Service extension type, please use ConnectAbility.");
3275 return ERR_WRONG_INTERFACE_CALL;
3276 }
3277 }
3278 auto abilityInfo = abilityRequest.abilityInfo;
3279 int32_t validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : userId;
3280 HILOG_DEBUG("validUserId : %{public}d, singleton is : %{public}d",
3281 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3282
3283 result = CheckStaticCfgPermission(abilityInfo, false, -1);
3284 if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
3285 HILOG_ERROR("CheckStaticCfgPermission error, result is %{public}d.", result);
3286 return ERR_STATIC_CFG_PERMISSION;
3287 }
3288
3289 AppExecFwk::ExtensionAbilityType targetExtensionType = abilityInfo.extensionAbilityType;
3290 HILOG_DEBUG("extension type %{public}d.", targetExtensionType);
3291 if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
3292 if (!AAFwk::UIExtensionUtils::IsUIExtension(targetExtensionType)
3293 && targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW) {
3294 HILOG_ERROR("Try to connect UI extension, but target ability is not UI extension.");
3295 return ERR_WRONG_INTERFACE_CALL;
3296 }
3297
3298 // Cause window has used this api, don't check it when type is window.
3299 if (targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW &&
3300 !PermissionVerification::GetInstance()->VerifyCallingPermission(
3301 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY)) {
3302 HILOG_ERROR("Permission %{public}s verification failed.",
3303 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY);
3304 return ERR_PERMISSION_DENIED;
3305 }
3306 }
3307
3308 auto type = abilityInfo.type;
3309 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
3310 HILOG_ERROR("Connect ability failed, target ability is not Service.");
3311 return TARGET_ABILITY_NOT_SERVICE;
3312 }
3313
3314 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
3315 afterCheckExecuter_->DoProcess(abilityRequest.want, 0, GetUserId(), false, callerToken);
3316 if (result != ERR_OK) {
3317 HILOG_ERROR("afterCheckExecuter_ is nullptr or DoProcess return error.");
3318 return result;
3319 }
3320
3321 result = CheckCallServicePermission(abilityRequest);
3322 if (result != ERR_OK) {
3323 HILOG_ERROR("%{public}s CheckCallServicePermission error.", __func__);
3324 return result;
3325 }
3326 result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
3327 if (result != ERR_OK) {
3328 HILOG_ERROR("ConnectAbility: App data ability preloading failed, '%{public}s', %{public}d",
3329 abilityInfo.bundleName.c_str(),
3330 result);
3331 return result;
3332 }
3333
3334 auto connectManager = GetConnectManagerByUserId(validUserId);
3335 if (connectManager == nullptr) {
3336 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", validUserId);
3337 return ERR_INVALID_VALUE;
3338 }
3339
3340 ReportEventToSuspendManager(abilityInfo);
3341 return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo);
3342 }
3343
ConnectRemoteAbility(Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)3344 int AbilityManagerService::ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken,
3345 const sptr<IRemoteObject> &connect)
3346 {
3347 HILOG_INFO("%{public}s begin ConnectAbilityRemote", __func__);
3348 if (AddStartControlParam(want, callerToken) != ERR_OK) {
3349 HILOG_ERROR("%{public}s AddStartControlParam failed.", __func__);
3350 return ERR_INVALID_VALUE;
3351 }
3352 DistributedClient dmsClient;
3353 return dmsClient.ConnectRemoteAbility(want, connect);
3354 }
3355
DisconnectLocalAbility(const sptr<IAbilityConnection> & connect)3356 int AbilityManagerService::DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)
3357 {
3358 HILOG_DEBUG("called.");
3359 CHECK_POINTER_AND_RETURN(connectManager_, ERR_NO_INIT);
3360 if (connectManager_->DisconnectAbilityLocked(connect) == ERR_OK) {
3361 return ERR_OK;
3362 }
3363 // If current connectManager_ does not exist connect, then try connectManagerU0
3364 auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
3365 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
3366 if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
3367 return ERR_OK;
3368 }
3369
3370 // EnterpriseAdminExtensionAbility Scene
3371 connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT);
3372 CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
3373 return connectManager->DisconnectAbilityLocked(connect);
3374 }
3375
DisconnectRemoteAbility(const sptr<IRemoteObject> & connect)3376 int AbilityManagerService::DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)
3377 {
3378 HILOG_INFO("%{public}s begin DisconnectAbilityRemote", __func__);
3379 int32_t callerUid = IPCSkeleton::GetCallingUid();
3380 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3381 DistributedClient dmsClient;
3382 return dmsClient.DisconnectRemoteAbility(connect, callerUid, accessToken);
3383 }
3384
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callBack,AAFwk::WantParams & wantParams)3385 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
3386 int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
3387 {
3388 HILOG_INFO("amsServ %{public}s called.", __func__);
3389 HILOG_INFO("ContinueMission missionId: %{public}d", missionId);
3390 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3391 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3392 return CHECK_PERMISSION_FAILED;
3393 }
3394
3395 DistributedClient dmsClient;
3396 return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams);
3397 }
3398
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,const std::string & bundleName,const sptr<IRemoteObject> & callBack,AAFwk::WantParams & wantParams)3399 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
3400 const std::string &bundleName, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
3401 {
3402 HILOG_INFO("amsServ %{public}s called.", __func__);
3403 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3404 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3405 return CHECK_PERMISSION_FAILED;
3406 }
3407
3408 DistributedClient dmsClient;
3409 return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, bundleName, callBack, wantParams);
3410 }
3411
ContinueAbility(const std::string & deviceId,int32_t missionId,uint32_t versionCode)3412 int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)
3413 {
3414 HILOG_INFO("ContinueAbility missionId = %{public}d, version = %{public}u.", missionId, versionCode);
3415 if (!CheckCallerIsDmsProcess()) {
3416 HILOG_ERROR("Check processName failed");
3417 return ERR_INVALID_VALUE;
3418 }
3419
3420 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
3421 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3422 abilityRecord = uiAbilityLifecycleManager_->GetAbilityRecordsById(missionId);
3423 } else {
3424 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
3425 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3426 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
3427 }
3428 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3429
3430 abilityRecord->ContinueAbility(deviceId, versionCode);
3431 return ERR_OK;
3432 }
3433
StartContinuation(const Want & want,const sptr<IRemoteObject> & abilityToken,int32_t status)3434 int AbilityManagerService::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)
3435 {
3436 HILOG_INFO("Start Continuation.");
3437 if (!CheckIfOperateRemote(want)) {
3438 HILOG_ERROR("deviceId or bundle name or abilityName empty");
3439 return ERR_INVALID_VALUE;
3440 }
3441 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3442
3443 int32_t appUid = IPCSkeleton::GetCallingUid();
3444 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3445 HILOG_INFO("AbilityManagerService::Try to StartContinuation, AccessTokenID = %{public}u", accessToken);
3446 int32_t missionId = -1;
3447 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3448 missionId = uiAbilityLifecycleManager_->GetSessionIdByAbilityToken(abilityToken);
3449 if (!missionId) {
3450 HILOG_ERROR("Invalid missionId id.");
3451 return ERR_INVALID_VALUE;
3452 }
3453 } else {
3454 missionId = GetMissionIdByAbilityToken(abilityToken);
3455 }
3456 if (missionId < 0) {
3457 HILOG_ERROR("AbilityManagerService::StartContinuation failed to get missionId.");
3458 return ERR_INVALID_VALUE;
3459 }
3460 DistributedClient dmsClient;
3461 auto result = dmsClient.StartContinuation(want, missionId, appUid, status, accessToken);
3462 if (result != ERR_OK) {
3463 HILOG_ERROR("StartContinuation failed, result = %{public}d, notify caller", result);
3464 NotifyContinuationResult(missionId, result);
3465 }
3466 return result;
3467 }
3468
NotifyCompleteContinuation(const std::string & deviceId,int32_t sessionId,bool isSuccess)3469 void AbilityManagerService::NotifyCompleteContinuation(const std::string &deviceId,
3470 int32_t sessionId, bool isSuccess)
3471 {
3472 HILOG_INFO("NotifyCompleteContinuation.");
3473 DistributedClient dmsClient;
3474 dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess);
3475 }
3476
NotifyContinuationResult(int32_t missionId,int32_t result)3477 int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result)
3478 {
3479 HILOG_INFO("Notify Continuation Result : %{public}d.", result);
3480
3481 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
3482 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3483 abilityRecord = uiAbilityLifecycleManager_->GetAbilityRecordsById(missionId);
3484 } else {
3485 sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
3486 CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3487 abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
3488 }
3489 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3490
3491 abilityRecord->NotifyContinuationResult(result);
3492 return ERR_OK;
3493 }
3494
StartSyncRemoteMissions(const std::string & devId,bool fixConflict,int64_t tag)3495 int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
3496 {
3497 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3498 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3499 return CHECK_PERMISSION_FAILED;
3500 }
3501 DistributedClient dmsClient;
3502 return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag);
3503 }
3504
StopSyncRemoteMissions(const std::string & devId)3505 int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId)
3506 {
3507 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3508 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3509 return CHECK_PERMISSION_FAILED;
3510 }
3511 DistributedClient dmsClient;
3512 return dmsClient.StopSyncRemoteMissions(devId);
3513 }
3514
RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)3515 int AbilityManagerService::RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
3516 {
3517 return DelayedSingleton<ConnectionStateManager>::GetInstance()->RegisterObserver(observer);
3518 }
3519
UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)3520 int AbilityManagerService::UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
3521 {
3522 return DelayedSingleton<ConnectionStateManager>::GetInstance()->UnregisterObserver(observer);
3523 }
3524
GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> & infos)3525 int AbilityManagerService::GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)
3526 {
3527 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
3528 HILOG_ERROR("can not get dlp connection infos if caller is not sa.");
3529 return CHECK_PERMISSION_FAILED;
3530 }
3531 DelayedSingleton<ConnectionStateManager>::GetInstance()->GetDlpConnectionInfos(infos);
3532
3533 return ERR_OK;
3534 }
3535
GetConnectionData(std::vector<AbilityRuntime::ConnectionData> & connectionData)3536 int AbilityManagerService::GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)
3537 {
3538 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
3539 HILOG_ERROR("can not get connection data if caller is not sa.");
3540 return CHECK_PERMISSION_FAILED;
3541 }
3542 DelayedSingleton<ConnectionStateManager>::GetInstance()->GetConnectionData(connectionData);
3543
3544 return ERR_OK;
3545 }
3546
RegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)3547 int AbilityManagerService::RegisterMissionListener(const std::string &deviceId,
3548 const sptr<IRemoteMissionListener> &listener)
3549 {
3550 CHECK_CALLER_IS_SYSTEM_APP;
3551 std::string localDeviceId;
3552 if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
3553 HILOG_ERROR("RegisterMissionListener: Check DeviceId failed");
3554 return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
3555 }
3556 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
3557 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3558 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3559 return CHECK_PERMISSION_FAILED;
3560 }
3561 DistributedClient dmsClient;
3562 return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
3563 }
3564
RegisterOnListener(const std::string & type,const sptr<IRemoteOnListener> & listener)3565 int AbilityManagerService::RegisterOnListener(const std::string &type,
3566 const sptr<IRemoteOnListener> &listener)
3567 {
3568 CHECK_CALLER_IS_SYSTEM_APP;
3569 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
3570 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3571 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3572 return CHECK_PERMISSION_FAILED;
3573 }
3574 DistributedClient dmsClient;
3575 return dmsClient.RegisterOnListener(type, listener->AsObject());
3576 }
3577
RegisterOffListener(const std::string & type,const sptr<IRemoteOnListener> & listener)3578 int AbilityManagerService::RegisterOffListener(const std::string &type,
3579 const sptr<IRemoteOnListener> &listener)
3580 {
3581 CHECK_CALLER_IS_SYSTEM_APP;
3582 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
3583 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3584 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3585 return CHECK_PERMISSION_FAILED;
3586 }
3587 DistributedClient dmsClient;
3588 return dmsClient.RegisterOffListener(type, listener->AsObject());
3589 }
3590
UnRegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)3591 int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId,
3592 const sptr<IRemoteMissionListener> &listener)
3593 {
3594 CHECK_CALLER_IS_SYSTEM_APP;
3595 std::string localDeviceId;
3596 if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
3597 HILOG_ERROR("RegisterMissionListener: Check DeviceId failed");
3598 return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
3599 }
3600 CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
3601 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3602 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3603 return CHECK_PERMISSION_FAILED;
3604 }
3605 DistributedClient dmsClient;
3606 return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
3607 }
3608
GetWantSender(const WantSenderInfo & wantSenderInfo,const sptr<IRemoteObject> & callerToken)3609 sptr<IWantSender> AbilityManagerService::GetWantSender(
3610 const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken)
3611 {
3612 HILOG_DEBUG("called");
3613 CHECK_POINTER_AND_RETURN(pendingWantManager_, nullptr);
3614
3615 auto bms = GetBundleManager();
3616 CHECK_POINTER_AND_RETURN(bms, nullptr);
3617
3618 int32_t callerUid = IPCSkeleton::GetCallingUid();
3619 int32_t userId = wantSenderInfo.userId;
3620 bool bundleMgrResult = false;
3621 if (userId < 0) {
3622 if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
3623 GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
3624 HILOG_ERROR("GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
3625 return nullptr;
3626 }
3627 }
3628
3629 int32_t appUid = 0;
3630 if (!wantSenderInfo.allWants.empty()) {
3631 AppExecFwk::BundleInfo bundleInfo;
3632 std::string bundleName = wantSenderInfo.allWants.back().want.GetElement().GetBundleName();
3633 bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(bundleName,
3634 AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
3635 if (bundleMgrResult) {
3636 appUid = bundleInfo.uid;
3637 }
3638 HILOG_DEBUG("App bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), appUid);
3639 }
3640 if (!CheckSenderWantInfo(callerUid, wantSenderInfo)) {
3641 HILOG_ERROR("check bundleName failed");
3642 return nullptr;
3643 }
3644
3645 bool isSystemApp = false;
3646 if (!wantSenderInfo.bundleName.empty()) {
3647 AppExecFwk::BundleInfo bundleInfo;
3648 bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(wantSenderInfo.bundleName,
3649 AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
3650 if (bundleMgrResult) {
3651 isSystemApp = bundleInfo.applicationInfo.isSystemApp;
3652 }
3653 }
3654
3655 HILOG_DEBUG("bundleName = %{public}s", wantSenderInfo.bundleName.c_str());
3656 return pendingWantManager_->GetWantSender(callerUid, appUid, isSystemApp, wantSenderInfo, callerToken);
3657 }
3658
SendWantSender(sptr<IWantSender> target,const SenderInfo & senderInfo)3659 int AbilityManagerService::SendWantSender(sptr<IWantSender> target, const SenderInfo &senderInfo)
3660 {
3661 HILOG_INFO("Send want sender.");
3662 CHECK_POINTER_AND_RETURN(pendingWantManager_, ERR_INVALID_VALUE);
3663 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
3664 return pendingWantManager_->SendWantSender(target, senderInfo);
3665 }
3666
CancelWantSender(const sptr<IWantSender> & sender)3667 void AbilityManagerService::CancelWantSender(const sptr<IWantSender> &sender)
3668 {
3669 HILOG_DEBUG("called.");
3670 CHECK_POINTER(pendingWantManager_);
3671 CHECK_POINTER(sender);
3672
3673 sptr<IRemoteObject> obj = sender->AsObject();
3674 if (!obj || obj->IsProxyObject()) {
3675 HILOG_ERROR("obj is nullptr or obj is a proxy obj.");
3676 return;
3677 }
3678
3679 auto bms = GetBundleManager();
3680 CHECK_POINTER(bms);
3681
3682 int32_t callerUid = IPCSkeleton::GetCallingUid();
3683 sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
3684
3685 int userId = -1;
3686 if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
3687 GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
3688 HILOG_ERROR("GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
3689 return;
3690 }
3691 bool isSystemApp = false;
3692 if (record->GetKey() != nullptr && !record->GetKey()->GetBundleName().empty()) {
3693 AppExecFwk::BundleInfo bundleInfo;
3694 bool bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(record->GetKey()->GetBundleName(),
3695 AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
3696 if (!bundleMgrResult) {
3697 HILOG_ERROR("GetBundleInfo is fail.");
3698 return;
3699 }
3700 isSystemApp = bundleInfo.applicationInfo.isSystemApp;
3701 }
3702
3703 pendingWantManager_->CancelWantSender(isSystemApp, sender);
3704 }
3705
GetPendingWantUid(const sptr<IWantSender> & target)3706 int AbilityManagerService::GetPendingWantUid(const sptr<IWantSender> &target)
3707 {
3708 HILOG_INFO("%{public}s:begin.", __func__);
3709
3710 if (pendingWantManager_ == nullptr) {
3711 HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__);
3712 return -1;
3713 }
3714 if (target == nullptr) {
3715 HILOG_ERROR("%s, target is nullptr", __func__);
3716 return -1;
3717 }
3718 return pendingWantManager_->GetPendingWantUid(target);
3719 }
3720
GetPendingWantUserId(const sptr<IWantSender> & target)3721 int AbilityManagerService::GetPendingWantUserId(const sptr<IWantSender> &target)
3722 {
3723 HILOG_INFO("%{public}s:begin.", __func__);
3724
3725 if (pendingWantManager_ == nullptr) {
3726 HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__);
3727 return -1;
3728 }
3729 if (target == nullptr) {
3730 HILOG_ERROR("%s, target is nullptr", __func__);
3731 return -1;
3732 }
3733 return pendingWantManager_->GetPendingWantUserId(target);
3734 }
3735
GetPendingWantBundleName(const sptr<IWantSender> & target)3736 std::string AbilityManagerService::GetPendingWantBundleName(const sptr<IWantSender> &target)
3737 {
3738 HILOG_INFO("Get pending want bundle name.");
3739 CHECK_POINTER_AND_RETURN(pendingWantManager_, "");
3740 CHECK_POINTER_AND_RETURN(target, "");
3741 return pendingWantManager_->GetPendingWantBundleName(target);
3742 }
3743
GetPendingWantCode(const sptr<IWantSender> & target)3744 int AbilityManagerService::GetPendingWantCode(const sptr<IWantSender> &target)
3745 {
3746 HILOG_INFO("%{public}s:begin.", __func__);
3747
3748 if (pendingWantManager_ == nullptr) {
3749 HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__);
3750 return -1;
3751 }
3752 if (target == nullptr) {
3753 HILOG_ERROR("%s, target is nullptr", __func__);
3754 return -1;
3755 }
3756 return pendingWantManager_->GetPendingWantCode(target);
3757 }
3758
GetPendingWantType(const sptr<IWantSender> & target)3759 int AbilityManagerService::GetPendingWantType(const sptr<IWantSender> &target)
3760 {
3761 HILOG_INFO("%{public}s:begin.", __func__);
3762
3763 if (pendingWantManager_ == nullptr) {
3764 HILOG_ERROR("%s, pendingWantManager_ is nullptr", __func__);
3765 return -1;
3766 }
3767 if (target == nullptr) {
3768 HILOG_ERROR("%s, target is nullptr", __func__);
3769 return -1;
3770 }
3771 return pendingWantManager_->GetPendingWantType(target);
3772 }
3773
RegisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)3774 void AbilityManagerService::RegisterCancelListener(const sptr<IWantSender> &sender,
3775 const sptr<IWantReceiver> &receiver)
3776 {
3777 HILOG_INFO("Register cancel listener.");
3778 CHECK_POINTER(pendingWantManager_);
3779 CHECK_POINTER(sender);
3780 CHECK_POINTER(receiver);
3781 pendingWantManager_->RegisterCancelListener(sender, receiver);
3782 }
3783
UnregisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)3784 void AbilityManagerService::UnregisterCancelListener(
3785 const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)
3786 {
3787 HILOG_INFO("Unregister cancel listener.");
3788 CHECK_POINTER(pendingWantManager_);
3789 CHECK_POINTER(sender);
3790 CHECK_POINTER(receiver);
3791 pendingWantManager_->UnregisterCancelListener(sender, receiver);
3792 }
3793
GetPendingRequestWant(const sptr<IWantSender> & target,std::shared_ptr<Want> & want)3794 int AbilityManagerService::GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)
3795 {
3796 HILOG_DEBUG("Get pending request want.");
3797 CHECK_POINTER_AND_RETURN(pendingWantManager_, ERR_INVALID_VALUE);
3798 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
3799 CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE);
3800 CHECK_CALLER_IS_SYSTEM_APP;
3801 return pendingWantManager_->GetPendingRequestWant(target, want);
3802 }
3803
LockMissionForCleanup(int32_t missionId)3804 int AbilityManagerService::LockMissionForCleanup(int32_t missionId)
3805 {
3806 HILOG_INFO("request unlock mission for clean up all, id :%{public}d", missionId);
3807 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3808 CHECK_CALLER_IS_SYSTEM_APP;
3809
3810 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3811 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3812 return CHECK_PERMISSION_FAILED;
3813 }
3814 return currentMissionListManager_->SetMissionLockedState(missionId, true);
3815 }
3816
UnlockMissionForCleanup(int32_t missionId)3817 int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId)
3818 {
3819 HILOG_INFO("request unlock mission for clean up all, id :%{public}d", missionId);
3820 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3821 CHECK_CALLER_IS_SYSTEM_APP;
3822
3823 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3824 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3825 return CHECK_PERMISSION_FAILED;
3826 }
3827 return currentMissionListManager_->SetMissionLockedState(missionId, false);
3828 }
3829
SetLockedState(int32_t sessionId,bool lockedState)3830 void AbilityManagerService::SetLockedState(int32_t sessionId, bool lockedState)
3831 {
3832 HILOG_INFO("request lock abilityRecord, sessionId :%{public}d", sessionId);
3833 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
3834 HILOG_ERROR("Not sceneboard called, not allowed.");
3835 return;
3836 }
3837 auto abilityRecord = uiAbilityLifecycleManager_->GetAbilityRecordsById(sessionId);
3838 if (!abilityRecord) {
3839 HILOG_ERROR("abilityRecord is null.");
3840 return;
3841 }
3842 abilityRecord->SetLockedState(lockedState);
3843 }
3844
RegisterMissionListener(const sptr<IMissionListener> & listener)3845 int AbilityManagerService::RegisterMissionListener(const sptr<IMissionListener> &listener)
3846 {
3847 HILOG_INFO("request RegisterMissionListener ");
3848 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3849 CHECK_CALLER_IS_SYSTEM_APP;
3850
3851 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3852 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3853 return CHECK_PERMISSION_FAILED;
3854 }
3855 return currentMissionListManager_->RegisterMissionListener(listener);
3856 }
3857
UnRegisterMissionListener(const sptr<IMissionListener> & listener)3858 int AbilityManagerService::UnRegisterMissionListener(const sptr<IMissionListener> &listener)
3859 {
3860 HILOG_INFO("request RegisterMissionListener ");
3861 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3862 CHECK_CALLER_IS_SYSTEM_APP;
3863
3864 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3865 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3866 return CHECK_PERMISSION_FAILED;
3867 }
3868 return currentMissionListManager_->UnRegisterMissionListener(listener);
3869 }
3870
GetMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)3871 int AbilityManagerService::GetMissionInfos(const std::string& deviceId, int32_t numMax,
3872 std::vector<MissionInfo> &missionInfos)
3873 {
3874 HILOG_INFO("request GetMissionInfos.");
3875 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3876 CHECK_CALLER_IS_SYSTEM_APP;
3877
3878 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3879 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3880 return CHECK_PERMISSION_FAILED;
3881 }
3882
3883 if (CheckIsRemote(deviceId)) {
3884 return GetRemoteMissionInfos(deviceId, numMax, missionInfos);
3885 }
3886
3887 return currentMissionListManager_->GetMissionInfos(numMax, missionInfos);
3888 }
3889
GetRemoteMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)3890 int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax,
3891 std::vector<MissionInfo> &missionInfos)
3892 {
3893 HILOG_INFO("GetRemoteMissionInfos begin");
3894 DistributedClient dmsClient;
3895 int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos);
3896 if (result != ERR_OK) {
3897 HILOG_ERROR("GetRemoteMissionInfos failed, result = %{public}d", result);
3898 return result;
3899 }
3900 return ERR_OK;
3901 }
3902
GetMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)3903 int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId,
3904 MissionInfo &missionInfo)
3905 {
3906 HILOG_INFO("request GetMissionInfo, missionId:%{public}d", missionId);
3907 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3908 CHECK_CALLER_IS_SYSTEM_APP;
3909
3910 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3911 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3912 return CHECK_PERMISSION_FAILED;
3913 }
3914
3915 if (CheckIsRemote(deviceId)) {
3916 return GetRemoteMissionInfo(deviceId, missionId, missionInfo);
3917 }
3918
3919 return currentMissionListManager_->GetMissionInfo(missionId, missionInfo);
3920 }
3921
GetRemoteMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)3922 int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId,
3923 MissionInfo &missionInfo)
3924 {
3925 HILOG_INFO("GetMissionInfoFromDms begin");
3926 std::vector<MissionInfo> missionVector;
3927 int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector);
3928 if (result != ERR_OK) {
3929 return result;
3930 }
3931 for (auto iter = missionVector.begin(); iter != missionVector.end(); iter++) {
3932 if (iter->id == missionId) {
3933 missionInfo = *iter;
3934 return ERR_OK;
3935 }
3936 }
3937 HILOG_WARN("missionId not found");
3938 return ERR_INVALID_VALUE;
3939 }
3940
CleanMission(int32_t missionId)3941 int AbilityManagerService::CleanMission(int32_t missionId)
3942 {
3943 HILOG_INFO("request CleanMission, missionId:%{public}d", missionId);
3944 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3945 CHECK_CALLER_IS_SYSTEM_APP;
3946
3947 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3948 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3949 return CHECK_PERMISSION_FAILED;
3950 }
3951
3952 return currentMissionListManager_->ClearMission(missionId);
3953 }
3954
CleanAllMissions()3955 int AbilityManagerService::CleanAllMissions()
3956 {
3957 HILOG_INFO("request CleanAllMissions ");
3958 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3959 CHECK_CALLER_IS_SYSTEM_APP;
3960
3961 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3962 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3963 return CHECK_PERMISSION_FAILED;
3964 }
3965
3966 Want want;
3967 want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME);
3968 if (!IsAbilityControllerStart(want, AbilityConfig::LAUNCHER_BUNDLE_NAME)) {
3969 HILOG_ERROR("IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
3970 return ERR_WOULD_BLOCK;
3971 }
3972
3973 return currentMissionListManager_->ClearAllMissions();
3974 }
3975
MoveMissionToFront(int32_t missionId)3976 int AbilityManagerService::MoveMissionToFront(int32_t missionId)
3977 {
3978 HILOG_INFO("request MoveMissionToFront, missionId:%{public}d", missionId);
3979 CHECK_CALLER_IS_SYSTEM_APP;
3980 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
3981 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
3982 return CHECK_PERMISSION_FAILED;
3983 }
3984
3985 if (!IsAbilityControllerStartById(missionId)) {
3986 HILOG_ERROR("IsAbilityControllerStart false");
3987 return ERR_WOULD_BLOCK;
3988 }
3989
3990 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3991 if (!uiAbilityLifecycleManager_) {
3992 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
3993 return ERR_INVALID_VALUE;
3994 }
3995 return uiAbilityLifecycleManager_->MoveMissionToFront(missionId);
3996 }
3997
3998 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
3999
4000 return currentMissionListManager_->MoveMissionToFront(missionId);
4001 }
4002
MoveMissionToFront(int32_t missionId,const StartOptions & startOptions)4003 int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)
4004 {
4005 HILOG_INFO("request MoveMissionToFront, missionId:%{public}d", missionId);
4006 CHECK_CALLER_IS_SYSTEM_APP;
4007 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4008 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
4009 return CHECK_PERMISSION_FAILED;
4010 }
4011
4012 if (!IsAbilityControllerStartById(missionId)) {
4013 HILOG_ERROR("IsAbilityControllerStart false");
4014 return ERR_WOULD_BLOCK;
4015 }
4016
4017 auto options = std::make_shared<StartOptions>(startOptions);
4018 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4019 if (!uiAbilityLifecycleManager_) {
4020 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
4021 return ERR_INVALID_VALUE;
4022 }
4023 return uiAbilityLifecycleManager_->MoveMissionToFront(missionId, options);
4024 }
4025 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
4026
4027 return currentMissionListManager_->MoveMissionToFront(missionId, options);
4028 }
4029
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)4030 int AbilityManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
4031 {
4032 CHECK_CALLER_IS_SYSTEM_APP;
4033 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4034 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
4035 return CHECK_PERMISSION_FAILED;
4036 }
4037 if (wmsHandler_) {
4038 auto ret = wmsHandler_->MoveMissionsToForeground(missionIds, topMissionId);
4039 if (ret) {
4040 HILOG_ERROR("MoveMissionsToForeground failed, missiondIds may be invalid");
4041 return ERR_INVALID_VALUE;
4042 } else {
4043 return NO_ERROR;
4044 }
4045 }
4046 return ERR_NO_INIT;
4047 }
4048
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)4049 int AbilityManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
4050 std::vector<int32_t>& result)
4051 {
4052 CHECK_CALLER_IS_SYSTEM_APP;
4053 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4054 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
4055 return CHECK_PERMISSION_FAILED;
4056 }
4057 if (wmsHandler_) {
4058 auto ret = wmsHandler_->MoveMissionsToBackground(missionIds, result);
4059 if (ret) {
4060 HILOG_ERROR("MoveMissionsToBackground failed, missiondIds may be invalid");
4061 return ERR_INVALID_VALUE;
4062 } else {
4063 return NO_ERROR;
4064 }
4065 }
4066 return ERR_NO_INIT;
4067 }
4068
GetMissionIdByToken(const sptr<IRemoteObject> & token)4069 int32_t AbilityManagerService::GetMissionIdByToken(const sptr<IRemoteObject> &token)
4070 {
4071 HILOG_INFO("request GetMissionIdByToken.");
4072 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4073 if (!abilityRecord) {
4074 HILOG_ERROR("abilityRecord is null.");
4075 return ERR_INVALID_VALUE;
4076 }
4077 if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
4078 HILOG_ERROR("Permission deny.");
4079 return ERR_INVALID_VALUE;
4080 }
4081 return GetMissionIdByAbilityTokenInner(token);
4082 }
4083
IsAbilityControllerStartById(int32_t missionId)4084 bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId)
4085 {
4086 InnerMissionInfo innerMissionInfo;
4087 int getMission = DelayedSingleton<MissionInfoMgr>::GetInstance()->GetInnerMissionInfoById(
4088 missionId, innerMissionInfo);
4089 if (getMission != ERR_OK) {
4090 HILOG_ERROR("cannot find mission info from MissionInfoList by missionId: %{public}d", missionId);
4091 return true;
4092 }
4093 if (!IsAbilityControllerStart(innerMissionInfo.missionInfo.want, innerMissionInfo.missionInfo.want.GetBundle())) {
4094 HILOG_ERROR("IsAbilityControllerStart failed: %{public}s",
4095 innerMissionInfo.missionInfo.want.GetBundle().c_str());
4096 return false;
4097 }
4098 return true;
4099 }
4100
GetServiceRecordByElementName(const std::string & element)4101 std::shared_ptr<AbilityRecord> AbilityManagerService::GetServiceRecordByElementName(const std::string &element)
4102 {
4103 if (!connectManager_) {
4104 HILOG_ERROR("Connect manager is nullptr.");
4105 return nullptr;
4106 }
4107 return connectManager_->GetServiceRecordByElementName(element);
4108 }
4109
GetConnectRecordListByCallback(sptr<IAbilityConnection> callback)4110 std::list<std::shared_ptr<ConnectionRecord>> AbilityManagerService::GetConnectRecordListByCallback(
4111 sptr<IAbilityConnection> callback)
4112 {
4113 if (!connectManager_) {
4114 HILOG_ERROR("Connect manager is nullptr.");
4115 std::list<std::shared_ptr<ConnectionRecord>> connectList;
4116 return connectList;
4117 }
4118 return connectManager_->GetConnectRecordListByCallback(callback);
4119 }
4120
AcquireDataAbility(const Uri & uri,bool tryBind,const sptr<IRemoteObject> & callerToken)4121 sptr<IAbilityScheduler> AbilityManagerService::AcquireDataAbility(
4122 const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
4123 {
4124 auto bms = GetBundleManager();
4125 CHECK_POINTER_AND_RETURN(bms, nullptr);
4126
4127 auto localUri(uri);
4128 if (localUri.GetScheme() != AbilityConfig::SCHEME_DATA_ABILITY) {
4129 HILOG_ERROR("Acquire data ability with invalid uri scheme.");
4130 return nullptr;
4131 }
4132 std::vector<std::string> pathSegments;
4133 localUri.GetPathSegments(pathSegments);
4134 if (pathSegments.empty()) {
4135 HILOG_ERROR("Acquire data ability with invalid uri path.");
4136 return nullptr;
4137 }
4138
4139 auto userId = GetValidUserId(INVALID_USER_ID);
4140 AbilityRequest abilityRequest;
4141 std::string dataAbilityUri = localUri.ToString();
4142 HILOG_INFO("called. userId %{public}d", userId);
4143 bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo));
4144 if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) {
4145 HILOG_ERROR("Invalid ability info for data ability acquiring.");
4146 return nullptr;
4147 }
4148
4149 abilityRequest.callerToken = callerToken;
4150 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
4151 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
4152 if (!isSaCall && CheckCallDataAbilityPermission(abilityRequest, isShellCall, isSaCall) != ERR_OK) {
4153 HILOG_ERROR("Invalid ability request info for data ability acquiring.");
4154 return nullptr;
4155 }
4156
4157 HILOG_DEBUG("Query data ability info: %{public}s|%{public}s|%{public}s",
4158 abilityRequest.appInfo.name.c_str(), abilityRequest.appInfo.bundleName.c_str(),
4159 abilityRequest.abilityInfo.name.c_str());
4160
4161 if (CheckStaticCfgPermission(abilityRequest.abilityInfo, false, -1, true, isSaCall) !=
4162 AppExecFwk::Constants::PERMISSION_GRANTED) {
4163 if (!VerificationAllToken(callerToken)) {
4164 HILOG_INFO("VerificationAllToken fail");
4165 return nullptr;
4166 }
4167 }
4168
4169 if (abilityRequest.abilityInfo.applicationInfo.singleton) {
4170 userId = U0_USER_ID;
4171 }
4172
4173 std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManagerByUserId(userId);
4174 CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr);
4175 ReportEventToSuspendManager(abilityRequest.abilityInfo);
4176 bool isNotHap = isSaCall || isShellCall;
4177 UpdateCallerInfo(abilityRequest.want, callerToken);
4178 return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap);
4179 }
4180
ReleaseDataAbility(sptr<IAbilityScheduler> dataAbilityScheduler,const sptr<IRemoteObject> & callerToken)4181 int AbilityManagerService::ReleaseDataAbility(
4182 sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
4183 {
4184 HILOG_INFO("%{public}s, called.", __func__);
4185 if (!dataAbilityScheduler || !callerToken) {
4186 HILOG_ERROR("dataAbilitySchedule or callerToken is nullptr");
4187 return ERR_INVALID_VALUE;
4188 }
4189
4190 std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler);
4191 if (!dataAbilityManager) {
4192 HILOG_ERROR("dataAbilityScheduler is not exists");
4193 return ERR_INVALID_VALUE;
4194 }
4195
4196 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
4197 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
4198 bool isNotHap = isSaCall || isShellCall;
4199 return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isNotHap);
4200 }
4201
AttachAbilityThread(const sptr<IAbilityScheduler> & scheduler,const sptr<IRemoteObject> & token)4202 int AbilityManagerService::AttachAbilityThread(
4203 const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
4204 {
4205 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4206 HILOG_DEBUG("called.");
4207 CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE);
4208 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
4209 return ERR_INVALID_VALUE;
4210 }
4211 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4212 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4213 if (!JudgeSelfCalled(abilityRecord)) {
4214 return CHECK_PERMISSION_FAILED;
4215 }
4216
4217 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4218 auto abilityInfo = abilityRecord->GetAbilityInfo();
4219 auto type = abilityInfo.type;
4220 // force timeout ability for test
4221 if (IsNeedTimeoutForTest(abilityInfo.name, AbilityRecord::ConvertAbilityState(AbilityState::INITIAL))) {
4222 HILOG_WARN("force timeout ability for test, state:INITIAL, ability: %{public}s", abilityInfo.name.c_str());
4223 return ERR_OK;
4224 }
4225 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
4226 auto connectManager = GetConnectManagerByUserId(userId);
4227 if (!connectManager) {
4228 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
4229 return ERR_INVALID_VALUE;
4230 }
4231 return connectManager->AttachAbilityThreadLocked(scheduler, token);
4232 } else if (type == AppExecFwk::AbilityType::DATA) {
4233 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
4234 if (!dataAbilityManager) {
4235 HILOG_ERROR("dataAbilityManager is Null. userId=%{public}d", userId);
4236 return ERR_INVALID_VALUE;
4237 }
4238 return dataAbilityManager->AttachAbilityThread(scheduler, token);
4239 } else {
4240 FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::LOAD };
4241 auto entry = std::to_string(AbilityUtil::SystemTimeMillis()) + "; AbilityManagerService::AttachAbilityThread;" +
4242 " the end of load lifecycle.";
4243 FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
4244 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4245 return uiAbilityLifecycleManager_->AttachAbilityThread(scheduler, token);
4246 }
4247 int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
4248 auto missionListManager = GetListManagerByUserId(ownerMissionUserId);
4249 if (!missionListManager) {
4250 HILOG_ERROR("missionListManager is Null. userId=%{public}d", ownerMissionUserId);
4251 return ERR_INVALID_VALUE;
4252 }
4253 return missionListManager->AttachAbilityThread(scheduler, token);
4254 }
4255 }
4256
DumpFuncInit()4257 void AbilityManagerService::DumpFuncInit()
4258 {
4259 dumpFuncMap_[KEY_DUMP_SERVICE] = &AbilityManagerService::DumpStateInner;
4260 dumpFuncMap_[KEY_DUMP_DATA] = &AbilityManagerService::DataDumpStateInner;
4261
4262 dumpFuncMap_[KEY_DUMP_ALL] = &AbilityManagerService::DumpInner;
4263 dumpFuncMap_[KEY_DUMP_MISSION] = &AbilityManagerService::DumpMissionInner;
4264 dumpFuncMap_[KEY_DUMP_MISSION_LIST] = &AbilityManagerService::DumpMissionListInner;
4265 dumpFuncMap_[KEY_DUMP_MISSION_INFOS] = &AbilityManagerService::DumpMissionInfosInner;
4266 }
4267
DumpSysFuncInit()4268 void AbilityManagerService::DumpSysFuncInit()
4269 {
4270 dumpsysFuncMap_[KEY_DUMPSYS_ALL] = &AbilityManagerService::DumpSysInner;
4271 dumpsysFuncMap_[KEY_DUMPSYS_SERVICE] = &AbilityManagerService::DumpSysStateInner;
4272 dumpsysFuncMap_[KEY_DUMPSYS_PENDING] = &AbilityManagerService::DumpSysPendingInner;
4273 dumpsysFuncMap_[KEY_DUMPSYS_PROCESS] = &AbilityManagerService::DumpSysProcess;
4274 dumpsysFuncMap_[KEY_DUMPSYS_DATA] = &AbilityManagerService::DataDumpSysStateInner;
4275
4276 dumpsysFuncMap_[KEY_DUMPSYS_MISSION_LIST] = &AbilityManagerService::DumpSysMissionListInner;
4277 dumpsysFuncMap_[KEY_DUMPSYS_ABILITY] = &AbilityManagerService::DumpSysAbilityInner;
4278 }
4279
DumpSysInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4280 void AbilityManagerService::DumpSysInner(
4281 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
4282 {
4283 std::vector<std::string> argList;
4284 SplitStr(args, " ", argList);
4285 if (argList.empty()) {
4286 return;
4287 }
4288
4289 DumpSysMissionListInner(args, info, isClient, isUserID, userId);
4290 DumpSysStateInner(args, info, isClient, isUserID, userId);
4291 DumpSysPendingInner(args, info, isClient, isUserID, userId);
4292 DumpSysProcess(args, info, isClient, isUserID, userId);
4293 }
4294
DumpSysMissionListInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4295 void AbilityManagerService::DumpSysMissionListInner(
4296 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
4297 {
4298 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4299 DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId);
4300 return;
4301 }
4302 std::shared_ptr<MissionListManager> targetManager;
4303 if (isUserID) {
4304 std::lock_guard<ffrt::mutex> lock(managersMutex_);
4305 auto it = missionListManagers_.find(userId);
4306 if (it == missionListManagers_.end()) {
4307 info.push_back("error: No user found.");
4308 return;
4309 }
4310 targetManager = it->second;
4311 } else {
4312 targetManager = currentMissionListManager_;
4313 }
4314
4315 CHECK_POINTER(targetManager);
4316
4317 std::vector<std::string> argList;
4318 SplitStr(args, " ", argList);
4319 if (argList.empty()) {
4320 return;
4321 }
4322
4323 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
4324 targetManager->DumpMissionList(info, isClient, argList[1]);
4325 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4326 targetManager->DumpMissionList(info, isClient);
4327 } else {
4328 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4329 }
4330 }
4331
DumpSysMissionListInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4332 void AbilityManagerService::DumpSysMissionListInnerBySCB(
4333 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
4334 {
4335 if (isUserID) {
4336 if (!CheckUserIdActive(userId)) {
4337 info.push_back("error: No user found.");
4338 return;
4339 }
4340 } else {
4341 userId = GetUserId();
4342 }
4343
4344 std::vector<std::string> argList;
4345 SplitStr(args, " ", argList);
4346 if (argList.empty()) {
4347 return;
4348 }
4349
4350 if (!uiAbilityLifecycleManager_) {
4351 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
4352 return;
4353 }
4354
4355 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
4356 uiAbilityLifecycleManager_->DumpMissionList(info, isClient, userId, argList[1]);
4357 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4358 uiAbilityLifecycleManager_->DumpMissionList(info, isClient, userId);
4359 } else {
4360 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4361 }
4362 }
4363
DumpSysAbilityInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4364 void AbilityManagerService::DumpSysAbilityInner(
4365 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
4366 {
4367 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4368 DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId);
4369 return;
4370 }
4371 std::shared_ptr<MissionListManager> targetManager;
4372 if (isUserID) {
4373 std::lock_guard<ffrt::mutex> lock(managersMutex_);
4374 auto it = missionListManagers_.find(userId);
4375 if (it == missionListManagers_.end()) {
4376 info.push_back("error: No user found.");
4377 return;
4378 }
4379 targetManager = it->second;
4380 } else {
4381 targetManager = currentMissionListManager_;
4382 }
4383
4384 CHECK_POINTER(targetManager);
4385
4386 std::vector<std::string> argList;
4387 SplitStr(args, " ", argList);
4388 if (argList.empty()) {
4389 return;
4390 }
4391 if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
4392 HILOG_INFO("argList = %{public}s", argList[1].c_str());
4393 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
4394 try {
4395 auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
4396 targetManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
4397 } catch (...) {
4398 HILOG_WARN("stoi(%{public}s) failed", argList[1].c_str());
4399 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4400 }
4401 } else {
4402 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4403 }
4404 }
4405
DumpSysAbilityInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4406 void AbilityManagerService::DumpSysAbilityInnerBySCB(
4407 const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
4408 {
4409 if (isUserID) {
4410 if (!CheckUserIdActive(userId)) {
4411 info.push_back("error: No user found.");
4412 return;
4413 }
4414 } else {
4415 userId = GetUserId();
4416 }
4417
4418 std::vector<std::string> argList;
4419 SplitStr(args, " ", argList);
4420 if (argList.empty()) {
4421 return;
4422 }
4423 if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
4424 HILOG_INFO("argList = %{public}s", argList[1].c_str());
4425 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
4426 try {
4427 auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
4428
4429 if (!uiAbilityLifecycleManager_) {
4430 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
4431 return;
4432 }
4433 uiAbilityLifecycleManager_->DumpMissionListByRecordId(info, isClient, abilityId, params, userId);
4434 } catch (...) {
4435 HILOG_WARN("stoi(%{public}s) failed", argList[1].c_str());
4436 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4437 }
4438 } else {
4439 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4440 }
4441 }
4442
DumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4443 void AbilityManagerService::DumpSysStateInner(
4444 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
4445 {
4446 HILOG_INFO("DumpSysStateInner begin:%{public}s", args.c_str());
4447 std::shared_ptr<AbilityConnectManager> targetManager;
4448
4449 if (isUserID) {
4450 std::lock_guard<ffrt::mutex> lock(managersMutex_);
4451 auto it = connectManagers_.find(userId);
4452 if (it == connectManagers_.end()) {
4453 info.push_back("error: No user found.");
4454 return;
4455 }
4456 targetManager = it->second;
4457 } else {
4458 targetManager = connectManager_;
4459 }
4460
4461 CHECK_POINTER(targetManager);
4462
4463 std::vector<std::string> argList;
4464 SplitStr(args, " ", argList);
4465 if (argList.empty()) {
4466 return;
4467 }
4468
4469 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
4470 targetManager->DumpState(info, isClient, argList[1]);
4471 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4472 targetManager->DumpState(info, isClient);
4473 } else {
4474 HILOG_INFO("uri = %{public}s", argList[1].c_str());
4475 std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
4476 targetManager->DumpStateByUri(info, isClient, argList[1], params);
4477 }
4478 }
4479
DumpSysPendingInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4480 void AbilityManagerService::DumpSysPendingInner(
4481 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
4482 {
4483 std::shared_ptr<PendingWantManager> targetManager;
4484 if (isUserID) {
4485 std::lock_guard<ffrt::mutex> lock(managersMutex_);
4486 auto it = pendingWantManagers_.find(userId);
4487 if (it == pendingWantManagers_.end()) {
4488 info.push_back("error: No user found.");
4489 return;
4490 }
4491 targetManager = it->second;
4492 } else {
4493 targetManager = pendingWantManager_;
4494 }
4495
4496 CHECK_POINTER(targetManager);
4497
4498 std::vector<std::string> argList;
4499 SplitStr(args, " ", argList);
4500 if (argList.empty()) {
4501 return;
4502 }
4503
4504 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
4505 targetManager->DumpByRecordId(info, argList[1]);
4506 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4507 targetManager->Dump(info);
4508 } else {
4509 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4510 }
4511 }
4512
DumpSysProcess(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4513 void AbilityManagerService::DumpSysProcess(
4514 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
4515 {
4516 std::vector<std::string> argList;
4517 SplitStr(args, " ", argList);
4518 if (argList.empty()) {
4519 return;
4520 }
4521 std::vector<AppExecFwk::RunningProcessInfo> ProcessInfos;
4522 int ret = 0;
4523 if (isUserID) {
4524 ret = GetProcessRunningInfosByUserId(ProcessInfos, userId);
4525 } else {
4526 ret = GetProcessRunningInfos(ProcessInfos);
4527 }
4528
4529 if (ret != ERR_OK || ProcessInfos.size() == 0) {
4530 return;
4531 }
4532
4533 std::string dumpInfo = " AppRunningRecords:";
4534 info.push_back(dumpInfo);
4535 auto processInfoID = 0;
4536 auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false);
4537 for (const auto& ProcessInfo : ProcessInfos) {
4538 if (hasProcessName && argList[1] != ProcessInfo.processName_) {
4539 continue;
4540 }
4541
4542 dumpInfo = " AppRunningRecord ID #" + std::to_string(processInfoID);
4543 processInfoID++;
4544 info.push_back(dumpInfo);
4545 dumpInfo = " process name [" + ProcessInfo.processName_ + "]";
4546 info.push_back(dumpInfo);
4547 dumpInfo = " pid #" + std::to_string(ProcessInfo.pid_) +
4548 " uid #" + std::to_string(ProcessInfo.uid_);
4549 info.push_back(dumpInfo);
4550 auto appState = static_cast<AppState>(ProcessInfo.state_);
4551 dumpInfo = " state #" + DelayedSingleton<AppScheduler>::GetInstance()->ConvertAppState(appState);
4552 info.push_back(dumpInfo);
4553 }
4554 }
4555
DataDumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4556 void AbilityManagerService::DataDumpSysStateInner(
4557 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
4558 {
4559 std::shared_ptr<DataAbilityManager> targetManager;
4560 if (isUserID) {
4561 std::lock_guard<ffrt::mutex> lock(managersMutex_);
4562 auto it = dataAbilityManagers_.find(userId);
4563 if (it == dataAbilityManagers_.end()) {
4564 info.push_back("error: No user found.");
4565 return;
4566 }
4567 targetManager = it->second;
4568 } else {
4569 targetManager = dataAbilityManager_;
4570 }
4571
4572 CHECK_POINTER(targetManager);
4573
4574 std::vector<std::string> argList;
4575 SplitStr(args, " ", argList);
4576 if (argList.empty()) {
4577 return;
4578 }
4579 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
4580 targetManager->DumpSysState(info, isClient, argList[1]);
4581 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4582 targetManager->DumpSysState(info, isClient);
4583 } else {
4584 info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
4585 }
4586 }
4587
DumpInner(const std::string & args,std::vector<std::string> & info)4588 void AbilityManagerService::DumpInner(const std::string &args, std::vector<std::string> &info)
4589 {
4590 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4591 if (!uiAbilityLifecycleManager_) {
4592 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
4593 return;
4594 }
4595 uiAbilityLifecycleManager_->Dump(info);
4596 return;
4597 }
4598
4599 if (currentMissionListManager_) {
4600 currentMissionListManager_->Dump(info);
4601 }
4602 }
4603
DumpMissionListInner(const std::string & args,std::vector<std::string> & info)4604 void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector<std::string> &info)
4605 {
4606 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4607 if (!uiAbilityLifecycleManager_) {
4608 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
4609 return;
4610 }
4611 uiAbilityLifecycleManager_->DumpMissionList(info, false, GetUserId(), " ");
4612 return;
4613 }
4614 if (currentMissionListManager_) {
4615 currentMissionListManager_->DumpMissionList(info, false, "");
4616 }
4617 }
4618
DumpMissionInfosInner(const std::string & args,std::vector<std::string> & info)4619 void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)
4620 {
4621 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4622 HILOG_INFO("call");
4623 Rosen::WindowManager::GetInstance().DumpSessionAll(info);
4624 return;
4625 }
4626 if (currentMissionListManager_) {
4627 currentMissionListManager_->DumpMissionInfos(info);
4628 }
4629 }
4630
DumpMissionInner(const std::string & args,std::vector<std::string> & info)4631 void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector<std::string> &info)
4632 {
4633 std::vector<std::string> argList;
4634 SplitStr(args, " ", argList);
4635 if (argList.empty()) {
4636 return;
4637 }
4638 if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4639 info.push_back("error: invalid argument, please see 'ability dump -h'.");
4640 return;
4641 }
4642 int missionId = DEFAULT_INVAL_VALUE;
4643 (void)StrToInt(argList[1], missionId);
4644
4645 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4646 HILOG_INFO("call");
4647 Rosen::WindowManager::GetInstance().DumpSessionWithId(missionId, info);
4648 return;
4649 }
4650
4651 CHECK_POINTER_LOG(currentMissionListManager_, "Current mission manager not init.");
4652 currentMissionListManager_->DumpMission(missionId, info);
4653 }
4654
DumpStateInner(const std::string & args,std::vector<std::string> & info)4655 void AbilityManagerService::DumpStateInner(const std::string &args, std::vector<std::string> &info)
4656 {
4657 CHECK_POINTER_LOG(connectManager_, "Current mission manager not init.");
4658 std::vector<std::string> argList;
4659 SplitStr(args, " ", argList);
4660 if (argList.empty()) {
4661 return;
4662 }
4663 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
4664 connectManager_->DumpState(info, false, argList[1]);
4665 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4666 connectManager_->DumpState(info, false);
4667 } else {
4668 info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
4669 }
4670 }
4671
DataDumpStateInner(const std::string & args,std::vector<std::string> & info)4672 void AbilityManagerService::DataDumpStateInner(const std::string &args, std::vector<std::string> &info)
4673 {
4674 std::vector<std::string> argList;
4675 SplitStr(args, " ", argList);
4676 if (argList.empty()) {
4677 return;
4678 }
4679 if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
4680 dataAbilityManager_->DumpState(info, argList[1]);
4681 } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
4682 dataAbilityManager_->DumpState(info);
4683 } else {
4684 info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
4685 }
4686 }
4687
DumpState(const std::string & args,std::vector<std::string> & info)4688 void AbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
4689 {
4690 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
4691 auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
4692 if (!isShellCall && !isHidumperServiceCall) {
4693 HILOG_ERROR("Permission deny.");
4694 return;
4695 }
4696 std::vector<std::string> argList;
4697 SplitStr(args, " ", argList);
4698 if (argList.empty()) {
4699 return;
4700 }
4701 auto it = dumpMap.find(argList[0]);
4702 if (it == dumpMap.end()) {
4703 return;
4704 }
4705 DumpKey key = it->second;
4706 auto itFunc = dumpFuncMap_.find(key);
4707 if (itFunc != dumpFuncMap_.end()) {
4708 auto dumpFunc = itFunc->second;
4709 if (dumpFunc != nullptr) {
4710 (this->*dumpFunc)(args, info);
4711 return;
4712 }
4713 }
4714 info.push_back("error: invalid argument, please see 'ability dump -h'.");
4715 }
4716
DumpSysState(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)4717 void AbilityManagerService::DumpSysState(
4718 const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
4719 {
4720 HILOG_DEBUG("%{public}s begin", __func__);
4721 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
4722 auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
4723 if (!isShellCall && !isHidumperServiceCall) {
4724 HILOG_ERROR("Permission deny.");
4725 return;
4726 }
4727 std::vector<std::string> argList;
4728 SplitStr(args, " ", argList);
4729 if (argList.empty()) {
4730 return;
4731 }
4732 auto it = dumpsysMap.find(argList[0]);
4733 if (it == dumpsysMap.end()) {
4734 return;
4735 }
4736 DumpsysKey key = it->second;
4737 auto itFunc = dumpsysFuncMap_.find(key);
4738 if (itFunc != dumpsysFuncMap_.end()) {
4739 auto dumpsysFunc = itFunc->second;
4740 if (dumpsysFunc != nullptr) {
4741 (this->*dumpsysFunc)(args, info, isClient, isUserID, userId);
4742 return;
4743 }
4744 }
4745 info.push_back("error: invalid argument, please see 'ability dump -h'.");
4746 }
4747
AbilityTransitionDone(const sptr<IRemoteObject> & token,int state,const PacMap & saveData)4748 int AbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
4749 {
4750 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4751 HILOG_DEBUG("Lifecycle: state:%{public}d.", state);
4752 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
4753 return ERR_INVALID_VALUE;
4754 }
4755 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4756 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
4757 if (!JudgeSelfCalled(abilityRecord)) {
4758 return CHECK_PERMISSION_FAILED;
4759 }
4760
4761 auto abilityInfo = abilityRecord->GetAbilityInfo();
4762 HILOG_INFO("Lifecycle: ability: %{public}s.", abilityRecord->GetURI().c_str());
4763 auto type = abilityInfo.type;
4764 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4765 // force timeout ability for test
4766 int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast<AbilityLifeCycleState>(state));
4767 bool isTerminate = abilityRecord->IsAbilityState(AbilityState::TERMINATING) && targetState == AbilityState::INITIAL;
4768 std::string tempState = isTerminate ? AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) :
4769 AbilityRecord::ConvertAbilityState(static_cast<AbilityState>(targetState));
4770 if (IsNeedTimeoutForTest(abilityInfo.name, tempState)) {
4771 HILOG_WARN("force timeout ability for test, state:%{public}s, ability: %{public}s",
4772 tempState.c_str(),
4773 abilityInfo.name.c_str());
4774 return ERR_OK;
4775 }
4776 if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
4777 auto connectManager = GetConnectManagerByUserId(userId);
4778 if (!connectManager) {
4779 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
4780 return ERR_INVALID_VALUE;
4781 }
4782 return connectManager->AbilityTransitionDone(token, state);
4783 }
4784 if (type == AppExecFwk::AbilityType::DATA) {
4785 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
4786 if (!dataAbilityManager) {
4787 HILOG_ERROR("dataAbilityManager is Null. userId=%{public}d", userId);
4788 return ERR_INVALID_VALUE;
4789 }
4790 return dataAbilityManager->AbilityTransitionDone(token, state);
4791 }
4792
4793 if (targetState == AbilityState::BACKGROUND) {
4794 FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::BACKGROUND };
4795 auto entry = std::to_string(AbilityUtil::SystemTimeMillis()) +
4796 "; AbilityManagerService::AbilityTransitionDone; the end of background lifecycle.";
4797 FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
4798 } else if (targetState != AbilityState::INITIAL) {
4799 FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::FOREGROUND };
4800 auto entry = std::to_string(AbilityUtil::SystemTimeMillis()) +
4801 "; AbilityManagerService::AbilityTransitionDone; the end of foreground lifecycle.";
4802 entry += " the end of foreground lifecycle.";
4803 FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
4804 }
4805
4806 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4807 return uiAbilityLifecycleManager_->AbilityTransactionDone(token, state, saveData);
4808 } else {
4809 int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
4810 auto missionListManager = GetListManagerByUserId(ownerMissionUserId);
4811 if (!missionListManager) {
4812 HILOG_ERROR("missionListManager is Null. userId=%{public}d", ownerMissionUserId);
4813 return ERR_INVALID_VALUE;
4814 }
4815 return missionListManager->AbilityTransactionDone(token, state, saveData);
4816 }
4817 }
4818
ScheduleConnectAbilityDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & remoteObject)4819 int AbilityManagerService::ScheduleConnectAbilityDone(
4820 const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
4821 {
4822 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4823 HILOG_DEBUG("called.");
4824 if (!VerificationAllToken(token)) {
4825 return ERR_INVALID_VALUE;
4826 }
4827
4828 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4829 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4830 if (!JudgeSelfCalled(abilityRecord)) {
4831 return CHECK_PERMISSION_FAILED;
4832 }
4833
4834 auto type = abilityRecord->GetAbilityInfo().type;
4835 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4836 HILOG_ERROR("Connect ability failed, target ability is not service.");
4837 return TARGET_ABILITY_NOT_SERVICE;
4838 }
4839 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4840 auto connectManager = GetConnectManagerByUserId(userId);
4841 if (!connectManager) {
4842 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
4843 return ERR_INVALID_VALUE;
4844 }
4845 return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject);
4846 }
4847
ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> & token)4848 int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
4849 {
4850 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4851 HILOG_INFO("Schedule disconnect ability done.");
4852 if (!VerificationAllToken(token)) {
4853 return ERR_INVALID_VALUE;
4854 }
4855
4856 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4857 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4858 if (!JudgeSelfCalled(abilityRecord)) {
4859 return CHECK_PERMISSION_FAILED;
4860 }
4861
4862 auto type = abilityRecord->GetAbilityInfo().type;
4863 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4864 HILOG_ERROR("Connect ability failed, target ability is not service.");
4865 return TARGET_ABILITY_NOT_SERVICE;
4866 }
4867 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4868 auto connectManager = GetConnectManagerByUserId(userId);
4869 if (!connectManager) {
4870 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
4871 return ERR_INVALID_VALUE;
4872 }
4873 return connectManager->ScheduleDisconnectAbilityDoneLocked(token);
4874 }
4875
ScheduleCommandAbilityDone(const sptr<IRemoteObject> & token)4876 int AbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
4877 {
4878 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4879 HILOG_INFO("Schedule command ability done.");
4880 if (!VerificationAllToken(token)) {
4881 return ERR_INVALID_VALUE;
4882 }
4883
4884 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4885 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4886 if (!JudgeSelfCalled(abilityRecord)) {
4887 return CHECK_PERMISSION_FAILED;
4888 }
4889 // force timeout ability for test
4890 if (IsNeedTimeoutForTest(abilityRecord->GetAbilityInfo().name, std::string("COMMAND"))) {
4891 HILOG_WARN("force timeout ability for test, state:COMMAND, ability: %{public}s",
4892 abilityRecord->GetAbilityInfo().name.c_str());
4893 return ERR_OK;
4894 }
4895 auto type = abilityRecord->GetAbilityInfo().type;
4896 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4897 HILOG_ERROR("Connect ability failed, target ability is not service.");
4898 return TARGET_ABILITY_NOT_SERVICE;
4899 }
4900 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4901 auto connectManager = GetConnectManagerByUserId(userId);
4902 if (!connectManager) {
4903 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
4904 return ERR_INVALID_VALUE;
4905 }
4906 return connectManager->ScheduleCommandAbilityDoneLocked(token);
4907 }
4908
ScheduleCommandAbilityWindowDone(const sptr<IRemoteObject> & token,const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd,AbilityCommand abilityCmd)4909 int AbilityManagerService::ScheduleCommandAbilityWindowDone(
4910 const sptr<IRemoteObject> &token,
4911 const sptr<SessionInfo> &sessionInfo,
4912 WindowCommand winCmd,
4913 AbilityCommand abilityCmd)
4914 {
4915 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4916 HILOG_DEBUG("enter.");
4917 if (!VerificationAllToken(token)) {
4918 return ERR_INVALID_VALUE;
4919 }
4920
4921 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4922 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4923 if (!JudgeSelfCalled(abilityRecord)) {
4924 return CHECK_PERMISSION_FAILED;
4925 }
4926
4927 if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)
4928 && !UIExtensionUtils::IsWindowExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
4929 HILOG_ERROR("target ability is not ui or window extension.");
4930 return ERR_INVALID_VALUE;
4931 }
4932 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4933 auto connectManager = GetConnectManagerByUserId(userId);
4934 if (!connectManager) {
4935 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
4936 return ERR_INVALID_VALUE;
4937 }
4938 return connectManager->ScheduleCommandAbilityWindowDone(token, sessionInfo, winCmd, abilityCmd);
4939 }
4940
OnAbilityRequestDone(const sptr<IRemoteObject> & token,const int32_t state)4941 void AbilityManagerService::OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)
4942 {
4943 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4944 auto abilityRecord = Token::GetAbilityRecordByToken(token);
4945 CHECK_POINTER(abilityRecord);
4946 HILOG_DEBUG("name is %{public}s", abilityRecord->GetAbilityInfo().name.c_str());
4947 auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
4948
4949 auto type = abilityRecord->GetAbilityInfo().type;
4950 switch (type) {
4951 case AppExecFwk::AbilityType::DATA: {
4952 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
4953 if (!dataAbilityManager) {
4954 HILOG_ERROR("dataAbilityManager is Null. userId=%{public}d", userId);
4955 return;
4956 }
4957 dataAbilityManager->OnAbilityRequestDone(token, state);
4958 break;
4959 }
4960 case AppExecFwk::AbilityType::SERVICE:
4961 case AppExecFwk::AbilityType::EXTENSION: {
4962 auto connectManager = GetConnectManagerByUserId(userId);
4963 if (!connectManager) {
4964 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
4965 return;
4966 }
4967 connectManager->OnAbilityRequestDone(token, state);
4968 break;
4969 }
4970 default: {
4971 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4972 uiAbilityLifecycleManager_->OnAbilityRequestDone(token, state);
4973 } else {
4974 int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
4975 auto missionListManager = GetListManagerByUserId(ownerMissionUserId);
4976 if (!missionListManager) {
4977 HILOG_ERROR("missionListManager is Null. userId=%{public}d", ownerMissionUserId);
4978 return;
4979 }
4980 missionListManager->OnAbilityRequestDone(token, state);
4981 }
4982 break;
4983 }
4984 }
4985 }
4986
OnAppStateChanged(const AppInfo & info)4987 void AbilityManagerService::OnAppStateChanged(const AppInfo &info)
4988 {
4989 HILOG_DEBUG("called");
4990 CHECK_POINTER_LOG(connectManager_, "Connect manager not init.");
4991 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4992 CHECK_POINTER_LOG(currentMissionListManager_, "Current mission list manager not init.");
4993 }
4994 connectManager_->OnAppStateChanged(info);
4995 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4996 uiAbilityLifecycleManager_->OnAppStateChanged(info, GetUserId());
4997 } else {
4998 currentMissionListManager_->OnAppStateChanged(info);
4999 }
5000 dataAbilityManager_->OnAppStateChanged(info);
5001 }
5002
GetEventHandler()5003 std::shared_ptr<AbilityEventHandler> AbilityManagerService::GetEventHandler()
5004 {
5005 return eventHandler_;
5006 }
5007
InitMissionListManager(int userId,bool switchUser)5008 void AbilityManagerService::InitMissionListManager(int userId, bool switchUser)
5009 {
5010 bool find = false;
5011 {
5012 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5013 auto iterator = missionListManagers_.find(userId);
5014 find = (iterator != missionListManagers_.end());
5015 if (find) {
5016 if (switchUser) {
5017 DelayedSingleton<MissionInfoMgr>::GetInstance()->Init(userId);
5018 currentMissionListManager_ = iterator->second;
5019 }
5020 }
5021 }
5022 if (!find) {
5023 auto manager = std::make_shared<MissionListManager>(userId);
5024 manager->Init();
5025 std::unique_lock<ffrt::mutex> lock(managersMutex_);
5026 missionListManagers_.emplace(userId, manager);
5027 if (switchUser) {
5028 currentMissionListManager_ = manager;
5029 }
5030 }
5031 }
5032
5033 // multi user scene
GetUserId() const5034 int32_t AbilityManagerService::GetUserId() const
5035 {
5036 if (userController_) {
5037 auto userId = userController_->GetCurrentUserId();
5038 HILOG_DEBUG("userId is %{public}d", userId);
5039 return userId;
5040 }
5041 return U0_USER_ID;
5042 }
5043
StartHighestPriorityAbility(int32_t userId,bool isBoot)5044 void AbilityManagerService::StartHighestPriorityAbility(int32_t userId, bool isBoot)
5045 {
5046 HILOG_DEBUG("%{public}s", __func__);
5047 auto bms = GetBundleManager();
5048 CHECK_POINTER(bms);
5049
5050 /* Query the highest priority ability or extension ability, and start it. usually, it is OOBE or launcher */
5051 Want want;
5052 want.AddEntity(HIGHEST_PRIORITY_ABILITY_ENTITY);
5053 AppExecFwk::AbilityInfo abilityInfo;
5054 AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
5055 int attemptNums = 0;
5056 while (!IN_PROCESS_CALL(bms->ImplicitQueryInfoByPriority(want,
5057 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId,
5058 abilityInfo, extensionAbilityInfo))) {
5059 HILOG_INFO("Waiting query highest priority ability info completed.");
5060 ++attemptNums;
5061 if (!isBoot && attemptNums > SWITCH_ACCOUNT_TRY) {
5062 HILOG_ERROR("Query highest priority ability failed.");
5063 return;
5064 }
5065 AbilityRequest abilityRequest;
5066 usleep(REPOLL_TIME_MICRO_SECONDS);
5067 }
5068
5069 if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
5070 HILOG_ERROR("Query highest priority ability failed");
5071 return;
5072 }
5073
5074 Want abilityWant; // donot use 'want' here, because the entity of 'want' is not empty
5075 if (!abilityInfo.name.empty()) {
5076 /* highest priority ability */
5077 HILOG_INFO("Start the highest priority ability. bundleName: %{public}s, ability:%{public}s",
5078 abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
5079 abilityWant.SetElementName(abilityInfo.bundleName, abilityInfo.name);
5080 } else {
5081 /* highest priority extension ability */
5082 HILOG_INFO("Start the highest priority extension ability. bundleName: %{public}s, ability:%{public}s",
5083 extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str());
5084 abilityWant.SetElementName(extensionAbilityInfo.bundleName, extensionAbilityInfo.name);
5085 }
5086
5087 #ifdef SUPPORT_GRAPHICS
5088 abilityWant.SetParam(NEED_STARTINGWINDOW, false);
5089 // wait BOOT_ANIMATION_STARTED to start LAUNCHER
5090 WaitBootAnimationStart();
5091 #endif
5092
5093 /* note: OOBE APP need disable itself, otherwise, it will be started when restart system everytime */
5094 (void)StartAbility(abilityWant, userId, DEFAULT_INVAL_VALUE);
5095 }
5096
GenerateAbilityRequest(const Want & want,int requestCode,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)5097 int AbilityManagerService::GenerateAbilityRequest(
5098 const Want &want, int requestCode, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
5099 {
5100 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5101 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
5102 if (abilityRecord && abilityRecord->GetAppIndex() != 0 &&
5103 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
5104 (const_cast<Want &>(want)).SetParam(DLP_INDEX, abilityRecord->GetAppIndex());
5105 }
5106
5107 if (abilityRecord != nullptr) {
5108 (const_cast<Want &>(want)).SetParam(DEBUG_APP, abilityRecord->IsDebugApp());
5109 }
5110
5111 request.want = want;
5112 request.requestCode = requestCode;
5113 request.callerToken = callerToken;
5114 request.startSetting = nullptr;
5115
5116 auto bms = GetBundleManager();
5117 CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
5118 auto abilityInfoFlag = (AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION |
5119 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION |
5120 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA);
5121 HILOG_DEBUG("QueryAbilityInfo from bms, userId is %{public}d.", userId);
5122 int32_t appIndex = want.GetIntParam(DLP_INDEX, 0);
5123 if (appIndex == 0) {
5124 IN_PROCESS_CALL_WITHOUT_RET(bms->QueryAbilityInfo(want, abilityInfoFlag, userId, request.abilityInfo));
5125 } else {
5126 IN_PROCESS_CALL_WITHOUT_RET(bms->GetSandboxAbilityInfo(want, appIndex,
5127 abilityInfoFlag, userId, request.abilityInfo));
5128 }
5129 if (request.abilityInfo.name.empty() || request.abilityInfo.bundleName.empty()) {
5130 // try to find extension
5131 std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
5132 if (appIndex == 0) {
5133 IN_PROCESS_CALL_WITHOUT_RET(bms->QueryExtensionAbilityInfos(want, abilityInfoFlag,
5134 userId, extensionInfos));
5135 } else {
5136 IN_PROCESS_CALL_WITHOUT_RET(bms->GetSandboxExtAbilityInfos(want, appIndex,
5137 abilityInfoFlag, userId, extensionInfos));
5138 }
5139 if (extensionInfos.size() <= 0) {
5140 HILOG_ERROR("GenerateAbilityRequest error. Get extension info failed.");
5141 return RESOLVE_ABILITY_ERR;
5142 }
5143
5144 AppExecFwk::ExtensionAbilityInfo extensionInfo = extensionInfos.front();
5145 if (extensionInfo.bundleName.empty() || extensionInfo.name.empty()) {
5146 HILOG_ERROR("extensionInfo empty.");
5147 return RESOLVE_ABILITY_ERR;
5148 }
5149 request.extensionProcessMode = extensionInfo.extensionProcessMode;
5150 HILOG_DEBUG("Extension ability info found, name=%{public}s.",
5151 extensionInfo.name.c_str());
5152 // For compatibility translates to AbilityInfo
5153 InitAbilityInfoFromExtension(extensionInfo, request.abilityInfo);
5154 }
5155 HILOG_DEBUG("QueryAbilityInfo success, ability name: %{public}s, is stage mode: %{public}d.",
5156 request.abilityInfo.name.c_str(), request.abilityInfo.isStageBasedModel);
5157
5158 if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
5159 request.collaboratorType = CollaboratorType::RESERVE_TYPE;
5160 } else if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::OTHERS_TYPE)) {
5161 request.collaboratorType = CollaboratorType::OTHERS_TYPE;
5162 }
5163
5164 if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) {
5165 HILOG_INFO("Stage mode, abilityInfo SERVICE type reset EXTENSION.");
5166 request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
5167 }
5168
5169 if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
5170 HILOG_ERROR("Get app info failed.");
5171 return RESOLVE_APP_ERR;
5172 }
5173 request.appInfo = request.abilityInfo.applicationInfo;
5174 request.uid = request.appInfo.uid;
5175 HILOG_DEBUG("GenerateAbilityRequest end, app name: %{public}s, moduleName name: %{public}s, uid: %{public}d.",
5176 request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid);
5177 if (!CheckDebugAppInDeveloperMode(request.appInfo.debug)) {
5178 return ERR_NOT_DEVELOPER_MODE;
5179 }
5180
5181 request.want.SetModuleName(request.abilityInfo.moduleName);
5182
5183 if (want.GetBoolParam(Want::PARAM_RESV_START_RECENT, false) &&
5184 AAFwk::PermissionVerification::GetInstance()->VerifyStartRecentAbilityPermission()) {
5185 request.startRecent = true;
5186 }
5187
5188 return ERR_OK;
5189 }
5190
GenerateExtensionAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)5191 int AbilityManagerService::GenerateExtensionAbilityRequest(
5192 const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
5193 {
5194 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
5195 if (abilityRecord && abilityRecord->GetAppIndex() != 0 &&
5196 abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
5197 (const_cast<Want &>(want)).SetParam(DLP_INDEX, abilityRecord->GetAppIndex());
5198 }
5199 request.want = want;
5200 request.callerToken = callerToken;
5201 request.startSetting = nullptr;
5202
5203 auto bms = GetBundleManager();
5204 CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
5205
5206 auto abilityInfoFlag = (AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_APPLICATION |
5207 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_PERMISSION |
5208 AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_WITH_METADATA);
5209 HILOG_DEBUG("QueryExtensionAbilityInfo from bms, userId is %{public}d.", userId);
5210 // try to find extension
5211 std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
5212 int32_t appIndex = want.GetIntParam(DLP_INDEX, 0);
5213 if (appIndex == 0) {
5214 IN_PROCESS_CALL_WITHOUT_RET(bms->QueryExtensionAbilityInfos(want, abilityInfoFlag, userId, extensionInfos));
5215 } else {
5216 IN_PROCESS_CALL_WITHOUT_RET(bms->GetSandboxExtAbilityInfos(want, appIndex,
5217 abilityInfoFlag, userId, extensionInfos));
5218 }
5219 if (extensionInfos.size() <= 0) {
5220 HILOG_ERROR("GenerateAbilityRequest error. Get extension info failed.");
5221 return RESOLVE_ABILITY_ERR;
5222 }
5223
5224 AppExecFwk::ExtensionAbilityInfo extensionInfo = extensionInfos.front();
5225 if (extensionInfo.bundleName.empty() || extensionInfo.name.empty()) {
5226 HILOG_ERROR("extensionInfo empty.");
5227 return RESOLVE_ABILITY_ERR;
5228 }
5229 HILOG_DEBUG("Extension ability info found, name=%{public}s.", extensionInfo.name.c_str());
5230 // For compatibility translates to AbilityInfo
5231 InitAbilityInfoFromExtension(extensionInfo, request.abilityInfo);
5232 request.extensionProcessMode = extensionInfo.extensionProcessMode;
5233
5234 HILOG_DEBUG("QueryAbilityInfo success, ability name: %{public}s, is stage mode: %{public}d.",
5235 request.abilityInfo.name.c_str(), request.abilityInfo.isStageBasedModel);
5236
5237 if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
5238 HILOG_ERROR("Get app info failed.");
5239 return RESOLVE_APP_ERR;
5240 }
5241 request.appInfo = request.abilityInfo.applicationInfo;
5242 request.uid = request.appInfo.uid;
5243 HILOG_DEBUG("GenerateAbilityRequest end, app name: %{public}s, bundle name: %{public}s, uid: %{public}d.",
5244 request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid);
5245 if (!CheckDebugAppInDeveloperMode(request.appInfo.debug)) {
5246 return ERR_NOT_DEVELOPER_MODE;
5247 }
5248
5249 HILOG_DEBUG("GenerateExtensionAbilityRequest, moduleName: %{public}s.", request.abilityInfo.moduleName.c_str());
5250 request.want.SetModuleName(request.abilityInfo.moduleName);
5251
5252 return ERR_OK;
5253 }
5254
StopServiceAbility(const Want & want,int32_t userId,const sptr<IRemoteObject> & token)5255 int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)
5256 {
5257 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5258 HILOG_DEBUG("call.");
5259
5260 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5261 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5262 if (!isSaCall && !isShellCall) {
5263 auto abilityRecord = Token::GetAbilityRecordByToken(token);
5264 if (abilityRecord == nullptr) {
5265 HILOG_ERROR("callerRecord is nullptr");
5266 return ERR_INVALID_VALUE;
5267 }
5268 }
5269
5270 int32_t validUserId = GetValidUserId(userId);
5271 if (!JudgeMultiUserConcurrency(validUserId)) {
5272 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
5273 return ERR_CROSS_USER;
5274 }
5275
5276 AbilityRequest abilityRequest;
5277 auto result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId);
5278 if (result != ERR_OK) {
5279 HILOG_ERROR("Generate ability request local error.");
5280 return result;
5281 }
5282
5283 auto abilityInfo = abilityRequest.abilityInfo;
5284 validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
5285 HILOG_DEBUG("validUserId : %{public}d, singleton is : %{public}d",
5286 validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
5287
5288 auto type = abilityInfo.type;
5289 if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
5290 HILOG_ERROR("Target ability is not service type.");
5291 return TARGET_ABILITY_NOT_SERVICE;
5292 }
5293
5294 auto res = JudgeAbilityVisibleControl(abilityInfo);
5295 if (res != ERR_OK) {
5296 HILOG_ERROR("Target ability is invisible");
5297 return res;
5298 }
5299
5300 auto connectManager = GetConnectManagerByUserId(validUserId);
5301 if (connectManager == nullptr) {
5302 return ERR_INVALID_VALUE;
5303 }
5304
5305 return connectManager->StopServiceAbility(abilityRequest);
5306 }
5307
OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)5308 void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)
5309 {
5310 CHECK_POINTER(abilityRecord);
5311 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5312 if (abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
5313 uiAbilityLifecycleManager_->OnAbilityDied(abilityRecord);
5314 return;
5315 }
5316 } else {
5317 auto manager = GetListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
5318 if (manager && abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
5319 ReleaseAbilityTokenMap(abilityRecord->GetToken());
5320 manager->OnAbilityDied(abilityRecord, GetUserId());
5321 return;
5322 }
5323 }
5324
5325 auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
5326 if (connectManager) {
5327 connectManager->OnAbilityDied(abilityRecord, GetUserId());
5328 return;
5329 }
5330
5331 auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken());
5332 if (dataAbilityManager) {
5333 dataAbilityManager->OnAbilityDied(abilityRecord);
5334 }
5335 }
5336
OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)5337 void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
5338 {
5339 CHECK_POINTER(callRecord);
5340 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5341 uiAbilityLifecycleManager_->OnCallConnectDied(callRecord);
5342 return;
5343 }
5344 if (currentMissionListManager_) {
5345 currentMissionListManager_->OnCallConnectDied(callRecord);
5346 }
5347 }
5348
ReleaseAbilityTokenMap(const sptr<IRemoteObject> & token)5349 void AbilityManagerService::ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)
5350 {
5351 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
5352 for (auto iter = callStubTokenMap_.begin(); iter != callStubTokenMap_.end(); iter++) {
5353 if (iter->second == token) {
5354 callStubTokenMap_.erase(iter);
5355 break;
5356 }
5357 }
5358 }
5359
KillProcess(const std::string & bundleName)5360 int AbilityManagerService::KillProcess(const std::string &bundleName)
5361 {
5362 HILOG_DEBUG("Kill process, bundleName: %{public}s", bundleName.c_str());
5363 CHECK_CALLER_IS_SYSTEM_APP;
5364 auto bms = GetBundleManager();
5365 CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED);
5366 int32_t userId = GetUserId();
5367 AppExecFwk::BundleInfo bundleInfo;
5368 if (!IN_PROCESS_CALL(
5369 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
5370 HILOG_ERROR("Failed to get bundle info when kill process.");
5371 return GET_BUNDLE_INFO_FAILED;
5372 }
5373
5374 if (bundleInfo.isKeepAlive) {
5375 HILOG_ERROR("Can not kill keep alive process.");
5376 return KILL_PROCESS_KEEP_ALIVE;
5377 }
5378
5379 int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName);
5380 if (ret != ERR_OK) {
5381 return KILL_PROCESS_FAILED;
5382 }
5383 return ERR_OK;
5384 }
5385
ClearUpApplicationData(const std::string & bundleName,const int32_t userId)5386 int AbilityManagerService::ClearUpApplicationData(const std::string &bundleName, const int32_t userId)
5387 {
5388 HILOG_DEBUG("ClearUpApplicationData, bundleName: %{public}s", bundleName.c_str());
5389 CHECK_CALLER_IS_SYSTEM_APP;
5390 int ret = DelayedSingleton<AppScheduler>::GetInstance()->ClearUpApplicationData(bundleName, userId);
5391 if (ret != ERR_OK) {
5392 return CLEAR_APPLICATION_DATA_FAIL;
5393 }
5394 return ERR_OK;
5395 }
5396
UninstallApp(const std::string & bundleName,int32_t uid)5397 int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid)
5398 {
5399 HILOG_DEBUG("Uninstall app, bundleName: %{public}s, uid=%{public}d", bundleName.c_str(), uid);
5400 pid_t callingPid = IPCSkeleton::GetCallingPid();
5401 pid_t pid = getpid();
5402 if (callingPid != pid) {
5403 HILOG_ERROR("%{public}s: Not bundleMgr call.", __func__);
5404 return CHECK_PERMISSION_FAILED;
5405 }
5406
5407 int32_t targetUserId = uid / BASE_USER_RANGE;
5408 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5409 uiAbilityLifecycleManager_->UninstallApp(bundleName, uid, targetUserId);
5410 } else if (targetUserId == U0_USER_ID) {
5411 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5412 for (auto item: missionListManagers_) {
5413 if (item.second) {
5414 item.second->UninstallApp(bundleName, uid);
5415 }
5416 }
5417 } else {
5418 auto listManager = GetListManagerByUserId(targetUserId);
5419 if (listManager) {
5420 listManager->UninstallApp(bundleName, uid);
5421 }
5422 }
5423
5424 if (pendingWantManager_) {
5425 pendingWantManager_->ClearPendingWantRecord(bundleName, uid);
5426 }
5427 int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplicationByUid(bundleName, uid);
5428 if (ret != ERR_OK) {
5429 return UNINSTALL_APP_FAILED;
5430 }
5431 DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->DeleteAppExitReason(bundleName);
5432 return ERR_OK;
5433 }
5434
GetBundleManager()5435 std::shared_ptr<AppExecFwk::BundleMgrHelper> AbilityManagerService::GetBundleManager()
5436 {
5437 if (bundleMgrHelper_ == nullptr) {
5438 bundleMgrHelper_ = AbilityUtil::GetBundleManagerHelper();
5439 }
5440 return bundleMgrHelper_;
5441 }
5442
PreLoadAppDataAbilities(const std::string & bundleName,const int32_t userId)5443 int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)
5444 {
5445 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5446 if (bundleName.empty()) {
5447 HILOG_ERROR("Invalid bundle name when app data abilities preloading.");
5448 return ERR_INVALID_VALUE;
5449 }
5450
5451 auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5452 if (dataAbilityManager == nullptr) {
5453 HILOG_ERROR("Invalid data ability manager when app data abilities preloading.");
5454 return ERR_INVALID_STATE;
5455 }
5456
5457 auto bms = GetBundleManager();
5458 CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
5459
5460 AppExecFwk::BundleInfo bundleInfo;
5461 bool ret = IN_PROCESS_CALL(
5462 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
5463 if (!ret) {
5464 HILOG_ERROR("Failed to get bundle info when app data abilities preloading, userId is %{public}d", userId);
5465 return RESOLVE_APP_ERR;
5466 }
5467
5468 auto begin = system_clock::now();
5469 AbilityRequest dataAbilityRequest;
5470 UpdateCallerInfo(dataAbilityRequest.want, nullptr);
5471 dataAbilityRequest.appInfo = bundleInfo.applicationInfo;
5472 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
5473 if (it->type != AppExecFwk::AbilityType::DATA) {
5474 continue;
5475 }
5476 if ((system_clock::now() - begin) >= DATA_ABILITY_START_TIMEOUT) {
5477 HILOG_ERROR("App data ability preloading for '%{public}s' timeout.", bundleName.c_str());
5478 return ERR_TIMED_OUT;
5479 }
5480 dataAbilityRequest.abilityInfo = *it;
5481 dataAbilityRequest.uid = bundleInfo.uid;
5482 HILOG_DEBUG("App data ability preloading: '%{public}s.%{public}s'...",
5483 it->bundleName.c_str(), it->name.c_str());
5484
5485 auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false);
5486 if (dataAbility == nullptr) {
5487 HILOG_ERROR(
5488 "Failed to preload data ability '%{public}s.%{public}s'.", it->bundleName.c_str(), it->name.c_str());
5489 return ERR_NULL_OBJECT;
5490 }
5491 }
5492
5493 HILOG_DEBUG("App data abilities preloading done.");
5494 return ERR_OK;
5495 }
5496
IsSystemUiApp(const AppExecFwk::AbilityInfo & info) const5497 bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const
5498 {
5499 if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) {
5500 return false;
5501 }
5502 return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR ||
5503 info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR ||
5504 info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME);
5505 }
5506
IsSystemUI(const std::string & bundleName) const5507 bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const
5508 {
5509 return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME;
5510 }
5511
HandleLoadTimeOut(int64_t abilityRecordId,bool isHalf)5512 void AbilityManagerService::HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf)
5513 {
5514 HILOG_DEBUG("Handle load timeout.");
5515 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5516 uiAbilityLifecycleManager_->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
5517 return;
5518 }
5519 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5520 for (auto& item : missionListManagers_) {
5521 if (item.second) {
5522 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
5523 }
5524 }
5525 }
5526
HandleActiveTimeOut(int64_t abilityRecordId)5527 void AbilityManagerService::HandleActiveTimeOut(int64_t abilityRecordId)
5528 {
5529 HILOG_DEBUG("Handle active timeout.");
5530 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5531 for (auto& item : missionListManagers_) {
5532 if (item.second) {
5533 item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecordId);
5534 }
5535 }
5536 }
5537
HandleInactiveTimeOut(int64_t abilityRecordId)5538 void AbilityManagerService::HandleInactiveTimeOut(int64_t abilityRecordId)
5539 {
5540 HILOG_DEBUG("Handle inactive timeout.");
5541 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5542 for (auto& item : missionListManagers_) {
5543 if (item.second) {
5544 item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
5545 }
5546 }
5547
5548 for (auto& item : connectManagers_) {
5549 if (item.second) {
5550 item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
5551 }
5552 }
5553 }
5554
HandleForegroundTimeOut(int64_t abilityRecordId,bool isHalf)5555 void AbilityManagerService::HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf)
5556 {
5557 HILOG_DEBUG("Handle foreground timeout.");
5558 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5559 uiAbilityLifecycleManager_->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
5560 return;
5561 }
5562 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5563 for (auto& item : missionListManagers_) {
5564 if (item.second) {
5565 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
5566 }
5567 }
5568 }
5569
HandleShareDataTimeOut(int64_t uniqueId)5570 void AbilityManagerService::HandleShareDataTimeOut(int64_t uniqueId)
5571 {
5572 WantParams wantParam;
5573 int32_t ret = GetShareDataPairAndReturnData(nullptr, ERR_TIMED_OUT, uniqueId, wantParam);
5574 if (ret) {
5575 HILOG_ERROR("acqurieShareData failed.");
5576 }
5577 }
5578
GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)5579 int32_t AbilityManagerService::GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,
5580 const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
5581 {
5582 HILOG_INFO("resultCode:%{public}d, uniqueId:%{public}d, wantParam size:%{public}d.",
5583 resultCode, uniqueId, wantParam.Size());
5584 auto it = iAcquireShareDataMap_.find(uniqueId);
5585 if (it != iAcquireShareDataMap_.end()) {
5586 auto shareDataPair = it->second;
5587 if (abilityRecord && shareDataPair.first != abilityRecord->GetAbilityRecordId()) {
5588 HILOG_ERROR("abilityRecord is not the abilityRecord from request.");
5589 return ERR_INVALID_VALUE;
5590 }
5591 auto callback = shareDataPair.second;
5592 if (!callback) {
5593 HILOG_ERROR("callback object is nullptr.");
5594 return ERR_INVALID_VALUE;
5595 }
5596 auto ret = callback->AcquireShareDataDone(resultCode, wantParam);
5597 iAcquireShareDataMap_.erase(it);
5598 return ret;
5599 }
5600 HILOG_ERROR("iAcquireShareData is null.");
5601 return ERR_INVALID_VALUE;
5602 }
5603
VerificationToken(const sptr<IRemoteObject> & token)5604 bool AbilityManagerService::VerificationToken(const sptr<IRemoteObject> &token)
5605 {
5606 HILOG_INFO("Verification token.");
5607 CHECK_POINTER_RETURN_BOOL(dataAbilityManager_);
5608 CHECK_POINTER_RETURN_BOOL(connectManager_);
5609 CHECK_POINTER_RETURN_BOOL(currentMissionListManager_);
5610
5611 if (currentMissionListManager_->GetAbilityRecordByToken(token)) {
5612 return true;
5613 }
5614 if (currentMissionListManager_->GetAbilityFromTerminateList(token)) {
5615 return true;
5616 }
5617
5618 if (dataAbilityManager_->GetAbilityRecordByToken(token)) {
5619 HILOG_INFO("Verification token4.");
5620 return true;
5621 }
5622
5623 if (connectManager_->GetExtensionByTokenFromServiceMap(token)) {
5624 HILOG_INFO("Verification token5.");
5625 return true;
5626 }
5627
5628 if (connectManager_->GetExtensionByTokenFromTerminatingMap(token)) {
5629 HILOG_INFO("Verification token5.");
5630 return true;
5631 }
5632
5633 HILOG_ERROR("Failed to verify token.");
5634 return false;
5635 }
5636
VerificationAllToken(const sptr<IRemoteObject> & token)5637 bool AbilityManagerService::VerificationAllToken(const sptr<IRemoteObject> &token)
5638 {
5639 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5640 HILOG_DEBUG("VerificationAllToken.");
5641 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5642 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5643 if (uiAbilityLifecycleManager_ != nullptr && uiAbilityLifecycleManager_->IsContainsAbility(token)) {
5644 return true;
5645 }
5646 } else {
5647 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "VerificationAllToken::SearchMissionListManagers");
5648 for (auto item: missionListManagers_) {
5649 if (item.second && item.second->GetAbilityRecordByToken(token)) {
5650 return true;
5651 }
5652
5653 if (item.second && item.second->GetAbilityFromTerminateList(token)) {
5654 return true;
5655 }
5656 }
5657 }
5658
5659 {
5660 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "VerificationAllToken::SearchDataAbilityManagers_");
5661 for (auto item: dataAbilityManagers_) {
5662 if (item.second && item.second->GetAbilityRecordByToken(token)) {
5663 return true;
5664 }
5665 }
5666 }
5667
5668 {
5669 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "VerificationAllToken::SearchConnectManagers_");
5670 for (auto item: connectManagers_) {
5671 if (item.second && item.second->GetExtensionByTokenFromServiceMap(token)) {
5672 return true;
5673 }
5674 if (item.second && item.second->GetExtensionByTokenFromTerminatingMap(token)) {
5675 return true;
5676 }
5677 }
5678 }
5679 HILOG_ERROR("Failed to verify all token.");
5680 return false;
5681 }
5682
GetDataAbilityManager(const sptr<IAbilityScheduler> & scheduler)5683 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManager(
5684 const sptr<IAbilityScheduler> &scheduler)
5685 {
5686 if (scheduler == nullptr) {
5687 HILOG_ERROR("the param ability scheduler is nullptr");
5688 return nullptr;
5689 }
5690
5691 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5692 for (auto& item: dataAbilityManagers_) {
5693 if (item.second && item.second->ContainsDataAbility(scheduler)) {
5694 return item.second;
5695 }
5696 }
5697
5698 return nullptr;
5699 }
5700
GetListManagerByUserId(int32_t userId)5701 std::shared_ptr<MissionListManager> AbilityManagerService::GetListManagerByUserId(int32_t userId)
5702 {
5703 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5704 auto it = missionListManagers_.find(userId);
5705 if (it != missionListManagers_.end()) {
5706 return it->second;
5707 }
5708 HILOG_ERROR("%{public}s, Failed to get Manager. UserId = %{public}d", __func__, userId);
5709 return nullptr;
5710 }
5711
GetConnectManagerByUserId(int32_t userId)5712 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByUserId(int32_t userId)
5713 {
5714 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5715 auto it = connectManagers_.find(userId);
5716 if (it != connectManagers_.end()) {
5717 return it->second;
5718 }
5719 HILOG_ERROR("%{public}s, Failed to get Manager. UserId = %{public}d", __func__, userId);
5720 return nullptr;
5721 }
5722
GetDataAbilityManagerByUserId(int32_t userId)5723 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId)
5724 {
5725 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5726 auto it = dataAbilityManagers_.find(userId);
5727 if (it != dataAbilityManagers_.end()) {
5728 return it->second;
5729 }
5730 HILOG_ERROR("%{public}s, Failed to get Manager. UserId = %{public}d", __func__, userId);
5731 return nullptr;
5732 }
5733
GetConnectManagerByToken(const sptr<IRemoteObject> & token)5734 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByToken(
5735 const sptr<IRemoteObject> &token)
5736 {
5737 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5738 for (auto item: connectManagers_) {
5739 if (item.second && item.second->GetExtensionByTokenFromServiceMap(token)) {
5740 return item.second;
5741 }
5742 if (item.second && item.second->GetExtensionByTokenFromTerminatingMap(token)) {
5743 return item.second;
5744 }
5745 }
5746
5747 return nullptr;
5748 }
5749
GetDataAbilityManagerByToken(const sptr<IRemoteObject> & token)5750 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByToken(
5751 const sptr<IRemoteObject> &token)
5752 {
5753 std::lock_guard<ffrt::mutex> lock(managersMutex_);
5754 for (auto item: dataAbilityManagers_) {
5755 if (item.second && item.second->GetAbilityRecordByToken(token)) {
5756 return item.second;
5757 }
5758 }
5759
5760 return nullptr;
5761 }
5762
StartResidentApps()5763 void AbilityManagerService::StartResidentApps()
5764 {
5765 HILOG_DEBUG("%{public}s", __func__);
5766 ConnectBmsService();
5767 auto bms = GetBundleManager();
5768 CHECK_POINTER_IS_NULLPTR(bms);
5769 std::vector<AppExecFwk::BundleInfo> bundleInfos;
5770 if (!IN_PROCESS_CALL(
5771 bms->GetBundleInfos(OHOS::AppExecFwk::GET_BUNDLE_DEFAULT, bundleInfos, U0_USER_ID))) {
5772 HILOG_ERROR("Get resident bundleinfos failed");
5773 return;
5774 }
5775
5776 HILOG_INFO("StartResidentApps GetBundleInfos size: %{public}zu", bundleInfos.size());
5777
5778 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos);
5779 if (!bundleInfos.empty()) {
5780 #ifdef SUPPORT_GRAPHICS
5781 WaitBootAnimationStart();
5782 #endif
5783 DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
5784 }
5785 }
5786
StartAutoStartupApps()5787 void AbilityManagerService::StartAutoStartupApps()
5788 {
5789 HILOG_DEBUG("Called.");
5790 if (abilityAutoStartupService_ == nullptr) {
5791 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
5792 return;
5793 }
5794 std::vector<AutoStartupInfo> infoList;
5795 int32_t result = abilityAutoStartupService_->QueryAllAutoStartupApplicationsWithoutPermission(infoList);
5796 if (result != ERR_OK) {
5797 HILOG_ERROR("Failed to query data.");
5798 return;
5799 }
5800
5801 constexpr int retryCount = 5;
5802 RetryStartAutoStartupApps(infoList, retryCount);
5803 }
5804
RetryStartAutoStartupApps(const std::vector<AutoStartupInfo> & infoList,int32_t retryCount)5805 void AbilityManagerService::RetryStartAutoStartupApps(
5806 const std::vector<AutoStartupInfo> &infoList, int32_t retryCount)
5807 {
5808 HILOG_DEBUG("Called, retryCount: %{public}d, infoList.size:%{public}zu", retryCount, infoList.size());
5809 std::vector<AutoStartupInfo> failedList;
5810 for (auto info : infoList) {
5811 AppExecFwk::ElementName element;
5812 element.SetBundleName(info.bundleName);
5813 element.SetAbilityName(info.abilityName);
5814 element.SetModuleName(info.moduleName);
5815 Want want;
5816 want.SetElement(element);
5817 want.SetParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, true);
5818 if (StartAbility(want) != ERR_OK) {
5819 failedList.push_back(info);
5820 }
5821 }
5822
5823 HILOG_DEBUG("RetryCount: %{public}d, failedList.size:%{public}zu", retryCount, failedList.size());
5824 if (!failedList.empty() && retryCount > 0) {
5825 auto retryStartAutoStartupAppsTask = [aams = weak_from_this(), list = failedList, retryCount]() {
5826 auto obj = aams.lock();
5827 if (obj == nullptr) {
5828 HILOG_ERROR("Retry start auto startup app error, obj is nullptr");
5829 return;
5830 }
5831 obj->RetryStartAutoStartupApps(list, retryCount - 1);
5832 };
5833 constexpr int delaytime = 2000;
5834 taskHandler_->SubmitTask(retryStartAutoStartupAppsTask, "RetryStartAutoStartupApps", delaytime);
5835 }
5836 }
5837
SubscribeScreenUnlockedEvent()5838 void AbilityManagerService::SubscribeScreenUnlockedEvent()
5839 {
5840 HILOG_DEBUG("Called.");
5841 // add listen screen unlocked.
5842 EventFwk::MatchingSkills matchingSkills;
5843 matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
5844 EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
5845 subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
5846 auto callback = [abilityManager = weak_from_this()]() {
5847 HILOG_DEBUG("On screen unlocked.");
5848 auto abilityMgr = abilityManager.lock();
5849 if (abilityMgr == nullptr) {
5850 HILOG_ERROR("Invalid abilityMgr pointer.");
5851 return;
5852 }
5853 auto taskHandler = abilityMgr->GetTaskHandler();
5854 if (taskHandler == nullptr) {
5855 HILOG_ERROR("Invalid taskHandler pointer.");
5856 return;
5857 }
5858 auto startAutoStartupAppsTask = [abilityManager]() {
5859 auto abilityMgr = abilityManager.lock();
5860 if (abilityMgr == nullptr) {
5861 HILOG_ERROR("Invalid abilityMgr pointer.");
5862 return;
5863 }
5864 abilityMgr->StartAutoStartupApps();
5865 abilityMgr->UnSubscribeScreenUnlockedEvent();
5866 };
5867 taskHandler->SubmitTask(startAutoStartupAppsTask, "StartAutoStartupApps");
5868 };
5869 screenSubscriber_ = std::make_shared<AbilityRuntime::AbilityManagerEventSubscriber>(subscribeInfo, callback);
5870 bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber_);
5871 if (!subResult) {
5872 constexpr int retryCount = 20;
5873 RetrySubscribeScreenUnlockedEvent(retryCount);
5874 }
5875 }
5876
UnSubscribeScreenUnlockedEvent()5877 void AbilityManagerService::UnSubscribeScreenUnlockedEvent()
5878 {
5879 HILOG_DEBUG("Called.");
5880 bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_);
5881 HILOG_DEBUG("Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult);
5882 }
5883
RetrySubscribeScreenUnlockedEvent(int32_t retryCount)5884 void AbilityManagerService::RetrySubscribeScreenUnlockedEvent(int32_t retryCount)
5885 {
5886 HILOG_DEBUG("RetryCount: %{public}d.", retryCount);
5887 auto retrySubscribeScreenUnlockedEventTask = [aams = weak_from_this(), screenSubscriber = screenSubscriber_,
5888 retryCount]() {
5889 bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber);
5890 auto obj = aams.lock();
5891 if (obj == nullptr) {
5892 HILOG_ERROR("Retry subscribe screen unlocked event, obj is nullptr.");
5893 return;
5894 }
5895 if (!subResult && retryCount > 0) {
5896 obj->RetrySubscribeScreenUnlockedEvent(retryCount - 1);
5897 }
5898 };
5899 constexpr int delaytime = 200;
5900 taskHandler_->SubmitTask(retrySubscribeScreenUnlockedEventTask, "RetrySubscribeScreenUnlockedEvent", delaytime);
5901 }
5902
ConnectBmsService()5903 void AbilityManagerService::ConnectBmsService()
5904 {
5905 HILOG_DEBUG("%{public}s", __func__);
5906 HILOG_INFO("Waiting AppMgr Service run completed.");
5907 while (!DelayedSingleton<AppScheduler>::GetInstance()->Init(shared_from_this())) {
5908 HILOG_ERROR("failed to init AppScheduler");
5909 usleep(REPOLL_TIME_MICRO_SECONDS);
5910 }
5911
5912 HILOG_INFO("Waiting BundleMgr Service run completed.");
5913 /* wait until connected to bundle manager service */
5914 std::lock_guard<ffrt::mutex> guard(globalLock_);
5915 while (iBundleManager_ == nullptr) {
5916 sptr<IRemoteObject> bundle_obj =
5917 OHOS::DelayedSingleton<SaMgrClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
5918 if (bundle_obj == nullptr) {
5919 HILOG_ERROR("failed to get bundle manager service");
5920 usleep(REPOLL_TIME_MICRO_SECONDS);
5921 continue;
5922 }
5923 iBundleManager_ = iface_cast<AppExecFwk::IBundleMgr>(bundle_obj);
5924 }
5925
5926 HILOG_INFO("Connect bms success!");
5927 }
5928
GetWantSenderInfo(const sptr<IWantSender> & target,std::shared_ptr<WantSenderInfo> & info)5929 int AbilityManagerService::GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)
5930 {
5931 HILOG_INFO("Get pending request info.");
5932 CHECK_POINTER_AND_RETURN(pendingWantManager_, ERR_INVALID_VALUE);
5933 CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
5934 CHECK_POINTER_AND_RETURN(info, ERR_INVALID_VALUE);
5935 return pendingWantManager_->GetWantSenderInfo(target, info);
5936 }
5937
GetAppMemorySize()5938 int AbilityManagerService::GetAppMemorySize()
5939 {
5940 HILOG_INFO("service GetAppMemorySize start");
5941 const char *key = "const.product.arkheaplimit";
5942 const char *def = "512m";
5943 char *valueGet = nullptr;
5944 unsigned int len = 128;
5945 int ret = GetParameter(key, def, valueGet, len);
5946 int resultInt = 0;
5947 if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
5948 if (valueGet == nullptr) {
5949 HILOG_WARN("%{public}s, valueGet is nullptr", __func__);
5950 return APP_MEMORY_SIZE;
5951 }
5952 int len = strlen(valueGet);
5953 for (int i = 0; i < len; i++) {
5954 if (valueGet[i] >= '0' && valueGet[i] <= '9') {
5955 resultInt *= SIZE_10;
5956 resultInt += valueGet[i] - '0';
5957 }
5958 }
5959 if (resultInt == 0) {
5960 return APP_MEMORY_SIZE;
5961 }
5962 return resultInt;
5963 }
5964 return APP_MEMORY_SIZE;
5965 }
5966
IsRamConstrainedDevice()5967 bool AbilityManagerService::IsRamConstrainedDevice()
5968 {
5969 HILOG_INFO("service IsRamConstrainedDevice start");
5970 const char *key = "const.product.islowram";
5971 const char *def = "0";
5972 char *valueGet = nullptr;
5973 unsigned int len = 128;
5974 int ret = GetParameter(key, def, valueGet, len);
5975 if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
5976 int value = atoi(valueGet);
5977 if (value) {
5978 return true;
5979 }
5980 return false;
5981 }
5982 return false;
5983 }
5984
GetMissionIdByAbilityToken(const sptr<IRemoteObject> & token)5985 int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)
5986 {
5987 auto abilityRecord = Token::GetAbilityRecordByToken(token);
5988 if (!abilityRecord) {
5989 HILOG_ERROR("abilityRecord is Null.");
5990 return -1;
5991 }
5992 if (!JudgeSelfCalled(abilityRecord)) {
5993 return -1;
5994 }
5995 return GetMissionIdByAbilityTokenInner(token);
5996 }
5997
GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> & token)5998 int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)
5999 {
6000 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6001 if (!abilityRecord) {
6002 HILOG_ERROR("abilityRecord is Null.");
6003 return -1;
6004 }
6005 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6006 return uiAbilityLifecycleManager_->GetSessionIdByAbilityToken(token);
6007 }
6008 auto userId = abilityRecord->GetOwnerMissionUserId();
6009 auto missionListManager = GetListManagerByUserId(userId);
6010 if (!missionListManager) {
6011 HILOG_ERROR("missionListManager is Null. owner mission userId=%{public}d", userId);
6012 return -1;
6013 }
6014 return missionListManager->GetMissionIdByAbilityToken(token);
6015 }
6016
GetAbilityTokenByMissionId(int32_t missionId)6017 sptr<IRemoteObject> AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId)
6018 {
6019 if (!currentMissionListManager_) {
6020 return nullptr;
6021 }
6022 return currentMissionListManager_->GetAbilityTokenByMissionId(missionId);
6023 }
6024
StartRemoteAbilityByCall(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)6025 int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken,
6026 const sptr<IRemoteObject> &connect)
6027 {
6028 HILOG_INFO("%{public}s begin StartRemoteAbilityByCall", __func__);
6029 Want remoteWant = want;
6030 if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
6031 HILOG_ERROR("%{public}s AddStartControlParam failed.", __func__);
6032 return ERR_INVALID_VALUE;
6033 }
6034 int32_t missionId = -1;
6035 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6036 missionId = uiAbilityLifecycleManager_->GetSessionIdByAbilityToken(callerToken);
6037 if (!missionId) {
6038 HILOG_ERROR("Invalid missionId id.");
6039 return ERR_INVALID_VALUE;
6040 }
6041 } else {
6042 missionId = GetMissionIdByAbilityToken(callerToken);
6043 }
6044 if (missionId < 0) {
6045 return ERR_INVALID_VALUE;
6046 }
6047 remoteWant.SetParam(DMS_MISSION_ID, missionId);
6048 DistributedClient dmsClient;
6049 return dmsClient.StartRemoteAbilityByCall(remoteWant, connect);
6050 }
6051
ReleaseRemoteAbility(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element)6052 int AbilityManagerService::ReleaseRemoteAbility(const sptr<IRemoteObject> &connect,
6053 const AppExecFwk::ElementName &element)
6054 {
6055 DistributedClient dmsClient;
6056 return dmsClient.ReleaseRemoteAbility(connect, element);
6057 }
6058
StartAbilityByCall(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId)6059 int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect,
6060 const sptr<IRemoteObject> &callerToken, int32_t accountId)
6061 {
6062 HILOG_INFO("call ability.");
6063 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
6064 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
6065 if (IsCrossUserCall(accountId)) {
6066 CHECK_CALLER_IS_SYSTEM_APP;
6067 }
6068
6069 if (VerifyAccountPermission(accountId) == CHECK_PERMISSION_FAILED) {
6070 HILOG_ERROR("%{public}s: Permission verification failed.", __func__);
6071 return CHECK_PERMISSION_FAILED;
6072 }
6073
6074 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6075 if (abilityRecord && !JudgeSelfCalled(abilityRecord)) {
6076 return CHECK_PERMISSION_FAILED;
6077 }
6078
6079 auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
6080 interceptorExecuter_->DoProcess(want, 0, GetUserId(), false);
6081 if (result != ERR_OK) {
6082 HILOG_ERROR("interceptorExecuter_ is nullptr or DoProcess return error.");
6083 return result;
6084 }
6085
6086 if (CheckIfOperateRemote(want)) {
6087 HILOG_INFO("start remote ability by call");
6088 return StartRemoteAbilityByCall(want, callerToken, connect->AsObject());
6089 }
6090
6091 int32_t oriValidUserId = GetValidUserId(accountId);
6092 if (!JudgeMultiUserConcurrency(oriValidUserId)) {
6093 HILOG_ERROR("Multi-user non-concurrent mode is not satisfied.");
6094 return ERR_CROSS_USER;
6095 }
6096
6097 AbilityRequest abilityRequest;
6098 abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
6099 abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
6100 abilityRequest.callerToken = callerToken;
6101 abilityRequest.startSetting = nullptr;
6102 abilityRequest.want = want;
6103 abilityRequest.connect = connect;
6104 result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
6105 if (result != ERR_OK) {
6106 HILOG_ERROR("Generate ability request error.");
6107 return result;
6108 }
6109
6110 if (!abilityRequest.abilityInfo.isStageBasedModel) {
6111 HILOG_ERROR("target ability is not stage base model.");
6112 return RESOLVE_CALL_ABILITY_VERSION_ERR;
6113 }
6114
6115 result = CheckStartByCallPermission(abilityRequest);
6116 if (result != ERR_OK) {
6117 HILOG_ERROR("CheckStartByCallPermission fail, result: %{public}d", result);
6118 return result;
6119 }
6120
6121 HILOG_DEBUG("abilityInfo.applicationInfo.singleton is %{public}s",
6122 abilityRequest.abilityInfo.applicationInfo.singleton ? "true" : "false");
6123 UpdateCallerInfo(abilityRequest.want, callerToken);
6124 result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
6125 afterCheckExecuter_->DoProcess(abilityRequest.want, 0, GetUserId(), false, callerToken);
6126 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6127 ReportEventToSuspendManager(abilityRequest.abilityInfo);
6128 abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
6129 return uiAbilityLifecycleManager_->ResolveLocked(abilityRequest, oriValidUserId);
6130 }
6131
6132 auto missionListMgr = GetListManagerByUserId(oriValidUserId);
6133 if (missionListMgr == nullptr) {
6134 HILOG_ERROR("missionListMgr is Null. Designated User Id=%{public}d", oriValidUserId);
6135 return ERR_INVALID_VALUE;
6136 }
6137 ReportEventToSuspendManager(abilityRequest.abilityInfo);
6138
6139 if (result != ERR_OK) {
6140 HILOG_ERROR("afterCheckExecuter_ is nullptr or DoProcess return error.");
6141 return result;
6142 }
6143
6144 return missionListMgr->ResolveLocked(abilityRequest);
6145 }
6146
StartAbilityJust(AbilityRequest & abilityRequest,int32_t validUserId)6147 int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)
6148 {
6149 HILOG_DEBUG("call");
6150 UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
6151 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6152 ReportEventToSuspendManager(abilityRequest.abilityInfo);
6153 return uiAbilityLifecycleManager_->ResolveLocked(abilityRequest, validUserId);
6154 }
6155
6156 auto missionListMgr = GetListManagerByUserId(validUserId);
6157 if (missionListMgr == nullptr) {
6158 HILOG_ERROR("missionListMgr is Null. Designated User Id=%{public}d", validUserId);
6159 return ERR_INVALID_VALUE;
6160 }
6161 ReportEventToSuspendManager(abilityRequest.abilityInfo);
6162
6163 return missionListMgr->ResolveLocked(abilityRequest);
6164 }
6165
ReleaseCall(const sptr<IAbilityConnection> & connect,const AppExecFwk::ElementName & element)6166 int AbilityManagerService::ReleaseCall(
6167 const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
6168 {
6169 HILOG_DEBUG("Release called ability.");
6170
6171 CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
6172 CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
6173 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6174 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
6175 }
6176
6177 std::string elementName = element.GetURI();
6178 HILOG_DEBUG("try to release called ability, name: %{public}s.", elementName.c_str());
6179
6180 if (CheckIsRemote(element.GetDeviceID())) {
6181 HILOG_INFO("release remote ability");
6182 return ReleaseRemoteAbility(connect->AsObject(), element);
6183 }
6184
6185 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6186 return uiAbilityLifecycleManager_->ReleaseCallLocked(connect, element);
6187 }
6188
6189 return currentMissionListManager_->ReleaseCallLocked(connect, element);
6190 }
6191
JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo & abilityInfo)6192 int AbilityManagerService::JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)
6193 {
6194 HILOG_DEBUG("Call.");
6195 if (abilityInfo.visible) {
6196 return ERR_OK;
6197 }
6198 auto callerTokenId = IPCSkeleton::GetCallingTokenID();
6199 if (callerTokenId == abilityInfo.applicationInfo.accessTokenId ||
6200 callerTokenId == static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID())) { // foundation call is allowed
6201 return ERR_OK;
6202 }
6203 if (AccessTokenKit::VerifyAccessToken(callerTokenId,
6204 PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == AppExecFwk::Constants::PERMISSION_GRANTED) {
6205 return ERR_OK;
6206 }
6207 HILOG_ERROR("callerToken: %{private}u, targetToken: %{private}u, caller doesn's have permission",
6208 callerTokenId, abilityInfo.applicationInfo.accessTokenId);
6209 return ABILITY_VISIBLE_FALSE_DENY_REQUEST;
6210 }
6211
StartUser(int userId)6212 int AbilityManagerService::StartUser(int userId)
6213 {
6214 HILOG_DEBUG("%{public}s, userId:%{public}d", __func__, userId);
6215 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
6216 HILOG_ERROR("%{public}s: Permission verification failed, not account process", __func__);
6217 return CHECK_PERMISSION_FAILED;
6218 }
6219
6220 if (userController_) {
6221 return userController_->StartUser(userId, true);
6222 }
6223 return 0;
6224 }
6225
StopUser(int userId,const sptr<IStopUserCallback> & callback)6226 int AbilityManagerService::StopUser(int userId, const sptr<IStopUserCallback> &callback)
6227 {
6228 HILOG_DEBUG("%{public}s", __func__);
6229 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
6230 HILOG_ERROR("%{public}s: Permission verification failed, not account process", __func__);
6231 return CHECK_PERMISSION_FAILED;
6232 }
6233
6234 auto ret = -1;
6235 if (userController_) {
6236 ret = userController_->StopUser(userId);
6237 HILOG_DEBUG("ret = %{public}d", ret);
6238 }
6239 if (callback) {
6240 callback->OnStopUserDone(userId, ret);
6241 }
6242 return 0;
6243 }
6244
LogoutUser(int32_t userId)6245 int AbilityManagerService::LogoutUser(int32_t userId)
6246 {
6247 if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
6248 HILOG_ERROR("Permission verification failed, not account process");
6249 return CHECK_PERMISSION_FAILED;
6250 }
6251
6252 if (userController_) {
6253 auto ret = userController_->LogoutUser(userId);
6254 HILOG_DEBUG("logout user return = %{public}d", ret);
6255 return ret;
6256 }
6257 return ERR_OK;
6258 }
6259
OnAcceptWantResponse(const AAFwk::Want & want,const std::string & flag)6260 void AbilityManagerService::OnAcceptWantResponse(
6261 const AAFwk::Want &want, const std::string &flag)
6262 {
6263 HILOG_DEBUG("On accept want response");
6264 if (uiAbilityLifecycleManager_ && Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6265 uiAbilityLifecycleManager_->OnAcceptWantResponse(want, flag);
6266 return;
6267 }
6268 if (!currentMissionListManager_) {
6269 return;
6270 }
6271 currentMissionListManager_->OnAcceptWantResponse(want, flag);
6272 }
6273
OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want & want)6274 void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want)
6275 {
6276 HILOG_DEBUG("%{public}s called.", __func__);
6277 if (uiAbilityLifecycleManager_ && Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6278 uiAbilityLifecycleManager_->OnStartSpecifiedAbilityTimeoutResponse(want);
6279 return;
6280 }
6281 if (!currentMissionListManager_) {
6282 return;
6283 }
6284 currentMissionListManager_->OnStartSpecifiedAbilityTimeoutResponse(want);
6285 }
6286
OnStartSpecifiedProcessResponse(const AAFwk::Want & want,const std::string & flag)6287 void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag)
6288 {
6289 HILOG_DEBUG("flag = %{public}s", flag.c_str());
6290 if (uiAbilityLifecycleManager_ && Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6291 uiAbilityLifecycleManager_->OnStartSpecifiedProcessResponse(want, flag);
6292 return;
6293 }
6294 }
6295
OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want & want)6296 void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want)
6297 {
6298 HILOG_DEBUG("%{public}s called.", __func__);
6299 if (uiAbilityLifecycleManager_ && Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6300 uiAbilityLifecycleManager_->OnStartSpecifiedAbilityTimeoutResponse(want);
6301 return;
6302 }
6303 }
6304
GetAbilityRunningInfos(std::vector<AbilityRunningInfo> & info)6305 int AbilityManagerService::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
6306 {
6307 HILOG_DEBUG("Get running ability infos.");
6308 CHECK_CALLER_IS_SYSTEM_APP;
6309 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
6310 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6311 uiAbilityLifecycleManager_->GetAbilityRunningInfos(info, isPerm, GetUserId());
6312 } else {
6313 if (!currentMissionListManager_) {
6314 return ERR_INVALID_VALUE;
6315 }
6316 currentMissionListManager_->GetAbilityRunningInfos(info, isPerm);
6317 }
6318
6319 UpdateFocusState(info);
6320
6321 return ERR_OK;
6322 }
6323
UpdateFocusState(std::vector<AbilityRunningInfo> & info)6324 void AbilityManagerService::UpdateFocusState(std::vector<AbilityRunningInfo> &info)
6325 {
6326 if (info.empty()) {
6327 return;
6328 }
6329
6330 #ifdef SUPPORT_GRAPHICS
6331 sptr<IRemoteObject> token;
6332 int ret = IN_PROCESS_CALL(GetTopAbility(token));
6333 if (ret != ERR_OK || token == nullptr) {
6334 return;
6335 }
6336
6337 auto abilityRecord = Token::GetAbilityRecordByToken(token);
6338 if (abilityRecord == nullptr) {
6339 HILOG_WARN("%{public}s abilityRecord is null.", __func__);
6340 return;
6341 }
6342
6343 for (auto &item : info) {
6344 if (item.uid == abilityRecord->GetUid() && item.pid == abilityRecord->GetPid() &&
6345 item.ability == abilityRecord->GetElementName()) {
6346 item.abilityState = static_cast<int>(AbilityState::ACTIVE);
6347 break;
6348 }
6349 }
6350 #endif
6351 }
6352
GetExtensionRunningInfos(int upperLimit,std::vector<ExtensionRunningInfo> & info)6353 int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)
6354 {
6355 HILOG_DEBUG("Get extension infos, upperLimit : %{public}d", upperLimit);
6356 CHECK_CALLER_IS_SYSTEM_APP;
6357 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
6358 if (!connectManager_) {
6359 return ERR_INVALID_VALUE;
6360 }
6361
6362 connectManager_->GetExtensionRunningInfos(upperLimit, info, GetUserId(), isPerm);
6363 return ERR_OK;
6364 }
6365
GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> & info)6366 int AbilityManagerService::GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)
6367 {
6368 return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfos(info);
6369 }
6370
GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> & info,int32_t userId)6371 int AbilityManagerService::GetProcessRunningInfosByUserId(
6372 std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)
6373 {
6374 return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfosByUserId(info, userId);
6375 }
6376
ClearUserData(int32_t userId)6377 void AbilityManagerService::ClearUserData(int32_t userId)
6378 {
6379 HILOG_DEBUG("%{public}s", __func__);
6380 std::unique_lock<ffrt::mutex> lock(managersMutex_);
6381 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6382 missionListManagers_.erase(userId);
6383 }
6384 connectManagers_.erase(userId);
6385 dataAbilityManagers_.erase(userId);
6386 pendingWantManagers_.erase(userId);
6387 }
6388
RegisterSnapshotHandler(const sptr<ISnapshotHandler> & handler)6389 int AbilityManagerService::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
6390 {
6391 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6392 if (!isSaCall) {
6393 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
6394 return 0;
6395 }
6396
6397 if (!currentMissionListManager_) {
6398 HILOG_ERROR("snapshot: currentMissionListManager_ is nullptr.");
6399 return INNER_ERR;
6400 }
6401 currentMissionListManager_->RegisterSnapshotHandler(handler);
6402 HILOG_INFO("snapshot: AbilityManagerService register snapshot handler success.");
6403 return ERR_OK;
6404 }
6405
GetMissionSnapshot(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot,bool isLowResolution)6406 int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId,
6407 MissionSnapshot& missionSnapshot, bool isLowResolution)
6408 {
6409 CHECK_CALLER_IS_SYSTEM_APP;
6410 if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
6411 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
6412 return CHECK_PERMISSION_FAILED;
6413 }
6414
6415 if (CheckIsRemote(deviceId)) {
6416 HILOG_INFO("get remote mission snapshot.");
6417 return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot);
6418 }
6419 HILOG_INFO("get local mission snapshot.");
6420 if (!currentMissionListManager_) {
6421 HILOG_ERROR("snapshot: currentMissionListManager_ is nullptr.");
6422 return INNER_ERR;
6423 }
6424 auto token = GetAbilityTokenByMissionId(missionId);
6425 bool result = currentMissionListManager_->GetMissionSnapshot(missionId, token, missionSnapshot, isLowResolution);
6426 if (!result) {
6427 return INNER_ERR;
6428 }
6429 return ERR_OK;
6430 }
6431
UpdateMissionSnapShot(const sptr<IRemoteObject> & token,const std::shared_ptr<Media::PixelMap> & pixelMap)6432 void AbilityManagerService::UpdateMissionSnapShot(const sptr<IRemoteObject> &token,
6433 const std::shared_ptr<Media::PixelMap> &pixelMap)
6434 {
6435 if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)) {
6436 return;
6437 }
6438 if (currentMissionListManager_) {
6439 currentMissionListManager_->UpdateSnapShot(token, pixelMap);
6440 }
6441 }
6442
EnableRecoverAbility(const sptr<IRemoteObject> & token)6443 void AbilityManagerService::EnableRecoverAbility(const sptr<IRemoteObject>& token)
6444 {
6445 if (token == nullptr) {
6446 return;
6447 }
6448 auto record = Token::GetAbilityRecordByToken(token);
6449 if (record == nullptr) {
6450 HILOG_ERROR("%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
6451 return;
6452 }
6453
6454 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
6455 auto tokenID = record->GetApplicationInfo().accessTokenId;
6456 if (callingTokenId != tokenID) {
6457 HILOG_ERROR("AppRecovery ScheduleRecoverAbility not self, not enabled");
6458 return;
6459 }
6460 {
6461 std::lock_guard<ffrt::mutex> guard(globalLock_);
6462 auto it = appRecoveryHistory_.find(record->GetUid());
6463 if (it == appRecoveryHistory_.end()) {
6464 appRecoveryHistory_.emplace(record->GetUid(), 0);
6465 }
6466 }
6467
6468 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6469 const auto& abilityInfo = record->GetAbilityInfo();
6470 (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->AddAbilityRecoverInfo(
6471 abilityInfo.bundleName, abilityInfo.moduleName, abilityInfo.name,
6472 uiAbilityLifecycleManager_->GetSessionIdByAbilityToken(token));
6473 } else {
6474 auto userId = record->GetOwnerMissionUserId();
6475 auto missionListMgr = GetListManagerByUserId(userId);
6476 if (missionListMgr == nullptr) {
6477 HILOG_ERROR("missionListMgr is nullptr");
6478 return;
6479 }
6480 missionListMgr->EnableRecoverAbility(record->GetMissionId());
6481 }
6482 }
6483
RecoverAbilityRestart(const Want & want)6484 void AbilityManagerService::RecoverAbilityRestart(const Want& want)
6485 {
6486 std::string identity = IPCSkeleton::ResetCallingIdentity();
6487 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
6488 int32_t ret = StartAbility(want, userId, 0);
6489 if (ret != ERR_OK) {
6490 HILOG_ERROR("%{public}s AppRecovery::failed to restart ability. %{public}d", __func__, ret);
6491 }
6492 IPCSkeleton::SetCallingIdentity(identity);
6493 }
6494
ReportAppRecoverResult(const int32_t appId,const AppExecFwk::ApplicationInfo & appInfo,const std::string & abilityName,const std::string & result)6495 void AbilityManagerService::ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo,
6496 const std::string& abilityName, const std::string& result)
6497 {
6498 HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
6499 "APP_UID", appId,
6500 "VERSION_CODE", std::to_string(appInfo.versionCode),
6501 "VERSION_NAME", appInfo.versionName,
6502 "BUNDLE_NAME", appInfo.bundleName,
6503 "ABILITY_NAME", abilityName,
6504 "RECOVERY_RESULT", result);
6505 }
6506
AppRecoverKill(pid_t pid,int32_t reason)6507 void AbilityManagerService::AppRecoverKill(pid_t pid, int32_t reason)
6508 {
6509 AppExecFwk::AppFaultDataBySA faultDataSA;
6510 faultDataSA.errorObject.name = "appRecovery";
6511 switch (reason) {
6512 case AppExecFwk::StateReason::CPP_CRASH:
6513 faultDataSA.faultType = AppExecFwk::FaultDataType::CPP_CRASH;
6514 break;
6515 case AppExecFwk::StateReason::JS_ERROR:
6516 faultDataSA.faultType = AppExecFwk::FaultDataType::JS_ERROR;
6517 break;
6518 case AppExecFwk::StateReason::LIFECYCLE:
6519 case AppExecFwk::StateReason::APP_FREEZE:
6520 faultDataSA.faultType = AppExecFwk::FaultDataType::APP_FREEZE;
6521 break;
6522 default:
6523 faultDataSA.faultType = AppExecFwk::FaultDataType::UNKNOWN;
6524 }
6525 faultDataSA.pid = pid;
6526 IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFaultBySA(faultDataSA));
6527 }
6528
ScheduleRecoverAbility(const sptr<IRemoteObject> & token,int32_t reason,const Want * want)6529 void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)
6530 {
6531 if (token == nullptr) {
6532 return;
6533 }
6534 auto record = Token::GetAbilityRecordByToken(token);
6535 if (record == nullptr) {
6536 HILOG_ERROR("%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
6537 return;
6538 }
6539
6540 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
6541 auto tokenID = record->GetApplicationInfo().accessTokenId;
6542 if (callingTokenId != tokenID) {
6543 HILOG_ERROR("AppRecovery ScheduleRecoverAbility not self, not enabled");
6544 return;
6545 }
6546
6547 if (reason == AppExecFwk::StateReason::APP_FREEZE) {
6548 RecordAppExitReason(REASON_APP_FREEZE);
6549 }
6550
6551 AAFwk::Want curWant;
6552 {
6553 std::lock_guard<ffrt::mutex> guard(globalLock_);
6554 auto type = record->GetAbilityInfo().type;
6555 if (type != AppExecFwk::AbilityType::PAGE) {
6556 HILOG_ERROR("%{public}s AppRecovery::only do recover for page ability.", __func__);
6557 return;
6558 }
6559
6560 constexpr int64_t MIN_RECOVERY_TIME = 60;
6561 int64_t now = time(nullptr);
6562 auto it = appRecoveryHistory_.find(record->GetUid());
6563 auto appInfo = record->GetApplicationInfo();
6564 auto abilityInfo = record->GetAbilityInfo();
6565
6566 if ((it != appRecoveryHistory_.end()) &&
6567 (it->second + MIN_RECOVERY_TIME > now)) {
6568 HILOG_ERROR("%{public}s AppRecovery recover app more than once in one minute, just kill app(%{public}d).",
6569 __func__, record->GetPid());
6570 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_WITHIN_ONE_MINUTE");
6571 AppRecoverKill(record->GetPid(), reason);
6572 return;
6573 }
6574
6575 if (want != nullptr) {
6576 HILOG_DEBUG("BundleName:%{public}s targetBundleName:%{public}s.",
6577 appInfo.bundleName.c_str(), want->GetElement().GetBundleName().c_str());
6578 if (want->GetElement().GetBundleName().empty() ||
6579 (appInfo.bundleName.compare(want->GetElement().GetBundleName()) != 0)) {
6580 HILOG_ERROR("AppRecovery BundleName not match, Not recovery ability!");
6581 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_BUNDLE_NAME_NOT_MATCH");
6582 return;
6583 } else if (want->GetElement().GetAbilityName().empty()) {
6584 HILOG_DEBUG("AppRecovery recovery target ability is empty");
6585 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_TARGET_ABILITY_EMPTY");
6586 return;
6587 } else {
6588 auto bms = GetBundleManager();
6589 if (bms == nullptr) {
6590 HILOG_ERROR("bms is nullptr");
6591 return;
6592 }
6593 AppExecFwk::BundleInfo bundleInfo;
6594 auto bundleName = want->GetElement().GetBundleName();
6595 int32_t userId = GetUserId();
6596 bool ret = IN_PROCESS_CALL(
6597 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo,
6598 userId));
6599 if (!ret) {
6600 HILOG_ERROR("AppRecovery Failed to get bundle info, not do recovery!");
6601 return;
6602 }
6603 bool isRestartPage = false;
6604 auto abilityName = want->GetElement().GetAbilityName();
6605 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
6606 if ((abilityName.compare(it->name) == 0) && it->type == AppExecFwk::AbilityType::PAGE) {
6607 isRestartPage = true;
6608 break;
6609 }
6610 }
6611 if (!isRestartPage) {
6612 HILOG_INFO("AppRecovery the target ability type is not PAGE!");
6613 ReportAppRecoverResult(record->GetUid(), appInfo, abilityName, "FAIL_TARGET_ABILITY_NOT_PAGE");
6614 return;
6615 }
6616 }
6617 }
6618
6619 appRecoveryHistory_[record->GetUid()] = now;
6620 curWant = (want == nullptr) ? record->GetWant() : *want;
6621 curWant.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
6622
6623 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "SUCCESS");
6624 AppRecoverKill(record->GetPid(), reason);
6625 }
6626
6627 constexpr int delaytime = 1000;
6628 std::string taskName = "AppRecovery_kill:" + std::to_string(record->GetPid());
6629 auto task = std::bind(&AbilityManagerService::RecoverAbilityRestart, this, curWant);
6630 HILOG_INFO("AppRecovery RecoverAbilityRestart task begin");
6631 taskHandler_->SubmitTask(task, taskName, delaytime);
6632 }
6633
GetRemoteMissionSnapshotInfo(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot)6634 int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId,
6635 MissionSnapshot& missionSnapshot)
6636 {
6637 HILOG_INFO("GetRemoteMissionSnapshotInfo begin");
6638 std::unique_ptr<MissionSnapshot> missionSnapshotPtr = std::make_unique<MissionSnapshot>();
6639 DistributedClient dmsClient;
6640 int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr);
6641 if (result != ERR_OK) {
6642 HILOG_ERROR("GetRemoteMissionSnapshotInfo failed, result = %{public}d", result);
6643 return result;
6644 }
6645 missionSnapshot = *missionSnapshotPtr;
6646 return ERR_OK;
6647 }
6648
StartSwitchUserDialog()6649 void AbilityManagerService::StartSwitchUserDialog()
6650 {
6651 HILOG_DEBUG("Start switch user dialog extension ability come");
6652 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6653 HILOG_ERROR("Scene board enabled, dialog not show.");
6654 return;
6655 }
6656
6657 if (userController_ == nullptr) {
6658 HILOG_ERROR("User Controller instance is nullptr.");
6659 return;
6660 }
6661
6662 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
6663 if (sysDialog == nullptr) {
6664 HILOG_ERROR("System dialog scheduler instance is nullptr.");
6665 return;
6666 }
6667
6668 Want dialogWant = sysDialog->GetSwitchUserDialogWant();
6669 StartSwitchUserDialogInner(dialogWant, userController_->GetFreezingNewUserId());
6670 }
6671
6672
StartSwitchUserDialogInner(const Want & want,int32_t lastUserId)6673 void AbilityManagerService::StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)
6674 {
6675 HILOG_DEBUG("Start switch user dialog inner come");
6676 EventInfo eventInfo = BuildEventInfo(want, lastUserId);
6677 eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
6678 EventReport::SendExtensionEvent(EventName::START_SERVICE, HiSysEventType::BEHAVIOR, eventInfo);
6679 AbilityRequest abilityRequest;
6680 auto result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
6681 if (result != ERR_OK) {
6682 HILOG_ERROR("Generate ability request local error.");
6683 eventInfo.errCode = result;
6684 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
6685 return;
6686 }
6687
6688 auto abilityInfo = abilityRequest.abilityInfo;
6689 auto startUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
6690 result = CheckOptExtensionAbility(want, abilityRequest, startUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
6691 if (result != ERR_OK) {
6692 HILOG_ERROR("Check extensionAbility type error.");
6693 eventInfo.errCode = result;
6694 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
6695 return;
6696 }
6697
6698 auto connectManager = GetConnectManagerByUserId(startUserId);
6699 if (connectManager == nullptr) {
6700 InitConnectManager(startUserId, false);
6701 connectManager = GetConnectManagerByUserId(startUserId);
6702 if (connectManager == nullptr) {
6703 HILOG_ERROR("ConnectManager is nullptr. userId=%{public}d", startUserId);
6704 eventInfo.errCode = ERR_INVALID_VALUE;
6705 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
6706 return;
6707 }
6708 }
6709
6710 eventInfo.errCode = connectManager->StartAbility(abilityRequest);
6711 if (eventInfo.errCode != ERR_OK) {
6712 HILOG_ERROR("EventInfo errCode is %{public}d", eventInfo.errCode);
6713 EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
6714 }
6715 }
6716
StartFreezingScreen()6717 void AbilityManagerService::StartFreezingScreen()
6718 {
6719 HILOG_INFO("%{public}s", __func__);
6720 #ifdef SUPPORT_GRAPHICS
6721 StartSwitchUserDialog();
6722 std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
6723 IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Freeze(displayIds));
6724 #endif
6725 }
6726
StopFreezingScreen()6727 void AbilityManagerService::StopFreezingScreen()
6728 {
6729 HILOG_INFO("%{public}s", __func__);
6730 #ifdef SUPPORT_GRAPHICS
6731 std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
6732 IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Unfreeze(displayIds));
6733 StopSwitchUserDialog();
6734 #endif
6735 }
6736
UserStarted(int32_t userId)6737 void AbilityManagerService::UserStarted(int32_t userId)
6738 {
6739 HILOG_INFO("%{public}s", __func__);
6740 InitConnectManager(userId, false);
6741 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6742 InitMissionListManager(userId, false);
6743 }
6744 InitDataAbilityManager(userId, false);
6745 InitPendWantManager(userId, false);
6746 }
6747
SwitchToUser(int32_t oldUserId,int32_t userId)6748 void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId)
6749 {
6750 HILOG_INFO("%{public}s, oldUserId:%{public}d, newUserId:%{public}d", __func__, oldUserId, userId);
6751 SwitchManagers(userId);
6752 if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6753 PauseOldUser(oldUserId);
6754 ConnectBmsService();
6755 StartUserApps();
6756 }
6757 bool isBoot = oldUserId == U0_USER_ID ? true : false;
6758 StartHighestPriorityAbility(userId, isBoot);
6759 PauseOldConnectManager(oldUserId);
6760 }
6761
SwitchManagers(int32_t userId,bool switchUser)6762 void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser)
6763 {
6764 HILOG_INFO("%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId);
6765 InitConnectManager(userId, switchUser);
6766 if (userId != U0_USER_ID && !Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6767 InitMissionListManager(userId, switchUser);
6768 }
6769 InitDataAbilityManager(userId, switchUser);
6770 InitPendWantManager(userId, switchUser);
6771 HILOG_INFO("%{public}s, SwitchManagers:%{public}d-----end", __func__, userId);
6772 }
6773
PauseOldUser(int32_t userId)6774 void AbilityManagerService::PauseOldUser(int32_t userId)
6775 {
6776 HILOG_INFO("%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId);
6777 PauseOldMissionListManager(userId);
6778 HILOG_INFO("%{public}s, PauseOldUser:%{public}d-----end", __func__, userId);
6779 }
6780
PauseOldMissionListManager(int32_t userId)6781 void AbilityManagerService::PauseOldMissionListManager(int32_t userId)
6782 {
6783 HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId);
6784 std::lock_guard<ffrt::mutex> lock(managersMutex_);
6785 auto it = missionListManagers_.find(userId);
6786 if (it == missionListManagers_.end()) {
6787 HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----end1", __func__, userId);
6788 return;
6789 }
6790 auto manager = it->second;
6791 if (!manager) {
6792 HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----end2", __func__, userId);
6793 return;
6794 }
6795 manager->PauseManager();
6796 HILOG_INFO("%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId);
6797 }
6798
PauseOldConnectManager(int32_t userId)6799 void AbilityManagerService::PauseOldConnectManager(int32_t userId)
6800 {
6801 HILOG_INFO("%{public}s, PauseOldConnectManager:%{public}d-----begin", __func__, userId);
6802 if (userId == U0_USER_ID) {
6803 HILOG_INFO("%{public}s, u0 not stop, id:%{public}d-----nullptr", __func__, userId);
6804 return;
6805 }
6806
6807 std::lock_guard<ffrt::mutex> lock(managersMutex_);
6808 auto it = connectManagers_.find(userId);
6809 if (it == connectManagers_.end()) {
6810 HILOG_INFO("%{public}s, PauseOldConnectManager:%{public}d-----no user", __func__, userId);
6811 return;
6812 }
6813 auto manager = it->second;
6814 if (!manager) {
6815 HILOG_INFO("%{public}s, PauseOldConnectManager:%{public}d-----nullptr", __func__, userId);
6816 return;
6817 }
6818 manager->PauseExtensions();
6819 HILOG_INFO("%{public}s, PauseOldConnectManager:%{public}d-----end", __func__, userId);
6820 }
6821
StartUserApps()6822 void AbilityManagerService::StartUserApps()
6823 {
6824 if (currentMissionListManager_ && currentMissionListManager_->IsStarted()) {
6825 HILOG_INFO("missionListManager ResumeManager");
6826 currentMissionListManager_->ResumeManager();
6827 }
6828 }
6829
InitConnectManager(int32_t userId,bool switchUser)6830 void AbilityManagerService::InitConnectManager(int32_t userId, bool switchUser)
6831 {
6832 bool find = false;
6833 {
6834 std::lock_guard<ffrt::mutex> lock(managersMutex_);
6835 auto it = connectManagers_.find(userId);
6836 find = (it != connectManagers_.end());
6837 if (find) {
6838 if (switchUser) {
6839 connectManager_ = it->second;
6840 }
6841 }
6842 }
6843 if (!find) {
6844 auto manager = std::make_shared<AbilityConnectManager>(userId);
6845 manager->SetTaskHandler(taskHandler_);
6846 manager->SetEventHandler(eventHandler_);
6847 std::unique_lock<ffrt::mutex> lock(managersMutex_);
6848 connectManagers_.emplace(userId, manager);
6849 if (switchUser) {
6850 connectManager_ = manager;
6851 }
6852 }
6853 }
6854
InitDataAbilityManager(int32_t userId,bool switchUser)6855 void AbilityManagerService::InitDataAbilityManager(int32_t userId, bool switchUser)
6856 {
6857 bool find = false;
6858 {
6859 std::lock_guard<ffrt::mutex> lock(managersMutex_);
6860 auto it = dataAbilityManagers_.find(userId);
6861 find = (it != dataAbilityManagers_.end());
6862 if (find) {
6863 if (switchUser) {
6864 dataAbilityManager_ = it->second;
6865 }
6866 }
6867 }
6868 if (!find) {
6869 auto manager = std::make_shared<DataAbilityManager>();
6870 std::unique_lock<ffrt::mutex> lock(managersMutex_);
6871 dataAbilityManagers_.emplace(userId, manager);
6872 if (switchUser) {
6873 dataAbilityManager_ = manager;
6874 }
6875 }
6876 }
6877
InitPendWantManager(int32_t userId,bool switchUser)6878 void AbilityManagerService::InitPendWantManager(int32_t userId, bool switchUser)
6879 {
6880 bool find = false;
6881 {
6882 std::lock_guard<ffrt::mutex> lock(managersMutex_);
6883 auto it = pendingWantManagers_.find(userId);
6884 find = (it != pendingWantManagers_.end());
6885 if (find) {
6886 if (switchUser) {
6887 pendingWantManager_ = it->second;
6888 }
6889 }
6890 }
6891 if (!find) {
6892 auto manager = std::make_shared<PendingWantManager>();
6893 std::unique_lock<ffrt::mutex> lock(managersMutex_);
6894 pendingWantManagers_.emplace(userId, manager);
6895 if (switchUser) {
6896 pendingWantManager_ = manager;
6897 }
6898 }
6899 }
6900
GetValidUserId(const int32_t userId)6901 int32_t AbilityManagerService::GetValidUserId(const int32_t userId)
6902 {
6903 HILOG_DEBUG("userId = %{public}d.", userId);
6904 int32_t validUserId = userId;
6905
6906 if (DEFAULT_INVAL_VALUE == userId) {
6907 validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
6908 HILOG_DEBUG("validUserId = %{public}d, CallingUid = %{public}d.", validUserId,
6909 IPCSkeleton::GetCallingUid());
6910 if (validUserId == U0_USER_ID) {
6911 validUserId = GetUserId();
6912 }
6913 }
6914 return validUserId;
6915 }
6916
SetAbilityController(const sptr<IAbilityController> & abilityController,bool imAStabilityTest)6917 int AbilityManagerService::SetAbilityController(const sptr<IAbilityController> &abilityController,
6918 bool imAStabilityTest)
6919 {
6920 HILOG_DEBUG("%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest);
6921 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyControllerPerm();
6922 if (!isPerm) {
6923 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
6924 return CHECK_PERMISSION_FAILED;
6925 }
6926
6927 std::lock_guard<ffrt::mutex> guard(globalLock_);
6928 abilityController_ = abilityController;
6929 controllerIsAStabilityTest_ = imAStabilityTest;
6930 HILOG_DEBUG("%{public}s, end", __func__);
6931 return ERR_OK;
6932 }
6933
SendANRProcessID(int pid)6934 int AbilityManagerService::SendANRProcessID(int pid)
6935 {
6936 HILOG_INFO("SendANRProcessID come, pid is %{public}d", pid);
6937 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6938 auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6939 if (!isSaCall && !isShellCall) {
6940 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
6941 return CHECK_PERMISSION_FAILED;
6942 }
6943
6944 AppExecFwk::ApplicationInfo appInfo;
6945 bool debug;
6946 auto appScheduler = DelayedSingleton<AppScheduler>::GetInstance();
6947 if (appScheduler->GetApplicationInfoByProcessID(pid, appInfo, debug) == ERR_OK) {
6948 std::lock_guard<ffrt::mutex> guard(globalLock_);
6949 auto it = appRecoveryHistory_.find(appInfo.uid);
6950 if (it != appRecoveryHistory_.end()) {
6951 return ERR_OK;
6952 }
6953 }
6954
6955 if (debug) {
6956 HILOG_ERROR("SendANRProcessID error, debug mode.");
6957 return ERR_INVALID_VALUE;
6958 }
6959
6960 auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
6961 if (!sysDialog) {
6962 HILOG_ERROR("SystemDialogScheduler is nullptr.");
6963 return ERR_INVALID_VALUE;
6964 }
6965
6966 Want want;
6967 if (!sysDialog->GetANRDialogWant(GetUserId(), pid, want)) {
6968 HILOG_ERROR("GetANRDialogWant failed.");
6969 return ERR_INVALID_VALUE;
6970 }
6971 return StartAbility(want);
6972 }
6973
IsRunningInStabilityTest()6974 bool AbilityManagerService::IsRunningInStabilityTest()
6975 {
6976 std::lock_guard<ffrt::mutex> guard(globalLock_);
6977 bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_;
6978 HILOG_DEBUG("%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret);
6979 return ret;
6980 }
6981
IsAbilityControllerStart(const Want & want,const std::string & bundleName)6982 bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName)
6983 {
6984 HILOG_DEBUG("method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
6985 if (abilityController_ == nullptr) {
6986 HILOG_DEBUG("abilityController_ is nullptr");
6987 return true;
6988 }
6989
6990 if (controllerIsAStabilityTest_) {
6991 bool isStart = abilityController_->AllowAbilityStart(want, bundleName);
6992 if (!isStart) {
6993 HILOG_INFO("Not finishing start ability because controller starting: %{public}s", bundleName.c_str());
6994 return false;
6995 }
6996 }
6997 return true;
6998 }
6999
IsAbilityControllerForeground(const std::string & bundleName)7000 bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName)
7001 {
7002 HILOG_DEBUG("method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
7003 if (abilityController_ == nullptr) {
7004 HILOG_DEBUG("abilityController_ is nullptr");
7005 return true;
7006 }
7007
7008 if (controllerIsAStabilityTest_) {
7009 bool isResume = abilityController_->AllowAbilityBackground(bundleName);
7010 if (!isResume) {
7011 HILOG_INFO("Not finishing terminate ability because controller resuming: %{public}s", bundleName.c_str());
7012 return false;
7013 }
7014 }
7015 return true;
7016 }
7017
InitAbilityInfoFromExtension(AppExecFwk::ExtensionAbilityInfo & extensionInfo,AppExecFwk::AbilityInfo & abilityInfo)7018 int32_t AbilityManagerService::InitAbilityInfoFromExtension(AppExecFwk::ExtensionAbilityInfo &extensionInfo,
7019 AppExecFwk::AbilityInfo &abilityInfo)
7020 {
7021 abilityInfo.applicationName = extensionInfo.applicationInfo.name;
7022 abilityInfo.applicationInfo = extensionInfo.applicationInfo;
7023 abilityInfo.bundleName = extensionInfo.bundleName;
7024 abilityInfo.package = extensionInfo.moduleName;
7025 abilityInfo.moduleName = extensionInfo.moduleName;
7026 abilityInfo.name = extensionInfo.name;
7027 abilityInfo.srcEntrance = extensionInfo.srcEntrance;
7028 abilityInfo.srcPath = extensionInfo.srcEntrance;
7029 abilityInfo.iconPath = extensionInfo.icon;
7030 abilityInfo.iconId = extensionInfo.iconId;
7031 abilityInfo.label = extensionInfo.label;
7032 abilityInfo.labelId = extensionInfo.labelId;
7033 abilityInfo.description = extensionInfo.description;
7034 abilityInfo.descriptionId = extensionInfo.descriptionId;
7035 abilityInfo.priority = extensionInfo.priority;
7036 abilityInfo.permissions = extensionInfo.permissions;
7037 abilityInfo.readPermission = extensionInfo.readPermission;
7038 abilityInfo.writePermission = extensionInfo.writePermission;
7039 abilityInfo.uri = extensionInfo.uri;
7040 abilityInfo.extensionAbilityType = extensionInfo.type;
7041 abilityInfo.visible = extensionInfo.visible;
7042 abilityInfo.resourcePath = extensionInfo.resourcePath;
7043 abilityInfo.enabled = extensionInfo.enabled;
7044 abilityInfo.isModuleJson = true;
7045 abilityInfo.isStageBasedModel = true;
7046 abilityInfo.process = extensionInfo.process;
7047 abilityInfo.metadata = extensionInfo.metadata;
7048 abilityInfo.compileMode = extensionInfo.compileMode;
7049 abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
7050 abilityInfo.extensionTypeName = extensionInfo.extensionTypeName;
7051 if (!extensionInfo.hapPath.empty()) {
7052 abilityInfo.hapPath = extensionInfo.hapPath;
7053 }
7054 return 0;
7055 }
7056
StartUserTest(const Want & want,const sptr<IRemoteObject> & observer)7057 int AbilityManagerService::StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)
7058 {
7059 HILOG_DEBUG("enter");
7060 if (observer == nullptr) {
7061 HILOG_ERROR("observer is nullptr");
7062 return ERR_INVALID_VALUE;
7063 }
7064
7065 std::string bundleName = want.GetStringParam("-b");
7066 if (bundleName.empty()) {
7067 HILOG_ERROR("Invalid bundle name");
7068 return ERR_INVALID_VALUE;
7069 }
7070
7071 auto bms = GetBundleManager();
7072 CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL);
7073 AppExecFwk::BundleInfo bundleInfo;
7074 if (!IN_PROCESS_CALL(
7075 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID))) {
7076 HILOG_ERROR("Failed to get bundle info by U0_USER_ID %{public}d.", U0_USER_ID);
7077 int32_t userId = GetUserId();
7078 if (!IN_PROCESS_CALL(
7079 bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
7080 HILOG_ERROR("Failed to get bundle info by userId %{public}d.", userId);
7081 return GET_BUNDLE_INFO_FAILED;
7082 }
7083 }
7084
7085 return DelayedSingleton<AppScheduler>::GetInstance()->StartUserTest(want, observer, bundleInfo, GetUserId());
7086 }
7087
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName)7088 int AbilityManagerService::FinishUserTest(
7089 const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
7090 {
7091 HILOG_DEBUG("enter");
7092 if (bundleName.empty()) {
7093 HILOG_ERROR("Invalid bundle name.");
7094 return ERR_INVALID_VALUE;
7095 }
7096
7097 return DelayedSingleton<AppScheduler>::GetInstance()->FinishUserTest(msg, resultCode, bundleName);
7098 }
7099
GetTopAbility(sptr<IRemoteObject> & token)7100 int AbilityManagerService::GetTopAbility(sptr<IRemoteObject> &token)
7101 {
7102 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7103 if (!isSaCall) {
7104 HILOG_ERROR("Permission verification failed");
7105 return CHECK_PERMISSION_FAILED;
7106 }
7107 #ifdef SUPPORT_GRAPHICS
7108 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7109 Rosen::FocusChangeInfo focusChangeInfo;
7110 Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
7111 token = focusChangeInfo.abilityToken_;
7112 } else {
7113 if (!wmsHandler_) {
7114 HILOG_ERROR("wmsHandler_ is nullptr.");
7115 return ERR_INVALID_VALUE;
7116 }
7117 wmsHandler_->GetFocusWindow(token);
7118 }
7119
7120 if (!token) {
7121 HILOG_ERROR("token is nullptr");
7122 return ERR_INVALID_VALUE;
7123 }
7124 #endif
7125 return ERR_OK;
7126 }
7127
DelegatorDoAbilityForeground(const sptr<IRemoteObject> & token)7128 int AbilityManagerService::DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)
7129 {
7130 HILOG_DEBUG("enter");
7131 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
7132 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7133 auto sessionId = uiAbilityLifecycleManager_->GetSessionIdByAbilityToken(token);
7134 if (!sessionId) {
7135 HILOG_ERROR("Invalid session id.");
7136 return ERR_INVALID_VALUE;
7137 }
7138 auto&& abilityRecord = Token::GetAbilityRecordByToken(token);
7139 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7140 auto want = abilityRecord->GetWant();
7141 if (!IsAbilityControllerStart(want, want.GetBundle())) {
7142 HILOG_ERROR("SceneBoard IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
7143 return ERR_WOULD_BLOCK;
7144 }
7145 return ERR_OK;
7146 }
7147 auto missionId = GetMissionIdByAbilityToken(token);
7148 if (missionId < 0) {
7149 HILOG_ERROR("Invalid mission id.");
7150 return ERR_INVALID_VALUE;
7151 }
7152 return DelegatorMoveMissionToFront(missionId);
7153 }
7154
DelegatorDoAbilityBackground(const sptr<IRemoteObject> & token)7155 int AbilityManagerService::DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)
7156 {
7157 HILOG_DEBUG("enter");
7158 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7159 return ERR_OK;
7160 }
7161 return MinimizeAbility(token, true);
7162 }
7163
DoAbilityForeground(const sptr<IRemoteObject> & token,uint32_t flag)7164 int AbilityManagerService::DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)
7165 {
7166 HILOG_DEBUG("DoAbilityForeground, sceneFlag:%{public}u", flag);
7167 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
7168 if (!VerificationToken(token) && !VerificationAllToken(token)) {
7169 HILOG_ERROR("%{public}s token error.", __func__);
7170 return ERR_INVALID_VALUE;
7171 }
7172
7173 std::lock_guard<ffrt::mutex> guard(globalLock_);
7174 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7175 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7176 if (!JudgeSelfCalled(abilityRecord)) {
7177 return CHECK_PERMISSION_FAILED;
7178 }
7179
7180 auto type = abilityRecord->GetAbilityInfo().type;
7181 if (type != AppExecFwk::AbilityType::PAGE) {
7182 HILOG_ERROR("Cannot minimize except page ability.");
7183 return ERR_WRONG_INTERFACE_CALL;
7184 }
7185
7186 if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
7187 HILOG_ERROR("IsAbilityControllerForeground false.");
7188 return ERR_WOULD_BLOCK;
7189 }
7190
7191 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
7192 return currentMissionListManager_->DoAbilityForeground(abilityRecord, flag);
7193 }
7194
DoAbilityBackground(const sptr<IRemoteObject> & token,uint32_t flag)7195 int AbilityManagerService::DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)
7196 {
7197 HILOG_DEBUG("DoAbilityBackground, sceneFlag:%{public}u", flag);
7198 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
7199
7200 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7201 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7202
7203 abilityRecord->lifeCycleStateInfo_.sceneFlag = flag;
7204 int ret = MinimizeAbility(token);
7205 abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL;
7206 return ret;
7207 }
7208
DelegatorMoveMissionToFront(int32_t missionId)7209 int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId)
7210 {
7211 HILOG_INFO("enter missionId : %{public}d", missionId);
7212 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
7213
7214 if (!IsAbilityControllerStartById(missionId)) {
7215 HILOG_ERROR("IsAbilityControllerStart false");
7216 return ERR_WOULD_BLOCK;
7217 }
7218
7219 return currentMissionListManager_->MoveMissionToFront(missionId);
7220 }
7221
UpdateCallerInfo(Want & want,const sptr<IRemoteObject> & callerToken)7222 void AbilityManagerService::UpdateCallerInfo(Want& want, const sptr<IRemoteObject> &callerToken)
7223 {
7224 int32_t tokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
7225 int32_t callerUid = IPCSkeleton::GetCallingUid();
7226 int32_t callerPid = IPCSkeleton::GetCallingPid();
7227 want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
7228 want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
7229 want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
7230 want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
7231 want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
7232 want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
7233
7234 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7235 if (!abilityRecord) {
7236 want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
7237 want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, std::string(""));
7238 want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
7239 want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, std::string(""));
7240 } else {
7241 std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
7242 want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
7243 want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
7244 std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
7245 want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
7246 want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
7247 }
7248 }
7249
UpdateAsCallerSourceInfo(Want & want,sptr<IRemoteObject> asCallerSourceToken)7250 void AbilityManagerService::UpdateAsCallerSourceInfo(Want& want, sptr<IRemoteObject> asCallerSourceToken)
7251 {
7252 AppExecFwk::RunningProcessInfo processInfo = {};
7253 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByToken(asCallerSourceToken, processInfo);
7254
7255 auto abilityRecord = Token::GetAbilityRecordByToken(asCallerSourceToken);
7256 if (abilityRecord == nullptr) {
7257 HILOG_ERROR("abilityRecord is nullptr");
7258 return;
7259 }
7260 int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
7261
7262 want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
7263 want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
7264 want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
7265 want.SetParam(Want::PARAM_RESV_CALLER_UID, processInfo.uid_);
7266 want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
7267 want.SetParam(Want::PARAM_RESV_CALLER_PID, processInfo.pid_);
7268
7269 std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
7270 want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
7271 want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
7272 std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
7273 want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
7274 want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
7275 }
7276
UpdateCallerInfoFromToken(Want & want,const sptr<IRemoteObject> & token)7277 void AbilityManagerService::UpdateCallerInfoFromToken(Want& want, const sptr<IRemoteObject> &token)
7278 {
7279 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7280 if (!abilityRecord) {
7281 HILOG_WARN("caller abilityRecord is null.");
7282 return;
7283 }
7284
7285 int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
7286 int32_t callerUid = abilityRecord->GetUid();
7287 int32_t callerPid = abilityRecord->GetPid();
7288 want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
7289 want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
7290 want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
7291 want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
7292 want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
7293 want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
7294
7295 std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
7296 want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
7297 want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
7298 std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
7299 want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
7300 want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
7301 }
7302
JudgeMultiUserConcurrency(const int32_t userId)7303 bool AbilityManagerService::JudgeMultiUserConcurrency(const int32_t userId)
7304 {
7305 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7306
7307 if (userId == U0_USER_ID) {
7308 HILOG_DEBUG("%{public}s, userId is 0.", __func__);
7309 return true;
7310 }
7311
7312 HILOG_DEBUG("userId : %{public}d, current userId : %{public}d", userId, GetUserId());
7313
7314 // Only non-concurrent mode is supported
7315 bool concurrencyMode = CONCURRENCY_MODE_FALSE;
7316 if (!concurrencyMode) {
7317 return (userId == GetUserId());
7318 }
7319
7320 return true;
7321 }
7322
7323 #ifdef ABILITY_COMMAND_FOR_TEST
ForceTimeoutForTest(const std::string & abilityName,const std::string & state)7324 int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, const std::string &state)
7325 {
7326 if (abilityName.empty()) {
7327 HILOG_ERROR("abilityName is empty.");
7328 return INVALID_DATA;
7329 }
7330 if (abilityName == "clean") {
7331 timeoutMap_.clear();
7332 return ERR_OK;
7333 }
7334 if (state != AbilityRecord::ConvertAbilityState(AbilityState::INITIAL) &&
7335 state != AbilityRecord::ConvertAbilityState(AbilityState::INACTIVE) &&
7336 state != AbilityRecord::ConvertAbilityState(AbilityState::FOREGROUND) &&
7337 state != AbilityRecord::ConvertAbilityState(AbilityState::BACKGROUND) &&
7338 state != AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) &&
7339 state != std::string("COMMAND")) {
7340 HILOG_ERROR("lifecycle state is invalid.");
7341 return INVALID_DATA;
7342 }
7343 timeoutMap_.insert(std::make_pair(state, abilityName));
7344 return ERR_OK;
7345 }
7346 #endif
7347
CheckStaticCfgPermission(AppExecFwk::AbilityInfo & abilityInfo,bool isStartAsCaller,uint32_t callerTokenId,bool isData,bool isSaCall)7348 int AbilityManagerService::CheckStaticCfgPermission(AppExecFwk::AbilityInfo &abilityInfo, bool isStartAsCaller,
7349 uint32_t callerTokenId, bool isData, bool isSaCall)
7350 {
7351 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7352 if (!isData) {
7353 isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7354 }
7355 if (isSaCall) {
7356 // do not need check static config permission when start ability by SA
7357 return AppExecFwk::Constants::PERMISSION_GRANTED;
7358 }
7359
7360 uint32_t tokenId;
7361 if (isStartAsCaller) {
7362 tokenId = callerTokenId;
7363 } else {
7364 tokenId = IPCSkeleton::GetCallingTokenID();
7365 }
7366
7367 if (abilityInfo.applicationInfo.accessTokenId == tokenId) {
7368 return ERR_OK;
7369 }
7370
7371 if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
7372 abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) ||
7373 (abilityInfo.type == AppExecFwk::AbilityType::DATA)) {
7374 // just need check the read permission and write permission of extension ability or data ability
7375 if (!abilityInfo.readPermission.empty()) {
7376 int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission, false);
7377 if (checkReadPermission == ERR_OK) {
7378 return AppExecFwk::Constants::PERMISSION_GRANTED;
7379 }
7380 HILOG_WARN("verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str());
7381 }
7382 if (!abilityInfo.writePermission.empty()) {
7383 int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission, false);
7384 if (checkWritePermission == ERR_OK) {
7385 return AppExecFwk::Constants::PERMISSION_GRANTED;
7386 }
7387 HILOG_WARN("verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str());
7388 }
7389
7390 if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) {
7391 // 'readPermission' and 'writePermission' take precedence over 'permission'
7392 // when 'readPermission' or 'writePermission' is not empty, no need check 'permission'
7393 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
7394 }
7395 }
7396
7397 // verify permission if 'permission' is not empty
7398 if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId,
7399 PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) {
7400 return AppExecFwk::Constants::PERMISSION_GRANTED;
7401 }
7402
7403 for (auto permission : abilityInfo.permissions) {
7404 if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false)
7405 != AppExecFwk::Constants::PERMISSION_GRANTED) {
7406 HILOG_ERROR("verify access token fail, permission: %{public}s", permission.c_str());
7407 return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
7408 }
7409 }
7410
7411 return AppExecFwk::Constants::PERMISSION_GRANTED;
7412 }
7413
IsNeedTimeoutForTest(const std::string & abilityName,const std::string & state) const7414 bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const
7415 {
7416 for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) {
7417 if (iter->first == state && iter->second == abilityName) {
7418 return true;
7419 }
7420 }
7421 return false;
7422 }
7423
GetValidDataAbilityUri(const std::string & abilityInfoUri,std::string & adjustUri)7424 bool AbilityManagerService::GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)
7425 {
7426 // note: do not use abilityInfo.uri directly, need check uri first.
7427 size_t firstSeparator = abilityInfoUri.find_first_of('/');
7428 size_t lastSeparator = abilityInfoUri.find_last_of('/');
7429 if (lastSeparator - firstSeparator != 1) {
7430 HILOG_ERROR("ability info uri error, uri: %{public}s", abilityInfoUri.c_str());
7431 return false;
7432 }
7433
7434 adjustUri = abilityInfoUri;
7435 adjustUri.insert(lastSeparator, "/");
7436 return true;
7437 }
7438
GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> & abilityInfos,const std::string & mainAbility,std::string & uri)7439 bool AbilityManagerService::GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos,
7440 const std::string &mainAbility, std::string &uri)
7441 {
7442 if (abilityInfos.empty() || mainAbility.empty()) {
7443 HILOG_ERROR("abilityInfos or mainAbility is empty. mainAbility: %{public}s", mainAbility.c_str());
7444 return false;
7445 }
7446
7447 std::string dataAbilityUri;
7448 for (auto abilityInfo : abilityInfos) {
7449 if (abilityInfo.type == AppExecFwk::AbilityType::DATA &&
7450 abilityInfo.name == mainAbility) {
7451 dataAbilityUri = abilityInfo.uri;
7452 HILOG_INFO("get data ability uri: %{public}s", dataAbilityUri.c_str());
7453 break;
7454 }
7455 }
7456
7457 return GetValidDataAbilityUri(dataAbilityUri, uri);
7458 }
7459
GetAbilityRunningInfo(std::vector<AbilityRunningInfo> & info,std::shared_ptr<AbilityRecord> & abilityRecord)7460 void AbilityManagerService::GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info,
7461 std::shared_ptr<AbilityRecord> &abilityRecord)
7462 {
7463 AbilityRunningInfo runningInfo;
7464 AppExecFwk::RunningProcessInfo processInfo;
7465
7466 runningInfo.ability = abilityRecord->GetElementName();
7467 runningInfo.startTime = abilityRecord->GetStartTime();
7468 runningInfo.abilityState = static_cast<int>(abilityRecord->GetAbilityState());
7469
7470 DelayedSingleton<AppScheduler>::GetInstance()->
7471 GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
7472 runningInfo.pid = processInfo.pid_;
7473 runningInfo.uid = processInfo.uid_;
7474 runningInfo.processName = processInfo.processName_;
7475 info.emplace_back(runningInfo);
7476 }
7477
VerifyAccountPermission(int32_t userId)7478 int AbilityManagerService::VerifyAccountPermission(int32_t userId)
7479 {
7480 if ((userId < 0) || (userController_ && (userController_->GetCurrentUserId() == userId))) {
7481 return ERR_OK;
7482 }
7483 return AAFwk::PermissionVerification::GetInstance()->VerifyAccountPermission();
7484 }
7485
7486 #ifdef ABILITY_COMMAND_FOR_TEST
BlockAmsService()7487 int AbilityManagerService::BlockAmsService()
7488 {
7489 HILOG_DEBUG("%{public}s", __func__);
7490 if (AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
7491 HILOG_ERROR("Not shell call");
7492 return ERR_PERMISSION_DENIED;
7493 }
7494 if (taskHandler_) {
7495 HILOG_DEBUG("%{public}s begin post block ams service task", __func__);
7496 auto BlockAmsServiceTask = [aams = shared_from_this()]() {
7497 while (1) {
7498 HILOG_DEBUG("%{public}s begin waiting", __func__);
7499 std::this_thread::sleep_for(BLOCK_AMS_SERVICE_TIME*1s);
7500 }
7501 };
7502 taskHandler_->SubmitTask(BlockAmsServiceTask, "blockamsservice");
7503 return ERR_OK;
7504 }
7505 return ERR_NO_INIT;
7506 }
7507
BlockAbility(int32_t abilityRecordId)7508 int AbilityManagerService::BlockAbility(int32_t abilityRecordId)
7509 {
7510 HILOG_DEBUG("%{public}s", __func__);
7511 if (AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
7512 HILOG_ERROR("Not shell call");
7513 return ERR_PERMISSION_DENIED;
7514 }
7515 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7516 return uiAbilityLifecycleManager_->BlockAbility(abilityRecordId, GetUserId());
7517 }
7518 CHECK_POINTER_AND_RETURN(currentMissionListManager_, ERR_NO_INIT);
7519 return currentMissionListManager_->BlockAbility(abilityRecordId);
7520 }
7521
BlockAppService()7522 int AbilityManagerService::BlockAppService()
7523 {
7524 HILOG_DEBUG("%{public}s", __func__);
7525 if (AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
7526 HILOG_ERROR("Not shell call");
7527 return ERR_PERMISSION_DENIED;
7528 }
7529 return DelayedSingleton<AppScheduler>::GetInstance()->BlockAppService();
7530 }
7531 #endif
7532
FreeInstallAbilityFromRemote(const Want & want,const sptr<IRemoteObject> & callback,int32_t userId,int requestCode)7533 int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
7534 int32_t userId, int requestCode)
7535 {
7536 auto callingUid = IPCSkeleton::GetCallingUid();
7537 if (callingUid != DMS_UID) {
7538 HILOG_ERROR("The interface only support for DMS");
7539 return CHECK_PERMISSION_FAILED;
7540 }
7541 int32_t validUserId = GetValidUserId(userId);
7542 if (freeInstallManager_ == nullptr) {
7543 HILOG_ERROR("freeInstallManager_ is nullptr");
7544 return ERR_INVALID_VALUE;
7545 }
7546 return freeInstallManager_->FreeInstallAbilityFromRemote(want, callback, validUserId, requestCode);
7547 }
7548
GetTopAbility(bool isNeedLocalDeviceId)7549 AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId)
7550 {
7551 HILOG_DEBUG("%{public}s start.", __func__);
7552 AppExecFwk::ElementName elementName = {};
7553 #ifdef SUPPORT_GRAPHICS
7554 sptr<IRemoteObject> token;
7555 int ret = IN_PROCESS_CALL(GetTopAbility(token));
7556 if (ret) {
7557 return elementName;
7558 }
7559 if (!token) {
7560 HILOG_ERROR("token is nullptr");
7561 return elementName;
7562 }
7563 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7564 if (abilityRecord == nullptr) {
7565 HILOG_ERROR("%{public}s abilityRecord is null.", __func__);
7566 return elementName;
7567 }
7568 elementName = abilityRecord->GetElementName();
7569 bool isDeviceEmpty = elementName.GetDeviceID().empty();
7570 std::string localDeviceId;
7571 if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
7572 elementName.SetDeviceID(localDeviceId);
7573 }
7574 #endif
7575 return elementName;
7576 }
7577
GetElementNameByToken(sptr<IRemoteObject> token,bool isNeedLocalDeviceId)7578 AppExecFwk::ElementName AbilityManagerService::GetElementNameByToken(sptr<IRemoteObject> token,
7579 bool isNeedLocalDeviceId)
7580 {
7581 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7582 HILOG_DEBUG("%{public}s start.", __func__);
7583 AppExecFwk::ElementName elementName = {};
7584 #ifdef SUPPORT_GRAPHICS
7585 if (!token) {
7586 HILOG_ERROR("token is nullptr");
7587 return elementName;
7588 }
7589 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7590 if (abilityRecord == nullptr) {
7591 HILOG_ERROR("%{public}s abilityRecord is null.", __func__);
7592 return elementName;
7593 }
7594 elementName = abilityRecord->GetElementName();
7595 bool isDeviceEmpty = elementName.GetDeviceID().empty();
7596 std::string localDeviceId;
7597 if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
7598 elementName.SetDeviceID(localDeviceId);
7599 }
7600 #endif
7601 return elementName;
7602 }
7603
Dump(int fd,const std::vector<std::u16string> & args)7604 int AbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
7605 {
7606 HILOG_DEBUG("Dump begin fd: %{public}d", fd);
7607 std::string result;
7608 auto errCode = Dump(args, result);
7609 int ret = dprintf(fd, "%s\n", result.c_str());
7610 if (ret < 0) {
7611 HILOG_ERROR("dprintf error");
7612 return ERR_AAFWK_HIDUMP_ERROR;
7613 }
7614 HILOG_DEBUG("Dump end");
7615 return errCode;
7616 }
7617
Dump(const std::vector<std::u16string> & args,std::string & result)7618 int AbilityManagerService::Dump(const std::vector<std::u16string>& args, std::string& result)
7619 {
7620 ErrCode errCode = ERR_OK;
7621 auto size = args.size();
7622 if (size == 0) {
7623 ShowHelp(result);
7624 return errCode;
7625 }
7626
7627 std::vector<std::string> argsStr;
7628 for (auto arg : args) {
7629 argsStr.emplace_back(Str16ToStr8(arg));
7630 }
7631
7632 if (argsStr[0] == "-h") {
7633 ShowHelp(result);
7634 } else {
7635 errCode = ProcessMultiParam(argsStr, result);
7636 if (errCode == ERR_AAFWK_HIDUMP_INVALID_ARGS) {
7637 ShowIllegalInfomation(result);
7638 }
7639 }
7640 return errCode;
7641 }
7642
ProcessMultiParam(std::vector<std::string> & argsStr,std::string & result)7643 ErrCode AbilityManagerService::ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)
7644 {
7645 HILOG_DEBUG("%{public}s begin", __func__);
7646 bool isClient = false;
7647 bool isUser = false;
7648 int userID = DEFAULT_INVAL_VALUE;
7649 std::vector<std::string>::iterator it;
7650 for (it = argsStr.begin(); it != argsStr.end();) {
7651 if (*it == ARGS_CLIENT) {
7652 isClient = true;
7653 it = argsStr.erase(it);
7654 continue;
7655 }
7656 if (*it == ARGS_USER_ID) {
7657 it = argsStr.erase(it);
7658 if (it == argsStr.end()) {
7659 HILOG_ERROR("ARGS_USER_ID id invalid");
7660 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
7661 }
7662 (void)StrToInt(*it, userID);
7663 if (userID < 0) {
7664 HILOG_ERROR("ARGS_USER_ID id invalid");
7665 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
7666 }
7667 isUser = true;
7668 it = argsStr.erase(it);
7669 continue;
7670 }
7671 it++;
7672 }
7673 std::string cmd;
7674 for (unsigned int i = 0; i < argsStr.size(); i++) {
7675 cmd.append(argsStr[i]);
7676 if (i != argsStr.size() - 1) {
7677 cmd.append(" ");
7678 }
7679 }
7680 HILOG_INFO("%{public}s, isClient:%{public}d, userID is : %{public}d, cmd is : %{public}s",
7681 __func__, isClient, userID, cmd.c_str());
7682
7683 std::vector<std::string> dumpResults;
7684 DumpSysState(cmd, dumpResults, isClient, isUser, userID);
7685 for (auto it : dumpResults) {
7686 result += it + "\n";
7687 }
7688 return ERR_OK;
7689 }
7690
ShowHelp(std::string & result)7691 void AbilityManagerService::ShowHelp(std::string& result)
7692 {
7693 result.append("Usage:\n")
7694 .append("-h ")
7695 .append("help text for the tool\n")
7696 .append("-a [-c | -u {UserId}] ")
7697 .append("dump all ability infomation in the system or all ability infomation of client/UserId\n")
7698 .append("-l ")
7699 .append("dump all mission list information in the system\n")
7700 .append("-i {AbilityRecordId} ")
7701 .append("dump an ability infomation by ability record id\n")
7702 .append("-e ")
7703 .append("dump all extension infomation in the system(FA: ServiceAbilityRecords, Stage: ExtensionRecords)\n")
7704 .append("-p [PendingWantRecordId] ")
7705 .append("dump all pendingwant record infomation in the system\n")
7706 .append("-r ")
7707 .append("dump all process in the system\n")
7708 .append("-d ")
7709 .append("dump all data ability infomation in the system");
7710 }
7711
ShowIllegalInfomation(std::string & result)7712 void AbilityManagerService::ShowIllegalInfomation(std::string& result)
7713 {
7714 result.append(ILLEGAL_INFOMATION);
7715 }
7716
DumpAbilityInfoDone(std::vector<std::string> & infos,const sptr<IRemoteObject> & callerToken)7717 int AbilityManagerService::DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)
7718 {
7719 HILOG_DEBUG("DumpAbilityInfoDone begin");
7720 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7721 if (abilityRecord == nullptr) {
7722 HILOG_ERROR("abilityRecord nullptr");
7723 return ERR_INVALID_VALUE;
7724 }
7725 if (!JudgeSelfCalled(abilityRecord)) {
7726 return CHECK_PERMISSION_FAILED;
7727 }
7728 abilityRecord->DumpAbilityInfoDone(infos);
7729 return ERR_OK;
7730 }
7731
SetMissionContinueState(const sptr<IRemoteObject> & token,const AAFwk::ContinueState & state)7732 int AbilityManagerService::SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)
7733 {
7734 HILOG_DEBUG("SetMissionContinueState begin. State: %{public}d", state);
7735
7736 CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
7737
7738 int32_t missionId = GetMissionIdByAbilityToken(token);
7739 if (missionId == -1) {
7740 HILOG_ERROR("SetMissionContinueState failed to get missionId. State: %{public}d", state);
7741 return ERR_INVALID_VALUE;
7742 }
7743
7744 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7745 if (!abilityRecord) {
7746 HILOG_ERROR("SetMissionContinueState: No such ability record. Mission id: %{public}d, state: %{public}d",
7747 missionId, state);
7748 return -1;
7749 }
7750
7751 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7752 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
7753 if (callingTokenId != tokenID) {
7754 HILOG_ERROR("SetMissionContinueState not self, not enabled. Mission id: %{public}d, state: %{public}d",
7755 missionId, state);
7756 return -1;
7757 }
7758
7759 auto userId = abilityRecord->GetOwnerMissionUserId();
7760 auto missionListManager = GetListManagerByUserId(userId);
7761 if (!missionListManager) {
7762 HILOG_ERROR("failed to find mission list manager. Mission id: %{public}d, state: %{public}d",
7763 missionId, state);
7764 return -1;
7765 }
7766
7767 auto setResult = missionListManager->SetMissionContinueState(token, missionId, state);
7768 if (setResult != ERR_OK) {
7769 HILOG_ERROR("missionListManager set failed, result: %{public}d, mission id: %{public}d, state: %{public}d",
7770 setResult, missionId, state);
7771 return setResult;
7772 }
7773
7774 DistributedClient dmsClient;
7775 auto result = dmsClient.SetMissionContinueState(missionId, state);
7776 if (result != ERR_OK) {
7777 HILOG_ERROR("Notify DMS client failed, result: %{public}d. Mission id: %{public}d, state: %{public}d",
7778 result, missionId, state);
7779 }
7780
7781 HILOG_DEBUG("SetMissionContinueState end. Mission id: %{public}d, state: %{public}d", missionId, state);
7782 return ERR_OK;
7783 }
7784
7785 #ifdef SUPPORT_GRAPHICS
SetMissionLabel(const sptr<IRemoteObject> & token,const std::string & label)7786 int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
7787 {
7788 HILOG_DEBUG("%{public}s", __func__);
7789 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7790 if (!abilityRecord) {
7791 HILOG_ERROR("no such ability record");
7792 return -1;
7793 }
7794
7795 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7796 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
7797 if (callingTokenId != tokenID) {
7798 HILOG_ERROR("SetMissionLabel not self, not enabled");
7799 return -1;
7800 }
7801
7802 auto userId = abilityRecord->GetOwnerMissionUserId();
7803 auto missionListManager = GetListManagerByUserId(userId);
7804 if (!missionListManager) {
7805 HILOG_ERROR("failed to find mission list manager when set mission label.");
7806 return -1;
7807 }
7808
7809 return missionListManager->SetMissionLabel(token, label);
7810 }
7811
SetMissionIcon(const sptr<IRemoteObject> & token,const std::shared_ptr<OHOS::Media::PixelMap> & icon)7812 int AbilityManagerService::SetMissionIcon(const sptr<IRemoteObject> &token,
7813 const std::shared_ptr<OHOS::Media::PixelMap> &icon)
7814 {
7815 HILOG_DEBUG("%{public}s", __func__);
7816 CHECK_CALLER_IS_SYSTEM_APP;
7817 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7818 if (!abilityRecord) {
7819 HILOG_ERROR("no such ability record");
7820 return -1;
7821 }
7822
7823 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7824 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
7825 if (callingTokenId != tokenID) {
7826 HILOG_ERROR("not self, not enable to set mission icon");
7827 return -1;
7828 }
7829
7830 auto userId = abilityRecord->GetOwnerMissionUserId();
7831 auto missionListManager = GetListManagerByUserId(userId);
7832 if (!missionListManager) {
7833 HILOG_ERROR("failed to find mission list manager.");
7834 return -1;
7835 }
7836
7837 return missionListManager->SetMissionIcon(token, icon);
7838 }
7839
RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> & handler)7840 int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler)
7841 {
7842 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7843 if (!isSaCall) {
7844 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
7845 return CHECK_PERMISSION_FAILED;
7846 }
7847 wmsHandler_ = handler;
7848 HILOG_DEBUG("%{public}s: WMS handler registered successfully.", __func__);
7849 return ERR_OK;
7850 }
7851
GetWMSHandler() const7852 sptr<IWindowManagerServiceHandler> AbilityManagerService::GetWMSHandler() const
7853 {
7854 return wmsHandler_;
7855 }
7856
CompleteFirstFrameDrawing(const sptr<IRemoteObject> & abilityToken)7857 void AbilityManagerService::CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)
7858 {
7859 HILOG_DEBUG("%{public}s is called.", __func__);
7860 std::lock_guard<ffrt::mutex> lock(managersMutex_);
7861 for (auto& item : missionListManagers_) {
7862 if (item.second) {
7863 item.second->CompleteFirstFrameDrawing(abilityToken);
7864 }
7865 }
7866 }
7867
ShowPickerDialog(const Want & want,int32_t userId,const sptr<IRemoteObject> & callerToken)7868 int32_t AbilityManagerService::ShowPickerDialog(
7869 const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)
7870 {
7871 AAFwk::Want newWant = want;
7872 std::string sharePickerBundleName =
7873 OHOS::system::GetParameter(SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME);
7874 std::string sharePickerAbilityName =
7875 OHOS::system::GetParameter(SHARE_PICKER_DIALOG_ABILITY_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME);
7876 newWant.SetElementName(sharePickerBundleName, sharePickerAbilityName);
7877 newWant.SetParam(TOKEN_KEY, callerToken);
7878 // note: clear actions
7879 newWant.SetAction("");
7880 return IN_PROCESS_CALL(StartAbility(newWant, DEFAULT_INVAL_VALUE, userId));
7881 }
7882
CheckWindowMode(int32_t windowMode,const std::vector<AppExecFwk::SupportWindowMode> & windowModes) const7883 bool AbilityManagerService::CheckWindowMode(int32_t windowMode,
7884 const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const
7885 {
7886 HILOG_INFO("Window mode is %{public}d.", windowMode);
7887 if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED) {
7888 return true;
7889 }
7890 auto it = windowModeMap.find(windowMode);
7891 if (it != windowModeMap.end()) {
7892 auto bmsWindowMode = it->second;
7893 for (auto mode : windowModes) {
7894 if (mode == bmsWindowMode) {
7895 return true;
7896 }
7897 }
7898 }
7899 return false;
7900 }
7901
PrepareTerminateAbility(const sptr<IRemoteObject> & token,sptr<IPrepareTerminateCallback> & callback)7902 int AbilityManagerService::PrepareTerminateAbility(const sptr<IRemoteObject> &token,
7903 sptr<IPrepareTerminateCallback> &callback)
7904 {
7905 HILOG_DEBUG("call");
7906 if (callback == nullptr) {
7907 HILOG_ERROR("callback is nullptr.");
7908 return ERR_INVALID_VALUE;
7909 }
7910 if (!CheckPrepareTerminateEnable()) {
7911 callback->DoPrepareTerminate();
7912 return ERR_INVALID_VALUE;
7913 }
7914
7915 auto abilityRecord = Token::GetAbilityRecordByToken(token);
7916 if (abilityRecord == nullptr) {
7917 HILOG_ERROR("record is nullptr.");
7918 callback->DoPrepareTerminate();
7919 return ERR_INVALID_VALUE;
7920 }
7921
7922 if (!JudgeSelfCalled(abilityRecord)) {
7923 HILOG_ERROR("Not self call.");
7924 callback->DoPrepareTerminate();
7925 return CHECK_PERMISSION_FAILED;
7926 }
7927
7928 auto type = abilityRecord->GetAbilityInfo().type;
7929 if (type != AppExecFwk::AbilityType::PAGE) {
7930 HILOG_ERROR("Only support PAGE.");
7931 callback->DoPrepareTerminate();
7932 return RESOLVE_CALL_ABILITY_TYPE_ERR;
7933 }
7934
7935 auto timeoutTask = [&callback]() {
7936 callback->DoPrepareTerminate();
7937 };
7938 int prepareTerminateTimeout =
7939 AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * PREPARE_TERMINATE_TIMEOUT_MULTIPLE;
7940 if (taskHandler_) {
7941 taskHandler_->SubmitTask(timeoutTask, "PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()),
7942 prepareTerminateTimeout);
7943 }
7944
7945 bool res = abilityRecord->PrepareTerminateAbility();
7946 if (!res) {
7947 callback->DoPrepareTerminate();
7948 }
7949 if (taskHandler_) {
7950 taskHandler_->CancelTask("PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()));
7951 }
7952 return ERR_OK;
7953 }
7954
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)7955 void AbilityManagerService::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
7956 {
7957 HILOG_INFO("handle focused event");
7958 if (!currentMissionListManager_) {
7959 HILOG_ERROR("current mission manager is null");
7960 return;
7961 }
7962
7963 int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
7964 currentMissionListManager_->NotifyMissionFocused(missionId);
7965 }
7966
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)7967 void AbilityManagerService::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
7968 {
7969 HILOG_INFO("handle unfocused event");
7970 if (!currentMissionListManager_) {
7971 HILOG_ERROR("current mission manager is null");
7972 return;
7973 }
7974
7975 int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
7976 currentMissionListManager_->NotifyMissionUnfocused(missionId);
7977 }
7978
InitFocusListener()7979 void AbilityManagerService::InitFocusListener()
7980 {
7981 HILOG_INFO("Init ability focus listener");
7982 if (focusListener_) {
7983 return;
7984 }
7985
7986 focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
7987 auto registerTask = [innerService = shared_from_this()]() {
7988 if (innerService) {
7989 HILOG_INFO("RegisterFocusListener task");
7990 innerService->RegisterFocusListener();
7991 }
7992 };
7993 if (taskHandler_) {
7994 taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
7995 }
7996 }
7997
RegisterFocusListener()7998 void AbilityManagerService::RegisterFocusListener()
7999 {
8000 HILOG_INFO("Register focus listener");
8001 if (!focusListener_) {
8002 HILOG_ERROR("no listener obj");
8003 return;
8004 }
8005 Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
8006 HILOG_INFO("Register focus listener success");
8007 }
8008
InitPrepareTerminateConfig()8009 void AbilityManagerService::InitPrepareTerminateConfig()
8010 {
8011 char value[PREPARE_TERMINATE_ENABLE_SIZE] = "false";
8012 int retSysParam = GetParameter(PREPARE_TERMINATE_ENABLE_PARAMETER, "false", value, PREPARE_TERMINATE_ENABLE_SIZE);
8013 HILOG_INFO("CheckPrepareTerminateEnable, %{public}s value is %{public}s.", PREPARE_TERMINATE_ENABLE_PARAMETER,
8014 value);
8015 if (retSysParam > 0 && !std::strcmp(value, "true")) {
8016 isPrepareTerminateEnable_ = true;
8017 }
8018 }
8019 #endif
8020
CheckCallServicePermission(const AbilityRequest & abilityRequest)8021 int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest)
8022 {
8023 if (abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()) == BROKER_UID &&
8024 abilityRequest.want.GetElement().GetBundleName() == SHELL_ASSISTANT_BUNDLENAME) {
8025 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
8026 if (collaborator != nullptr) {
8027 HILOG_INFO("Collaborator CheckCallAbilityPermission.");
8028 return collaborator->CheckCallAbilityPermission(abilityRequest.want);
8029 }
8030 }
8031 if (abilityRequest.abilityInfo.isStageBasedModel) {
8032 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
8033 HILOG_DEBUG("extensionType is %{public}d.", static_cast<int>(extensionType));
8034 if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE ||
8035 extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE) {
8036 return CheckCallServiceExtensionPermission(abilityRequest);
8037 } else {
8038 return CheckCallOtherExtensionPermission(abilityRequest);
8039 }
8040 } else {
8041 return CheckCallServiceAbilityPermission(abilityRequest);
8042 }
8043 }
8044
CheckCallDataAbilityPermission(AbilityRequest & abilityRequest,bool isShell,bool isSACall)8045 int AbilityManagerService::CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)
8046 {
8047 abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo;
8048 abilityRequest.uid = abilityRequest.appInfo.uid;
8049 if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) {
8050 HILOG_ERROR("Invalid app info for data ability acquiring.");
8051 return ERR_INVALID_VALUE;
8052 }
8053 if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) {
8054 HILOG_ERROR("BMS query result is not a data ability.");
8055 return ERR_WRONG_INTERFACE_CALL;
8056 }
8057
8058 AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest,
8059 true, isShell, isSACall);
8060 if (isShell) {
8061 verificationInfo.isBackgroundCall = true;
8062 }
8063 if (!isShell && IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall, true) != ERR_OK) {
8064 return ERR_INVALID_VALUE;
8065 }
8066 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallDataAbilityPermission(verificationInfo,
8067 isShell);
8068 if (result != ERR_OK) {
8069 HILOG_ERROR("Do not have permission to start DataAbility");
8070 return result;
8071 }
8072
8073 return ERR_OK;
8074 }
8075
CreateVerificationInfo(const AbilityRequest & abilityRequest,bool isData,bool isShell,bool isSA)8076 AAFwk::PermissionVerification::VerificationInfo AbilityManagerService::CreateVerificationInfo(
8077 const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)
8078 {
8079 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
8080 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
8081 verificationInfo.visible = abilityRequest.abilityInfo.visible;
8082 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
8083 HILOG_DEBUG("Call ServiceAbility or DataAbility, target bundleName: %{public}s.",
8084 abilityRequest.appInfo.bundleName.c_str());
8085 if (whiteListassociatedWakeUpFlag_ &&
8086 WHITE_LIST_ASS_WAKEUP_SET.find(abilityRequest.appInfo.bundleName) != WHITE_LIST_ASS_WAKEUP_SET.end()) {
8087 HILOG_DEBUG("Call ServiceAbility or DataAbility, target bundle in white-list, allow associatedWakeUp.");
8088 verificationInfo.associatedWakeUp = true;
8089 } else {
8090 verificationInfo.associatedWakeUp = abilityRequest.appInfo.associatedWakeUp;
8091 }
8092 if (!isData) {
8093 isSA = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8094 isShell = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
8095 }
8096 if (isSA || isShell) {
8097 return verificationInfo;
8098 }
8099 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
8100 if (callerAbility) {
8101 verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
8102 }
8103
8104 return verificationInfo;
8105 }
8106
CheckCallServiceExtensionPermission(const AbilityRequest & abilityRequest)8107 int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)
8108 {
8109 HILOG_DEBUG("begin");
8110
8111 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
8112 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
8113 verificationInfo.visible = abilityRequest.abilityInfo.visible;
8114 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
8115 verificationInfo.isBackgroundCall = false;
8116 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo);
8117 if (result != ERR_OK) {
8118 HILOG_ERROR("Do not have permission to start ServiceExtension or DataShareExtension");
8119 }
8120 return result;
8121 }
8122
CheckCallOtherExtensionPermission(const AbilityRequest & abilityRequest)8123 int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)
8124 {
8125 HILOG_DEBUG("Call");
8126 if (IPCSkeleton::GetCallingUid() != BROKER_UID && AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
8127 return ERR_OK;
8128 }
8129
8130 auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
8131 HILOG_DEBUG("OtherExtension type: %{public}d.", static_cast<int32_t>(extensionType));
8132 if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) {
8133 return ERR_OK;
8134 }
8135 if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) {
8136 return ERR_OK;
8137 }
8138 if (extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD) {
8139 if (!abilityRequest.appInfo.isSystemApp) {
8140 HILOG_ERROR("The application requesting the call is a non system application.");
8141 return CHECK_PERMISSION_FAILED;
8142 }
8143 std::string jsonDataStr = abilityRequest.want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY);
8144 AbilityBase::ViewData viewData;
8145 viewData.FromJsonString(jsonDataStr.c_str());
8146 if (!CheckCallingTokenId(viewData.bundleName)) {
8147 HILOG_ERROR("Not %{public}s called, not allowed.", viewData.bundleName.c_str());
8148 return ERR_WRONG_INTERFACE_CALL;
8149 }
8150 return ERR_OK;
8151 }
8152 if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
8153 return ERR_OK;
8154 }
8155 if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
8156 return ERR_OK;
8157 }
8158 const std::string fileAccessPermission = "ohos.permission.FILE_ACCESS_MANAGER";
8159 if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION &&
8160 AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(fileAccessPermission)) {
8161 HILOG_DEBUG("Temporary, FILEACCESS_EXTENSION use serviceExtension start-up rule.");
8162 return CheckCallServiceExtensionPermission(abilityRequest);
8163 }
8164
8165 HILOG_ERROR("Not SA, can not start other Extension");
8166 return CHECK_PERMISSION_FAILED;
8167 }
8168
8169
CheckCallServiceAbilityPermission(const AbilityRequest & abilityRequest)8170 int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)
8171 {
8172 HILOG_DEBUG("Call");
8173 AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest);
8174 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
8175 return ERR_INVALID_VALUE;
8176 }
8177
8178 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceAbilityPermission(verificationInfo);
8179 if (result != ERR_OK) {
8180 HILOG_ERROR("Do not have permission to start ServiceAbility");
8181 }
8182 return result;
8183 }
8184
CheckCallAbilityPermission(const AbilityRequest & abilityRequest)8185 int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest)
8186 {
8187 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8188 HILOG_DEBUG("Call");
8189
8190 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
8191 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
8192 verificationInfo.visible = abilityRequest.abilityInfo.visible;
8193 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
8194 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
8195 return ERR_INVALID_VALUE;
8196 }
8197
8198 int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission(verificationInfo);
8199 if (result != ERR_OK) {
8200 HILOG_ERROR("Do not have permission to start PageAbility(FA) or Ability(Stage)");
8201 }
8202 return result;
8203 }
8204
CheckStartByCallPermission(const AbilityRequest & abilityRequest)8205 int AbilityManagerService::CheckStartByCallPermission(const AbilityRequest &abilityRequest)
8206 {
8207 HILOG_INFO("Call");
8208 // check whether the target ability is page type and not specified mode.
8209 if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::PAGE ||
8210 abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
8211 HILOG_ERROR("Called ability is not common ability.");
8212 return RESOLVE_CALL_ABILITY_TYPE_ERR;
8213 }
8214
8215 AAFwk::PermissionVerification::VerificationInfo verificationInfo;
8216 verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
8217 verificationInfo.visible = abilityRequest.abilityInfo.visible;
8218 verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
8219 if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
8220 return ERR_INVALID_VALUE;
8221 }
8222
8223 if (AAFwk::PermissionVerification::GetInstance()->CheckStartByCallPermission(verificationInfo) != ERR_OK) {
8224 HILOG_ERROR("Do not have permission to StartAbilityByCall.");
8225 return RESOLVE_CALL_NO_PERMISSIONS;
8226 }
8227 HILOG_DEBUG("The caller has permission to resolve the call proxy of common ability.");
8228
8229 return ERR_OK;
8230 }
8231
IsCallFromBackground(const AbilityRequest & abilityRequest,bool & isBackgroundCall,bool isData)8232 int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall,
8233 bool isData)
8234 {
8235 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8236 if (!isData && AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
8237 isBackgroundCall = true;
8238 return ERR_OK;
8239 }
8240
8241 if (!isData && (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
8242 AbilityUtil::IsStartFreeInstall(abilityRequest.want))) {
8243 isBackgroundCall = false;
8244 return ERR_OK;
8245 }
8246
8247 AppExecFwk::RunningProcessInfo processInfo;
8248 std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
8249 if (callerAbility) {
8250 if (callerAbility->IsForeground() || callerAbility->GetAbilityForegroundingFlag()) {
8251 isBackgroundCall = false;
8252 return ERR_OK;
8253 }
8254 // CallerAbility is not foreground, so check process state
8255 DelayedSingleton<AppScheduler>::GetInstance()->
8256 GetRunningProcessInfoByToken(callerAbility->GetToken(), processInfo);
8257 } else {
8258 auto callerPid = IPCSkeleton::GetCallingPid();
8259 DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
8260 if (processInfo.processName_.empty()) {
8261 HILOG_DEBUG("Can not find caller application by callerPid: %{private}d.", callerPid);
8262 if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
8263 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
8264 HILOG_DEBUG("Caller has PERMISSION_START_ABILITIES_FROM_BACKGROUND, PASS.");
8265 isBackgroundCall = false;
8266 return ERR_OK;
8267 }
8268 HILOG_ERROR("Caller does not have PERMISSION_START_ABILITIES_FROM_BACKGROUND, REJECT.");
8269 return ERR_INVALID_VALUE;
8270 }
8271 }
8272
8273 if (IsDelegatorCall(processInfo, abilityRequest)) {
8274 HILOG_DEBUG("The call is from AbilityDelegator, allow background-call.");
8275 isBackgroundCall = false;
8276 return ERR_OK;
8277 }
8278
8279 if (backgroundJudgeFlag_) {
8280 isBackgroundCall = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND &&
8281 !processInfo.isFocused && !processInfo.isAbilityForegrounding;
8282 } else {
8283 isBackgroundCall = !processInfo.isFocused;
8284 if (!processInfo.isFocused && processInfo.state_ == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) {
8285 // Allow background startup within 1 second after application startup if state is FOREGROUND
8286 int64_t aliveTime = AbilityUtil::SystemTimeMillis() - processInfo.startTimeMillis_;
8287 isBackgroundCall = aliveTime > APP_ALIVE_TIME_MS;
8288 HILOG_DEBUG("Process %{public}s is alive %{public}s ms.",
8289 processInfo.processName_.c_str(), std::to_string(aliveTime).c_str());
8290 }
8291 }
8292 HILOG_DEBUG("backgroundJudgeFlag: %{public}d, isBackgroundCall: %{public}d, callerAppState: %{public}d.",
8293 static_cast<int32_t>(backgroundJudgeFlag_),
8294 static_cast<int32_t>(isBackgroundCall),
8295 static_cast<int32_t>(processInfo.state_));
8296
8297 return ERR_OK;
8298 }
8299
IsTargetPermission(const Want & want) const8300 bool AbilityManagerService::IsTargetPermission(const Want &want) const
8301 {
8302 if (want.GetElement().GetBundleName() == PERMISSIONMGR_BUNDLE_NAME &&
8303 want.GetElement().GetAbilityName() == PERMISSIONMGR_ABILITY_NAME) {
8304 return true;
8305 }
8306
8307 return false;
8308 }
8309
IsDelegatorCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest)8310 inline bool AbilityManagerService::IsDelegatorCall(
8311 const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest)
8312 {
8313 /* To make sure the AbilityDelegator is not counterfeited
8314 * 1. The caller-process must be test-process
8315 * 2. The callerToken must be nullptr
8316 */
8317 if (processInfo.isTestProcess &&
8318 !abilityRequest.callerToken && abilityRequest.want.GetBoolParam(IS_DELEGATOR_CALL, false)) {
8319 return true;
8320 }
8321 return false;
8322 }
8323
CheckNewRuleSwitchState(const std::string & param)8324 bool AbilityManagerService::CheckNewRuleSwitchState(const std::string ¶m)
8325 {
8326 char value[NEW_RULE_VALUE_SIZE] = "false";
8327 int retSysParam = GetParameter(param.c_str(), "false", value, NEW_RULE_VALUE_SIZE);
8328 HILOG_INFO("CheckNewRuleSwitchState, %{public}s value is %{public}s.", param.c_str(), value);
8329 if (retSysParam > 0 && !std::strcmp(value, "true")) {
8330 return true;
8331 }
8332 return false;
8333 }
8334
GetStartUpNewRuleFlag() const8335 bool AbilityManagerService::GetStartUpNewRuleFlag() const
8336 {
8337 return startUpNewRule_;
8338 }
8339
CallRequestDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callStub)8340 void AbilityManagerService::CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)
8341 {
8342 {
8343 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
8344 callStubTokenMap_[callStub] = token;
8345 }
8346 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8347 CHECK_POINTER(abilityRecord);
8348 if (!JudgeSelfCalled(abilityRecord)) {
8349 return;
8350 }
8351
8352 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8353 uiAbilityLifecycleManager_->CallRequestDone(abilityRecord, callStub);
8354 return;
8355 }
8356
8357 if (!currentMissionListManager_) {
8358 HILOG_ERROR("currentMissionListManager_ is null.");
8359 return;
8360 }
8361 currentMissionListManager_->CallRequestDone(abilityRecord, callStub);
8362 }
8363
GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> & callStub,sptr<IRemoteObject> & token)8364 void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)
8365 {
8366 std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
8367 auto it = callStubTokenMap_.find(callStub);
8368 if (it == callStubTokenMap_.end()) {
8369 token = nullptr;
8370 return;
8371 }
8372 token = callStubTokenMap_[callStub];
8373 }
8374
AddStartControlParam(Want & want,const sptr<IRemoteObject> & callerToken)8375 int AbilityManagerService::AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)
8376 {
8377 if (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
8378 AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
8379 return ERR_OK;
8380 }
8381 auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8382 CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8383 int32_t apiVersion = abilityRecord->GetApplicationInfo().apiTargetVersion;
8384 want.SetParam(DMS_API_VERSION, apiVersion);
8385 bool isCallerBackground = true;
8386 AppExecFwk::RunningProcessInfo processInfo;
8387 DelayedSingleton<AppScheduler>::GetInstance()->
8388 GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
8389 if (backgroundJudgeFlag_) {
8390 isCallerBackground = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND;
8391 } else {
8392 isCallerBackground = !processInfo.isFocused;
8393 }
8394 want.SetParam(DMS_IS_CALLER_BACKGROUND, isCallerBackground);
8395 return ERR_OK;
8396 }
8397
CheckDlpForExtension(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,EventInfo & eventInfo,const EventName & eventName)8398 int AbilityManagerService::CheckDlpForExtension(
8399 const Want &want, const sptr<IRemoteObject> &callerToken,
8400 int32_t userId, EventInfo &eventInfo, const EventName &eventName)
8401 {
8402 // check if form frs
8403 auto callingUid = IPCSkeleton::GetCallingUid();
8404 std::string bundleName = want.GetBundle();
8405 if (callingUid == FOUNDATION_UID && FRS_BUNDLE_NAME == bundleName) {
8406 return ERR_OK;
8407 }
8408
8409 if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
8410 VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
8411 !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
8412 HILOG_ERROR("%{public}s: Permission verification failed", __func__);
8413 eventInfo.errCode = CHECK_PERMISSION_FAILED;
8414 EventReport::SendExtensionEvent(eventName, HiSysEventType::FAULT, eventInfo);
8415 return CHECK_PERMISSION_FAILED;
8416 }
8417 return ERR_OK;
8418 }
8419
JudgeSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)8420 bool AbilityManagerService::JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
8421 {
8422 if (IPCSkeleton::GetCallingPid() == getpid()) {
8423 return true;
8424 }
8425
8426 auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8427 auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
8428 if (callingTokenId != tokenID) {
8429 HILOG_ERROR("Is not self, not enabled");
8430 return false;
8431 }
8432
8433 return true;
8434 }
8435
GetFocusAbility()8436 std::shared_ptr<AbilityRecord> AbilityManagerService::GetFocusAbility()
8437 {
8438 #ifdef SUPPORT_GRAPHICS
8439 sptr<IRemoteObject> token;
8440 if (!wmsHandler_) {
8441 HILOG_ERROR("wmsHandler_ is nullptr.");
8442 return nullptr;
8443 }
8444
8445 wmsHandler_->GetFocusWindow(token);
8446 if (!token) {
8447 HILOG_ERROR("token is nullptr");
8448 return nullptr;
8449 }
8450
8451 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8452 if (!abilityRecord) {
8453 HILOG_ERROR("abilityRecord is nullptr.");
8454 }
8455 return abilityRecord;
8456 #endif
8457
8458 return nullptr;
8459 }
8460
CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId,bool & isFocused)8461 int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)
8462 {
8463 sptr<IRemoteObject> token;
8464 auto ret = GetTopAbility(token);
8465 if (ret != ERR_OK) {
8466 HILOG_ERROR("GetTopAbility failed");
8467 return ret;
8468 }
8469
8470 bool focused = false;
8471 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
8472 auto connectManager = GetConnectManagerByUserId(userId);
8473 if (connectManager) {
8474 focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
8475 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
8476 } else {
8477 HILOG_WARN("connectManager is nullptr, userId: %{public}d", userId);
8478 }
8479 if (!focused && userId != U0_USER_ID) {
8480 HILOG_DEBUG("Check connectManager in user0");
8481 connectManager = GetConnectManagerByUserId(U0_USER_ID);
8482 if (connectManager) {
8483 focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
8484 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
8485 } else {
8486 HILOG_WARN("connectManager is nullptr, userId: 0");
8487 }
8488 }
8489 isFocused = focused;
8490 HILOG_DEBUG("isFocused: %{public}d", isFocused);
8491 return ERR_OK;
8492 }
8493
AddFreeInstallObserver(const sptr<AbilityRuntime::IFreeInstallObserver> & observer)8494 int AbilityManagerService::AddFreeInstallObserver(const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
8495 {
8496 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8497 if (freeInstallManager_ == nullptr) {
8498 HILOG_ERROR("freeInstallManager_ is nullptr.");
8499 return ERR_INVALID_VALUE;
8500 }
8501 return freeInstallManager_->AddFreeInstallObserver(observer);
8502 }
8503
IsValidMissionIds(const std::vector<int32_t> & missionIds,std::vector<MissionValidResult> & results)8504 int32_t AbilityManagerService::IsValidMissionIds(
8505 const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)
8506 {
8507 auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
8508 auto missionlistMgr = GetListManagerByUserId(userId);
8509 if (missionlistMgr == nullptr) {
8510 HILOG_ERROR("missionlistMgr is nullptr.");
8511 return ERR_INVALID_VALUE;
8512 }
8513
8514 return missionlistMgr->IsValidMissionIds(missionIds, results);
8515 }
8516
VerifyPermission(const std::string & permission,int pid,int uid)8517 int AbilityManagerService::VerifyPermission(const std::string &permission, int pid, int uid)
8518 {
8519 HILOG_INFO("permission=%{public}s, pid=%{public}d, uid=%{public}d",
8520 permission.c_str(),
8521 pid,
8522 uid);
8523 if (permission.empty()) {
8524 HILOG_ERROR("VerifyPermission permission invalid");
8525 return CHECK_PERMISSION_FAILED;
8526 }
8527
8528 auto bms = GetBundleManager();
8529 CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
8530
8531 std::string bundleName;
8532 if (IN_PROCESS_CALL(bms->GetNameForUid(uid, bundleName)) != ERR_OK) {
8533 HILOG_ERROR("VerifyPermission failed to get bundle name by uid");
8534 return CHECK_PERMISSION_FAILED;
8535 }
8536
8537 int account = -1;
8538 DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, account);
8539 AppExecFwk::ApplicationInfo appInfo;
8540 if (!IN_PROCESS_CALL(bms->GetApplicationInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
8541 account, appInfo))) {
8542 HILOG_ERROR("VerifyPermission failed to get application info");
8543 return CHECK_PERMISSION_FAILED;
8544 }
8545
8546 int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false);
8547 if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
8548 HILOG_ERROR("VerifyPermission %{public}d: PERMISSION_DENIED", appInfo.accessTokenId);
8549 return CHECK_PERMISSION_FAILED;
8550 }
8551
8552 return ERR_OK;
8553 }
8554
AcquireShareData(const int32_t & missionId,const sptr<IAcquireShareDataCallback> & shareData)8555 int32_t AbilityManagerService::AcquireShareData(
8556 const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)
8557 {
8558 HILOG_DEBUG("missionId is %{public}d.", missionId);
8559 CHECK_CALLER_IS_SYSTEM_APP;
8560 std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
8561 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8562 abilityRecord = uiAbilityLifecycleManager_->GetAbilityRecordsById(missionId);
8563 } else {
8564 if (!currentMissionListManager_) {
8565 HILOG_ERROR("currentMissionListManager_ is null.");
8566 return ERR_INVALID_VALUE;
8567 }
8568 std::shared_ptr<Mission> mission = currentMissionListManager_->GetMissionById(missionId);
8569 if (!mission) {
8570 HILOG_ERROR("mission is null.");
8571 return ERR_INVALID_VALUE;
8572 }
8573 abilityRecord = mission->GetAbilityRecord();
8574 }
8575 if (!abilityRecord) {
8576 HILOG_ERROR("abilityRecord is null.");
8577 return ERR_INVALID_VALUE;
8578 }
8579 uniqueId_ = (uniqueId_ == INT_MAX) ? 0 : (uniqueId_ + 1);
8580 std::pair<int64_t, const sptr<IAcquireShareDataCallback>> shareDataPair =
8581 std::make_pair(abilityRecord->GetAbilityRecordId(), shareData);
8582 iAcquireShareDataMap_.emplace(uniqueId_, shareDataPair);
8583 abilityRecord->ShareData(uniqueId_);
8584 return ERR_OK;
8585 }
8586
ShareDataDone(const sptr<IRemoteObject> & token,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)8587 int32_t AbilityManagerService::ShareDataDone(
8588 const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
8589 {
8590 HILOG_INFO("resultCode:%{public}d, uniqueId:%{public}d.", resultCode, uniqueId);
8591 if (!VerificationAllToken(token)) {
8592 return ERR_INVALID_VALUE;
8593 }
8594 auto abilityRecord = Token::GetAbilityRecordByToken(token);
8595 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record is nullptr.");
8596 if (!JudgeSelfCalled(abilityRecord)) {
8597 return CHECK_PERMISSION_FAILED;
8598 }
8599 CHECK_POINTER_AND_RETURN_LOG(eventHandler_, ERR_INVALID_VALUE, "fail to get abilityEventHandler.");
8600 eventHandler_->RemoveEvent(SHAREDATA_TIMEOUT_MSG, uniqueId);
8601 return GetShareDataPairAndReturnData(abilityRecord, resultCode, uniqueId, wantParam);
8602 }
8603
NotifySaveAsResult(const Want & want,int resultCode,int requestCode)8604 int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCode, int requestCode)
8605 {
8606 HILOG_DEBUG("requestCode is %{public}d.", requestCode);
8607
8608 //caller check
8609 if (!CheckCallerIsDlpManager(GetBundleManager())) {
8610 HILOG_WARN("caller check failed");
8611 return ERR_INVALID_CALLER;
8612 }
8613
8614 for (const auto &item : startAbilityChain_) {
8615 if (item.second->GetHandlerName() == StartAbilitySandboxSavefile::handlerName_) {
8616 auto savefileHandler = (StartAbilitySandboxSavefile*)(item.second.get());
8617 savefileHandler->HandleResult(want, resultCode, requestCode);
8618 break;
8619 }
8620 }
8621 return ERR_OK;
8622 }
8623
RecordAppExitReasonAtUpgrade(const AppExecFwk::BundleInfo & bundleInfo)8624 void AbilityManagerService::RecordAppExitReasonAtUpgrade(const AppExecFwk::BundleInfo &bundleInfo)
8625 {
8626 if (bundleInfo.abilityInfos.empty()) {
8627 HILOG_ERROR("abilityInfos is empty.");
8628 return;
8629 }
8630
8631 std::vector<std::string> abilityList;
8632 for (auto abilityInfo : bundleInfo.abilityInfos) {
8633 if (!abilityInfo.name.empty()) {
8634 abilityList.push_back(abilityInfo.name);
8635 }
8636 }
8637
8638 if (!abilityList.empty()) {
8639 DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->SetAppExitReason(
8640 bundleInfo.name, abilityList, REASON_UPGRADE);
8641 }
8642 }
8643
SetRootSceneSession(const sptr<IRemoteObject> & rootSceneSession)8644 void AbilityManagerService::SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)
8645 {
8646 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
8647 HILOG_ERROR("Not sceneboard called, not allowed.");
8648 return;
8649 }
8650 uiAbilityLifecycleManager_->SetRootSceneSession(rootSceneSession);
8651 }
8652
CallUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)8653 void AbilityManagerService::CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
8654 {
8655 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
8656 HILOG_ERROR("Not sceneboard called, not allowed.");
8657 return;
8658 }
8659 uiAbilityLifecycleManager_->CallUIAbilityBySCB(sessionInfo);
8660 }
8661
SetSessionManagerService(const sptr<IRemoteObject> & sessionManagerService)8662 int32_t AbilityManagerService::SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)
8663 {
8664 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
8665 HILOG_ERROR("Not sceneboard called, not allowed.");
8666 return ERR_WRONG_INTERFACE_CALL;
8667 }
8668
8669 HILOG_INFO("Call SetSessionManagerService of WMS.");
8670 auto ret = Rosen::MockSessionManagerService::GetInstance().SetSessionManagerService(sessionManagerService);
8671 if (ret) {
8672 HILOG_DEBUG("Call SetSessionManagerService of WMS.");
8673 return ERR_OK;
8674 }
8675 HILOG_ERROR("SMS SetSessionManagerService return false.");
8676 return ERR_OK;
8677 }
8678
CheckPrepareTerminateEnable()8679 bool AbilityManagerService::CheckPrepareTerminateEnable()
8680 {
8681 if (!isPrepareTerminateEnable_) {
8682 HILOG_DEBUG("Only support PC.");
8683 return false;
8684 }
8685 if (!AAFwk::PermissionVerification::GetInstance()->VerifyPrepareTerminatePermission()) {
8686 HILOG_DEBUG("failed, please apply permission ohos.permission.PREPARE_APP_TERMINATE");
8687 return false;
8688 }
8689 return true;
8690 }
8691
StartSpecifiedAbilityBySCB(const Want & want)8692 void AbilityManagerService::StartSpecifiedAbilityBySCB(const Want &want)
8693 {
8694 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
8695 HILOG_ERROR("Not sceneboard called, not allowed.");
8696 return;
8697 }
8698 int32_t userId = GetUserId();
8699 uiAbilityLifecycleManager_->StartSpecifiedAbilityBySCB(want, userId);
8700 }
8701
RegisterIAbilityManagerCollaborator(int32_t type,const sptr<IAbilityManagerCollaborator> & impl)8702 int32_t AbilityManagerService::RegisterIAbilityManagerCollaborator(
8703 int32_t type, const sptr<IAbilityManagerCollaborator> &impl)
8704 {
8705 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8706 auto callingUid = IPCSkeleton::GetCallingUid();
8707 if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
8708 HILOG_ERROR("The interface only support for broker");
8709 return CHECK_PERMISSION_FAILED;
8710 }
8711 if (!CheckCollaboratorType(type)) {
8712 HILOG_ERROR("collaborator register failed, invalid type.");
8713 return ERR_INVALID_VALUE;
8714 }
8715 {
8716 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
8717 collaboratorMap_[type] = impl;
8718 }
8719 return ERR_OK;
8720 }
8721
UnregisterIAbilityManagerCollaborator(int32_t type)8722 int32_t AbilityManagerService::UnregisterIAbilityManagerCollaborator(int32_t type)
8723 {
8724 auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8725 auto callingUid = IPCSkeleton::GetCallingUid();
8726 if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
8727 HILOG_ERROR("The interface only support for broker");
8728 return CHECK_PERMISSION_FAILED;
8729 }
8730 if (!CheckCollaboratorType(type)) {
8731 HILOG_ERROR("collaborator unregister failed, invalid type.");
8732 return ERR_INVALID_VALUE;
8733 }
8734 {
8735 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
8736 collaboratorMap_.erase(type);
8737 }
8738 return ERR_OK;
8739 }
8740
GetCollaborator(int32_t type)8741 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetCollaborator(int32_t type)
8742 {
8743 if (!CheckCollaboratorType(type)) {
8744 return nullptr;
8745 }
8746 {
8747 std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
8748 auto it = collaboratorMap_.find(type);
8749 if (it != collaboratorMap_.end()) {
8750 return it->second;
8751 }
8752 }
8753 return nullptr;
8754 }
8755
CheckCollaboratorType(int32_t type)8756 bool AbilityManagerService::CheckCollaboratorType(int32_t type)
8757 {
8758 if (type != CollaboratorType::RESERVE_TYPE && type != CollaboratorType::OTHERS_TYPE) {
8759 return false;
8760 }
8761 return true;
8762 }
8763
GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> & sessionInfo,std::shared_ptr<AbilityConnectManager> & connectManager,std::shared_ptr<AbilityRecord> & targetAbility)8764 void AbilityManagerService::GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo,
8765 std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility)
8766 {
8767 targetAbility = nullptr;
8768 int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
8769 HILOG_DEBUG("userId=%{public}d", userId);
8770 connectManager = GetConnectManagerByUserId(userId);
8771 if (connectManager) {
8772 targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
8773 } else {
8774 HILOG_WARN("connectManager is nullptr, userId: %{public}d", userId);
8775 }
8776 if (targetAbility == nullptr && userId != U0_USER_ID) {
8777 HILOG_DEBUG("try to find UIExtension in user0");
8778 connectManager = GetConnectManagerByUserId(U0_USER_ID);
8779 if (connectManager) {
8780 targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
8781 } else {
8782 HILOG_WARN("connectManager is nullptr, userId: 0");
8783 }
8784 }
8785 }
8786
RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)8787 int32_t AbilityManagerService::RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
8788 {
8789 if (abilityAutoStartupService_ == nullptr) {
8790 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
8791 return ERR_NO_INIT;
8792 }
8793 return abilityAutoStartupService_->RegisterAutoStartupSystemCallback(callback);
8794 }
8795
UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)8796 int32_t AbilityManagerService::UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
8797 {
8798 if (abilityAutoStartupService_ == nullptr) {
8799 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
8800 return ERR_NO_INIT;
8801 }
8802 return abilityAutoStartupService_->UnregisterAutoStartupSystemCallback(callback);
8803 }
8804
SetApplicationAutoStartup(const AutoStartupInfo & info)8805 int32_t AbilityManagerService::SetApplicationAutoStartup(const AutoStartupInfo &info)
8806 {
8807 if (abilityAutoStartupService_ == nullptr) {
8808 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
8809 return ERR_NO_INIT;
8810 }
8811 return abilityAutoStartupService_->SetApplicationAutoStartup(info);
8812 }
8813
CancelApplicationAutoStartup(const AutoStartupInfo & info)8814 int32_t AbilityManagerService::CancelApplicationAutoStartup(const AutoStartupInfo &info)
8815 {
8816 if (abilityAutoStartupService_ == nullptr) {
8817 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
8818 return ERR_NO_INIT;
8819 }
8820 return abilityAutoStartupService_->CancelApplicationAutoStartup(info);
8821 }
8822
QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> & infoList)8823 int32_t AbilityManagerService::QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)
8824 {
8825 if (abilityAutoStartupService_ == nullptr) {
8826 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
8827 return ERR_NO_INIT;
8828 }
8829 return abilityAutoStartupService_->QueryAllAutoStartupApplications(infoList);
8830 }
8831
PrepareTerminateAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isTerminate)8832 int AbilityManagerService::PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)
8833 {
8834 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8835 HILOG_DEBUG("Call.");
8836 if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
8837 HILOG_ERROR("sessionInfo is nullptr");
8838 return ERR_INVALID_VALUE;
8839 }
8840
8841 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
8842 HILOG_ERROR("Not sceneboard called, not allowed.");
8843 return ERR_WRONG_INTERFACE_CALL;
8844 }
8845
8846 if (!uiAbilityLifecycleManager_) {
8847 HILOG_ERROR("failed, uiAbilityLifecycleManager is nullptr");
8848 return ERR_INVALID_VALUE;
8849 }
8850
8851 auto abilityRecord = uiAbilityLifecycleManager_->GetUIAbilityRecordBySessionInfo(sessionInfo);
8852 isTerminate = uiAbilityLifecycleManager_->PrepareTerminateAbility(abilityRecord);
8853
8854 return ERR_OK;
8855 }
8856
RegisterSessionHandler(const sptr<IRemoteObject> & object)8857 int AbilityManagerService::RegisterSessionHandler(const sptr<IRemoteObject> &object)
8858 {
8859 HILOG_INFO("call");
8860 CHECK_POINTER_AND_RETURN(uiAbilityLifecycleManager_, ERR_NO_INIT);
8861 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
8862 HILOG_ERROR("Not sceneboard called, not allowed.");
8863 return ERR_WRONG_INTERFACE_CALL;
8864 }
8865 sptr<ISessionHandler> handler = iface_cast<ISessionHandler>(object);
8866 uiAbilityLifecycleManager_->SetSessionHandler(handler);
8867 return ERR_OK;
8868 }
8869
CheckUserIdActive(int32_t userId)8870 bool AbilityManagerService::CheckUserIdActive(int32_t userId)
8871 {
8872 std::vector<int32_t> osActiveAccountIds;
8873 auto ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
8874 QueryActiveOsAccountIds(osActiveAccountIds);
8875 if (ret != ERR_OK) {
8876 HILOG_ERROR("QueryActiveOsAccountIds failed.");
8877 return false;
8878 }
8879 if (osActiveAccountIds.empty()) {
8880 HILOG_ERROR("%{public}s, QueryActiveOsAccountIds is empty, no accounts.", __func__);
8881 return false;
8882 }
8883 auto iter = std::find(osActiveAccountIds.begin(), osActiveAccountIds.end(), userId);
8884 if (iter == osActiveAccountIds.end()) {
8885 return false;
8886 }
8887 return true;
8888 }
8889
RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)8890 int32_t AbilityManagerService::RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
8891 {
8892 HILOG_DEBUG("Called.");
8893 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
8894 HILOG_ERROR("Permission verification failed.");
8895 return CHECK_PERMISSION_FAILED;
8896 }
8897 return DelayedSingleton<AppScheduler>::GetInstance()->RegisterAppDebugListener(listener);
8898 }
8899
UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)8900 int32_t AbilityManagerService::UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
8901 {
8902 HILOG_DEBUG("Called.");
8903 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
8904 HILOG_ERROR("Permission verification failed.");
8905 return CHECK_PERMISSION_FAILED;
8906 }
8907 return DelayedSingleton<AppScheduler>::GetInstance()->UnregisterAppDebugListener(listener);
8908 }
8909
AttachAppDebug(const std::string & bundleName)8910 int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName)
8911 {
8912 HILOG_DEBUG("Called.");
8913 if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
8914 HILOG_ERROR("Developer Mode is false.");
8915 return ERR_NOT_DEVELOPER_MODE;
8916 }
8917
8918 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
8919 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
8920 HILOG_ERROR("Permission verification failed.");
8921 return CHECK_PERMISSION_FAILED;
8922 }
8923
8924 if (abilityDebugDeal_ == nullptr) {
8925 HILOG_DEBUG("Creat ability debug deal object.");
8926 abilityDebugDeal_ = std::make_shared<AbilityDebugDeal>();
8927 if (abilityDebugDeal_ != nullptr) {
8928 abilityDebugDeal_->RegisterAbilityDebugResponse();
8929 }
8930 }
8931 return DelayedSingleton<AppScheduler>::GetInstance()->AttachAppDebug(bundleName);
8932 }
8933
DetachAppDebug(const std::string & bundleName)8934 int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName)
8935 {
8936 HILOG_DEBUG("Called.");
8937 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
8938 !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
8939 HILOG_ERROR("Permission verification failed.");
8940 return CHECK_PERMISSION_FAILED;
8941 }
8942
8943 return DelayedSingleton<AppScheduler>::GetInstance()->DetachAppDebug(bundleName);
8944 }
8945
ExecuteIntent(uint64_t key,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)8946 int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken,
8947 const InsightIntentExecuteParam ¶m)
8948 {
8949 HILOG_DEBUG("Called.");
8950 auto paramPtr = std::make_shared<InsightIntentExecuteParam>(param);
8951 int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateParam(key, callerToken,
8952 paramPtr);
8953 if (ret != ERR_OK) {
8954 return ret;
8955 }
8956
8957 Want want;
8958 ret = InsightIntentExecuteManager::GenerateWant(paramPtr, want);
8959 if (ret != ERR_OK) {
8960 return ret;
8961 }
8962
8963 switch (param.executeMode_) {
8964 case AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND:
8965 HILOG_DEBUG("ExecuteMode UI_ABILITY_FOREGROUND.");
8966 ret = StartAbilityWithInsightIntent(want);
8967 break;
8968 case AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND: {
8969 HILOG_DEBUG("ExecuteMode UI_ABILITY_BACKGROUND.");
8970 ret = StartAbilityByCallWithInsightIntent(want, callerToken, param);
8971 break;
8972 }
8973 case AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY:
8974 HILOG_WARN("ExecuteMode UI_EXTENSION_ABILITY not supported.");
8975 ret = ERR_INVALID_OPERATION;
8976 break;
8977 case AppExecFwk::ExecuteMode::SERVICE_EXTENSION_ABILITY:
8978 HILOG_DEBUG("ExecuteMode SERVICE_EXTENSION_ABILITY.");
8979 ret = StartExtensionAbilityWithInsightIntent(want, AppExecFwk::ExtensionAbilityType::SERVICE);
8980 break;
8981 default:
8982 HILOG_ERROR("Invalid ExecuteMode.");
8983 ret = ERR_INVALID_OPERATION;
8984 break;
8985 }
8986 if (ret == START_ABILITY_WAITING) {
8987 HILOG_DEBUG("Top ability is foregrounding. The intent will be queued for execution");
8988 ret = ERR_OK;
8989 }
8990 if (ret != ERR_OK) {
8991 DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->RemoveExecuteIntent(paramPtr->insightIntentId_);
8992 }
8993
8994 HILOG_DEBUG("ExecuteIntent done, ret: %{public}d.", ret);
8995 return ret;
8996 }
8997
IsAbilityStarted(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord,const int32_t oriValidUserId)8998 bool AbilityManagerService::IsAbilityStarted(AbilityRequest &abilityRequest,
8999 std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)
9000 {
9001 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9002 HILOG_INFO("scene board is enable");
9003 if (uiAbilityLifecycleManager_ == nullptr) {
9004 return false;
9005 }
9006 return uiAbilityLifecycleManager_->IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId);
9007 }
9008
9009 auto missionListMgr = GetListManagerByUserId(oriValidUserId);
9010 if (missionListMgr == nullptr) {
9011 return false;
9012 }
9013 return missionListMgr->IsAbilityStarted(abilityRequest, targetRecord);
9014 }
9015
CheckDebugAppInDeveloperMode(bool isDebugApp)9016 bool AbilityManagerService::CheckDebugAppInDeveloperMode(bool isDebugApp)
9017 {
9018 if (isDebugApp && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
9019 HILOG_ERROR("Debugging application cannot run in non developer mode.");
9020 return false;
9021 }
9022 return true;
9023 }
9024
OnExecuteIntent(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord)9025 int32_t AbilityManagerService::OnExecuteIntent(AbilityRequest &abilityRequest,
9026 std::shared_ptr<AbilityRecord> &targetRecord)
9027 {
9028 HILOG_INFO("OnExecuteIntent");
9029 if (targetRecord == nullptr || targetRecord->GetScheduler() == nullptr) {
9030 return ERR_INVALID_VALUE;
9031 }
9032 targetRecord->GetScheduler()->OnExecuteIntent(abilityRequest.want);
9033
9034 return ERR_OK;
9035 }
9036
StartAbilityWithInsightIntent(const Want & want,int32_t userId,int requestCode)9037 int32_t AbilityManagerService::StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)
9038 {
9039 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9040 bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
9041 if (startWithAccount || IsCrossUserCall(userId)) {
9042 (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
9043 CHECK_CALLER_IS_SYSTEM_APP;
9044 }
9045 EventInfo eventInfo = BuildEventInfo(want, userId);
9046 EventReport::SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
9047 int32_t ret = StartAbilityWrap(want, nullptr, requestCode, userId);
9048 if (ret != ERR_OK) {
9049 eventInfo.errCode = ret;
9050 EventReport::SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
9051 }
9052 return ret;
9053 }
9054
StartExtensionAbilityWithInsightIntent(const Want & want,AppExecFwk::ExtensionAbilityType extensionType)9055 int32_t AbilityManagerService::StartExtensionAbilityWithInsightIntent(const Want &want,
9056 AppExecFwk::ExtensionAbilityType extensionType)
9057 {
9058 HILOG_DEBUG("called.");
9059 return StartExtensionAbilityInner(want, nullptr, DEFAULT_INVAL_VALUE, extensionType, true);
9060 }
9061
StartAbilityByCallWithInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)9062 int32_t AbilityManagerService::StartAbilityByCallWithInsightIntent(const Want &want,
9063 const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam ¶m)
9064 {
9065 HILOG_INFO("call StartAbilityByCallWithInsightIntent.");
9066 sptr<IAbilityConnection> connect = sptr<AbilityBackgroundConnection>::MakeSptr();
9067 if (connect == nullptr) {
9068 HILOG_ERROR("Invalid connect.");
9069 return ERR_INVALID_VALUE;
9070 }
9071
9072 AbilityRequest abilityRequest;
9073 abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
9074 abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
9075 abilityRequest.callerToken = callerToken;
9076 abilityRequest.startSetting = nullptr;
9077 abilityRequest.want = want;
9078 abilityRequest.connect = connect;
9079 int32_t result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
9080 if (result != ERR_OK) {
9081 HILOG_ERROR("Generate ability request error.");
9082 return result;
9083 }
9084 std::shared_ptr<AbilityRecord> targetRecord;
9085 int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
9086 auto missionListMgr = GetListManagerByUserId(oriValidUserId);
9087 if (IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId)) {
9088 HILOG_INFO("ability has already started");
9089 result = OnExecuteIntent(abilityRequest, targetRecord);
9090 } else {
9091 result = StartAbilityByCall(want, connect, callerToken);
9092 }
9093
9094 HILOG_INFO("StartAbilityByCallWithInsightIntent %{public}d", result);
9095 return result;
9096 }
9097
IsAbilityControllerStart(const Want & want)9098 bool AbilityManagerService::IsAbilityControllerStart(const Want &want)
9099 {
9100 auto callingUid = IPCSkeleton::GetCallingUid();
9101 bool isBrokerCall = (callingUid == BROKER_UID || callingUid == BROKER_RESERVE_UID);
9102 if (isBrokerCall) {
9103 return IsAbilityControllerStart(want, want.GetBundle());
9104 }
9105 HILOG_ERROR("The interface only support for broker");
9106 return true;
9107 }
9108
ExecuteInsightIntentDone(const sptr<IRemoteObject> & token,uint64_t intentId,const InsightIntentExecuteResult & result)9109 int32_t AbilityManagerService::ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId,
9110 const InsightIntentExecuteResult &result)
9111 {
9112 HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9113 auto abilityRecord = Token::GetAbilityRecordByToken(token);
9114 CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
9115 if (!JudgeSelfCalled(abilityRecord)) {
9116 return CHECK_PERMISSION_FAILED;
9117 }
9118
9119 // check send by same bundleName.
9120 std::string bundleNameStored = "";
9121 auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetBundleName(intentId, bundleNameStored);
9122 if (ret != ERR_OK) {
9123 HILOG_ERROR("Get matched bundleName failed, intentId: %{public}" PRIu64"", intentId);
9124 return ERR_INVALID_VALUE;
9125 }
9126
9127 std::string bundleName = abilityRecord->GetAbilityInfo().bundleName;
9128 if (bundleNameStored != bundleName) {
9129 HILOG_ERROR("BundleName %{public}s and %{public}s mismatch.", bundleName.c_str(), bundleNameStored.c_str());
9130 return ERR_INVALID_VALUE;
9131 }
9132
9133 return DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
9134 intentId, result.innerErr, result);
9135 }
9136
SetApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)9137 int32_t AbilityManagerService::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
9138 {
9139 if (abilityAutoStartupService_ == nullptr) {
9140 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
9141 return ERR_NO_INIT;
9142 }
9143 return abilityAutoStartupService_->SetApplicationAutoStartupByEDM(info, flag);
9144 }
9145
CancelApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)9146 int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
9147 {
9148 if (abilityAutoStartupService_ == nullptr) {
9149 HILOG_ERROR("abilityAutoStartupService_ is nullptr.");
9150 return ERR_NO_INIT;
9151 }
9152 return abilityAutoStartupService_->CancelApplicationAutoStartupByEDM(info, flag);
9153 }
9154
GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> & list)9155 int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)
9156 {
9157 HILOG_DEBUG("Called.");
9158 CHECK_CALLER_IS_SYSTEM_APP;
9159 auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
9160 if (!isPerm) {
9161 HILOG_ERROR("Permission verification failed.");
9162 return CHECK_PERMISSION_FAILED;
9163 }
9164
9165 std::vector<AbilityRunningInfo> abilityRunningInfos;
9166 if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9167 uiAbilityLifecycleManager_->GetAbilityRunningInfos(abilityRunningInfos, isPerm, GetUserId());
9168 } else {
9169 if (currentMissionListManager_ == nullptr) {
9170 HILOG_ERROR("Current mission list manager is nullptr.");
9171 return ERR_NULL_OBJECT;
9172 }
9173 currentMissionListManager_->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
9174 }
9175
9176 for (auto &info : abilityRunningInfos) {
9177 if (info.abilityState != AbilityState::FOREGROUND) {
9178 continue;
9179 }
9180
9181 AppExecFwk::AbilityStateData abilityData;
9182 abilityData.bundleName = info.ability.GetBundleName();
9183 abilityData.moduleName = info.ability.GetModuleName();
9184 abilityData.abilityName = info.ability.GetAbilityName();
9185 abilityData.abilityState = info.abilityState;
9186 abilityData.pid = info.pid;
9187 abilityData.uid = info.uid;
9188 abilityData.abilityType = static_cast<int32_t>(AppExecFwk::AbilityType::PAGE);
9189 list.push_back(abilityData);
9190 }
9191 HILOG_DEBUG("Get foreground ui abilities end, list.size = %{public}zu.", list.size());
9192 return ERR_OK;
9193 }
9194
HandleProcessFrozen(const std::vector<int32_t> & pidList,int32_t uid)9195 void AbilityManagerService::HandleProcessFrozen(const std::vector<int32_t> &pidList, int32_t uid)
9196 {
9197 auto userId = uid / BASE_USER_RANGE;
9198 auto connectManager = GetConnectManagerByUserId(userId);
9199 if (connectManager == nullptr) {
9200 HILOG_ERROR("can not find user connect manager");
9201 return;
9202 }
9203 connectManager->HandleProcessFrozen(pidList, uid);
9204 }
9205
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)9206 void AbilityManagerService::NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)
9207 {
9208 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9209 if (collaborator == nullptr) {
9210 HILOG_ERROR("collaborator GetCollaborator is nullptr.");
9211 return;
9212 }
9213 collaborator->UpdateConfiguration(config, userId);
9214 }
9215
OpenFile(const Uri & uri,uint32_t flag)9216 int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag)
9217 {
9218 auto accessTokenId = IPCSkeleton::GetCallingTokenID();
9219 if (!AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission(uri, flag, accessTokenId)) {
9220 HILOG_ERROR("premission check failed");
9221 return -1;
9222 }
9223 auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9224 if (collaborator == nullptr) {
9225 HILOG_ERROR("collaborator GetCollaborator is nullptr.");
9226 return ERR_COLLABORATOR_NOT_REGISTER;
9227 }
9228 return collaborator->OpenFile(uri, flag);
9229 }
9230
GetDialogSessionInfo(const std::string dialogSessionId,sptr<DialogSessionInfo> & dialogSessionInfo)9231 int AbilityManagerService::GetDialogSessionInfo(const std::string dialogSessionId,
9232 sptr<DialogSessionInfo> &dialogSessionInfo)
9233 {
9234 CHECK_CALLER_IS_SYSTEM_APP;
9235 CHECK_POINTER_AND_RETURN(dialogSessionRecord_, ERR_INVALID_VALUE);
9236 dialogSessionInfo = dialogSessionRecord_->GetDialogSessionInfo(dialogSessionId);
9237 if (dialogSessionInfo) {
9238 HILOG_DEBUG("success");
9239 return ERR_OK;
9240 }
9241 HILOG_DEBUG("fail");
9242 return INNER_ERR;
9243 }
9244
GenerateDialogSessionRecord(AbilityRequest & abilityRequest,int32_t userId,std::string & dialogSessionId,std::vector<DialogAppInfo> & dialogAppInfos,bool isSelector)9245 bool AbilityManagerService::GenerateDialogSessionRecord(AbilityRequest &abilityRequest, int32_t userId,
9246 std::string &dialogSessionId, std::vector<DialogAppInfo> &dialogAppInfos, bool isSelector)
9247 {
9248 CHECK_POINTER_AND_RETURN(dialogSessionRecord_, ERR_INVALID_VALUE);
9249 if (!isSelector && dialogAppInfos.size() == 1) {
9250 dialogAppInfos.front().bundleName = abilityRequest.abilityInfo.bundleName;
9251 dialogAppInfos.front().moduleName = abilityRequest.abilityInfo.moduleName;
9252 dialogAppInfos.front().abilityName = abilityRequest.abilityInfo.name;
9253 dialogAppInfos.front().iconId = abilityRequest.abilityInfo.iconId;
9254 dialogAppInfos.front().labelId = abilityRequest.abilityInfo.labelId;
9255 }
9256 return dialogSessionRecord_->GenerateDialogSessionRecord(abilityRequest, userId,
9257 dialogSessionId, dialogAppInfos, isSelector);
9258 }
9259
CreateModalDialog(const Want & replaceWant,sptr<IRemoteObject> callerToken,std::string dialogSessionId)9260 int AbilityManagerService::CreateModalDialog(const Want &replaceWant, sptr<IRemoteObject> callerToken,
9261 std::string dialogSessionId)
9262 {
9263 (const_cast<Want &>(replaceWant)).SetParam("dialogSessionId", dialogSessionId);
9264 auto connection = std::make_shared<OHOS::Rosen::ModalSystemUiExtension>();
9265 if (callerToken == nullptr) {
9266 HILOG_DEBUG("create modal ui extension for system");
9267 return connection->CreateModalUIExtension(replaceWant) ? ERR_OK : INNER_ERR;
9268 }
9269 auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
9270 if (!callerRecord) {
9271 HILOG_ERROR("callerRecord is nullptr.");
9272 return ERR_INVALID_VALUE;
9273 }
9274
9275 sptr<IRemoteObject> token;
9276 int ret = IN_PROCESS_CALL(GetTopAbility(token));
9277 if (ret != ERR_OK || token == nullptr) {
9278 HILOG_ERROR("token is nullptr");
9279 return ERR_INVALID_VALUE;
9280 }
9281
9282 if (callerRecord->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE && token == callerToken) {
9283 HILOG_DEBUG("create modal ui extension for application");
9284 return callerRecord->CreateModalUIExtension(replaceWant);
9285 }
9286 HILOG_DEBUG("create modal ui extension for system");
9287 return connection->CreateModalUIExtension(replaceWant) ? ERR_OK : INNER_ERR;
9288 }
9289
SendDialogResult(const Want & want,const std::string dialogSessionId,bool isAllowed)9290 int AbilityManagerService::SendDialogResult(const Want &want, const std::string dialogSessionId, bool isAllowed)
9291 {
9292 CHECK_CALLER_IS_SYSTEM_APP;
9293 CHECK_POINTER_AND_RETURN(dialogSessionRecord_, ERR_INVALID_VALUE);
9294 if (!isAllowed) {
9295 HILOG_INFO("user refuse to jump");
9296 dialogSessionRecord_->ClearDialogContext(dialogSessionId);
9297 return ERR_OK;
9298 }
9299 std::shared_ptr<DialogCallerInfo> dialogCallerInfo = dialogSessionRecord_->GetDialogCallerInfo(dialogSessionId);
9300 if (dialogCallerInfo == nullptr) {
9301 HILOG_ERROR("dialog caller info is nullptr");
9302 dialogSessionRecord_->ClearDialogContext(dialogSessionId);
9303 return ERR_INVALID_VALUE;
9304 }
9305 auto targetWant = dialogCallerInfo->targetWant;
9306 targetWant.SetElement(want.GetElement());
9307 targetWant.SetParam("isSelector", dialogCallerInfo->isSelector);
9308 targetWant.SetParam("dialogSessionId", dialogSessionId);
9309 sptr<IRemoteObject> callerToken = dialogCallerInfo->callerToken;
9310 return StartAbilityAsCaller(targetWant, callerToken, nullptr, dialogCallerInfo->userId,
9311 dialogCallerInfo->requestCode, true);
9312 }
9313
RemoveLauncherDeathRecipient(int32_t userId)9314 void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId)
9315 {
9316 auto connectManager = GetConnectManagerByUserId(userId);
9317 if (connectManager == nullptr) {
9318 HILOG_ERROR("connectManager is nullptr. userId=%{public}d", userId);
9319 return;
9320 }
9321 connectManager->RemoveLauncherDeathRecipient();
9322 }
9323
GenerateEmbeddableUIAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)9324 int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest(
9325 const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
9326 {
9327 int32_t screenMode = want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
9328 int32_t result = ERR_OK;
9329 if (screenMode == AAFwk::HALF_SCREEN_MODE) {
9330 result = GenerateAbilityRequest(want, -1, request, callerToken, userId);
9331 request.abilityInfo.isModuleJson = true;
9332 request.abilityInfo.isStageBasedModel = true;
9333 request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
9334 request.abilityInfo.extensionAbilityType = AppExecFwk::ExtensionAbilityType::UI;
9335 struct timespec time = {0, 0};
9336 clock_gettime(CLOCK_MONOTONIC, &time);
9337 int64_t times = static_cast<int64_t>(time.tv_sec);
9338 request.abilityInfo.process = request.abilityInfo.bundleName + PROCESS_SUFFIX + std::to_string(times);
9339 } else {
9340 result = GenerateExtensionAbilityRequest(want, request, callerToken, userId);
9341 }
9342 return result;
9343 }
9344
UpdateSessionInfoBySCB(const std::vector<SessionInfo> & sessionInfos,int32_t userId)9345 void AbilityManagerService::UpdateSessionInfoBySCB(const std::vector<SessionInfo> &sessionInfos, int32_t userId)
9346 {
9347 if (!CheckCallingTokenId(BUNDLE_NAME_SCENEBOARD)) {
9348 HILOG_ERROR("Not sceneboard called, not allowed.");
9349 return;
9350 }
9351 HILOG_INFO("The sceneboard is being restored.");
9352 uiAbilityLifecycleManager_->UpdateSessionInfoBySCB(sessionInfos, userId);
9353 }
9354
CheckSenderWantInfo(int32_t callerUid,const WantSenderInfo & wantSenderInfo)9355 bool AbilityManagerService::CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)
9356 {
9357 if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9358 auto bms = GetBundleManager();
9359 CHECK_POINTER_AND_RETURN(bms, false);
9360
9361 std::string bundleName;
9362 if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
9363 HILOG_ERROR("Get Bundle Name failed.");
9364 return false;
9365 }
9366 if (wantSenderInfo.bundleName != bundleName) {
9367 HILOG_ERROR("wantSender bundleName check failed");
9368 return false;
9369 }
9370 }
9371 return true;
9372 }
9373
CheckCallerIsDmsProcess()9374 bool AbilityManagerService::CheckCallerIsDmsProcess()
9375 {
9376 Security::AccessToken::NativeTokenInfo nativeTokenInfo;
9377 uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
9378 auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
9379 int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
9380 if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
9381 result != ERR_OK || nativeTokenInfo.processName != DMS_PROCESS_NAME) {
9382 HILOG_ERROR("caller is not dms");
9383 return false;
9384 }
9385 return true;
9386 }
9387
WaitBootAnimationStart()9388 void AbilityManagerService::WaitBootAnimationStart()
9389 {
9390 char value[BOOTEVENT_BOOT_ANIMATION_READY_SIZE] = "";
9391 int32_t ret = GetParameter(BOOTEVENT_BOOT_ANIMATION_READY.c_str(), "", value,
9392 BOOTEVENT_BOOT_ANIMATION_READY_SIZE);
9393 if (ret > 0 && !std::strcmp(value, "false")) {
9394 // Get new param success and new param is not ready, wait the new param.
9395 WaitParameter(BOOTEVENT_BOOT_ANIMATION_READY.c_str(), "true",
9396 AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
9397 } else if (ret <= 0 || !std::strcmp(value, "")) {
9398 // Get new param failed or new param is not set, wait the old param.
9399 WaitParameter(BOOTEVENT_BOOT_ANIMATION_STARTED.c_str(), "true",
9400 AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
9401 }
9402 // other, the animation is ready, not wait.
9403 }
9404 } // namespace AAFwk
9405 } // namespace OHOS
9406