• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2023-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "ability_manager_service.h"
17 
18 #include "ability_background_connection.h"
19 #include "ability_connect_manager.h"
20 #include "ability_manager_radar.h"
21 #include "ability_resident_process_rdb.h"
22 #include "accesstoken_kit.h"
23 #include "ability_manager_xcollie.h"
24 #ifdef APP_DOMAIN_VERIFY_ENABLED
25 #include "ag_convert_callback_impl.h"
26 #include "app_domain_verify_mgr_client.h"
27 #endif
28 #include "app_utils.h"
29 #include "app_exit_reason_data_manager.h"
30 #include "application_util.h"
31 #include "assert_fault_callback_death_mgr.h"
32 #include "concurrent_task_client.h"
33 #include "connection_state_manager.h"
34 #include "display_manager.h"
35 #include "distributed_client.h"
36 #ifdef WITH_DLP
37 #include "dlp_utils.h"
38 #endif // WITH_DLP
39 #include "freeze_util.h"
40 #include "global_constant.h"
41 #include "hitrace_meter.h"
42 #include "insight_intent_execute_manager.h"
43 #include "interceptor/ability_jump_interceptor.h"
44 #include "interceptor/control_interceptor.h"
45 #include "interceptor/crowd_test_interceptor.h"
46 #include "interceptor/disposed_rule_interceptor.h"
47 #include "interceptor/ecological_rule_interceptor.h"
48 #include "interceptor/extension_control_interceptor.h"
49 #include "interceptor/screen_unlock_interceptor.h"
50 #include "interceptor/start_other_app_interceptor.h"
51 #include "ipc_skeleton.h"
52 #include "iservice_registry.h"
53 #include "mock_session_manager_service.h"
54 #include "modal_system_ui_extension.h"
55 #include "os_account_manager_wrapper.h"
56 #include "permission_constants.h"
57 #include "process_options.h"
58 #include "recovery_param.h"
59 #include "res_sched_util.h"
60 #include "restart_app_manager.h"
61 #include "scene_board_judgement.h"
62 #include "server_constant.h"
63 #include "softbus_bus_center.h"
64 #include "start_ability_handler/start_ability_sandbox_savefile.h"
65 #include "start_ability_utils.h"
66 #include "startup_util.h"
67 #include "status_bar_delegate_interface.h"
68 #include "string_wrapper.h"
69 #include "ui_extension_utils.h"
70 #include "unlock_screen_manager.h"
71 #include "uri_permission_manager_client.h"
72 #include "uri_utils.h"
73 #include "view_data.h"
74 #include "xcollie/watchdog.h"
75 #include "config_policy_utils.h"
76 #include "utils/ability_permission_util.h"
77 #include "utils/app_mgr_util.h"
78 #include "utils/dump_utils.h"
79 #include "utils/extension_permissions_util.h"
80 #include "utils/window_options_utils.h"
81 #ifdef SUPPORT_GRAPHICS
82 #include "dialog_session_manager.h"
83 #include "application_anr_listener.h"
84 #include "input_manager.h"
85 #include "ability_first_frame_state_observer_manager.h"
86 #include "session_manager_lite.h"
87 #include "window_focus_changed_listener.h"
88 #endif
89 
90 using OHOS::AppExecFwk::ElementName;
91 using OHOS::Security::AccessToken::AccessTokenKit;
92 
93 namespace OHOS {
94 using AbilityRuntime::FreezeUtil;
95 namespace AAFwk {
96 using AutoStartupInfo = AbilityRuntime::AutoStartupInfo;
97 using GetExtensionAbilityInfoFlag = AppExecFwk::GetExtensionAbilityInfoFlag;
98 namespace {
99 #define CHECK_CALLER_IS_SYSTEM_APP                                                             \
100     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
101         TAG_LOGE(AAFwkTag::ABILITYMGR,                                                         \
102         "The caller is not system-app, can not use system-api");                               \
103         return ERR_NOT_SYSTEM_APP;                                                             \
104     }
105 
106 constexpr const char* ARGS_USER_ID = "-u";
107 constexpr const char* ARGS_CLIENT = "-c";
108 constexpr const char* ILLEGAL_INFOMATION = "The arguments are illegal and you can enter '-h' for help.";
109 
110 
111 constexpr int32_t NEW_RULE_VALUE_SIZE = 6;
112 constexpr int32_t APP_ALIVE_TIME_MS = 1000;  // Allow background startup within 1 second after application startup
113 constexpr int32_t REGISTER_FOCUS_DELAY = 5000;
114 constexpr size_t OFFSET = 32;
115 constexpr const char* IS_DELEGATOR_CALL = "isDelegatorCall";
116 
117 // Startup rule switch
118 constexpr const char* COMPONENT_STARTUP_NEW_RULES = "component.startup.newRules";
119 constexpr const char* NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI = "component.startup.newRules.except.LauncherSystemUI";
120 constexpr const char* BACKGROUND_JUDGE_FLAG = "component.startup.backgroundJudge.flag";
121 constexpr const char* WHITE_LIST_ASS_WAKEUP_FLAG = "component.startup.whitelist.associatedWakeUp";
122 
123 // White list app
124 constexpr const char* BUNDLE_NAME_SETTINGSDATA = "com.ohos.settingsdata";
125 // Support prepare terminate
126 constexpr int32_t PREPARE_TERMINATE_ENABLE_SIZE = 6;
127 constexpr const char* PREPARE_TERMINATE_ENABLE_PARAMETER = "persist.sys.prepare_terminate";
128 // UIExtension type
129 constexpr const char* UIEXTENSION_TYPE_KEY = "ability.want.params.uiExtensionType";
130 constexpr const char* UIEXTENSION_TARGET_TYPE_KEY = "ability.want.params.uiExtensionTargetType";
131 constexpr const char* SYSTEM_SHARE = "share";
132 constexpr const char* SYSTEM_SHARE_TYPE = "sysPicker/share";
133 // Share picker params
134 constexpr char SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY[] = "const.system.sharePicker.bundleName";
135 constexpr char SHARE_PICKER_DIALOG_ABILITY_NAME_KEY[] = "const.system.sharePicker.abilityName";
136 constexpr char SHARE_PICKER_UIEXTENSION_NAME_KEY[] = "const.system.sharePicker.UIExtensionAbilityName";
137 constexpr char SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME[] = "com.ohos.sharepickerdialog";
138 constexpr char SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME[] = "PickerDialog";
139 constexpr char TOKEN_KEY[] = "ohos.ability.params.token";
140 // Developer mode param
141 constexpr char DEVELOPER_MODE_STATE[] = "const.security.developermode.state";
142 constexpr char PRODUCT_APPBOOT_SETTING_ENABLED[] = "const.product.appboot.setting.enabled";
143 // Broker params key
144 constexpr const char* KEY_VISIBLE_ID = "ohos.anco.param.visible";
145 constexpr const char* START_ABILITY_TYPE = "ABILITY_INNER_START_WITH_ACCOUNT";
146 constexpr const char* SHELL_ASSISTANT_BUNDLENAME = "com.huawei.shell_assistant";
147 constexpr const char* SHELL_ASSISTANT_ABILITYNAME = "MainAbility";
148 constexpr const char* BUNDLE_NAME_DIALOG = "com.ohos.amsdialog";
149 constexpr const char* STR_PHONE = "phone";
150 constexpr const char* PARAM_RESV_ANCO_CALLER_UID = "ohos.anco.param.callerUid";
151 constexpr const char* PARAM_RESV_ANCO_CALLER_BUNDLENAME = "ohos.anco.param.callerBundleName";
152 // Distributed continued session Id
153 constexpr const char* DMS_CONTINUED_SESSION_ID = "ohos.dms.continueSessionId";
154 constexpr const char* DMS_PERSISTENT_ID = "ohos.dms.persistentId";
155 constexpr const char* DMS_CALLER_BUNDLE_NAME = "ohos.dms.param.sourceCallerBundleName";
156 constexpr const char* DMS_CALLER_ABILITY_NAME = "ohos.dms.param.sourceCallerAbilityName";
157 constexpr const char* DMS_CALLER_NATIVE_NAME = "ohos.dms.param.sourceCallerNativeName";
158 constexpr const char* DMS_CALLER_APP_ID = "ohos.dms.param.sourceCallerAppId";
159 constexpr const char* DMS_CALLER_APP_IDENTIFIER = "ohos.dms.param.sourceCallerAppIdentifier";
160 
161 constexpr const char* DEBUG_APP = "debugApp";
162 constexpr const char* NATIVE_DEBUG = "nativeDebug";
163 constexpr const char* AUTO_FILL_PASSWORD_TPYE = "autoFill/password";
164 constexpr const char* AUTO_FILL_SMART_TPYE = "autoFill/smart";
165 constexpr size_t INDEX_ZERO = 0;
166 constexpr size_t INDEX_ONE = 1;
167 constexpr size_t INDEX_TWO = 2;
168 constexpr size_t ARGC_THREE = 3;
169 constexpr static char WANT_PARAMS_VIEW_DATA_KEY[] = "ohos.ability.params.viewData";
170 constexpr const char* WANT_PARAMS_APP_RESTART_FLAG = "ohos.aafwk.app.restart";
171 
172 constexpr int32_t FOUNDATION_UID = 5523;
173 constexpr const char* FRS_BUNDLE_NAME = "com.ohos.formrenderservice";
174 constexpr const char* FOUNDATION_PROCESS_NAME = "foundation";
175 constexpr const char* RSS_PROCESS_NAME = "resource_schedule_service";
176 constexpr const char* IS_PRELOAD_UIEXTENSION_ABILITY = "ability.want.params.is_preload_uiextension_ability";
177 constexpr const char* UIEXTENSION_MODAL_TYPE = "ability.want.params.modalType";
178 constexpr const char* SUPPORT_CLOSE_ON_BLUR = "supportCloseOnBlur";
179 constexpr const char* ATOMIC_SERVICE_PREFIX = "com.atomicservice.";
180 constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohosSpecifiedProcessFlag";
181 constexpr const char* VERIFY_DOMINATE_SCREEN = "persist.sys.abilityms.verify_start_ability_without_caller_token";
182 constexpr const char* CALLER_REQUEST_CODE = "ohos.extra.param.key.callerRequestCode";
183 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
184 constexpr const char* IS_SHELL_CALL = "isShellCall";
185 
186 constexpr char ASSERT_FAULT_DETAIL[] = "assertFaultDialogDetail";
187 constexpr char PRODUCT_ASSERT_FAULT_DIALOG_ENABLED[] = "persisit.sys.abilityms.support_assert_fault_dialog";
188 
189 constexpr int32_t RESOURCE_SCHEDULE_UID = 1096;
190 constexpr int32_t UPDATE_CONFIG_FLAG_COVER = 1;
191 constexpr int32_t UPDATE_CONFIG_FLAG_APPEND = 2;
192 
193 const std::unordered_set<std::string> COMMON_PICKER_TYPE = {
194     "share", "action"
195 };
196 std::atomic<bool> g_isDmsAlive = false;
197 
SendAbilityEvent(const EventName & eventName,HiSysEventType type,const EventInfo & eventInfo)198 void SendAbilityEvent(const EventName &eventName, HiSysEventType type, const EventInfo &eventInfo)
199 {
200     auto taskHandler = DelayedSingleton<AbilityManagerService>::GetInstance()->GetTaskHandler();
201     if (taskHandler == nullptr) {
202         TAG_LOGI(AAFwkTag::ABILITYMGR, "task handler null.");
203         return;
204     }
205     taskHandler->SubmitTask([eventName, type, eventInfo]() {
206         EventReport::SendAbilityEvent(eventName, type, eventInfo);
207         });
208 }
209 } // namespace
210 
211 using namespace std::chrono;
212 using namespace std::chrono_literals;
213 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
214 using namespace BackgroundTaskMgr;
215 #endif
216 const bool CONCURRENCY_MODE_FALSE = false;
217 constexpr int32_t MAIN_USER_ID = 100;
218 constexpr auto DATA_ABILITY_START_TIMEOUT = 5s;
219 constexpr int32_t NON_ANONYMIZE_LENGTH = 6;
220 constexpr uint32_t SCENE_FLAG_NORMAL = 0;
221 constexpr int32_t MAX_NUMBER_OF_DISTRIBUTED_MISSIONS = 20;
222 constexpr int32_t SWITCH_ACCOUNT_TRY = 3;
223 constexpr int32_t CONVERT_CALLBACK_TIMEOUT_SECONDS = 2; // 2s
224 constexpr const char* EMPTY_DEVICE_ID = "";
225 constexpr int32_t APP_MEMORY_SIZE = 512;
226 constexpr int32_t GET_PARAMETER_INCORRECT = -9;
227 constexpr int32_t GET_PARAMETER_OTHER = -1;
228 constexpr int32_t SIZE_10 = 10;
229 constexpr int32_t HIDUMPER_SERVICE_UID = 1212;
230 constexpr int32_t ACCOUNT_MGR_SERVICE_UID = 3058;
231 constexpr int32_t BROKER_UID = 5557;
232 constexpr int32_t BROKER_RESERVE_UID = 5005;
233 constexpr int32_t DMS_UID = 5522;
234 constexpr int32_t PREPARE_TERMINATE_TIMEOUT_MULTIPLE = 10;
235 constexpr int32_t BOOTEVENT_COMPLETED_DELAY_TIME = 1000;
236 constexpr int32_t BOOTEVENT_BOOT_ANIMATION_READY_SIZE = 6;
237 constexpr const char* BUNDLE_NAME_KEY = "bundleName";
238 constexpr const char* DM_PKG_NAME = "ohos.distributedhardware.devicemanager";
239 constexpr const char* ACTION_CHOOSE = "ohos.want.action.select";
240 constexpr const char* HIGHEST_PRIORITY_ABILITY_ENTITY = "flag.home.intent.from.system";
241 constexpr const char* DMS_API_VERSION = "dmsApiVersion";
242 constexpr const char* DMS_IS_CALLER_BACKGROUND = "dmsIsCallerBackGround";
243 constexpr const char* DMS_PROCESS_NAME = "distributedsched";
244 constexpr const char* DMS_MISSION_ID = "dmsMissionId";
245 constexpr const char* BOOTEVENT_APPFWK_READY = "bootevent.appfwk.ready";
246 constexpr const char* BOOTEVENT_BOOT_COMPLETED = "bootevent.boot.completed";
247 constexpr const char* BOOTEVENT_BOOT_ANIMATION_STARTED = "bootevent.bootanimation.started";
248 constexpr const char* BOOTEVENT_BOOT_ANIMATION_READY = "bootevent.bootanimation.ready";
249 constexpr const char* NEED_STARTINGWINDOW = "ohos.ability.NeedStartingWindow";
250 constexpr const char* PERMISSIONMGR_BUNDLE_NAME = "com.ohos.permissionmanager";
251 constexpr const char* PERMISSIONMGR_ABILITY_NAME = "com.ohos.permissionmanager.GrantAbility";
252 constexpr const char* IS_CALL_BY_SCB = "isCallBySCB";
253 constexpr const char* SPECIFY_TOKEN_ID = "specifyTokenId";
254 constexpr const char* PROCESS_SUFFIX = "embeddable";
255 constexpr int32_t DEFAULT_DMS_MISSION_ID = -1;
256 constexpr const char* PARAM_PREVENT_STARTABILITY = "persist.sys.abilityms.prevent_startability";
257 constexpr const char* SUSPEND_SERVICE_CONFIG_FILE = "/etc/efficiency_manager/prevent_startability_whitelist.json";
258 constexpr int32_t MAX_BUFFER = 2048;
259 constexpr int32_t API12 = 12;
260 constexpr int32_t API_VERSION_MOD = 100;
261 constexpr const char* WHITE_LIST = "white_list";
262 
263 const bool REGISTER_RESULT =
264     SystemAbility::MakeAndRegisterAbility(DelayedSingleton<AbilityManagerService>::GetInstance().get());
265 sptr<AbilityManagerService> AbilityManagerService::instance_;
266 
AbilityManagerService()267 AbilityManagerService::AbilityManagerService()
268     : SystemAbility(ABILITY_MGR_SERVICE_ID, true),
269       state_(ServiceRunningState::STATE_NOT_START),
270       bundleMgrHelper_(nullptr)
271 {}
272 
~AbilityManagerService()273 AbilityManagerService::~AbilityManagerService()
274 {}
275 
GetPubInstance()276 std::shared_ptr<AbilityManagerService> AbilityManagerService::GetPubInstance()
277 {
278     return DelayedSingleton<AbilityManagerService>::GetInstance();
279 }
280 
OnStart()281 void AbilityManagerService::OnStart()
282 {
283     if (state_ == ServiceRunningState::STATE_RUNNING) {
284         TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service has already started.");
285         return;
286     }
287     TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service starting.");
288     if (!Init()) {
289         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to init ability manager service.");
290         return;
291     }
292     state_ = ServiceRunningState::STATE_RUNNING;
293     /* Publish service maybe failed, so we need call this function at the last,
294      * so it can't affect the TDD test program */
295     instance_ = DelayedSingleton<AbilityManagerService>::GetInstance().get();
296     if (instance_ == nullptr) {
297         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability manager service enter OnStart, but instance_ is nullptr!");
298         return;
299     }
300     bool ret = Publish(instance_);
301     if (!ret) {
302         TAG_LOGE(AAFwkTag::ABILITYMGR, "Publish ability manager service failed!");
303         return;
304     }
305 
306     SetParameter(BOOTEVENT_APPFWK_READY, "true");
307     AddSystemAbilityListener(BACKGROUND_TASK_MANAGER_SERVICE_ID);
308     AddSystemAbilityListener(DISTRIBUTED_SCHED_SA_ID);
309     AddSystemAbilityListener(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
310 #ifdef SUPPORT_SCREEN
311     AddSystemAbilityListener(MULTIMODAL_INPUT_SERVICE_ID);
312 #endif
313     TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service start success.");
314     auto pid = getpid();
315     std::unordered_map<std::string, std::string> payload;
316     payload["pid"] = std::to_string(pid);
317     OHOS::ConcurrentTask::ConcurrentTaskClient::GetInstance().RequestAuth(payload);
318 }
319 
Init()320 bool AbilityManagerService::Init()
321 {
322     HiviewDFX::Watchdog::GetInstance().InitFfrtWatchdog(); // For ffrt watchdog available in foundation
323     taskHandler_ = TaskHandlerWrap::CreateQueueHandler(AbilityConfig::NAME_ABILITY_MGR_SERVICE);
324     eventHandler_ = std::make_shared<AbilityEventHandler>(taskHandler_, weak_from_this());
325     freeInstallManager_ = std::make_shared<FreeInstallManager>(weak_from_this());
326     CHECK_POINTER_RETURN_BOOL(freeInstallManager_);
327 
328     // init user controller.
329     userController_ = std::make_shared<UserController>();
330     userController_->Init();
331     AmsConfigurationParameter::GetInstance().Parse();
332     TAG_LOGI(AAFwkTag::ABILITYMGR, "Ability manager service config parse");
333     subManagersHelper_ = std::make_shared<SubManagersHelper>(taskHandler_, eventHandler_);
334     subManagersHelper_->InitSubManagers(MAIN_USER_ID, true);
335     SwitchManagers(U0_USER_ID, false);
336 #ifdef SUPPORT_GRAPHICS
337     implicitStartProcessor_ = std::make_shared<ImplicitStartProcessor>();
338     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
339         InitFocusListener();
340     }
341     AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().Init();
342 #endif
343 
344     DelayedSingleton<ConnectionStateManager>::GetInstance()->Init(taskHandler_);
345 
346     InitInterceptor();
347     InitStartAbilityChain();
348     InitDeepLinkReserve();
349 
350     abilityAutoStartupService_ = std::make_shared<AbilityRuntime::AbilityAutoStartupService>();
351     InitPushTask();
352     AbilityCacheManager::GetInstance().Init(AppUtils::GetInstance().GetLimitMaximumExtensionsPerDevice(),
353         AppUtils::GetInstance().GetLimitMaximumExtensionsPerProc());
354 
355     SubscribeScreenUnlockedEvent();
356     appExitReasonHelper_ = std::make_shared<AppExitReasonHelper>(subManagersHelper_);
357     TAG_LOGI(AAFwkTag::ABILITYMGR, "Init success.");
358     return true;
359 }
360 
InitDeepLinkReserve()361 void AbilityManagerService::InitDeepLinkReserve()
362 {
363     if (!DeepLinkReserveConfig::GetInstance().LoadConfiguration()) {
364         TAG_LOGE(AAFwkTag::ABILITYMGR, "InitDeepLinkReserve failed.");
365     }
366 }
367 
InitInterceptor()368 void AbilityManagerService::InitInterceptor()
369 {
370     interceptorExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
371     interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
372     interceptorExecuter_->AddInterceptor("CrowdTest", std::make_shared<CrowdTestInterceptor>());
373     interceptorExecuter_->AddInterceptor("Control", std::make_shared<ControlInterceptor>());
374     afterCheckExecuter_ = std::make_shared<AbilityInterceptorExecuter>();
375     afterCheckExecuter_->AddInterceptor("ExtensionControl", std::make_shared<ExtensionControlInterceptor>());
376     afterCheckExecuter_->AddInterceptor("StartOtherApp", std::make_shared<StartOtherAppInterceptor>());
377     afterCheckExecuter_->AddInterceptor("DisposedRule", std::make_shared<DisposedRuleInterceptor>());
378     afterCheckExecuter_->AddInterceptor("EcologicalRule", std::make_shared<EcologicalRuleInterceptor>());
379     afterCheckExecuter_->SetTaskHandler(taskHandler_);
380     bool isAppJumpEnabled = OHOS::system::GetBoolParameter(
381         OHOS::AppExecFwk::PARAMETER_APP_JUMP_INTERCEPTOR_ENABLE, false);
382     if (isAppJumpEnabled) {
383         TAG_LOGI(AAFwkTag::ABILITYMGR, "App jump intercetor enabled, add AbilityJumpInterceptor to Executer");
384         interceptorExecuter_->AddInterceptor("AbilityJump", std::make_shared<AbilityJumpInterceptor>());
385     }
386 }
387 
InitInterceptorForScreenUnlock()388 void AbilityManagerService::InitInterceptorForScreenUnlock()
389 {
390     if (interceptorExecuter_) {
391         interceptorExecuter_->AddInterceptor("ScreenUnlock", std::make_shared<ScreenUnlockInterceptor>());
392     }
393 }
394 
InitPushTask()395 void AbilityManagerService::InitPushTask()
396 {
397     if (taskHandler_ == nullptr) {
398         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler_ is nullptr.");
399         return;
400     }
401 
402     auto initStartupFlagTask = [aams = shared_from_this()]() { aams->InitStartupFlag(); };
403     taskHandler_->SubmitTask(initStartupFlagTask, "InitStartupFlag");
404 
405     auto initPrepareTerminateConfigTask = [aams = shared_from_this()]() { aams->InitPrepareTerminateConfig(); };
406     taskHandler_->SubmitTask(initPrepareTerminateConfigTask, "InitPrepareTerminateConfig");
407 
408     auto initExtensionConfigTask = []() {
409         DelayedSingleton<ExtensionConfig>::GetInstance()->LoadExtensionConfiguration();
410     };
411     taskHandler_->SubmitTask(initExtensionConfigTask, "InitExtensionConfigTask");
412 
413     auto bootCompletedTask = [handler = taskHandler_]() {
414         if (ApplicationUtil::IsBootCompleted()) {
415             auto task = []() {
416                 ApplicationUtil::AppFwkBootEventCallback(BOOTEVENT_BOOT_COMPLETED, "true", nullptr);
417             };
418             handler->SubmitTask(task, "BootCompletedDelayTask", BOOTEVENT_COMPLETED_DELAY_TIME);
419         } else {
420             WatchParameter(BOOTEVENT_BOOT_COMPLETED, ApplicationUtil::AppFwkBootEventCallback, nullptr);
421             TAG_LOGI(AAFwkTag::ABILITYMGR, "init call, InitPushTask suc");
422         }
423     };
424     if (!ParseJsonFromBoot(SUSPEND_SERVICE_CONFIG_FILE)) {
425         TAG_LOGE(AAFwkTag::ABILITYMGR, "Parse json from boot fail");
426     }
427     isParamStartAbilityEnable_ = system::GetBoolParameter(PARAM_PREVENT_STARTABILITY, false);
428     taskHandler_->SubmitTask(bootCompletedTask, "BootCompletedTask");
429 }
430 
InitStartupFlag()431 void AbilityManagerService::InitStartupFlag()
432 {
433     startUpNewRule_ = CheckNewRuleSwitchState(COMPONENT_STARTUP_NEW_RULES);
434     newRuleExceptLauncherSystemUI_ = CheckNewRuleSwitchState(NEW_RULES_EXCEPT_LAUNCHER_SYSTEMUI);
435     backgroundJudgeFlag_ = CheckNewRuleSwitchState(BACKGROUND_JUDGE_FLAG);
436     whiteListassociatedWakeUpFlag_ = CheckNewRuleSwitchState(WHITE_LIST_ASS_WAKEUP_FLAG);
437 }
438 
InitStartAbilityChain()439 void AbilityManagerService::InitStartAbilityChain()
440 {
441     auto startSandboxSaveFile = std::make_shared<StartAbilitySandboxSavefile>();
442     startAbilityChain_.emplace(startSandboxSaveFile->GetPriority(), startSandboxSaveFile);
443 }
444 
OnStop()445 void AbilityManagerService::OnStop()
446 {
447     TAG_LOGI(AAFwkTag::ABILITYMGR, "Stop ability manager service.");
448 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
449     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
450     if (bgtaskObserver_) {
451         int ret = BackgroundTaskMgrHelper::UnsubscribeBackgroundTask(*bgtaskObserver_);
452         if (ret != ERR_OK) {
453             TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bgtask failed, err:%{public}d.", ret);
454         }
455     }
456 #endif
457     if (abilityBundleEventCallback_) {
458         auto bms = GetBundleManager();
459         if (bms) {
460             bool ret = IN_PROCESS_CALL(bms->UnregisterBundleEventCallback(abilityBundleEventCallback_));
461             if (ret != ERR_OK) {
462                 TAG_LOGE(AAFwkTag::ABILITYMGR, "unsubscribe bundle event callback failed, err:%{public}d.", ret);
463             }
464         }
465     }
466     eventHandler_.reset();
467     taskHandler_.reset();
468     state_ = ServiceRunningState::STATE_NOT_START;
469 }
470 
QueryServiceState() const471 ServiceRunningState AbilityManagerService::QueryServiceState() const
472 {
473     return state_;
474 }
475 
StartAbility(const Want & want,int32_t userId,int requestCode)476 int AbilityManagerService::StartAbility(const Want &want, int32_t userId, int requestCode)
477 {
478     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
479     bool isDebugApp = want.GetBoolParam(DEBUG_APP, false);
480     bool hasWindowOptions = (want.HasParameter(Want::PARAM_RESV_WINDOW_LEFT) ||
481         want.HasParameter(Want::PARAM_RESV_WINDOW_TOP) ||
482         want.HasParameter(Want::PARAM_RESV_WINDOW_HEIGHT) ||
483         want.HasParameter(Want::PARAM_RESV_WINDOW_WIDTH));
484     TAG_LOGD(AAFwkTag::ABILITYMGR, "isDebugApp=%{public}d, hasWindowOptions=%{public}d",
485         static_cast<int>(isDebugApp), static_cast<int>(hasWindowOptions));
486     bool checkDeveloperModeFlag = (isDebugApp || hasWindowOptions);
487     if (checkDeveloperModeFlag) {
488         if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
489             TAG_LOGE(AAFwkTag::ABILITYMGR, "not developer Mode");
490             return ERR_NOT_DEVELOPER_MODE;
491         }
492     }
493     if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
494         TAG_LOGE(AAFwkTag::ABILITYMGR, "Screen need passord to unlock");
495         return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
496     }
497     TAG_LOGD(AAFwkTag::ABILITYMGR, "coldStart:%{public}d", want.GetBoolParam("coldStart", false));
498     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
499     if (startWithAccount || IsCrossUserCall(userId)) {
500         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
501         CHECK_CALLER_IS_SYSTEM_APP;
502     }
503     if (hasWindowOptions && !AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
504         TAG_LOGE(AAFwkTag::ABILITYMGR, "window options not supported");
505         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
506     }
507     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
508     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
509     EventInfo eventInfo = BuildEventInfo(want, userId);
510     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
511     int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
512     AAFWK::ContinueRadar::GetInstance().ClickIconStartAbility("StartAbilityWrap", want.GetFlags(), ret);
513     if (ret != ERR_OK) {
514         eventInfo.errCode = ret;
515         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
516     }
517     return ret;
518 }
519 
StartAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)520 int AbilityManagerService::StartAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
521     int32_t userId, int requestCode)
522 {
523     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
524     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
525     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
526     return StartAbilityByFreeInstall(want, callerToken, userId, requestCode);
527 }
528 
StartAbilityByFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int32_t requestCode)529 int32_t AbilityManagerService::StartAbilityByFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
530     int32_t userId, int32_t requestCode)
531 {
532     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
533     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
534     if (startWithAccount || IsCrossUserCall(userId)) {
535         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
536         CHECK_CALLER_IS_SYSTEM_APP;
537     }
538     auto flags = want.GetFlags();
539     EventInfo eventInfo = BuildEventInfo(want, userId);
540     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
541     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
542         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed!");
543         eventInfo.errCode = ERR_INVALID_VALUE;
544         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
545         return ERR_INVALID_CONTINUATION_FLAG;
546     }
547 
548     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d",
549         want.GetElement().GetAbilityName().c_str(), userId);
550 
551     int32_t ret = StartAbilityWrap(want, callerToken, requestCode, false, userId);
552     if (ret != ERR_OK) {
553         eventInfo.errCode = ret;
554         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
555     }
556     return ret;
557 }
558 
StartAbilityWithSpecifyTokenId(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,int32_t userId,int requestCode)559 int AbilityManagerService::StartAbilityWithSpecifyTokenId(const Want &want, const sptr<IRemoteObject> &callerToken,
560     uint32_t specifyTokenId, int32_t userId, int requestCode)
561 {
562     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
563         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with specialId, the current process is not foundation process.");
564         return ERR_INVALID_CONTINUATION_FLAG;
565     }
566     return StartAbilityWithSpecifyTokenIdInner(want, callerToken, specifyTokenId, false, userId, requestCode);
567 }
568 
StartAbilityWithSpecifyTokenIdInner(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId,bool isPendingWantCaller,int32_t userId,int requestCode)569 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const sptr<IRemoteObject> &callerToken,
570     uint32_t specifyTokenId, bool isPendingWantCaller, int32_t userId, int requestCode)
571 {
572     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
573     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
574     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
575     auto flags = want.GetFlags();
576     EventInfo eventInfo = BuildEventInfo(want, userId);
577     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
578     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
579         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed.");
580         eventInfo.errCode = ERR_INVALID_VALUE;
581         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
582         return ERR_INVALID_CONTINUATION_FLAG;
583     }
584 
585     TAG_LOGI(AAFwkTag::ABILITYMGR,
586         "Start ability come, ability is %{public}s, userId is %{public}d, specifyTokenId is %{public}u.",
587         want.GetElement().GetAbilityName().c_str(), userId, specifyTokenId);
588 
589     int32_t ret = StartAbilityWrap(want, callerToken, requestCode, isPendingWantCaller, userId, false, specifyTokenId);
590     if (ret != ERR_OK) {
591         eventInfo.errCode = ret;
592         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
593     }
594     return ret;
595 }
596 
StartAbilityWithSpecifyTokenIdInner(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId)597 int AbilityManagerService::StartAbilityWithSpecifyTokenIdInner(const Want &want, const StartOptions &startOptions,
598     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller,
599     int32_t userId, int requestCode, uint32_t callerTokenId)
600 {
601     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions by trigger.");
602     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
603     return StartUIAbilityForOptionWrap(
604         want, startOptions, callerToken, isPendingWantCaller, userId, requestCode, callerTokenId);
605 }
606 
StartAbilityByInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,uint64_t intentId,int32_t userId)607 int32_t AbilityManagerService::StartAbilityByInsightIntent(const Want &want, const sptr<IRemoteObject> &callerToken,
608     uint64_t intentId, int32_t userId)
609 {
610     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
611     std::string bundleNameFromWant = want.GetElement().GetBundleName();
612     std::string bundleNameFromIntentMgr = "";
613     if (DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->
614         GetBundleName(intentId, bundleNameFromIntentMgr) != ERR_OK) {
615         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched intentId");
616         return ERR_INVALID_VALUE;
617     }
618     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
619     if (abilityRecord == nullptr) {
620         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such bundle matched token");
621         return ERR_INVALID_VALUE;
622     }
623     std::string bundleNameFromAbilityRecord = abilityRecord->GetAbilityInfo().bundleName;
624     if (!bundleNameFromWant.empty() && bundleNameFromWant == bundleNameFromIntentMgr &&
625         bundleNameFromWant == bundleNameFromAbilityRecord) {
626         TAG_LOGI(AAFwkTag::ABILITYMGR, "bundleName match");
627         return StartAbility(want, callerToken, userId, -1);
628     }
629     TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleName not match");
630     return ERR_INSIGHT_INTENT_START_INVALID_COMPONENT;
631 }
632 
StartAbilityByUIContentSession(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)633 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const sptr<IRemoteObject> &callerToken,
634     const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
635 {
636     if (!callerToken || !sessionInfo) {
637         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo is nullptr");
638         return ERR_INVALID_VALUE;
639     }
640     sptr<IRemoteObject> token;
641     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
642         Rosen::FocusChangeInfo focusChangeInfo;
643         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
644         token = focusChangeInfo.abilityToken_;
645     } else {
646         if (!wmsHandler_) {
647             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
648             return ERR_INVALID_VALUE;
649         }
650         wmsHandler_->GetFocusWindow(token);
651     }
652 
653     if (!token) {
654         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
655         return ERR_INVALID_VALUE;
656     }
657 
658     if (token != sessionInfo->callerToken) {
659         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken is not equal to top ablity token");
660         return NOT_TOP_ABILITY;
661     }
662     return StartAbility(want, callerToken, userId, requestCode);
663 }
664 
StartAbilityByUIContentSession(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,const sptr<SessionInfo> & sessionInfo,int32_t userId,int requestCode)665 int AbilityManagerService::StartAbilityByUIContentSession(const Want &want, const StartOptions &startOptions,
666     const sptr<IRemoteObject> &callerToken, const sptr<SessionInfo> &sessionInfo, int32_t userId, int requestCode)
667 {
668     if (!callerToken || !sessionInfo) {
669         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken or sessionInfo is nullptr");
670         return ERR_INVALID_VALUE;
671     }
672     sptr<IRemoteObject> token;
673     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
674         Rosen::FocusChangeInfo focusChangeInfo;
675         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
676         token = focusChangeInfo.abilityToken_;
677     } else {
678         if (!wmsHandler_) {
679             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
680             return ERR_INVALID_VALUE;
681         }
682         wmsHandler_->GetFocusWindow(token);
683     }
684 
685     if (!token) {
686         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
687         return ERR_INVALID_VALUE;
688     }
689 
690     if (token != sessionInfo->callerToken) {
691         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken is not equal to top ablity token");
692         return NOT_TOP_ABILITY;
693     }
694     return StartAbility(want, startOptions, callerToken, userId, requestCode);
695 }
696 
StartAbilityOnlyUIAbility(const Want & want,const sptr<IRemoteObject> & callerToken,uint32_t specifyTokenId)697 int AbilityManagerService::StartAbilityOnlyUIAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
698     uint32_t specifyTokenId)
699 {
700     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
701         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with specialId, the current process is not foundation process.");
702         return ERR_INVALID_CONTINUATION_FLAG;
703     }
704 
705     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
706     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
707     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
708     auto flags = want.GetFlags();
709     EventInfo eventInfo = BuildEventInfo(want, DEFAULT_INVAL_VALUE);
710     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
711     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
712         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed.");
713         eventInfo.errCode = ERR_INVALID_VALUE;
714         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
715         return ERR_INVALID_CONTINUATION_FLAG;
716     }
717 
718     TAG_LOGI(AAFwkTag::ABILITYMGR,
719         "Start ability come, ability is %{public}s, userId is %{public}d, specifyTokenId is %{public}u.",
720         want.GetElement().GetAbilityName().c_str(), DEFAULT_INVAL_VALUE, specifyTokenId);
721 
722     int32_t ret = StartAbilityWrap(want, callerToken, DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, specifyTokenId, false, false, true);
723     if (ret != ERR_OK) {
724         eventInfo.errCode = ret;
725         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
726     }
727     return ret;
728 }
729 
StartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)730 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
731     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
732 {
733     return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId, requestCode);
734 }
735 
ImplicitStartAbilityAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)736 int AbilityManagerService::ImplicitStartAbilityAsCaller(const Want &want, const sptr<IRemoteObject> &callerToken,
737     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode)
738 {
739     return StartAbilityAsCallerDetails(want, callerToken, asCallerSourceToken, userId,
740         requestCode, true);
741 }
742 
StartAbilityAsCallerDetails(const Want & want,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode,bool isImplicit)743 int AbilityManagerService::StartAbilityAsCallerDetails(const Want &want, const sptr<IRemoteObject> &callerToken,
744     sptr<IRemoteObject> asCallerSourceToken, int32_t userId, int requestCode, bool isImplicit)
745 {
746     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
747     CHECK_CALLER_IS_SYSTEM_APP;
748     auto flags = want.GetFlags();
749     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
750     EventInfo eventInfo = BuildEventInfo(want, userId);
751     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
752     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
753         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility with continuation flags is not allowed!");
754         eventInfo.errCode = ERR_INVALID_VALUE;
755         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
756         return ERR_INVALID_CONTINUATION_FLAG;
757     }
758 
759     AAFwk::Want newWant = want;
760     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
761     TAG_LOGI(AAFwkTag::ABILITYMGR, "Start ability come, ability is %{public}s, userId is %{public}d",
762         want.GetElement().GetAbilityName().c_str(), userId);
763     std::string callerPkg;
764     std::string targetPkg;
765     if (AbilityUtil::CheckJumpInterceptorWant(newWant, callerPkg, targetPkg)) {
766         TAG_LOGI(AAFwkTag::ABILITYMGR,
767             "the call is from interceptor dialog, callerPkg:%{public}s, targetPkg:%{public}s",
768             callerPkg.c_str(), targetPkg.c_str());
769         AbilityUtil::AddAbilityJumpRuleToBms(callerPkg, targetPkg, GetUserId());
770     }
771     int32_t ret = StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true,
772         0, false, isImplicit);
773     if (ret != ERR_OK) {
774         eventInfo.errCode = ret;
775         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
776     }
777     return ret;
778 }
779 
StartAbilityPublicPrechainCheck(StartAbilityParams & params)780 int AbilityManagerService::StartAbilityPublicPrechainCheck(StartAbilityParams &params)
781 {
782     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
783     // 1. CheckCallerToken
784     if (params.callerToken != nullptr && !VerificationAllToken(params.callerToken)) {
785         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
786             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
787         if (!isSpecificSA) {
788             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
789             return ERR_INVALID_CALLER;
790         }
791         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__);
792     }
793 
794     // 2. validUserId, multi-user
795     if (!JudgeMultiUserConcurrency(params.GetValidUserId())) {
796         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
797         return ERR_CROSS_USER;
798     }
799 
800     return ERR_OK;
801 }
802 
StartAbilityPrechainInterceptor(StartAbilityParams & params)803 int AbilityManagerService::StartAbilityPrechainInterceptor(StartAbilityParams &params)
804 {
805     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
806     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(params.want, params.requestCode,
807         GetUserId(), true, nullptr);
808     auto interceptorResult = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
809         interceptorExecuter_->DoProcess(interceptorParam);
810     if (interceptorResult != ERR_OK) {
811         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
812         return interceptorResult;
813     }
814 
815     return ERR_OK;
816 }
817 
StartAbilityInChain(StartAbilityParams & params,int & result)818 bool AbilityManagerService::StartAbilityInChain(StartAbilityParams &params, int &result)
819 {
820     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
821     std::shared_ptr<StartAbilityHandler> reqHandler;
822     for (const auto &item : startAbilityChain_) {
823         if (item.second->MatchStartRequest(params)) {
824             reqHandler = item.second;
825             break;
826         }
827     }
828 
829     if (!reqHandler) {
830         return false;
831     }
832 
833     result = StartAbilityPublicPrechainCheck(params);
834     if (result != ERR_OK) {
835         return true;
836     }
837     result = StartAbilityPrechainInterceptor(params);
838     if (result != ERR_OK) {
839         return true;
840     }
841     result = reqHandler->HandleStartRequest(params);
842     return true;
843 }
844 
StartAbilityWrap(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,bool isPendingWantCaller,int32_t userId,bool isStartAsCaller,uint32_t specifyToken,bool isForegroundToRestartApp,bool isImplicit,bool isUIAbilityOnly)845 int AbilityManagerService::StartAbilityWrap(const Want &want, const sptr<IRemoteObject> &callerToken,
846     int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyToken,
847     bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
848 {
849     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
850     StartAbilityParams startParams(const_cast<Want &>(want));
851     startParams.callerToken = callerToken;
852     startParams.userId = userId;
853     startParams.requestCode = requestCode;
854     startParams.isStartAsCaller = isStartAsCaller;
855     startParams.SetValidUserId(GetValidUserId(userId));
856 
857     int result = ERR_OK;
858     if (StartAbilityInChain(startParams, result)) {
859         return result;
860     }
861 
862     return StartAbilityInner(want, callerToken,
863         requestCode, isPendingWantCaller, userId, isStartAsCaller, specifyToken, isForegroundToRestartApp, isImplicit,
864         isUIAbilityOnly);
865 }
866 
SetReserveInfo(const std::string & linkString,AbilityRequest & abilityRequest)867 void AbilityManagerService::SetReserveInfo(const std::string &linkString, AbilityRequest& abilityRequest)
868 {
869     if (!linkString.size()) {
870         return;
871     }
872 
873     std::string reservedBundleName = "";
874     if (DeepLinkReserveConfig::GetInstance().isLinkReserved(linkString, reservedBundleName)) {
875         abilityRequest.uriReservedFlag = true;
876         abilityRequest.reservedBundleName = reservedBundleName;
877     } else {
878         abilityRequest.uriReservedFlag = false;
879         abilityRequest.reservedBundleName = reservedBundleName;
880     }
881 }
882 
CheckExtensionCallPermission(const Want & want,const AbilityRequest & abilityRequest,uint32_t specifyTokenId)883 int AbilityManagerService::CheckExtensionCallPermission(const Want& want, const AbilityRequest& abilityRequest,
884     uint32_t specifyTokenId)
885 {
886     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "startExtensionCheck");
887     auto isSACall = AAFwk::PermissionVerification::GetInstance()->IsSACallByTokenId(specifyTokenId);
888     auto isSystemAppCall = AAFwk::PermissionVerification::GetInstance()->IsSystemAppCallByTokenId(specifyTokenId);
889     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCallByTokenId(specifyTokenId);
890     auto isToPermissionMgr = IsTargetPermission(want);
891     if (!isSACall && !isSystemAppCall && !isShellCall && !isToPermissionMgr) {
892         TAG_LOGE(AAFwkTag::ABILITYMGR,
893             "Cannot start extension by start ability, use startServiceExtensionAbility.");
894         return ERR_WRONG_INTERFACE_CALL;
895     }
896     int result = CheckCallServicePermission(abilityRequest);
897     if (result != ERR_OK) {
898         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
899     }
900     return result;
901 }
902 
CheckServiceCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)903 int AbilityManagerService::CheckServiceCallPermission(const AbilityRequest& abilityRequest,
904     const AppExecFwk::AbilityInfo& abilityInfo)
905 {
906     TAG_LOGD(AAFwkTag::ABILITYMGR,
907         "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
908     int result = CheckCallServicePermission(abilityRequest);
909     if (result != ERR_OK) {
910         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
911     }
912     return result;
913 }
914 
CheckBrokerCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo)915 int AbilityManagerService::CheckBrokerCallPermission(const AbilityRequest& abilityRequest,
916     const AppExecFwk::AbilityInfo& abilityInfo)
917 {
918     // temp add for broker, remove when delete issacall
919     if (abilityRequest.collaboratorType != CollaboratorType::RESERVE_TYPE && !abilityInfo.visible) {
920         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check permission failed");
921         return CHECK_PERMISSION_FAILED;
922     }
923     TAG_LOGD(AAFwkTag::ABILITYMGR,
924         "Check call service or extension permission, name is %{public}s.", abilityInfo.name.c_str());
925     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
926     if (collaborator == nullptr) {
927         TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator is nullptr.");
928         return CHECK_PERMISSION_FAILED;
929     }
930     int result = collaborator->CheckCallAbilityPermission(abilityRequest.want);
931     if (result != ERR_OK) {
932         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker.");
933         return CHECK_PERMISSION_FAILED;
934     }
935     return result;
936 }
937 
CheckAbilityCallPermission(const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,uint32_t specifyTokenId)938 int AbilityManagerService::CheckAbilityCallPermission(const AbilityRequest& abilityRequest,
939     const AppExecFwk::AbilityInfo& abilityInfo, uint32_t specifyTokenId)
940 {
941     TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
942     int result = CheckCallAbilityPermission(abilityRequest, specifyTokenId);
943     if (result != ERR_OK) {
944         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
945     }
946     return result;
947 }
948 
CheckCallPermission(const Want & want,const AppExecFwk::AbilityInfo & abilityInfo,const AbilityRequest & abilityRequest,bool isForegroundToRestartApp,bool isSendDialogResult,uint32_t specifyTokenId,const std::string & callerBundleName)949 int AbilityManagerService::CheckCallPermission(const Want& want, const AppExecFwk::AbilityInfo& abilityInfo,
950     const AbilityRequest& abilityRequest, bool isForegroundToRestartApp,
951     bool isSendDialogResult, uint32_t specifyTokenId,
952     const std::string& callerBundleName)
953 {
954     auto type = abilityInfo.type;
955     if (type == AppExecFwk::AbilityType::DATA) {
956         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot start data ability by start ability.");
957         return ERR_WRONG_INTERFACE_CALL;
958     }
959     if (type == AppExecFwk::AbilityType::EXTENSION) {
960         return CheckExtensionCallPermission(want, abilityRequest, specifyTokenId);
961     }
962     if (type == AppExecFwk::AbilityType::SERVICE) {
963         return CheckServiceCallPermission(abilityRequest, abilityInfo);
964     }
965     if ((callerBundleName == SHELL_ASSISTANT_BUNDLENAME && AppUtils::GetInstance().IsSupportAncoApp()) ||
966         IPCSkeleton::GetCallingUid() == BROKER_UID) {
967         return CheckBrokerCallPermission(abilityRequest, abilityInfo);
968     }
969     if (!isForegroundToRestartApp && (!isSendDialogResult || want.GetBoolParam("isSelector", false))) {
970         return CheckAbilityCallPermission(abilityRequest, abilityInfo, specifyTokenId);
971     }
972     return ERR_OK;
973 }
974 
StartAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,bool isPendingWantCaller,int32_t userId,bool isStartAsCaller,uint32_t specifyTokenId,bool isForegroundToRestartApp,bool isImplicit,bool isUIAbilityOnly)975 int AbilityManagerService::StartAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
976     int requestCode, bool isPendingWantCaller, int32_t userId, bool isStartAsCaller, uint32_t specifyTokenId,
977     bool isForegroundToRestartApp, bool isImplicit, bool isUIAbilityOnly)
978 {
979     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
980     std::string dialogSessionId = want.GetStringParam("dialogSessionId");
981     bool isSendDialogResult = false;
982 #ifdef SUPPORT_SCREEN
983     if (!dialogSessionId.empty() &&
984         DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId) != nullptr) {
985         isSendDialogResult = true;
986     }
987 #endif // SUPPORT_SCREEN
988 
989     // prevent the app from dominating the screen
990     if (system::GetBoolParameter(VERIFY_DOMINATE_SCREEN, true) &&
991         callerToken == nullptr && !IsCallerSceneBoard() && !isSendDialogResult && !isForegroundToRestartApp &&
992         AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
993         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is invalid.");
994         return ERR_INVALID_CALLER;
995     }
996     {
997 #ifdef WITH_DLP
998         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
999         if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1000             VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1001             !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1002             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed.", __func__);
1003             return CHECK_PERMISSION_FAILED;
1004         }
1005 
1006         if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1007             InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1008             return StartExtensionAbilityInner(want, callerToken, userId,
1009                 AppExecFwk::ExtensionAbilityType::SERVICE, false, false, true, isStartAsCaller);
1010         }
1011 #endif // WITH_DLP
1012     }
1013 
1014     AbilityUtil::RemoveWindowModeKey(const_cast<Want &>(want));
1015     if (callerToken != nullptr && !VerificationAllToken(callerToken) && !isSendDialogResult) {
1016         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
1017             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
1018         if (!isSpecificSA) {
1019             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
1020             return ERR_INVALID_CALLER;
1021         }
1022         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__);
1023     }
1024 
1025     int32_t oriValidUserId = GetValidUserId(userId);
1026     int32_t validUserId = oriValidUserId;
1027     SetTargetCloneIndexInSameBundle(want, callerToken);
1028     int32_t appIndex = 0;
1029     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1030         return ERR_APP_CLONE_INDEX_INVALID;
1031     }
1032     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1033     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1034         true, nullptr);
1035     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1036         interceptorExecuter_->DoProcess(interceptorParam);
1037     if (result != ERR_OK) {
1038         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1039         return result;
1040     }
1041 
1042     if (callerToken != nullptr && CheckIfOperateRemote(want)) {
1043         TAG_LOGI(AAFwkTag::ABILITYMGR, "try to StartRemoteAbility");
1044         return StartRemoteAbility(want, requestCode, validUserId, callerToken);
1045     }
1046 
1047     if (!JudgeMultiUserConcurrency(validUserId)) {
1048         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1049         return ERR_CROSS_USER;
1050     }
1051 
1052     AbilityRequest abilityRequest;
1053 #ifdef SUPPORT_GRAPHICS
1054     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1055         abilityRequest.Voluation(want, requestCode, callerToken);
1056         if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1057             UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1058         } else if (!isStartAsCaller) {
1059             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1060             UpdateCallerInfo(abilityRequest.want, callerToken);
1061         } else {
1062             TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1063         }
1064         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1065         SetReserveInfo(want.GetUriString(), abilityRequest);
1066         return implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1067     }
1068     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1069         return ShowPickerDialog(want, validUserId, callerToken);
1070     }
1071 #endif
1072     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1073     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1074     std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
1075     bool selfFreeInstallEnable = (result == RESOLVE_ABILITY_ERR && want.GetElement().GetModuleName() != "" &&
1076                                   want.GetElement().GetBundleName() == callerBundleName);
1077     bool isStartFreeInstallByWant = AbilityUtil::IsStartFreeInstall(want);
1078     if (isStartFreeInstallByWant || selfFreeInstallEnable) {
1079         Want localWant;
1080         auto freeInstallResult = PreStartFreeInstall(want, callerToken, specifyTokenId, isStartAsCaller, localWant);
1081         if (freeInstallResult != ERR_OK) {
1082             TAG_LOGE(AAFwkTag::ABILITYMGR, "PreStartFreeInstall failed.");
1083             return freeInstallResult;
1084         }
1085 
1086         if (isStartFreeInstallByWant) {
1087             return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode,
1088                 callerToken, true, specifyTokenId);
1089         }
1090         int32_t ret = freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, false);
1091         if (ret == ERR_OK) {
1092             result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1093         }
1094     }
1095 
1096     if (result != ERR_OK) {
1097         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
1098         return result;
1099     }
1100 
1101     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1102         UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1103     } else if (!isStartAsCaller) {
1104         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1105         UpdateCallerInfo(abilityRequest.want, callerToken);
1106     } else if (callerBundleName == BUNDLE_NAME_DIALOG ||
1107         (isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1108         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1109         int32_t flag = false;
1110         if (callerBundleName == BUNDLE_NAME_DIALOG) {
1111             flag = true;
1112         }
1113         implicitStartProcessor_->ResetCallingIdentityAsCaller(
1114             abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), flag);
1115     }
1116 
1117     auto abilityInfo = abilityRequest.abilityInfo;
1118     if (isUIAbilityOnly && abilityInfo.type != AbilityType::PAGE) {
1119         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability type is not UIAbility");
1120         return ERR_INVALID_VALUE;
1121     }
1122     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1123     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
1124         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1125 
1126     if ((isSendDialogResult && want.GetBoolParam("isSelector", false))) {
1127         isImplicit = true;
1128     }
1129     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1130         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1131     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1132         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1133         return ERR_STATIC_CFG_PERMISSION;
1134     }
1135 
1136     result = CheckCallPermission(want, abilityInfo, abilityRequest, isForegroundToRestartApp,
1137         isSendDialogResult, specifyTokenId, callerBundleName);
1138     if (result != ERR_OK) {
1139         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallPermission error, result is %{public}d.", result);
1140         return result;
1141     }
1142 
1143     Want newWant = abilityRequest.want;
1144     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1145         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1146     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1147         afterCheckExecuter_->DoProcess(afterCheckParam);
1148     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1149     newWant.RemoveParam("queryWantFromErms");
1150     if (result != ERR_OK && isReplaceWantExist == false) {
1151         TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
1152         return result;
1153     }
1154 #ifdef SUPPORT_SCREEN
1155     if (result != ERR_OK && isReplaceWantExist && !isSendDialogResult &&
1156         callerBundleName != BUNDLE_NAME_DIALOG) {
1157         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1158     }
1159     if (result == ERR_OK &&
1160         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1161         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1162         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
1163     }
1164 #endif
1165     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1166         TAG_LOGD(AAFwkTag::ABILITYMGR, "PreLoadAppDataAbilities:%{public}s.", abilityInfo.bundleName.c_str());
1167         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1168         if (result != ERR_OK) {
1169             TAG_LOGE(AAFwkTag::ABILITYMGR,
1170                 "StartAbility: App data ability preloading failed, '%{public}s', %{public}d.",
1171                 abilityInfo.bundleName.c_str(), result);
1172             return result;
1173         }
1174     }
1175 
1176     if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
1177         abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
1178         SendStartAbilityOtherExtensionEvent(abilityInfo, abilityRequest.want, specifyTokenId);
1179         return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
1180     }
1181 
1182     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1183         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s.", abilityInfo.bundleName.c_str());
1184         return ERR_WOULD_BLOCK;
1185     }
1186 
1187     auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1188     UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1189     StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1190 
1191     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1192     if (specifyTokenId > 0) {
1193         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
1194         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1195         abilityRequest.specifyTokenId = specifyTokenId;
1196     }
1197     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1198     // sceneboard
1199     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1200         ReportEventToRSS(abilityInfo, abilityRequest.callerToken);
1201         abilityRequest.userId = oriValidUserId;
1202         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1203         // other sa or shell can not use continueSessionId and persistentId
1204         auto abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
1205         if (abilityRecord == nullptr &&
1206             !PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
1207             TAG_LOGW(AAFwkTag::ABILITYMGR, "StartAbilityInner, Remove continueSessionId and persistentId");
1208             abilityRequest.want.RemoveParam(DMS_CONTINUED_SESSION_ID);
1209             abilityRequest.want.RemoveParam(DMS_PERSISTENT_ID);
1210         }
1211         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1212         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1213         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1214     }
1215 
1216     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1217     if (missionListManager == nullptr) {
1218         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is nullptr. userId=%{public}d", validUserId);
1219         return ERR_INVALID_VALUE;
1220     }
1221 
1222     ReportAbilityStartInfoToRSS(abilityInfo);
1223     ReportEventToRSS(abilityInfo, callerToken);
1224     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability, name is %{public}s.", abilityInfo.name.c_str());
1225     return missionListManager->StartAbility(abilityRequest);
1226 }
1227 
PreStartFreeInstall(const Want & want,sptr<IRemoteObject> callerToken,uint32_t specifyTokenId,bool isStartAsCaller,Want & localWant)1228 int AbilityManagerService::PreStartFreeInstall(const Want &want, sptr<IRemoteObject> callerToken,
1229     uint32_t specifyTokenId, bool isStartAsCaller, Want &localWant)
1230 {
1231     if (freeInstallManager_ == nullptr) {
1232         return ERR_INVALID_VALUE;
1233     }
1234     (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1235     localWant = want;
1236     if (!localWant.GetDeviceId().empty()) {
1237         localWant.SetDeviceId("");
1238     }
1239     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
1240         UpdateCallerInfoFromToken(localWant, callerToken);
1241     } else if (!isStartAsCaller) {
1242         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1243         UpdateCallerInfo(localWant, callerToken);
1244     } else {
1245         TAG_LOGD(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1246     }
1247     return ERR_OK;
1248 }
1249 
StartAbilityByConnectManager(const Want & want,const AbilityRequest & abilityRequest,const AppExecFwk::AbilityInfo & abilityInfo,int validUserId,sptr<IRemoteObject> callerToken)1250 int AbilityManagerService::StartAbilityByConnectManager(const Want& want, const AbilityRequest& abilityRequest,
1251     const AppExecFwk::AbilityInfo& abilityInfo, int validUserId, sptr<IRemoteObject> callerToken)
1252 {
1253     auto connectManager = GetConnectManagerByUserId(validUserId);
1254     if (!connectManager) {
1255         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
1256         return ERR_INVALID_VALUE;
1257     }
1258     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start service or extension, name is %{public}s.", abilityInfo.name.c_str());
1259     ReportEventToRSS(abilityInfo, callerToken);
1260     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1261     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(const_cast<Want &>(abilityRequest.want),
1262         abilityRequest.abilityInfo.extensionAbilityType);
1263     return connectManager->StartAbility(abilityRequest);
1264 }
1265 
StartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1266 int AbilityManagerService::StartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1267     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1268 {
1269     return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode);
1270 }
1271 
ImplicitStartAbility(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1272 int AbilityManagerService::ImplicitStartAbility(const Want &want, const AbilityStartSetting &abilityStartSetting,
1273     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1274 {
1275     return StartAbilityDetails(want, abilityStartSetting, callerToken, userId, requestCode, true);
1276 }
1277 
StartAbilityDetails(const Want & want,const AbilityStartSetting & abilityStartSetting,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode,bool isImplicit)1278 int AbilityManagerService::StartAbilityDetails(const Want &want, const AbilityStartSetting &abilityStartSetting,
1279     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode, bool isImplicit)
1280 {
1281     if (want.GetBoolParam(DEBUG_APP, false) && !system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
1282         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
1283         return ERR_NOT_DEVELOPER_MODE;
1284     }
1285     if (!UnlockScreenManager::GetInstance().UnlockScreen()) {
1286         TAG_LOGE(AAFwkTag::ABILITYMGR, "Screen need passord to unlock");
1287         return ERR_UNLOCK_SCREEN_FAILED_IN_DEVELOPER_MODE;
1288     }
1289     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1290     StartAbilityParams startParams(const_cast<Want &>(want));
1291     startParams.callerToken = callerToken;
1292     startParams.userId = userId;
1293     startParams.requestCode = requestCode;
1294     startParams.SetValidUserId(GetValidUserId(userId));
1295 
1296     int result = ERR_OK;
1297     if (StartAbilityInChain(startParams, result)) {
1298         return result;
1299     }
1300 
1301     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1302     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability setting.");
1303     if (IsCrossUserCall(userId)) {
1304         CHECK_CALLER_IS_SYSTEM_APP;
1305     }
1306     EventInfo eventInfo = BuildEventInfo(want, userId);
1307     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1308 
1309 #ifdef WITH_DLP
1310     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1311         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1312         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1313         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
1314         eventInfo.errCode = CHECK_PERMISSION_FAILED;
1315         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1316         return CHECK_PERMISSION_FAILED;
1317     }
1318 #endif // WITH_DLP
1319 
1320     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1321         eventInfo.errCode = ERR_INVALID_VALUE;
1322         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1323         return ERR_INVALID_CALLER;
1324     }
1325 
1326     int32_t oriValidUserId = GetValidUserId(userId);
1327     int32_t validUserId = oriValidUserId;
1328     int32_t appIndex = 0;
1329     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1330         return ERR_APP_CLONE_INDEX_INVALID;
1331     }
1332     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1333     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1334         true, nullptr);
1335     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1336         interceptorExecuter_->DoProcess(interceptorParam);
1337     if (result != ERR_OK) {
1338         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1339         eventInfo.errCode = result;
1340         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1341         return result;
1342     }
1343 
1344     if (AbilityUtil::IsStartFreeInstall(want)) {
1345         if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1346             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1347             return ERR_INVALID_VALUE;
1348         }
1349         (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1350         Want localWant = want;
1351         UpdateCallerInfo(localWant, callerToken);
1352         return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode, callerToken, true);
1353     }
1354 
1355     if (!JudgeMultiUserConcurrency(validUserId)) {
1356         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1357         eventInfo.errCode = ERR_INVALID_VALUE;
1358         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1359         return ERR_CROSS_USER;
1360     }
1361 
1362     AbilityRequest abilityRequest;
1363 #ifdef SUPPORT_GRAPHICS
1364     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1365         abilityRequest.Voluation(
1366             want, requestCode, callerToken, std::make_shared<AbilityStartSetting>(abilityStartSetting));
1367         abilityRequest.callType = AbilityCallType::START_SETTINGS_TYPE;
1368         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1369         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
1370         if (result != ERR_OK) {
1371             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error.");
1372             eventInfo.errCode = result;
1373             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1374         }
1375         return result;
1376     }
1377     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1378         return ShowPickerDialog(want, validUserId, callerToken);
1379     }
1380 #endif
1381     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1382     if (result != ERR_OK) {
1383         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
1384         eventInfo.errCode = result;
1385         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1386         return result;
1387     }
1388     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1389 
1390     auto abilityInfo = abilityRequest.abilityInfo;
1391     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1392     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1393         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1394 
1395     result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
1396     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1397         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1398         eventInfo.errCode = result;
1399         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1400         return ERR_STATIC_CFG_PERMISSION;
1401     }
1402     result = CheckCallAbilityPermission(abilityRequest);
1403     if (result != ERR_OK) {
1404         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error.", __func__);
1405         eventInfo.errCode = result;
1406         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1407         return result;
1408     }
1409 
1410     abilityRequest.startSetting = std::make_shared<AbilityStartSetting>(abilityStartSetting);
1411 
1412     if (abilityInfo.type == AppExecFwk::AbilityType::DATA) {
1413         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot start data ability, use 'AcquireDataAbility()' instead.");
1414         eventInfo.errCode = ERR_INVALID_VALUE;
1415         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1416         return ERR_WRONG_INTERFACE_CALL;
1417     }
1418 
1419     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
1420         GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
1421     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1422         afterCheckExecuter_->DoProcess(afterCheckParam);
1423     if (result != ERR_OK) {
1424         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
1425         return result;
1426     }
1427 
1428     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1429         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1430         if (result != ERR_OK) {
1431             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
1432                 abilityInfo.bundleName.c_str(),
1433                 result);
1434             eventInfo.errCode = result;
1435             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1436             return result;
1437         }
1438     }
1439 #ifdef SUPPORT_GRAPHICS
1440     if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1441         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support for page type ability.");
1442         eventInfo.errCode = ERR_INVALID_VALUE;
1443         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1444         return ERR_WRONG_INTERFACE_CALL;
1445     }
1446 #endif
1447     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1448         eventInfo.errCode = ERR_WOULD_BLOCK;
1449         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1450         return ERR_WOULD_BLOCK;
1451     }
1452     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1453         UpdateCallerInfo(abilityRequest.want, callerToken);
1454         abilityRequest.userId = oriValidUserId;
1455         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1456         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1457         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1458         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1459     }
1460     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1461     if (missionListManager == nullptr) {
1462         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", validUserId);
1463         eventInfo.errCode = ERR_INVALID_VALUE;
1464         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1465         return ERR_INVALID_VALUE;
1466     }
1467     UpdateCallerInfo(abilityRequest.want, callerToken);
1468     auto ret = missionListManager->StartAbility(abilityRequest);
1469     if (ret != ERR_OK) {
1470         eventInfo.errCode = ret;
1471         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1472     }
1473     return ret;
1474 }
1475 
StartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1476 int AbilityManagerService::StartAbility(const Want &want, const StartOptions &startOptions,
1477     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1478 {
1479     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1480     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability with startOptions.");
1481     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1482     return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode);
1483 }
1484 
ImplicitStartAbility(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int32_t userId,int requestCode)1485 int AbilityManagerService::ImplicitStartAbility(const Want &want, const StartOptions &startOptions,
1486     const sptr<IRemoteObject> &callerToken, int32_t userId, int requestCode)
1487 {
1488     TAG_LOGD(AAFwkTag::ABILITYMGR, "Implicit Start ability with startOptions.");
1489     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1490     return StartUIAbilityForOptionWrap(want, startOptions, callerToken, false, userId, requestCode, 0, true);
1491 }
1492 
StartUIAbilityForOptionWrap(const Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,uint32_t callerTokenId,bool isImplicit,bool isCallByShortcut)1493 int AbilityManagerService::StartUIAbilityForOptionWrap(const Want &want, const StartOptions &options,
1494     sptr<IRemoteObject> callerToken, bool isPendingWantCaller, int32_t userId,
1495     int requestCode, uint32_t callerTokenId, bool isImplicit,
1496     bool isCallByShortcut)
1497 {
1498     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1499     auto ret = CheckProcessOptions(want, options, userId);
1500     if (ret != ERR_OK) {
1501         return ret;
1502     }
1503     return StartAbilityForOptionWrap(want, options, callerToken, isPendingWantCaller, userId, requestCode, false,
1504         callerTokenId, isImplicit, isCallByShortcut);
1505 }
1506 
StartAbilityAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,sptr<IRemoteObject> asCallerSourceToken,int32_t userId,int requestCode)1507 int AbilityManagerService::StartAbilityAsCaller(const Want &want, const StartOptions &startOptions,
1508     const sptr<IRemoteObject> &callerToken, sptr<IRemoteObject> asCallerSourceToken,
1509     int32_t userId, int requestCode)
1510 {
1511     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ability as caller with startOptions.");
1512     CHECK_CALLER_IS_SYSTEM_APP;
1513 
1514     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
1515     AAFwk::Want newWant = want;
1516     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1517     return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1518 }
1519 
StartAbilityForResultAsCaller(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1520 int AbilityManagerService::StartAbilityForResultAsCaller(
1521     const Want &want, const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1522 {
1523     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1524     CHECK_CALLER_IS_SYSTEM_APP;
1525     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1526 
1527     AAFwk::Want newWant = want;
1528     auto connectManager = GetCurrentConnectManager();
1529     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1530     auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1531     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1532     return StartAbilityWrap(newWant, callerToken, requestCode, false, userId, true);
1533 }
1534 
StartAbilityForResultAsCaller(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1535 int AbilityManagerService::StartAbilityForResultAsCaller(const Want &want, const StartOptions &startOptions,
1536     const sptr<IRemoteObject> &callerToken, int requestCode, int32_t userId)
1537 {
1538     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1539     CHECK_CALLER_IS_SYSTEM_APP;
1540 
1541     AAFwk::Want newWant = want;
1542     auto connectManager = GetCurrentConnectManager();
1543     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
1544     auto asCallerSourceToken = connectManager->GetUIExtensionSourceToken(callerToken);
1545     UpdateAsCallerSourceInfo(newWant, asCallerSourceToken, callerToken);
1546     return StartAbilityForOptionWrap(newWant, startOptions, callerToken, false, userId, requestCode, true);
1547 }
1548 
StartAbilityForOptionWrap(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,bool isStartAsCaller,uint32_t callerTokenId,bool isImplicit,bool isCallByShortcut)1549 int AbilityManagerService::StartAbilityForOptionWrap(const Want &want, const StartOptions &startOptions,
1550     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1551     bool isStartAsCaller, uint32_t callerTokenId, bool isImplicit, bool isCallByShortcut)
1552 {
1553     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1554     StartAbilityParams startParams(const_cast<Want &>(want));
1555     startParams.callerToken = callerToken;
1556     startParams.userId = userId;
1557     startParams.requestCode = requestCode;
1558     startParams.isStartAsCaller = isStartAsCaller;
1559     startParams.startOptions = &startOptions;
1560     startParams.SetValidUserId(GetValidUserId(userId));
1561 
1562     int result = ERR_OK;
1563     if (StartAbilityInChain(startParams, result)) {
1564         return result;
1565     }
1566 
1567     return StartAbilityForOptionInner(want, startOptions, callerToken, isPendingWantCaller, userId, requestCode,
1568         isStartAsCaller, callerTokenId, isImplicit, isCallByShortcut);
1569 }
1570 
StartAbilityForOptionInner(const Want & want,const StartOptions & startOptions,const sptr<IRemoteObject> & callerToken,bool isPendingWantCaller,int32_t userId,int requestCode,bool isStartAsCaller,uint32_t specifyTokenId,bool isImplicit,bool isCallByShortcut)1571 int AbilityManagerService::StartAbilityForOptionInner(const Want &want, const StartOptions &startOptions,
1572     const sptr<IRemoteObject> &callerToken, bool isPendingWantCaller, int32_t userId, int requestCode,
1573     bool isStartAsCaller, uint32_t specifyTokenId, bool isImplicit, bool isCallByShortcut)
1574 {
1575     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1576     // prevent the app from dominating the screen
1577     if (system::GetBoolParameter(VERIFY_DOMINATE_SCREEN, true) &&
1578         callerToken == nullptr && !IsCallerSceneBoard() && !isCallByShortcut &&
1579         AbilityPermissionUtil::GetInstance().IsDominateScreen(want, isPendingWantCaller)) {
1580         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is invalid.");
1581         return ERR_INVALID_CALLER;
1582     }
1583 
1584     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
1585     if (startWithAccount || IsCrossUserCall(userId)) {
1586         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
1587         CHECK_CALLER_IS_SYSTEM_APP;
1588     }
1589     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
1590     EventInfo eventInfo = BuildEventInfo(want, userId);
1591     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
1592 
1593 #ifdef WITH_DLP
1594     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1595         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
1596         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1597         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
1598         eventInfo.errCode = CHECK_PERMISSION_FAILED;
1599         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1600         return CHECK_PERMISSION_FAILED;
1601     }
1602 #endif // WITH_DLP
1603 
1604     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
1605         eventInfo.errCode = ERR_INVALID_VALUE;
1606         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1607         return ERR_INVALID_CALLER;
1608     }
1609 
1610     int32_t oriValidUserId = GetValidUserId(userId);
1611     int32_t validUserId = oriValidUserId;
1612     SetTargetCloneIndexInSameBundle(want, callerToken);
1613     int32_t appIndex = 0;
1614     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
1615         return ERR_APP_CLONE_INDEX_INVALID;
1616     }
1617     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
1618     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1619         true, nullptr);
1620     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1621         interceptorExecuter_->DoProcess(interceptorParam);
1622     if (result != ERR_OK) {
1623         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1624         eventInfo.errCode = result;
1625         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1626         return result;
1627     }
1628 
1629     if (AbilityUtil::IsStartFreeInstall(want)) {
1630         if (CheckIfOperateRemote(want) || freeInstallManager_ == nullptr) {
1631             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not start remote free install");
1632             return ERR_INVALID_VALUE;
1633         }
1634         (const_cast<Want &>(want)).RemoveParam("send_to_erms_embedded");
1635         Want localWant = want;
1636         if (!isStartAsCaller) {
1637             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1638             UpdateCallerInfo(localWant, callerToken);
1639         } else {
1640             TAG_LOGI(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1641         }
1642         return freeInstallManager_->StartFreeInstall(localWant, validUserId, requestCode,
1643             callerToken, true, specifyTokenId);
1644     }
1645     if (!JudgeMultiUserConcurrency(validUserId)) {
1646         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1647         eventInfo.errCode = ERR_INVALID_VALUE;
1648         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1649         return ERR_CROSS_USER;
1650     }
1651 
1652     AbilityRequest abilityRequest;
1653 #ifdef SUPPORT_GRAPHICS
1654     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
1655         abilityRequest.Voluation(want, requestCode, callerToken);
1656         if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
1657             bool windowFocused = startOptions.GetWindowFocused();
1658             abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowFocused);
1659         } else {
1660             abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
1661         }
1662         if (startOptions.GetDisplayID() == 0) {
1663             abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1664                 static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1665         } else {
1666             abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1667         }
1668         WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
1669         abilityRequest.callType = AbilityCallType::START_OPTIONS_TYPE;
1670         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
1671         if (specifyTokenId > 0 && callerToken) { // for sa specify tokenId and caller token
1672             UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
1673         } else if (!isStartAsCaller) {
1674             TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1675             UpdateCallerInfo(abilityRequest.want, callerToken);
1676         } else {
1677             TAG_LOGI(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1678         }
1679         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId,
1680             startOptions.GetWindowMode());
1681         if (result != ERR_OK) {
1682             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error.");
1683             eventInfo.errCode = result;
1684             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1685         }
1686         return result;
1687     }
1688     if (want.GetAction().compare(ACTION_CHOOSE) == 0) {
1689         return ShowPickerDialog(want, validUserId, callerToken);
1690     }
1691 #endif
1692     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
1693     if (result != ERR_OK) {
1694         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
1695         eventInfo.errCode = result;
1696         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1697         return result;
1698     }
1699 
1700     if (!isStartAsCaller) {
1701         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
1702         UpdateCallerInfo(abilityRequest.want, callerToken);
1703     } else {
1704         TAG_LOGI(AAFwkTag::ABILITYMGR, "start as caller, skip UpdateCallerInfo!");
1705     }
1706     auto abilityInfo = abilityRequest.abilityInfo;
1707     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1708     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, singleton is : %{public}d",
1709         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1710 
1711     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
1712         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, isImplicit);
1713     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1714         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1715         eventInfo.errCode = result;
1716         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1717         return ERR_STATIC_CFG_PERMISSION;
1718     }
1719     result = CheckCallAbilityPermission(abilityRequest, 0, isCallByShortcut);
1720     if (result != ERR_OK) {
1721         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallAbilityPermission error.", __func__);
1722         eventInfo.errCode = result;
1723         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1724         return result;
1725     }
1726 
1727     if (abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
1728         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support for page type ability.");
1729         eventInfo.errCode = ERR_INVALID_VALUE;
1730         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1731         return ERR_INVALID_VALUE;
1732     }
1733 
1734     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
1735         result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
1736         if (result != ERR_OK) {
1737             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
1738                 abilityInfo.bundleName.c_str(),
1739                 result);
1740             eventInfo.errCode = result;
1741             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1742             return result;
1743         }
1744     }
1745 
1746     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
1747         eventInfo.errCode = ERR_WOULD_BLOCK;
1748         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1749         return ERR_WOULD_BLOCK;
1750     }
1751 #ifdef SUPPORT_GRAPHICS
1752     if (abilityInfo.isStageBasedModel && !CheckWindowMode(startOptions.GetWindowMode(), abilityInfo.windowModes)) {
1753         return ERR_AAFWK_INVALID_WINDOW_MODE;
1754     }
1755 #endif
1756     if (startOptions.GetDisplayID() == 0) {
1757         abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID,
1758             static_cast<int32_t>(Rosen::DisplayManager::GetInstance().GetDefaultDisplayId()));
1759     } else {
1760         abilityRequest.want.SetParam(Want::PARAM_RESV_DISPLAY_ID, startOptions.GetDisplayID());
1761     }
1762     AbilityUtil::ProcessWindowMode(abilityRequest.want, abilityInfo.applicationInfo.accessTokenId,
1763         startOptions.GetWindowMode());
1764 
1765     WindowOptionsUtils::SetWindowPositionAndSize(abilityRequest.want, callerToken, startOptions);
1766 
1767     if (PermissionVerification::GetInstance()->IsSystemAppCall()) {
1768         bool focused = abilityRequest.want.GetBoolParam(Want::PARAM_RESV_WINDOW_FOCUSED, true);
1769         if (focused) {
1770             bool windowfocused = startOptions.GetWindowFocused();
1771             abilityRequest.want.SetParam(Want::PARAM_RESV_WINDOW_FOCUSED, windowfocused);
1772         }
1773     } else {
1774         abilityRequest.want.RemoveParam(Want::PARAM_RESV_WINDOW_FOCUSED);
1775     }
1776 
1777     Want newWant = abilityRequest.want;
1778     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
1779         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
1780     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1781         afterCheckExecuter_->DoProcess(afterCheckParam);
1782     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
1783     newWant.RemoveParam("queryWantFromErms");
1784 #ifdef SUPPORT_SCREEN
1785     if (result != ERR_OK && isReplaceWantExist == false) {
1786         TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
1787         return result;
1788     }
1789     if (result != ERR_OK && isReplaceWantExist) {
1790         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
1791     }
1792     if (result == ERR_OK &&
1793         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
1794         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
1795         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
1796     }
1797 #endif
1798 
1799     auto backFlag = StartAbilityUtils::ermsSupportBackToCallerFlag;
1800     UpdateBackToCallerFlag(callerToken, abilityRequest.want, requestCode, backFlag);
1801     StartAbilityUtils::ermsSupportBackToCallerFlag = false;
1802 
1803     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
1804     if (specifyTokenId > 0) {
1805         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
1806         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
1807         abilityRequest.specifyTokenId = specifyTokenId;
1808     }
1809     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
1810     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
1811         abilityRequest.userId = oriValidUserId;
1812         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
1813         abilityRequest.processOptions = startOptions.processOptions;
1814         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
1815         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
1816         return uiAbilityManager->NotifySCBToStartUIAbility(abilityRequest);
1817     }
1818     auto missionListManager = GetMissionListManagerByUserId(oriValidUserId);
1819     if (missionListManager == nullptr) {
1820         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", oriValidUserId);
1821         eventInfo.errCode = ERR_INVALID_VALUE;
1822         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1823         return ERR_INVALID_VALUE;
1824     }
1825 
1826     auto ret = missionListManager->StartAbility(abilityRequest);
1827     if (ret != ERR_OK) {
1828         eventInfo.errCode = ret;
1829         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
1830     }
1831     return ret;
1832 }
1833 
RequestDialogService(const Want & want,const sptr<IRemoteObject> & callerToken)1834 int32_t AbilityManagerService::RequestDialogService(const Want &want, const sptr<IRemoteObject> &callerToken)
1835 {
1836     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1837     auto flags = want.GetFlags();
1838     if ((flags & Want::FLAG_ABILITY_CONTINUATION) == Want::FLAG_ABILITY_CONTINUATION) {
1839         TAG_LOGE(AAFwkTag::ABILITYMGR, "RequestDialogService with continuation flags is not allowed!");
1840         return ERR_INVALID_CONTINUATION_FLAG;
1841     }
1842 
1843     TAG_LOGI(AAFwkTag::ABILITYMGR, "request dialog service, target is %{public}s", want.GetElement().GetURI().c_str());
1844     return RequestDialogServiceInner(want, callerToken, -1, -1);
1845 }
1846 
ReportDrawnCompleted(const sptr<IRemoteObject> & callerToken)1847 int32_t AbilityManagerService::ReportDrawnCompleted(const sptr<IRemoteObject> &callerToken)
1848 {
1849     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
1850     if (callerToken == nullptr) {
1851         TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken is nullptr");
1852         return INNER_ERR;
1853     }
1854 
1855     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
1856     if (abilityRecord == nullptr) {
1857         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr");
1858         return INNER_ERR;
1859     }
1860     auto abilityInfo = abilityRecord->GetAbilityInfo();
1861 
1862     EventInfo eventInfo;
1863     eventInfo.userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
1864     eventInfo.pid = IPCSkeleton::GetCallingPid();
1865     eventInfo.bundleName = abilityInfo.bundleName;
1866     eventInfo.moduleName = abilityInfo.moduleName;
1867     eventInfo.abilityName = abilityInfo.name;
1868     EventReport::SendAppEvent(EventName::DRAWN_COMPLETED, HiSysEventType::BEHAVIOR, eventInfo);
1869     return ERR_OK;
1870 }
1871 
RequestDialogServiceInner(const Want & want,const sptr<IRemoteObject> & callerToken,int requestCode,int32_t userId)1872 int32_t AbilityManagerService::RequestDialogServiceInner(const Want &want, const sptr<IRemoteObject> &callerToken,
1873     int requestCode, int32_t userId)
1874 {
1875     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1876     if (callerToken == nullptr || !VerificationAllToken(callerToken)) {
1877         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller is invalid.");
1878         return ERR_INVALID_CALLER;
1879     }
1880 
1881     {
1882 #ifdef WITH_DLP
1883         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "CHECK_DLP");
1884         if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
1885             !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
1886             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed.", __func__);
1887             return CHECK_PERMISSION_FAILED;
1888         }
1889 
1890         if (AbilityUtil::HandleDlpApp(const_cast<Want &>(want))) {
1891             TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot handle dlp by RequestDialogService.");
1892             return ERR_WRONG_INTERFACE_CALL;
1893         }
1894 #endif // WITH_DLP
1895     }
1896 
1897     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
1898     int32_t validUserId = GetValidUserId(userId);
1899     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
1900         true, nullptr);
1901     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
1902         interceptorExecuter_->DoProcess(interceptorParam);
1903     if (result != ERR_OK) {
1904         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
1905         return result;
1906     }
1907 
1908     if (!JudgeMultiUserConcurrency(validUserId)) {
1909         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
1910         return ERR_CROSS_USER;
1911     }
1912     AbilityRequest abilityRequest;
1913     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
1914     if (result != ERR_OK) {
1915         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error when RequestDialogService.");
1916         return result;
1917     }
1918     UpdateCallerInfo(abilityRequest.want, callerToken);
1919 
1920     auto abilityInfo = abilityRequest.abilityInfo;
1921     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
1922     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
1923         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
1924 
1925     result = CheckStaticCfgPermission(abilityRequest, false, -1);
1926     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
1927         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
1928         return ERR_STATIC_CFG_PERMISSION;
1929     }
1930 
1931     auto type = abilityInfo.type;
1932     if (type == AppExecFwk::AbilityType::EXTENSION &&
1933         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
1934         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check call ability permission, name is %{public}s.", abilityInfo.name.c_str());
1935         result = CheckCallServicePermission(abilityRequest);
1936         if (result != ERR_OK) {
1937             TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed");
1938             return result;
1939         }
1940     } else {
1941         TAG_LOGE(AAFwkTag::ABILITYMGR, "RequestDialogService do not support other component.");
1942         return ERR_WRONG_INTERFACE_CALL;
1943     }
1944 
1945     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, requestCode,
1946         GetUserId(), true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
1947     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
1948         afterCheckExecuter_->DoProcess(afterCheckParam);
1949     if (result != ERR_OK) {
1950         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
1951         return result;
1952     }
1953 
1954     auto connectManager = GetConnectManagerByUserId(validUserId);
1955     if (!connectManager) {
1956         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
1957         return ERR_INVALID_VALUE;
1958     }
1959     TAG_LOGD(AAFwkTag::ABILITYMGR,
1960         "request dialog service, start service extension,name is %{public}s.", abilityInfo.name.c_str());
1961     ReportEventToRSS(abilityInfo, callerToken);
1962     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
1963         abilityRequest.abilityInfo.extensionAbilityType);
1964     return connectManager->StartAbility(abilityRequest);
1965 }
1966 
OpenAtomicService(AAFwk::Want & want,const StartOptions & options,sptr<IRemoteObject> callerToken,int32_t requestCode,int32_t userId)1967 int32_t AbilityManagerService::OpenAtomicService(AAFwk::Want& want, const StartOptions &options,
1968     sptr<IRemoteObject> callerToken, int32_t requestCode, int32_t userId)
1969 {
1970     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
1971     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
1972     if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
1973         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is not hap.");
1974         return CHECK_PERMISSION_FAILED;
1975     }
1976     want.SetParam(AAFwk::SCREEN_MODE_KEY, AAFwk::ScreenMode::JUMP_SCREEN_MODE);
1977     return StartUIAbilityForOptionWrap(want, options, callerToken, false, userId, requestCode);
1978 }
1979 
StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo,bool & isColdStart,uint32_t sceneFlag)1980 int AbilityManagerService::StartUIAbilityBySCB(sptr<SessionInfo> sessionInfo, bool &isColdStart, uint32_t sceneFlag)
1981 {
1982     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1983     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call, sceneFlag: %{public}u", sceneFlag);
1984     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
1985         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
1986         return ERR_INVALID_VALUE;
1987     }
1988 
1989     if (!IsCallerSceneBoard()) {
1990         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
1991         return ERR_WRONG_INTERFACE_CALL;
1992     }
1993 
1994     if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
1995         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
1996     }
1997 
1998     std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
1999     if (sessionId.empty()) {
2000         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2001     }
2002 
2003     TAG_LOGI(AAFwkTag::ABILITYMGR, "sessionId=%{public}s", sessionId.c_str());
2004 
2005     if (freeInstallManager_ == nullptr) {
2006         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
2007         return ERR_INVALID_VALUE;
2008     }
2009     FreeInstallInfo taskInfo;
2010     if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
2011         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed to find free install task");
2012         if ((sessionInfo->want).GetElement().GetAbilityName().empty() ||
2013             (sessionInfo->want).GetElement().GetModuleName().empty()) {
2014             auto bundleMgrHelper = AbilityUtil::GetBundleManagerHelper();
2015             CHECK_POINTER_AND_RETURN(bundleMgrHelper, ERR_INVALID_VALUE);
2016             Want launchWant;
2017             auto errCode = IN_PROCESS_CALL(bundleMgrHelper->GetLaunchWantForBundle(
2018                 (sessionInfo->want).GetBundle(), launchWant, GetValidUserId(sessionInfo->userId)));
2019             if (errCode != ERR_OK) {
2020                 TAG_LOGE(AAFwkTag::ABILITYMGR, "GetLaunchWantForBundle returns %{public}d.", errCode);
2021                 return errCode;
2022             }
2023             (sessionInfo->want).SetElement(launchWant.GetElement());
2024         }
2025         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2026         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2027         if (uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo) == nullptr) {
2028             TAG_LOGI(AAFwkTag::ABILITYMGR, "first time open");
2029             auto err = StartUIAbilityByPreInstallInner(sessionInfo, 0, sceneFlag, isColdStart);
2030             if (err != ERR_OK) {
2031                 TAG_LOGE(AAFwkTag::ABILITYMGR, "startUIAbilityByPreInstallInner failed");
2032             }
2033             return err;
2034         }
2035         return StartUIAbilityBySCBDefault(sessionInfo, sceneFlag, isColdStart);
2036     }
2037 
2038     if (taskInfo.isFreeInstallFinished) {
2039         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task is already finished");
2040         if (!taskInfo.isInstalled) {
2041             TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
2042                 taskInfo.resultCode);
2043             return taskInfo.resultCode;
2044         }
2045         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install succeeds");
2046         auto err = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, sceneFlag, isColdStart);
2047         if (err != ERR_OK) {
2048             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilityByPreInstallInner failed.");
2049         }
2050         return err;
2051     }
2052 
2053     {
2054         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
2055         preStartSessionMap_[sessionId] = sessionInfo;
2056     }
2057 
2058     TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task is still in progress");
2059     const Want& want = sessionInfo->want;
2060     freeInstallManager_->SetSCBCallStatus(want.GetElement().GetBundleName(), want.GetElement().GetAbilityName(),
2061         want.GetStringParam(Want::PARAM_RESV_START_TIME), true);
2062     return ERR_OK;
2063 }
2064 
StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2065 int AbilityManagerService::StartUIAbilityBySCBDefault(sptr<SessionInfo> sessionInfo, uint32_t sceneFlag,
2066     bool &isColdStart)
2067 {
2068     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2069     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
2070 
2071     auto currentUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2072     if (sessionInfo->userId == DEFAULT_INVAL_VALUE) {
2073         sessionInfo->userId = currentUserId;
2074     }
2075 
2076     (sessionInfo->want).RemoveParam(AAFwk::SCREEN_MODE_KEY);
2077     EventInfo eventInfo = BuildEventInfo(sessionInfo->want, currentUserId);
2078     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
2079 
2080     auto requestCode = sessionInfo->requestCode;
2081     int32_t appIndex = 0;
2082     if (!StartAbilityUtils::GetAppIndex(sessionInfo->want, sessionInfo->callerToken, appIndex)) {
2083         return ERR_APP_CLONE_INDEX_INVALID;
2084     }
2085     StartAbilityInfoWrap threadLocalInfo(sessionInfo->want, currentUserId, appIndex, sessionInfo->callerToken);
2086     if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2087         TAG_LOGD(AAFwkTag::ABILITYMGR, "interceptorExecuter_ called");
2088         AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(sessionInfo->want, requestCode,
2089             currentUserId, true, nullptr);
2090         auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2091         interceptorExecuter_->DoProcess(interceptorParam);
2092         if (result != ERR_OK) {
2093             TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
2094             eventInfo.errCode = result;
2095             SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2096             return result;
2097         }
2098     }
2099 
2100     AbilityRequest abilityRequest;
2101     auto result = GenerateAbilityRequest(sessionInfo->want, requestCode, abilityRequest,
2102         sessionInfo->callerToken, currentUserId);
2103     if (result != ERR_OK) {
2104         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
2105         return result;
2106     }
2107     abilityRequest.collaboratorType = sessionInfo->collaboratorType;
2108     uint32_t specifyTokenId = static_cast<uint32_t>(sessionInfo->want.GetIntParam(SPECIFY_TOKEN_ID, 0));
2109     (sessionInfo->want).RemoveParam(SPECIFY_TOKEN_ID);
2110     abilityRequest.specifyTokenId = specifyTokenId;
2111 
2112     auto abilityInfo = abilityRequest.abilityInfo;
2113     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall() &&
2114         abilityInfo.type != AppExecFwk::AbilityType::PAGE) {
2115         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support for page type ability.");
2116         return ERR_INVALID_VALUE;
2117     }
2118 
2119     if (sessionInfo->want.GetBoolParam(IS_CALL_BY_SCB, true)) {
2120         TAG_LOGD(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ called");
2121         Want newWant = abilityRequest.want;
2122         AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(), true,
2123             sessionInfo->callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2124         result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2125             afterCheckExecuter_->DoProcess(afterCheckParam);
2126         bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
2127         newWant.RemoveParam("queryWantFromErms");
2128         if (result != ERR_OK) {
2129             if (isReplaceWantExist == false) {
2130                 TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
2131                 return result;
2132             }
2133             return DialogSessionManager::GetInstance().HandleErmsResultBySCB(abilityRequest, newWant);
2134         }
2135     }
2136 
2137     return StartUIAbilityBySCBDefaultCommon(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2138 }
2139 
StartUIAbilityBySCBDefaultCommon(AbilityRequest & abilityRequest,sptr<SessionInfo> sessionInfo,uint32_t sceneFlag,bool & isColdStart)2140 int32_t AbilityManagerService::StartUIAbilityBySCBDefaultCommon(AbilityRequest &abilityRequest,
2141     sptr<SessionInfo> sessionInfo, uint32_t sceneFlag, bool &isColdStart)
2142 {
2143     auto abilityInfo = abilityRequest.abilityInfo;
2144     if (!AbilityUtil::IsSystemDialogAbility(abilityInfo.bundleName, abilityInfo.name)) {
2145         int32_t result = PreLoadAppDataAbilities(abilityInfo.bundleName, IPCSkeleton::GetCallingUid() / BASE_USER_RANGE);
2146         if (result != ERR_OK) {
2147             TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility: App data ability preloading failed, '%{public}s', %{public}d",
2148                 abilityInfo.bundleName.c_str(), result);
2149             return result;
2150         }
2151     }
2152 
2153     ReportAbilityStartInfoToRSS(abilityInfo);
2154     ReportAbilityAssociatedStartInfoToRSS(abilityInfo, RES_TYPE_SCB_START_ABILITY, sessionInfo->callerToken);
2155     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2156     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2157     return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
2158 }
2159 
NotifySCBToRecoveryAfterInterception(const AbilityRequest & abilityRequest)2160 int32_t AbilityManagerService::NotifySCBToRecoveryAfterInterception(const AbilityRequest &abilityRequest)
2161 {
2162     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2163     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2164     return uiAbilityManager->NotifySCBToRecoveryAfterInterception(abilityRequest);
2165 }
2166 
CheckCallingTokenId(const std::string & bundleName,int32_t userId,int32_t appIndex)2167 bool AbilityManagerService::CheckCallingTokenId(const std::string &bundleName, int32_t userId, int32_t appIndex)
2168 {
2169     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2170     auto bundleMgrHelper = DelayedSingleton<AppExecFwk::BundleMgrHelper>::GetInstance();
2171     CHECK_POINTER_AND_RETURN(bundleMgrHelper, false);
2172     auto validUserId = GetValidUserId(userId);
2173     AppExecFwk::ApplicationInfo appInfo;
2174     IN_PROCESS_CALL_WITHOUT_RET(bundleMgrHelper->GetApplicationInfoWithAppIndex(bundleName,
2175         appIndex, validUserId, appInfo));
2176     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
2177     if (accessTokenId != appInfo.accessTokenId) {
2178         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
2179         return false;
2180     }
2181     return true;
2182 }
2183 
IsCallerSceneBoard()2184 bool AbilityManagerService::IsCallerSceneBoard()
2185 {
2186     int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
2187     auto connectManager = GetConnectManagerByUserId(userId);
2188     CHECK_POINTER_AND_RETURN(connectManager, false);
2189     auto sceneBoardTokenId = connectManager->GetSceneBoardTokenId();
2190     if (sceneBoardTokenId != 0 && IPCSkeleton::GetCallingTokenID() == sceneBoardTokenId) {
2191         return true;
2192     }
2193     return false;
2194 }
2195 
IsBackgroundTaskUid(const int uid)2196 bool AbilityManagerService::IsBackgroundTaskUid(const int uid)
2197 {
2198 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2199     std::lock_guard<ffrt::mutex> lock(bgtaskObserverMutex_);
2200     if (bgtaskObserver_) {
2201         return bgtaskObserver_->IsBackgroundTaskUid(uid);
2202     }
2203     return false;
2204 #else
2205     return false;
2206 #endif
2207 }
2208 
IsDmsAlive() const2209 bool AbilityManagerService::IsDmsAlive() const
2210 {
2211     return g_isDmsAlive.load();
2212 }
2213 
AppUpgradeCompleted(const std::string & bundleName,int32_t uid)2214 void AbilityManagerService::AppUpgradeCompleted(const std::string &bundleName, int32_t uid)
2215 {
2216     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2217         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sa call");
2218         return;
2219     }
2220 
2221     auto bms = GetBundleManager();
2222     CHECK_POINTER(bms);
2223     auto userId = uid / BASE_USER_RANGE;
2224     if (userId != U0_USER_ID && userId != GetUserId()) {
2225         TAG_LOGI(AAFwkTag::ABILITYMGR, "not current user");
2226         return;
2227     }
2228 
2229     AppExecFwk::BundleInfo bundleInfo;
2230     if (!IN_PROCESS_CALL(
2231         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId))) {
2232         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info.");
2233         return;
2234     }
2235 
2236     bool keepAliveEnable = bundleInfo.isKeepAlive;
2237     AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleInfo.name, keepAliveEnable);
2238     if (!keepAliveEnable) {
2239         TAG_LOGW(AAFwkTag::ABILITYMGR, "Not a resident application.");
2240         return;
2241     }
2242 
2243     std::vector<AppExecFwk::BundleInfo> bundleInfos = { bundleInfo };
2244     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId);
2245 
2246     if (!bundleInfos.empty()) {
2247         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
2248     }
2249 }
2250 
RecordAppExitReason(const ExitReason & exitReason)2251 int32_t AbilityManagerService::RecordAppExitReason(const ExitReason &exitReason)
2252 {
2253     TAG_LOGI(AAFwkTag::ABILITYMGR, "RecordAppExitReason reason:%{public}d, exitMsg: %{public}s", exitReason.reason,
2254         exitReason.exitMsg.c_str());
2255 
2256     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2257     return appExitReasonHelper_->RecordAppExitReason(exitReason);
2258 }
2259 
RecordProcessExitReason(const int32_t pid,const ExitReason & exitReason)2260 int32_t AbilityManagerService::RecordProcessExitReason(const int32_t pid, const ExitReason &exitReason)
2261 {
2262     TAG_LOGI(AAFwkTag::ABILITYMGR, "RecordProcessExitReason pid:%{public}d, reason:%{public}d, exitMsg: %{public}s",
2263         pid, exitReason.reason, exitReason.exitMsg.c_str());
2264 
2265     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
2266         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sa call");
2267         return ERR_PERMISSION_DENIED;
2268     }
2269 
2270     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2271     return appExitReasonHelper_->RecordProcessExitReason(pid, exitReason);
2272 }
2273 
ForceExitApp(const int32_t pid,const ExitReason & exitReason)2274 int32_t AbilityManagerService::ForceExitApp(const int32_t pid, const ExitReason &exitReason)
2275 {
2276     TAG_LOGI(AAFwkTag::ABILITYMGR, "ForceExitApp pid:%{public}d, reason:%{public}d, exitMsg: %{public}s",
2277         pid, exitReason.reason, exitReason.exitMsg.c_str());
2278 
2279     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
2280         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
2281         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sa or shell call");
2282         return ERR_PERMISSION_DENIED;
2283     }
2284 
2285     AppExecFwk::ApplicationInfo application;
2286     bool debug = false;
2287     auto ret = IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->GetApplicationInfoByProcessID(pid,
2288         application, debug));
2289     if (ret != ERR_OK) {
2290         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetApplicationInfoByProcessID failed.");
2291         return ret;
2292     }
2293 
2294     std::string bundleName = application.bundleName;
2295     int32_t uid = application.uid;
2296     int32_t appIndex = application.appIndex;
2297 
2298     CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
2299     appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
2300 
2301     return DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName);
2302 }
2303 
GetConfiguration(AppExecFwk::Configuration & config)2304 int32_t AbilityManagerService::GetConfiguration(AppExecFwk::Configuration& config)
2305 {
2306     auto appMgr = GetAppMgr();
2307     if (appMgr == nullptr) {
2308         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
2309         return -1;
2310     }
2311 
2312     return appMgr->GetConfiguration(config);
2313 }
2314 
GetAppMgr()2315 OHOS::sptr<OHOS::AppExecFwk::IAppMgr> AbilityManagerService::GetAppMgr()
2316 {
2317     if (appMgr_) {
2318         return appMgr_;
2319     }
2320 
2321     OHOS::sptr<OHOS::ISystemAbilityManager> systemAbilityManager =
2322         OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
2323     if (!systemAbilityManager) {
2324         return nullptr;
2325     }
2326     OHOS::sptr<OHOS::IRemoteObject> object = systemAbilityManager->GetSystemAbility(OHOS::APP_MGR_SERVICE_ID);
2327     appMgr_ = OHOS::iface_cast<OHOS::AppExecFwk::IAppMgr>(object);
2328     return appMgr_;
2329 }
2330 
CheckOptExtensionAbility(const Want & want,AbilityRequest & abilityRequest,int32_t validUserId,AppExecFwk::ExtensionAbilityType extensionType,bool isImplicit,bool isStartAsCaller)2331 int AbilityManagerService::CheckOptExtensionAbility(const Want &want, AbilityRequest &abilityRequest,
2332     int32_t validUserId, AppExecFwk::ExtensionAbilityType extensionType, bool isImplicit, bool isStartAsCaller)
2333 {
2334     auto abilityInfo = abilityRequest.abilityInfo;
2335     auto type = abilityInfo.type;
2336     if (type != AppExecFwk::AbilityType::EXTENSION) {
2337         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not extension ability, not allowed.");
2338         return ERR_WRONG_INTERFACE_CALL;
2339     }
2340     if (extensionType != AppExecFwk::ExtensionAbilityType::UNSPECIFIED &&
2341         extensionType != abilityInfo.extensionAbilityType) {
2342         TAG_LOGE(AAFwkTag::ABILITYMGR, "Extension ability type not match, set type: %{public}d, real type: %{public}d",
2343             static_cast<int32_t>(extensionType), static_cast<int32_t>(abilityInfo.extensionAbilityType));
2344         return ERR_WRONG_INTERFACE_CALL;
2345     }
2346 
2347     auto result = CheckStaticCfgPermission(abilityRequest, false, -1, false, false, isImplicit);
2348     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
2349         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
2350         return ERR_STATIC_CFG_PERMISSION;
2351     }
2352 
2353     if (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
2354         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
2355         result = CheckCallServiceExtensionPermission(abilityRequest);
2356         if (result != ERR_OK) {
2357             return result;
2358         }
2359     } else {
2360         result = CheckCallOtherExtensionPermission(abilityRequest);
2361         if (result != ERR_OK) {
2362             return result;
2363         }
2364     }
2365     if (!isStartAsCaller) {
2366         UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
2367     }
2368     return ERR_OK;
2369 }
2370 
OnAddSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2371 void AbilityManagerService::OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2372 {
2373     TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d add", systemAbilityId);
2374     switch (systemAbilityId) {
2375         case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2376             SubscribeBackgroundTask();
2377             break;
2378         }
2379         case DISTRIBUTED_SCHED_SA_ID: {
2380             g_isDmsAlive.store(true);
2381             break;
2382         }
2383         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2384             SubscribeBundleEventCallback();
2385             break;
2386         }
2387 #ifdef SUPPORT_SCREEN
2388         case MULTIMODAL_INPUT_SERVICE_ID: {
2389             auto anrListener = std::make_shared<ApplicationAnrListener>();
2390             MMI::InputManager::GetInstance()->SetAnrObserver(anrListener);
2391             break;
2392         }
2393 #endif
2394         default:
2395             break;
2396     }
2397 }
2398 
OnRemoveSystemAbility(int32_t systemAbilityId,const std::string & deviceId)2399 void AbilityManagerService::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId)
2400 {
2401     TAG_LOGI(AAFwkTag::ABILITYMGR, "systemAbilityId: %{public}d remove", systemAbilityId);
2402     switch (systemAbilityId) {
2403         case BACKGROUND_TASK_MANAGER_SERVICE_ID: {
2404             UnSubscribeBackgroundTask();
2405             break;
2406         }
2407         case DISTRIBUTED_SCHED_SA_ID: {
2408             g_isDmsAlive.store(false);
2409             break;
2410         }
2411         case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: {
2412             UnsubscribeBundleEventCallback();
2413             break;
2414         }
2415         default:
2416             break;
2417     }
2418 }
2419 
SubscribeBackgroundTask()2420 void AbilityManagerService::SubscribeBackgroundTask()
2421 {
2422 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2423     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2424     if (!bgtaskObserver_) {
2425         bgtaskObserver_ = std::make_shared<BackgroundTaskObserver>();
2426     }
2427     int ret = BackgroundTaskMgrHelper::SubscribeBackgroundTask(*bgtaskObserver_);
2428     if (ret != ERR_OK) {
2429         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s failed, err:%{public}d.", __func__, ret);
2430         return;
2431     }
2432     bgtaskObserver_->GetContinuousTaskApps();
2433     bgtaskObserver_->GetEfficiencyResourcesTaskApps();
2434     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success.", __func__);
2435 #endif
2436 }
2437 
UnSubscribeBackgroundTask()2438 void AbilityManagerService::UnSubscribeBackgroundTask()
2439 {
2440 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2441     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2442     if (!bgtaskObserver_) {
2443         return;
2444     }
2445     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s success.", __func__);
2446 #endif
2447 }
2448 
SubscribeBundleEventCallback()2449 void AbilityManagerService::SubscribeBundleEventCallback()
2450 {
2451     TAG_LOGI(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback begin.");
2452     if (taskHandler_) {
2453         TAG_LOGI(AAFwkTag::ABILITYMGR, "submit startResidentApps task");
2454         auto startResidentAppsTask = [aams = shared_from_this()]() { aams->StartResidentApps(U0_USER_ID); };
2455         taskHandler_->SubmitTask(startResidentAppsTask, "StartResidentApps");
2456     }
2457 
2458     if (abilityBundleEventCallback_) {
2459         return;
2460     }
2461 
2462     // Register abilityBundleEventCallback to receive hap updates
2463     abilityBundleEventCallback_ =
2464         new (std::nothrow) AbilityBundleEventCallback(taskHandler_, abilityAutoStartupService_);
2465     auto bms = GetBundleManager();
2466     if (bms) {
2467         bool ret = IN_PROCESS_CALL(bms->RegisterBundleEventCallback(abilityBundleEventCallback_));
2468         if (!ret) {
2469             TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterBundleEventCallback failed!");
2470         }
2471     } else {
2472         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get BundleManager failed!");
2473     }
2474     TAG_LOGD(AAFwkTag::ABILITYMGR, "SubscribeBundleEventCallback success.");
2475 }
2476 
UnsubscribeBundleEventCallback()2477 void AbilityManagerService::UnsubscribeBundleEventCallback()
2478 {
2479     if (!abilityBundleEventCallback_) {
2480         return;
2481     }
2482     abilityBundleEventCallback_ = nullptr;
2483     TAG_LOGD(AAFwkTag::ABILITYMGR, "UnsubscribeBundleEventCallback success.");
2484 }
2485 
ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo)2486 void AbilityManagerService::ReportAbilityStartInfoToRSS(const AppExecFwk::AbilityInfo &abilityInfo)
2487 {
2488     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2489     if (abilityInfo.type == AppExecFwk::AbilityType::PAGE &&
2490         abilityInfo.launchMode != AppExecFwk::LaunchMode::SPECIFIED) {
2491         std::vector<AppExecFwk::RunningProcessInfo> runningProcessInfos;
2492         if (IN_PROCESS_CALL(GetProcessRunningInfos(runningProcessInfos)) != ERR_OK) {
2493             return;
2494         }
2495         bool isColdStart = true;
2496         int32_t pid = 0;
2497         for (auto const &info : runningProcessInfos) {
2498             if (info.uid_ == abilityInfo.applicationInfo.uid) {
2499                 isColdStart = false;
2500                 pid = info.pid_;
2501                 break;
2502             }
2503         }
2504         ResSchedUtil::GetInstance().ReportAbilityStartInfoToRSS(abilityInfo, pid, isColdStart);
2505     }
2506 }
2507 
ReportAbilityAssociatedStartInfoToRSS(const AppExecFwk::AbilityInfo & abilityInfo,int64_t type,const sptr<IRemoteObject> & callerToken)2508 void AbilityManagerService::ReportAbilityAssociatedStartInfoToRSS(
2509     const AppExecFwk::AbilityInfo &abilityInfo, int64_t type, const sptr<IRemoteObject> &callerToken)
2510 {
2511     CHECK_POINTER_LOG(callerToken, "associated start caller token is nullptr");
2512     auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2513     CHECK_POINTER_LOG(callerAbility, "associated start caller ability is nullptr");
2514     int32_t callerUid = callerAbility->GetUid();
2515     int32_t callerPid = callerAbility->GetPid();
2516     ResSchedUtil::GetInstance().ReportAbilityAssociatedStartInfoToRSS(abilityInfo, type, callerUid, callerPid);
2517 }
2518 
ReportEventToRSS(const AppExecFwk::AbilityInfo & abilityInfo,sptr<IRemoteObject> callerToken)2519 void AbilityManagerService::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo,
2520     sptr<IRemoteObject> callerToken)
2521 {
2522     CHECK_POINTER_LOG(taskHandler_, "taskhandler null");
2523     std::string reason;
2524     if (abilityInfo.type == AppExecFwk::AbilityType::PAGE) {
2525         reason = "THAW_BY_START_PAGE_ABILITY";
2526     } else if (abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
2527                abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE) {
2528         reason = "THAW_BY_START_SERVICE_EXTENSION";
2529     } else if (abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
2530                AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo.extensionAbilityType)) {
2531         reason = "THAW_BY_START_UI_EXTENSION";
2532     } else {
2533         reason = "THAW_BY_START_NOT_PAGE_ABILITY";
2534     }
2535     const auto uid = abilityInfo.applicationInfo.uid;
2536     const auto bundleName = abilityInfo.applicationInfo.bundleName;
2537     auto callerAbility = Token::GetAbilityRecordByToken(callerToken);
2538     const int32_t callerPid = (callerAbility != nullptr) ? callerAbility->GetPid() : IPCSkeleton::GetCallingPid();
2539     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}d_%{public}s reason=%{public}s callerPid=%{public}d", uid,
2540         bundleName.c_str(), reason.c_str(), callerPid);
2541     taskHandler_->SubmitTask([reason, uid, bundleName, callerPid]() {
2542         ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason, callerPid);
2543     });
2544 }
2545 
StartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2546 int AbilityManagerService::StartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2547     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2548 {
2549     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2550     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2551     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
2552         return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false);
2553     }
2554     return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true);
2555 }
2556 
ImplicitStartExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)2557 int AbilityManagerService::ImplicitStartExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
2558     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
2559 {
2560     InsightIntentExecuteParam::RemoveInsightIntent(const_cast<Want &>(want));
2561     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
2562         return StartExtensionAbilityInner(want, callerToken, userId, extensionType, false, true);
2563     }
2564     return StartExtensionAbilityInner(want, callerToken, userId, extensionType, true, true);
2565 }
2566 
PreloadUIExtensionAbility(const Want & want,std::string & bundleName,int32_t userId)2567 int AbilityManagerService::PreloadUIExtensionAbility(const Want &want, std::string &bundleName, int32_t userId)
2568 {
2569     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
2570     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2571     // check preload ui extension permission.
2572     CHECK_CALLER_IS_SYSTEM_APP;
2573     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
2574         PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY)) {
2575         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
2576             PermissionConstants::PERMISSION_PRELOAD_UI_EXTENSION_ABILITY);
2577         return ERR_PERMISSION_DENIED;
2578     }
2579     return PreloadUIExtensionAbilityInner(want, bundleName, userId);
2580 }
2581 
PreloadUIExtensionAbilityInner(const Want & want,std::string & hostBundleName,int32_t userId)2582 int AbilityManagerService::PreloadUIExtensionAbilityInner(const Want &want, std::string &hostBundleName, int32_t userId)
2583 {
2584     TAG_LOGD(AAFwkTag::ABILITYMGR, "Preload ui extension called, elementName: %{public}s.",
2585         want.GetElement().GetURI().c_str());
2586     int32_t validUserId = GetValidUserId(userId);
2587     AbilityRequest abilityRequest;
2588     ErrCode result = ERR_OK;
2589     result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, validUserId);
2590     if (result != ERR_OK) {
2591         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
2592         return result;
2593     }
2594     abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
2595     abilityRequest.want.SetParam(IS_PRELOAD_UIEXTENSION_ABILITY, true);
2596     auto abilityInfo = abilityRequest.abilityInfo;
2597     auto res = JudgeAbilityVisibleControl(abilityInfo);
2598     if (res != ERR_OK) {
2599         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is invisible");
2600         return res;
2601     }
2602     auto connectManager = GetConnectManagerByUserId(validUserId);
2603     if (connectManager == nullptr) {
2604         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", validUserId);
2605         return ERR_INVALID_VALUE;
2606     }
2607     return connectManager->PreloadUIExtensionAbilityLocked(abilityRequest, hostBundleName);
2608 }
2609 
UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> & abilityRecord,std::string & hostBundleName)2610 int AbilityManagerService::UnloadUIExtensionAbility(const std::shared_ptr<AAFwk::AbilityRecord> &abilityRecord,
2611     std::string &hostBundleName)
2612 {
2613     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call.");
2614     auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
2615     if (connectManager == nullptr) {
2616         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr.");
2617         return ERR_INVALID_VALUE;
2618     }
2619     return connectManager->UnloadUIExtensionAbility(abilityRecord, hostBundleName);
2620 }
2621 
RequestModalUIExtension(const Want & want)2622 int AbilityManagerService::RequestModalUIExtension(const Want &want)
2623 {
2624     CHECK_CALLER_IS_SYSTEM_APP;
2625     return RequestModalUIExtensionInner(want);
2626 }
2627 
RequestModalUIExtensionInner(Want want)2628 int AbilityManagerService::RequestModalUIExtensionInner(Want want)
2629 {
2630     sptr<IRemoteObject> token = nullptr;
2631     int ret = IN_PROCESS_CALL(GetTopAbility(token));
2632     if (ret == ERR_OK && token != nullptr) {
2633         // Gets the record corresponding to the current focus appliaction
2634         auto record = Token::GetAbilityRecordByToken(token);
2635         if (!record) {
2636             TAG_LOGE(AAFwkTag::ABILITYMGR, "Record is nullptr.");
2637             return ERR_INVALID_VALUE;
2638         }
2639 
2640         // Gets the bundleName corresponding to the
2641         // current focus appliaction
2642         std::string focusName = record->GetAbilityInfo().bundleName;
2643 
2644         // Gets the bundleName corresponding to the
2645         // current focus appliaction
2646         std::string callerName = want.GetParams().GetStringParam("bundleName");
2647 
2648         TAG_LOGI(AAFwkTag::ABILITYMGR,
2649                "focusbundlename: %{public}s, callerbundlename: %{public}s.",
2650                focusName.c_str(), callerName.c_str());
2651 
2652         // Compare
2653         if (record->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE &&
2654             focusName == callerName) {
2655             TAG_LOGD(AAFwkTag::ABILITYMGR, "CreateModalUIExtension is called!");
2656             return record->CreateModalUIExtension(want);
2657         }
2658     } else {
2659         TAG_LOGW(AAFwkTag::ABILITYMGR, "token is nullptr.");
2660     }
2661 
2662     TAG_LOGD(AAFwkTag::ABILITYMGR, "Window Modal System Create UIExtension is called!");
2663     want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
2664     auto connection = std::make_shared<Rosen::ModalSystemUiExtension>();
2665     return connection->CreateModalUIExtension(want) ? ERR_OK : INNER_ERR;
2666 }
2667 
ChangeAbilityVisibility(sptr<IRemoteObject> token,bool isShow)2668 int AbilityManagerService::ChangeAbilityVisibility(sptr<IRemoteObject> token, bool isShow)
2669 {
2670     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
2671     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
2672         TAG_LOGE(AAFwkTag::ABILITYMGR, "Capability not support.");
2673         return ERR_CAPABILITY_NOT_SUPPORT;
2674     }
2675     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2676     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2677     return uiAbilityManager->ChangeAbilityVisibility(token, isShow);
2678 }
2679 
ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo,bool isShow)2680 int AbilityManagerService::ChangeUIAbilityVisibilityBySCB(sptr<SessionInfo> sessionInfo, bool isShow)
2681 {
2682     if (!IsCallerSceneBoard()) {
2683         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
2684         return ERR_WRONG_INTERFACE_CALL;
2685     }
2686     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
2687     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
2688     return uiAbilityManager->ChangeUIAbilityVisibilityBySCB(sessionInfo, isShow);
2689 }
2690 
CheckWorkSchedulerPermission(const sptr<IRemoteObject> & callerToken,const uint32_t uid)2691 bool AbilityManagerService::CheckWorkSchedulerPermission(const sptr<IRemoteObject> &callerToken, const uint32_t uid)
2692 {
2693 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
2694     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
2695     std::unique_lock<ffrt::mutex> lock(bgtaskObserverMutex_);
2696     if (bgtaskObserver_ && abilityRecord) {
2697         auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
2698         if (callerAbilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::WORK_SCHEDULER) {
2699             return true;
2700         }
2701 
2702         if (!bgtaskObserver_->IsEfficiencyResourcesTaskUid(uid)) {
2703             TAG_LOGE(AAFwkTag::ABILITYMGR, "no permission to start extension by WorkScheduler");
2704             return false;
2705         }
2706     }
2707 #endif
2708     return true;
2709 }
2710 
StartExtensionAbilityInner(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType,bool checkSystemCaller,bool isImplicit,bool isDlp,bool isStartAsCaller)2711 int AbilityManagerService::StartExtensionAbilityInner(const Want &want, const sptr<IRemoteObject> &callerToken,
2712     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType, bool checkSystemCaller, bool isImplicit,
2713     bool isDlp, bool isStartAsCaller)
2714 {
2715     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2716     TAG_LOGI(AAFwkTag::ABILITYMGR,
2717         "Start extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
2718         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
2719     if (checkSystemCaller) {
2720         CHECK_CALLER_IS_SYSTEM_APP;
2721     }
2722     EventInfo eventInfo = BuildEventInfo(want, userId);
2723     eventInfo.extensionType = static_cast<int32_t>(extensionType);
2724 
2725     int result;
2726 #ifdef WITH_DLP
2727     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::START_EXTENSION_ERROR);
2728     if (result != ERR_OK) {
2729         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
2730         return result;
2731     }
2732 #endif // WITH_DLP
2733 
2734     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
2735         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
2736         eventInfo.errCode = ERR_INVALID_VALUE;
2737         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2738         return ERR_INVALID_CALLER;
2739     }
2740 
2741     int32_t validUserId = GetValidUserId(userId);
2742     int32_t appIndex = 0;
2743     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
2744         return ERR_APP_CLONE_INDEX_INVALID;
2745     }
2746     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken, true);
2747     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
2748     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
2749         interceptorExecuter_->DoProcess(interceptorParam);
2750     if (result != ERR_OK) {
2751         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
2752         eventInfo.errCode = result;
2753         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
2754         return result;
2755     }
2756 
2757     if (!JudgeMultiUserConcurrency(validUserId)) {
2758         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
2759         eventInfo.errCode = ERR_INVALID_VALUE;
2760         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2761         return ERR_CROSS_USER;
2762     }
2763 
2764     AbilityRequest abilityRequest;
2765 #ifdef SUPPORT_GRAPHICS
2766     if (ImplicitStartProcessor::IsImplicitStartAction(want)) {
2767         abilityRequest.Voluation(want, DEFAULT_INVAL_VALUE, callerToken);
2768         abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
2769         abilityRequest.extensionType = extensionType;
2770         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
2771         result = implicitStartProcessor_->ImplicitStartAbility(abilityRequest, validUserId);
2772         if (result != ERR_OK) {
2773             TAG_LOGE(AAFwkTag::ABILITYMGR, "implicit start ability error.");
2774             eventInfo.errCode = result;
2775             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2776         }
2777         return result;
2778     }
2779 #endif
2780     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
2781     if (result != ERR_OK) {
2782         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
2783         eventInfo.errCode = result;
2784         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2785         return result;
2786     }
2787 
2788     if (!CheckWorkSchedulerPermission(callerToken, abilityRequest.abilityInfo.applicationInfo.uid)) {
2789         return CHECK_PERMISSION_FAILED;
2790     }
2791     auto abilityInfo = abilityRequest.abilityInfo;
2792     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
2793     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
2794         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
2795 
2796 #ifdef WITH_DLP
2797     result = isDlp ? IN_PROCESS_CALL(
2798         CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller)) :
2799         CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType, isImplicit, isStartAsCaller);
2800     if (result != ERR_OK) {
2801         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error.");
2802         eventInfo.errCode = result;
2803         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2804         return result;
2805     }
2806 #endif // WITH_DLP
2807 
2808     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
2809         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), false, appIndex);
2810     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
2811         afterCheckExecuter_->DoProcess(afterCheckParam);
2812     if (result != ERR_OK) {
2813         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
2814         return result;
2815     }
2816 
2817     auto connectManager = GetConnectManagerByUserId(validUserId);
2818     if (!connectManager) {
2819         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
2820         eventInfo.errCode = ERR_INVALID_VALUE;
2821         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2822         return ERR_INVALID_VALUE;
2823     }
2824     if (!isStartAsCaller) {
2825         UpdateCallerInfo(abilityRequest.want, callerToken);
2826     }
2827     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
2828     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
2829         abilityRequest.abilityInfo.extensionAbilityType);
2830     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
2831     if (eventInfo.errCode != ERR_OK) {
2832         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2833     }
2834     ReportAbilityAssociatedStartInfoToRSS(abilityRequest.abilityInfo, RES_TYPE_EXTENSION_START_ABILITY, callerToken);
2835     return eventInfo.errCode;
2836 }
2837 
SetPickerElementName(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)2838 void AbilityManagerService::SetPickerElementName(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
2839 {
2840     CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
2841     std::string targetType = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TARGET_TYPE_KEY);
2842     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
2843         extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
2844         extensionSessionInfo->want.GetElement().GetAbilityName().empty() &&
2845         COMMON_PICKER_TYPE.find(targetType) != COMMON_PICKER_TYPE.end()) {
2846         std::string abilityName = "CommonSelectPickerAbility";
2847         std::string bundleName = "com.ohos.amsdialog";
2848         extensionSessionInfo->want.SetElementName(bundleName, abilityName);
2849         WantParams &parameters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
2850         parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box("sys/commonUI"));
2851         extensionSessionInfo->want.SetParams(parameters);
2852         return;
2853     }
2854     if (extensionSessionInfo->want.GetElement().GetBundleName().empty() &&
2855         extensionSessionInfo->want.GetElement().GetAbilityName().empty() && !targetType.empty()) {
2856         std::string abilityName;
2857         std::string bundleName;
2858         std::string pickerType;
2859         std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
2860         auto pickerMap = AmsConfigurationParameter::GetInstance().GetPickerMap();
2861         auto it = pickerMap.find(targetType);
2862         if (it == pickerMap.end()) {
2863             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not find the targetType: %{public}s", targetType.c_str());
2864             return;
2865         }
2866         pickerType = it->second;
2867         auto bms = GetBundleManager();
2868         CHECK_POINTER(bms);
2869         int32_t validUserId = GetValidUserId(userId);
2870         TAG_LOGI(AAFwkTag::ABILITYMGR, "targetType: %{public}s, pickerType: %{public}s, userId: %{public}d",
2871             targetType.c_str(), pickerType.c_str(), validUserId);
2872         auto flags = static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_WITH_PERMISSION) |
2873             static_cast<uint32_t>(GetExtensionAbilityInfoFlag::GET_EXTENSION_ABILITY_INFO_BY_TYPE_NAME);
2874         auto ret = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfosOnlyWithTypeName(pickerType,
2875             flags,
2876             validUserId,
2877             extensionInfos));
2878         if (ret != ERR_OK) {
2879             TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryExtensionAbilityInfosOnlyWithTypeName failed");
2880             return;
2881         }
2882         abilityName = extensionInfos[0].name;
2883         bundleName = extensionInfos[0].bundleName;
2884         TAG_LOGI(AAFwkTag::ABILITYMGR,
2885             "abilityName: %{public}s, bundleName: %{public}s", abilityName.c_str(), bundleName.c_str());
2886         extensionSessionInfo->want.SetElementName(bundleName, abilityName);
2887         WantParams &parameters = const_cast<WantParams &>(extensionSessionInfo->want.GetParams());
2888         parameters.SetParam(UIEXTENSION_TYPE_KEY, AAFwk::String::Box(pickerType));
2889         extensionSessionInfo->want.SetParams(parameters);
2890     }
2891 }
2892 
SetAutoFillElementName(const sptr<SessionInfo> & extensionSessionInfo)2893 void AbilityManagerService::SetAutoFillElementName(const sptr<SessionInfo> &extensionSessionInfo)
2894 {
2895     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
2896     CHECK_POINTER_IS_NULLPTR(extensionSessionInfo);
2897     std::vector<std::string> argList;
2898     if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_PASSWORD_TPYE) {
2899         SplitStr(KEY_AUTO_FILL_ABILITY, "/", argList);
2900     } else if (extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY) == AUTO_FILL_SMART_TPYE) {
2901         SplitStr(KEY_SMART_AUTO_FILL_ABILITY, "/", argList);
2902     } else {
2903         TAG_LOGW(AAFwkTag::ABILITYMGR, "It is not autofill type.");
2904         return;
2905     }
2906 
2907     if (argList.size() != ARGC_THREE) {
2908         TAG_LOGE(AAFwkTag::ABILITYMGR, "Parse auto fill extension element name failed.");
2909         return;
2910     }
2911     extensionSessionInfo->want.SetElementName(argList[INDEX_ZERO], argList[INDEX_TWO]);
2912     extensionSessionInfo->want.SetModuleName(argList[INDEX_ONE]);
2913 }
2914 
CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,AppExecFwk::ExtensionAbilityType extensionType)2915 int AbilityManagerService::CheckUIExtensionUsage(AppExecFwk::UIExtensionUsage uiExtensionUsage,
2916     AppExecFwk::ExtensionAbilityType extensionType)
2917 {
2918     if (uiExtensionUsage == UIExtensionUsage::EMBEDDED &&
2919         !AAFwk::UIExtensionUtils::IsPublicForEmbedded(extensionType)) {
2920         CHECK_CALLER_IS_SYSTEM_APP;
2921     }
2922 
2923     if (uiExtensionUsage == UIExtensionUsage::CONSTRAINED_EMBEDDED &&
2924         !AAFwk::UIExtensionUtils::IsPublicForConstrainedEmbedded(extensionType)) {
2925         TAG_LOGE(AAFwkTag::ABILITYMGR, "error extension type %u for SecureConstrainedEmbedded.", extensionType);
2926         return ERR_INVALID_VALUE;
2927     }
2928     return ERR_OK;
2929 }
2930 
StartUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int32_t userId)2931 int AbilityManagerService::StartUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int32_t userId)
2932 {
2933     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2934     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start ui extension ability come");
2935     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
2936     SetPickerElementName(extensionSessionInfo, userId);
2937     SetAutoFillElementName(extensionSessionInfo);
2938 
2939     if (extensionSessionInfo->want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
2940         int32_t screenMode = extensionSessionInfo->want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
2941         if (screenMode != AAFwk::EMBEDDED_FULL_SCREEN_MODE) {
2942             TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support embedded pull-ups");
2943             return ERR_INVALID_VALUE;
2944         }
2945         auto bms = GetBundleManager();
2946         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
2947         AppExecFwk::BundleInfo bundleInfo;
2948         if (!IN_PROCESS_CALL(bms->GetBundleInfo(extensionSessionInfo->want.GetBundle(),
2949             AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, GetValidUserId(userId)))) {
2950             TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get application info");
2951             return CHECK_PERMISSION_FAILED;
2952         }
2953         if (bundleInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE) {
2954             TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support atomicService");
2955             return ERR_INVALID_CALLER;
2956         }
2957         if (extensionSessionInfo->want.GetElement().GetAbilityName().empty()) {
2958             if (bundleInfo.abilityInfos.empty()) {
2959                 TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get abilityInfos");
2960                 return ERR_INVALID_VALUE;
2961             }
2962             extensionSessionInfo->want.SetElementName(bundleInfo.name, bundleInfo.abilityInfos.begin()->name);
2963         }
2964         extensionSessionInfo->want.SetParam("send_to_erms_embedded", 1);
2965     }
2966     std::string extensionTypeStr = extensionSessionInfo->want.GetStringParam(UIEXTENSION_TYPE_KEY);
2967     AppExecFwk::ExtensionAbilityType extensionType = extensionTypeStr.empty() ?
2968         AppExecFwk::ExtensionAbilityType::UI : AppExecFwk::ConvertToExtensionAbilityType(extensionTypeStr);
2969     if (extensionType == AppExecFwk::ExtensionAbilityType::UNSPECIFIED) {
2970         TAG_LOGE(AAFwkTag::ABILITYMGR, "Input extension ability type is invalid.");
2971         return ERR_INVALID_VALUE;
2972     }
2973     EventInfo eventInfo = BuildEventInfo(extensionSessionInfo->want, userId);
2974     eventInfo.extensionType = static_cast<int32_t>(extensionType);
2975 
2976     auto ret = CheckUIExtensionUsage(extensionSessionInfo->uiExtensionUsage, extensionType);
2977     if (ret != ERR_OK) {
2978         TAG_LOGE(AAFwkTag::ABILITYMGR, "check usage failed.");
2979         return ret;
2980     }
2981 
2982     if (InsightIntentExecuteParam::IsInsightIntentExecute(extensionSessionInfo->want)) {
2983         int32_t result = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateWant(
2984             extensionSessionInfo->want, AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY);
2985         if (result != ERR_OK) {
2986             return result;
2987         }
2988     }
2989 
2990     sptr<IRemoteObject> callerToken = extensionSessionInfo->callerToken;
2991 
2992 #ifdef WITH_DLP
2993     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, extensionSessionInfo->want) ||
2994         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
2995         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, extensionSessionInfo->want)) {
2996         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIExtensionAbility: Permission verification failed.");
2997         eventInfo.errCode = CHECK_PERMISSION_FAILED;
2998         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
2999         return CHECK_PERMISSION_FAILED;
3000     }
3001 #endif // WITH_DLP
3002 
3003     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3004         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIExtensionAbility VerificationAllToken failed.");
3005         eventInfo.errCode = ERR_INVALID_VALUE;
3006         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3007         return ERR_INVALID_CALLER;
3008     }
3009 
3010     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
3011     if (callerRecord == nullptr || !JudgeSelfCalled(callerRecord)) {
3012         TAG_LOGE(AAFwkTag::ABILITYMGR, "invalid callerToken.");
3013         eventInfo.errCode = ERR_INVALID_VALUE;
3014         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3015         return ERR_INVALID_CALLER;
3016     }
3017 
3018     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(extensionSessionInfo->want, 0, GetUserId(),
3019         true, nullptr);
3020     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3021         interceptorExecuter_->DoProcess(interceptorParam);
3022     if (result != ERR_OK) {
3023         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
3024         eventInfo.errCode = result;
3025         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3026         return result;
3027     }
3028 
3029     int32_t validUserId = GetValidUserId(userId);
3030     if (!JudgeMultiUserConcurrency(validUserId)) {
3031         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
3032         eventInfo.errCode = ERR_INVALID_VALUE;
3033         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3034         return ERR_INVALID_VALUE;
3035     }
3036 
3037     if (ImplicitStartProcessor::IsImplicitStartAction(extensionSessionInfo->want)) {
3038         TAG_LOGE(AAFwkTag::ABILITYMGR, "UI extension ability donot support implicit start.");
3039         eventInfo.errCode = ERR_INVALID_VALUE;
3040         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3041         return ERR_INVALID_VALUE;
3042     }
3043 
3044     AbilityRequest abilityRequest;
3045     abilityRequest.Voluation(extensionSessionInfo->want, DEFAULT_INVAL_VALUE, callerToken);
3046     abilityRequest.callType = AbilityCallType::START_EXTENSION_TYPE;
3047     abilityRequest.sessionInfo = extensionSessionInfo;
3048     result = GenerateEmbeddableUIAbilityRequest(extensionSessionInfo->want, abilityRequest, callerToken, validUserId);
3049     CHECK_POINTER_AND_RETURN(abilityRequest.sessionInfo, ERR_INVALID_VALUE);
3050     abilityRequest.sessionInfo->uiExtensionComponentId = (
3051         static_cast<uint64_t>(callerRecord->GetRecordId()) << OFFSET) |
3052         static_cast<uint64_t>(abilityRequest.sessionInfo->persistentId);
3053     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
3054         abilityRequest.sessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3055     if (result != ERR_OK) {
3056         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
3057         eventInfo.errCode = result;
3058         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3059         return result;
3060     }
3061     abilityRequest.extensionType = abilityRequest.abilityInfo.extensionAbilityType;
3062 
3063     auto abilityInfo = abilityRequest.abilityInfo;
3064     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3065     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
3066         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3067 
3068     result = CheckOptExtensionAbility(extensionSessionInfo->want, abilityRequest, validUserId, extensionType, true);
3069     if (result != ERR_OK) {
3070         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error.");
3071         eventInfo.errCode = result;
3072         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3073         return result;
3074     }
3075 
3076     sptr<IRemoteObject> parentToken = extensionSessionInfo->parentToken;
3077     if (parentToken && parentToken != callerToken) {
3078         UpdateCallerInfoFromToken(abilityRequest.want, parentToken);
3079     }
3080 
3081     result = JudgeAbilityVisibleControl(abilityInfo);
3082     if (result != ERR_OK) {
3083         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3084         eventInfo.errCode = result;
3085         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3086         return result;
3087     }
3088 
3089     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
3090         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
3091     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
3092         afterCheckExecuter_->DoProcess(afterCheckParam);
3093     if (result != ERR_OK) {
3094         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
3095         return result;
3096     }
3097 
3098     auto connectManager = GetConnectManagerByUserId(validUserId);
3099     if (!connectManager) {
3100         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
3101         eventInfo.errCode = ERR_INVALID_VALUE;
3102         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3103         return ERR_INVALID_VALUE;
3104     }
3105     ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
3106     TAG_LOGI(AAFwkTag::ABILITYMGR, "Start extension begin, name is %{public}s.", abilityInfo.name.c_str());
3107     UriUtils::GetInstance().CheckUriPermissionForUIExtension(abilityRequest.want,
3108         abilityRequest.abilityInfo.extensionAbilityType);
3109     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
3110     if (eventInfo.errCode != ERR_OK) {
3111         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3112     }
3113     return eventInfo.errCode;
3114 }
3115 
StopExtensionAbility(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,AppExecFwk::ExtensionAbilityType extensionType)3116 int AbilityManagerService::StopExtensionAbility(const Want &want, const sptr<IRemoteObject> &callerToken,
3117     int32_t userId, AppExecFwk::ExtensionAbilityType extensionType)
3118 {
3119     TAG_LOGI(AAFwkTag::ABILITYMGR,
3120         "Stop extension ability come, bundlename: %{public}s, ability is %{public}s, userId is %{public}d",
3121         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3122     if (extensionType != AppExecFwk::ExtensionAbilityType::VPN) {
3123         CHECK_CALLER_IS_SYSTEM_APP;
3124     }
3125     EventInfo eventInfo = BuildEventInfo(want, userId);
3126     eventInfo.extensionType = static_cast<int32_t>(extensionType);
3127 
3128     int result;
3129 #ifdef WITH_DLP
3130     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::STOP_EXTENSION_ERROR);
3131     if (result != ERR_OK) {
3132         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
3133         return result;
3134     }
3135 #endif // WITH_DLP
3136 
3137     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3138         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
3139         if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME)) {
3140             TAG_LOGE(AAFwkTag::ABILITYMGR, "VerificationAllToken failed.");
3141             eventInfo.errCode = ERR_INVALID_VALUE;
3142             EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3143             return ERR_INVALID_CALLER;
3144         }
3145         TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller is specific system ability.");
3146     }
3147 
3148     int32_t validUserId = GetValidUserId(userId);
3149     if (!JudgeMultiUserConcurrency(validUserId)) {
3150         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
3151         eventInfo.errCode = ERR_INVALID_VALUE;
3152         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3153         return ERR_CROSS_USER;
3154     }
3155 
3156     if (callerToken != nullptr && CheckIfOperateRemote(want)) {
3157         auto callerUid = IPCSkeleton::GetCallingUid();
3158         uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3159         DistributedClient dmsClient;
3160         return dmsClient.StopRemoteExtensionAbility(want, callerUid, accessToken, eventInfo.extensionType);
3161     }
3162 
3163     AbilityRequest abilityRequest;
3164     result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, validUserId);
3165     if (result != ERR_OK) {
3166         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
3167         eventInfo.errCode = result;
3168         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3169         return result;
3170     }
3171 
3172     auto abilityInfo = abilityRequest.abilityInfo;
3173     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
3174     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
3175         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
3176 
3177     result = CheckOptExtensionAbility(want, abilityRequest, validUserId, extensionType);
3178     if (result != ERR_OK) {
3179         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckOptExtensionAbility error.");
3180         eventInfo.errCode = result;
3181         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3182         return result;
3183     }
3184 
3185     auto connectManager = GetConnectManagerByUserId(validUserId);
3186     if (!connectManager) {
3187         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
3188         eventInfo.errCode = ERR_INVALID_VALUE;
3189         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3190         return ERR_INVALID_VALUE;
3191     }
3192     TAG_LOGI(AAFwkTag::ABILITYMGR, "Stop extension begin, name is %{public}s.", abilityInfo.name.c_str());
3193     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3194     if (eventInfo.errCode != ERR_OK) {
3195         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3196     }
3197     return eventInfo.errCode;
3198 }
3199 
StopSwitchUserDialog()3200 void AbilityManagerService::StopSwitchUserDialog()
3201 {
3202     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog extension ability come");
3203     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3204         TAG_LOGE(AAFwkTag::ABILITYMGR, "Scene board enabled.");
3205         return;
3206     }
3207 
3208     if (userController_ == nullptr || userController_->GetFreezingNewUserId() == DEFAULT_INVAL_VALUE) {
3209         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get last userId error.");
3210         return;
3211     }
3212 
3213     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
3214     if (sysDialog == nullptr) {
3215         TAG_LOGE(AAFwkTag::ABILITYMGR, "System dialog scheduler instance is nullptr.");
3216         return;
3217     }
3218     Want stopWant = sysDialog->GetSwitchUserDialogWant();
3219     StopSwitchUserDialogInner(stopWant, userController_->GetFreezingNewUserId());
3220 
3221     userController_->SetFreezingNewUserId(DEFAULT_INVAL_VALUE);
3222     return;
3223 }
3224 
StopSwitchUserDialogInner(const Want & want,const int32_t lastUserId)3225 void AbilityManagerService::StopSwitchUserDialogInner(const Want &want, const int32_t lastUserId)
3226 {
3227     TAG_LOGD(AAFwkTag::ABILITYMGR, "Stop switch user dialog inner come");
3228     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
3229     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
3230     AbilityRequest abilityRequest;
3231     auto result =
3232         GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
3233     if (result != ERR_OK) {
3234         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
3235         eventInfo.errCode = result;
3236         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3237         return;
3238     }
3239 
3240     auto abilityInfo = abilityRequest.abilityInfo;
3241     auto stopUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
3242     result = CheckOptExtensionAbility(want, abilityRequest, stopUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
3243     if (result != ERR_OK) {
3244         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check extensionAbility type error.");
3245         eventInfo.errCode = result;
3246         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3247         return;
3248     }
3249 
3250     auto connectManager = GetConnectManagerByUserId(stopUserId);
3251     if (connectManager == nullptr) {
3252         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectManager is nullptr. userId:%{public}d", stopUserId);
3253         eventInfo.errCode = ERR_INVALID_VALUE;
3254         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3255         return;
3256     }
3257 
3258     eventInfo.errCode = connectManager->StopServiceAbility(abilityRequest);
3259     if (eventInfo.errCode != ERR_OK) {
3260         TAG_LOGE(AAFwkTag::ABILITYMGR, "EventInfo errCode is %{public}d", eventInfo.errCode);
3261         EventReport::SendExtensionEvent(EventName::STOP_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
3262     }
3263 }
3264 
MoveAbilityToBackground(const sptr<IRemoteObject> & token)3265 int AbilityManagerService::MoveAbilityToBackground(const sptr<IRemoteObject> &token)
3266 {
3267     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3268     TAG_LOGD(AAFwkTag::ABILITYMGR, "Move ability to background begin");
3269     if (!VerificationAllToken(token)) {
3270         return ERR_INVALID_VALUE;
3271     }
3272     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3273     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3274     if (!JudgeSelfCalled(abilityRecord)) {
3275         return CHECK_PERMISSION_FAILED;
3276     }
3277 
3278     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3279         return ERR_WOULD_BLOCK;
3280     }
3281 
3282     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3283     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3284     if (!missionListManager) {
3285         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
3286         return ERR_INVALID_VALUE;
3287     }
3288     return missionListManager->MoveAbilityToBackground(abilityRecord);
3289 }
3290 
MoveUIAbilityToBackground(const sptr<IRemoteObject> token)3291 int32_t AbilityManagerService::MoveUIAbilityToBackground(const sptr<IRemoteObject> token)
3292 {
3293     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3294     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
3295     if (!AppUtils::GetInstance().EnableMoveUIAbilityToBackgroundApi()) {
3296         return ERR_OPERATION_NOT_SUPPORTED_ON_CURRENT_DEVICE;
3297     }
3298     if (!VerificationAllToken(token)) {
3299         return ERR_INVALID_VALUE;
3300     }
3301     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3302     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3303     if (!IsAppSelfCalled(abilityRecord)) {
3304         return CHECK_PERMISSION_FAILED;
3305     }
3306     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3307         TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not move ability to background in Wukong mode.");
3308         return ERR_WUKONG_MODE_CANT_MOVE_STATE;
3309     }
3310     if (!abilityRecord->IsAbilityState(FOREGROUND) && !abilityRecord->IsAbilityState(FOREGROUNDING)) {
3311         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability not in foregorund state.");
3312         return ERR_ABILITY_NOT_FOREGROUND;
3313     }
3314     if (abilityRecord->GetAbilityInfo().type != AppExecFwk::AbilityType::PAGE) {
3315         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot background non UIAbility.");
3316         return RESOLVE_CALL_ABILITY_TYPE_ERR;
3317     }
3318     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3319     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3320         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3321         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3322         return uiAbilityManager->NotifySCBToMinimizeUIAbility(abilityRecord, token);
3323     }
3324 
3325     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3326     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3327     return missionListManager->MoveAbilityToBackground(abilityRecord);
3328 }
3329 
TerminateAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3330 int AbilityManagerService::TerminateAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3331 {
3332     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3333     if (!abilityRecord) {
3334         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
3335         return ERR_INVALID_VALUE;
3336     }
3337     return TerminateAbilityWithFlag(token, resultCode, resultWant, true);
3338 }
3339 
BackToCallerAbilityWithResult(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,int64_t callerRequestCode)3340 int AbilityManagerService::BackToCallerAbilityWithResult(const sptr<IRemoteObject> &token, int resultCode,
3341     const Want *resultWant, int64_t callerRequestCode)
3342 {
3343     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3344     if (!abilityRecord) {
3345         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
3346         return ERR_INVALID_VALUE;
3347     }
3348     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3349     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3350         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3351         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3352         return uiAbilityManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant,
3353             callerRequestCode);
3354     }
3355     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3356     CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
3357     return missionListManager->BackToCallerAbilityWithResult(abilityRecord, resultCode, resultWant, callerRequestCode);
3358 }
3359 
CloseAbility(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant)3360 int AbilityManagerService::CloseAbility(const sptr<IRemoteObject> &token, int resultCode, const Want *resultWant)
3361 {
3362     EventInfo eventInfo;
3363     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3364     return TerminateAbilityWithFlag(token, resultCode, resultWant, false);
3365 }
3366 
TerminateAbilityWithFlag(const sptr<IRemoteObject> & token,int resultCode,const Want * resultWant,bool flag)3367 int AbilityManagerService::TerminateAbilityWithFlag(const sptr<IRemoteObject> &token, int resultCode,
3368     const Want *resultWant, bool flag)
3369 {
3370     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3371     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ability begin, flag:%{public}d.", flag);
3372     if (!VerificationAllToken(token)) {
3373         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
3374         return ERR_INVALID_VALUE;
3375     }
3376 
3377     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3378     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3379     if (!JudgeSelfCalled(abilityRecord)) {
3380         return CHECK_PERMISSION_FAILED;
3381     }
3382 
3383     if (IsSystemUiApp(abilityRecord->GetAbilityInfo())) {
3384         TAG_LOGE(AAFwkTag::ABILITYMGR, "System ui not allow terminate.");
3385         return ERR_INVALID_VALUE;
3386     }
3387 
3388     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
3389     auto type = abilityRecord->GetAbilityInfo().type;
3390     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
3391         auto connectManager = GetConnectManagerByUserId(userId);
3392         if (!connectManager) {
3393             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
3394             return ERR_INVALID_VALUE;
3395         }
3396         return connectManager->TerminateAbility(token);
3397     }
3398 
3399     if (type == AppExecFwk::AbilityType::DATA) {
3400         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot terminate data ability, use 'ReleaseDataAbility()' instead.");
3401         return ERR_WRONG_INTERFACE_CALL;
3402     }
3403 
3404     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3405         return ERR_WOULD_BLOCK;
3406     }
3407 
3408     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
3409     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
3410     if (missionListManager) {
3411         return missionListManager->TerminateAbility(abilityRecord, resultCode, resultWant, flag);
3412     }
3413     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListManager is Null. ownerUserId=%{public}d", ownerUserId);
3414     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3415         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
3416         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3417         return uiAbilityManager->CloseUIAbility(abilityRecord, resultCode, resultWant, false);
3418     }
3419     return ERR_INVALID_VALUE;
3420 }
3421 
TerminateUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,int resultCode,const Want * resultWant)3422 int AbilityManagerService::TerminateUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo, int resultCode,
3423     const Want *resultWant)
3424 {
3425     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3426     TAG_LOGD(AAFwkTag::ABILITYMGR, "Terminate ui extension ability begin.");
3427     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3428     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3429     std::shared_ptr<AbilityConnectManager> connectManager;
3430     std::shared_ptr<AbilityRecord> targetRecord;
3431     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3432     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3433     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3434 
3435     // self terminate or caller terminate is allowed.
3436     if (!(JudgeSelfCalled(targetRecord) || (abilityRecord != nullptr && JudgeSelfCalled(abilityRecord)))) {
3437         return CHECK_PERMISSION_FAILED;
3438     }
3439 
3440     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3441     if (result != ERR_OK) {
3442         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3443         return result;
3444     }
3445 
3446     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3447         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot terminate except ui extension ability.");
3448         return ERR_WRONG_INTERFACE_CALL;
3449     }
3450 
3451     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension persistentId: %{public}d, element: %{public}s.",
3452         extensionSessionInfo->persistentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3453     connectManager->TerminateAbilityWindowLocked(targetRecord, extensionSessionInfo);
3454     return ERR_OK;
3455 }
3456 
CloseUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)3457 int AbilityManagerService::CloseUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
3458 {
3459     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3460     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3461         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
3462         return ERR_INVALID_VALUE;
3463     }
3464 
3465     if (!IsCallerSceneBoard()) {
3466         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
3467         return ERR_WRONG_INTERFACE_CALL;
3468     }
3469 
3470     SetMinimizedDuringFreeInstall(sessionInfo);
3471 
3472     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3473     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3474     TAG_LOGI(AAFwkTag::ABILITYMGR,
3475         "close session: %{public}d, resultCode: %{public}d", sessionInfo->persistentId, sessionInfo->resultCode);
3476     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3477     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3478     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3479         return ERR_WOULD_BLOCK;
3480     }
3481 
3482     if (sessionInfo->isClearSession) {
3483         const auto &abilityInfo = abilityRecord->GetAbilityInfo();
3484         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
3485             DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName,
3486             abilityInfo.name);
3487     }
3488     EventInfo eventInfo;
3489     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
3490     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
3491     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
3492     eventInfo.errCode = uiAbilityManager->CloseUIAbility(abilityRecord, sessionInfo->resultCode,
3493         &(sessionInfo->want), sessionInfo->isClearSession);
3494     if (eventInfo.errCode != ERR_OK) {
3495         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
3496     }
3497     return eventInfo.errCode;
3498 }
3499 
SendResultToAbility(int32_t requestCode,int32_t resultCode,Want & resultWant)3500 int AbilityManagerService::SendResultToAbility(int32_t requestCode, int32_t resultCode, Want &resultWant)
3501 {
3502     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3503     if (!CheckCallerIsDmsProcess()) {
3504         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check processName failed");
3505         return ERR_INVALID_VALUE;
3506     }
3507     int missionId = resultWant.GetIntParam(DMS_MISSION_ID, DEFAULT_DMS_MISSION_ID);
3508     resultWant.RemoveParam(DMS_MISSION_ID);
3509     if (missionId == DEFAULT_DMS_MISSION_ID) {
3510         TAG_LOGE(AAFwkTag::ABILITYMGR, "MissionId is empty");
3511         return ERR_INVALID_VALUE;
3512     }
3513     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
3514     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3515         auto uiAbilityManager = GetCurrentUIAbilityManager();
3516         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3517         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
3518     } else {
3519         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
3520         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
3521         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
3522     }
3523     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3524 
3525     abilityRecord->SetResult(std::make_shared<AbilityResult>(requestCode, resultCode, resultWant));
3526     abilityRecord->SendResult(0, 0);
3527     return ERR_OK;
3528 }
3529 
StartRemoteAbility(const Want & want,int requestCode,int32_t validUserId,const sptr<IRemoteObject> & callerToken)3530 int AbilityManagerService::StartRemoteAbility(const Want &want, int requestCode, int32_t validUserId,
3531     const sptr<IRemoteObject> &callerToken)
3532 {
3533     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3534     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
3535     Want remoteWant = want;
3536     UpdateDmsCallerInfo(remoteWant, callerToken);
3537     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
3538         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
3539         return ERR_INVALID_VALUE;
3540     }
3541     if (AbilityUtil::IsStartFreeInstall(remoteWant)) {
3542         return freeInstallManager_ == nullptr ? ERR_INVALID_VALUE :
3543             freeInstallManager_->StartRemoteFreeInstall(remoteWant, requestCode, validUserId, callerToken);
3544     }
3545     if (remoteWant.GetBoolParam(Want::PARAM_RESV_FOR_RESULT, false)) {
3546         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: try to StartAbilityForResult", __func__);
3547         int32_t missionId = -1;
3548         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
3549             missionId = GetMissionIdByAbilityTokenInner(callerToken);
3550             if (!missionId) {
3551                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
3552                 return ERR_INVALID_VALUE;
3553             }
3554         } else {
3555             missionId = GetMissionIdByAbilityToken(callerToken);
3556         }
3557         if (missionId < 0) {
3558             return ERR_INVALID_VALUE;
3559         }
3560         remoteWant.SetParam(DMS_MISSION_ID, missionId);
3561     }
3562 
3563     int32_t callerUid = IPCSkeleton::GetCallingUid();
3564     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
3565     UriUtils::GetInstance().FilterUriWithPermissionDms(remoteWant, accessToken);
3566     DistributedClient dmsClient;
3567     int result = dmsClient.StartRemoteAbility(remoteWant, callerUid, requestCode, accessToken);
3568     if (result != ERR_NONE) {
3569         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartRemoteAbility failed, result = %{public}d", result);
3570     }
3571     return result;
3572 }
3573 
CheckIsRemote(const std::string & deviceId)3574 bool AbilityManagerService::CheckIsRemote(const std::string& deviceId)
3575 {
3576     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3577     if (deviceId.empty()) {
3578         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckIsRemote: deviceId is empty.");
3579         return false;
3580     }
3581     std::string localDeviceId;
3582     if (!GetLocalDeviceId(localDeviceId)) {
3583         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckIsRemote: get local deviceId failed");
3584         return false;
3585     }
3586     if (localDeviceId == deviceId) {
3587         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckIsRemote: deviceId is local.");
3588         return false;
3589     }
3590     TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIsRemote, deviceId = %{public}s", AnonymizeDeviceId(deviceId).c_str());
3591     return true;
3592 }
3593 
CheckIfOperateRemote(const Want & want)3594 bool AbilityManagerService::CheckIfOperateRemote(const Want &want)
3595 {
3596     std::string deviceId = want.GetElement().GetDeviceID();
3597     if (deviceId.empty() || want.GetElement().GetBundleName().empty() ||
3598         want.GetElement().GetAbilityName().empty()) {
3599         TAG_LOGD(AAFwkTag::ABILITYMGR, "CheckIfOperateRemote: DeviceId or BundleName or GetAbilityName empty");
3600         return false;
3601     }
3602     return CheckIsRemote(deviceId);
3603 }
3604 
GetLocalDeviceId(std::string & localDeviceId)3605 bool AbilityManagerService::GetLocalDeviceId(std::string& localDeviceId)
3606 {
3607     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3608     auto localNode = std::make_unique<NodeBasicInfo>();
3609     int32_t errCode = GetLocalNodeDeviceInfo(DM_PKG_NAME, localNode.get());
3610     if (errCode != ERR_OK) {
3611         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::GetLocalNodeDeviceInfo errCode = %{public}d", errCode);
3612         return false;
3613     }
3614     if (localNode != nullptr) {
3615         localDeviceId = localNode->networkId;
3616         TAG_LOGD(AAFwkTag::ABILITYMGR, "get local deviceId, deviceId = %{public}s",
3617             AnonymizeDeviceId(localDeviceId).c_str());
3618         return true;
3619     }
3620     TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::GetLocalDeviceId localDeviceId null");
3621     return false;
3622 }
3623 
AnonymizeDeviceId(const std::string & deviceId)3624 std::string AbilityManagerService::AnonymizeDeviceId(const std::string& deviceId)
3625 {
3626     if (deviceId.length() < NON_ANONYMIZE_LENGTH) {
3627         return EMPTY_DEVICE_ID;
3628     }
3629     std::string anonDeviceId = deviceId.substr(0, NON_ANONYMIZE_LENGTH);
3630     anonDeviceId.append("******");
3631     return anonDeviceId;
3632 }
3633 
MinimizeAbility(const sptr<IRemoteObject> & token,bool fromUser)3634 int AbilityManagerService::MinimizeAbility(const sptr<IRemoteObject> &token, bool fromUser)
3635 {
3636     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3637     TAG_LOGI(AAFwkTag::ABILITYMGR, "Minimize ability, fromUser:%{public}d.", fromUser);
3638     if (!VerificationAllToken(token)) {
3639         return ERR_INVALID_VALUE;
3640     }
3641 
3642     auto abilityRecord = Token::GetAbilityRecordByToken(token);
3643     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3644     if (!JudgeSelfCalled(abilityRecord)) {
3645         return CHECK_PERMISSION_FAILED;
3646     }
3647 
3648     auto type = abilityRecord->GetAbilityInfo().type;
3649     if (type != AppExecFwk::AbilityType::PAGE) {
3650         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except page ability.");
3651         return ERR_WRONG_INTERFACE_CALL;
3652     }
3653 
3654     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3655         return ERR_WOULD_BLOCK;
3656     }
3657 
3658     auto missionListManager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
3659     if (!missionListManager) {
3660         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null.");
3661         return ERR_INVALID_VALUE;
3662     }
3663     return missionListManager->MinimizeAbility(token, fromUser);
3664 }
3665 
MinimizeUIExtensionAbility(const sptr<SessionInfo> & extensionSessionInfo,bool fromUser)3666 int AbilityManagerService::MinimizeUIExtensionAbility(const sptr<SessionInfo> &extensionSessionInfo,
3667     bool fromUser)
3668 {
3669     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3670     TAG_LOGD(AAFwkTag::ABILITYMGR, "Minimize ui extension ability, fromUser:%{public}d.", fromUser);
3671     CHECK_POINTER_AND_RETURN(extensionSessionInfo, ERR_INVALID_VALUE);
3672     auto abilityRecord = Token::GetAbilityRecordByToken(extensionSessionInfo->callerToken);
3673     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3674     if (!JudgeSelfCalled(abilityRecord)) {
3675         return CHECK_PERMISSION_FAILED;
3676     }
3677 
3678     std::shared_ptr<AbilityConnectManager> connectManager;
3679     std::shared_ptr<AbilityRecord> targetRecord;
3680     GetConnectManagerAndUIExtensionBySessionInfo(extensionSessionInfo, connectManager, targetRecord);
3681     CHECK_POINTER_AND_RETURN(targetRecord, ERR_INVALID_VALUE);
3682     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
3683 
3684     auto result = JudgeAbilityVisibleControl(targetRecord->GetAbilityInfo());
3685     if (result != ERR_OK) {
3686         TAG_LOGE(AAFwkTag::ABILITYMGR, "JudgeAbilityVisibleControl error.");
3687         return result;
3688     }
3689 
3690     if (!UIExtensionUtils::IsUIExtension(targetRecord->GetAbilityInfo().extensionAbilityType)) {
3691         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except ui extension ability.");
3692         return ERR_WRONG_INTERFACE_CALL;
3693     }
3694     extensionSessionInfo->uiExtensionComponentId = (
3695         static_cast<uint64_t>(abilityRecord->GetRecordId()) << OFFSET) |
3696         static_cast<uint64_t>(extensionSessionInfo->persistentId);
3697     TAG_LOGD(AAFwkTag::ABILITYMGR, "UIExtension component id: %{public}" PRId64 ", element: %{public}s.",
3698         extensionSessionInfo->uiExtensionComponentId, extensionSessionInfo->want.GetElement().GetURI().c_str());
3699     connectManager->BackgroundAbilityWindowLocked(targetRecord, extensionSessionInfo);
3700     return ERR_OK;
3701 }
3702 
SetMinimizedDuringFreeInstall(const sptr<SessionInfo> & sessionInfo)3703 void AbilityManagerService::SetMinimizedDuringFreeInstall(const sptr<SessionInfo> &sessionInfo)
3704 {
3705     if (sessionInfo == nullptr) {
3706         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo null");
3707         return;
3708     }
3709 
3710     if (!(sessionInfo->want).HasParameter(KEY_SESSION_ID)) {
3711         return;
3712     }
3713 
3714     std::string sessionId = (sessionInfo->want).GetStringParam(KEY_SESSION_ID);
3715     if (sessionId.empty()) {
3716         return;
3717     }
3718 
3719     if (freeInstallManager_ == nullptr) {
3720         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ null");
3721         return;
3722     }
3723     FreeInstallInfo taskInfo;
3724     if (!freeInstallManager_->GetFreeInstallTaskInfo(sessionId, taskInfo)) {
3725         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task with sessionId=%{public}s does not exist",
3726             sessionId.c_str());
3727         return;
3728     }
3729 
3730     if (taskInfo.isFreeInstallFinished) {
3731         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install task finished");
3732         return;
3733     }
3734 
3735     {
3736         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
3737         auto it = preStartSessionMap_.find(sessionId);
3738         if (it == preStartSessionMap_.end()) {
3739             TAG_LOGI(AAFwkTag::ABILITYMGR, "session info with sessionId=%{public}s does not exist",
3740                 sessionId.c_str());
3741             return;
3742         }
3743         it->second->isMinimizedDuringFreeInstall = true;
3744     }
3745 }
3746 
MinimizeUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool fromUser,uint32_t sceneFlag)3747 int AbilityManagerService::MinimizeUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool fromUser,
3748     uint32_t sceneFlag)
3749 {
3750     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3751     TAG_LOGI(AAFwkTag::ABILITYMGR, "Called, sceneFlag: %{public}u", sceneFlag);
3752     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
3753         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
3754         return ERR_INVALID_VALUE;
3755     }
3756 
3757     if (!IsCallerSceneBoard()) {
3758         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
3759         return ERR_WRONG_INTERFACE_CALL;
3760     }
3761 
3762     SetMinimizedDuringFreeInstall(sessionInfo);
3763 
3764     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
3765     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
3766     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
3767     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
3768     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
3769         return ERR_WOULD_BLOCK;
3770     }
3771     return uiAbilityManager->MinimizeUIAbility(abilityRecord, fromUser, sceneFlag);
3772 }
3773 
ConnectAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t userId)3774 int AbilityManagerService::ConnectAbility(
3775     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken, int32_t userId)
3776 {
3777     return ConnectAbilityCommon(want, connect, callerToken, AppExecFwk::ExtensionAbilityType::SERVICE, userId);
3778 }
3779 
ConnectAbilityCommon(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,AppExecFwk::ExtensionAbilityType extensionType,int32_t userId,bool isQueryExtensionOnly)3780 int AbilityManagerService::ConnectAbilityCommon(
3781     const Want &want, const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
3782     AppExecFwk::ExtensionAbilityType extensionType, int32_t userId, bool isQueryExtensionOnly)
3783 {
3784     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3785     TAG_LOGI(AAFwkTag::ABILITYMGR,
3786         "Connect ability called, element uri: %{public}s.", want.GetElement().GetURI().c_str());
3787     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3788     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3789     if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && IsCrossUserCall(userId)) {
3790         CHECK_CALLER_IS_SYSTEM_APP;
3791     }
3792     EventInfo eventInfo = BuildEventInfo(want, userId);
3793 
3794     int result;
3795 #ifdef WITH_DLP
3796     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
3797     if (result != ERR_OK) {
3798         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
3799         eventInfo.errCode = result;
3800         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3801         return result;
3802     }
3803 #endif // WITH_DLP
3804 
3805     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
3806     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3807         interceptorExecuter_->DoProcess(interceptorParam);
3808     if (result != ERR_OK) {
3809         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
3810         eventInfo.errCode = result;
3811         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3812         return result;
3813     }
3814 
3815     int32_t validUserId = GetValidUserId(userId);
3816 
3817     if (AbilityUtil::IsStartFreeInstall(want) && freeInstallManager_ != nullptr) {
3818         std::string localDeviceId;
3819         if (!GetLocalDeviceId(localDeviceId)) {
3820             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Get Local DeviceId failed", __func__);
3821             eventInfo.errCode = ERR_INVALID_VALUE;
3822             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3823             return ERR_INVALID_VALUE;
3824         }
3825         result = freeInstallManager_->ConnectFreeInstall(want, validUserId, callerToken, localDeviceId);
3826         if (result != ERR_OK) {
3827             eventInfo.errCode = result;
3828             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3829             return result;
3830         }
3831     }
3832 
3833     Want abilityWant = want;
3834     AbilityRequest abilityRequest;
3835     std::string uri = abilityWant.GetUri().ToString();
3836     bool isFileUri = (abilityWant.GetUri().GetScheme() == "file");
3837     if (!uri.empty() && !isFileUri) {
3838         // if the want include uri, it may only has uri information. it is probably a datashare extension.
3839         TAG_LOGD(AAFwkTag::ABILITYMGR,
3840             "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
3841         AppExecFwk::ExtensionAbilityInfo extensionInfo;
3842         auto bms = GetBundleManager();
3843         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3844 
3845         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
3846         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
3847             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid extension ability info.");
3848             eventInfo.errCode = ERR_INVALID_VALUE;
3849             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3850             return ERR_INVALID_VALUE;
3851         }
3852         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
3853     }
3854 
3855     if (CheckIfOperateRemote(abilityWant)) {
3856         TAG_LOGD(AAFwkTag::ABILITYMGR, "AbilityManagerService::ConnectAbility. try to ConnectRemoteAbility");
3857         eventInfo.errCode = ConnectRemoteAbility(abilityWant, callerToken, connect->AsObject());
3858         if (eventInfo.errCode != ERR_OK) {
3859             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3860         }
3861         return eventInfo.errCode;
3862     }
3863     UpdateCallerInfo(abilityWant, callerToken);
3864 
3865     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
3866         TAG_LOGD(AAFwkTag::ABILITYMGR, "invalid Token.");
3867         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr, extensionType);
3868         if (eventInfo.errCode != ERR_OK) {
3869             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3870         }
3871         return eventInfo.errCode;
3872     }
3873     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken, extensionType, nullptr,
3874         isQueryExtensionOnly);
3875     if (eventInfo.errCode != ERR_OK) {
3876         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3877     }
3878     return eventInfo.errCode;
3879 }
3880 
ConnectUIExtensionAbility(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<SessionInfo> & sessionInfo,int32_t userId,sptr<UIExtensionAbilityConnectInfo> connectInfo)3881 int AbilityManagerService::ConnectUIExtensionAbility(const Want &want, const sptr<IAbilityConnection> &connect,
3882     const sptr<SessionInfo> &sessionInfo, int32_t userId, sptr<UIExtensionAbilityConnectInfo> connectInfo)
3883 {
3884     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3885     TAG_LOGD(AAFwkTag::ABILITYMGR,
3886         "Connect ui extension called, bundlename: %{public}s, ability is %{public}s, userId is %{pravite}d",
3887         want.GetElement().GetBundleName().c_str(), want.GetElement().GetAbilityName().c_str(), userId);
3888     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3889     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3890     CHECK_POINTER_AND_RETURN(sessionInfo, ERR_INVALID_VALUE);
3891 
3892     if (IsCrossUserCall(userId)) {
3893         CHECK_CALLER_IS_SYSTEM_APP;
3894     }
3895 
3896     EventInfo eventInfo = BuildEventInfo(want, userId);
3897     sptr<IRemoteObject> callerToken = sessionInfo->callerToken;
3898 
3899     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
3900         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectUIExtensionAbility VerificationAllToken failed.");
3901         eventInfo.errCode = ERR_INVALID_VALUE;
3902         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3903         return ERR_INVALID_CALLER;
3904     }
3905 
3906     int result;
3907 #ifdef WITH_DLP
3908     result = CheckDlpForExtension(want, callerToken, userId, eventInfo, EventName::CONNECT_SERVICE_ERROR);
3909     if (result != ERR_OK) {
3910         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckDlpForExtension error.");
3911         eventInfo.errCode = result;
3912         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3913         return result;
3914     }
3915 #endif // WITH_DLP
3916 
3917     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), false, nullptr);
3918     result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
3919         interceptorExecuter_->DoProcess(interceptorParam);
3920     if (result != ERR_OK) {
3921         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
3922         eventInfo.errCode = result;
3923         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3924         return result;
3925     }
3926 
3927     int32_t validUserId = GetValidUserId(userId);
3928 
3929     Want abilityWant = want;
3930     AbilityRequest abilityRequest;
3931     std::string uri = abilityWant.GetUri().ToString();
3932     if (!uri.empty()) {
3933         // if the want include uri, it may only has uri information.
3934         TAG_LOGI(AAFwkTag::ABILITYMGR,
3935             "%{public}s called. uri:%{public}s, userId %{public}d", __func__, uri.c_str(), validUserId);
3936         AppExecFwk::ExtensionAbilityInfo extensionInfo;
3937         auto bms = GetBundleManager();
3938         CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
3939 
3940         bool queryResult = IN_PROCESS_CALL(bms->QueryExtensionAbilityInfoByUri(uri, validUserId, extensionInfo));
3941         if (!queryResult || extensionInfo.name.empty() || extensionInfo.bundleName.empty()) {
3942             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid extension ability info.");
3943             eventInfo.errCode = ERR_INVALID_VALUE;
3944             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3945             return ERR_INVALID_VALUE;
3946         }
3947         abilityWant.SetElementName(extensionInfo.bundleName, extensionInfo.name);
3948     }
3949 
3950     UpdateCallerInfo(abilityWant, callerToken);
3951 
3952     if (callerToken != nullptr && callerToken->GetObjectDescriptor() != u"ohos.aafwk.AbilityToken") {
3953         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s invalid Token.", __func__);
3954         eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, nullptr,
3955             AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
3956         if (eventInfo.errCode != ERR_OK) {
3957             EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3958         }
3959         return eventInfo.errCode;
3960     }
3961     eventInfo.errCode = ConnectLocalAbility(abilityWant, validUserId, connect, callerToken,
3962         AppExecFwk::ExtensionAbilityType::UI, sessionInfo, false, connectInfo);
3963     if (eventInfo.errCode != ERR_OK) {
3964         EventReport::SendExtensionEvent(EventName::CONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3965     }
3966     return eventInfo.errCode;
3967 }
3968 
BuildEventInfo(const Want & want,int32_t userId)3969 EventInfo AbilityManagerService::BuildEventInfo(const Want &want, int32_t userId)
3970 {
3971     EventInfo eventInfo;
3972     eventInfo.userId = userId;
3973     eventInfo.bundleName = want.GetElement().GetBundleName();
3974     eventInfo.moduleName = want.GetElement().GetModuleName();
3975     eventInfo.abilityName = want.GetElement().GetAbilityName();
3976     return eventInfo;
3977 }
3978 
DisconnectAbility(sptr<IAbilityConnection> connect)3979 int AbilityManagerService::DisconnectAbility(sptr<IAbilityConnection> connect)
3980 {
3981     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3982     TAG_LOGD(AAFwkTag::ABILITYMGR, "Disconnect ability begin.");
3983     EventInfo eventInfo;
3984     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
3985     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
3986 
3987     if (ERR_OK != DisconnectLocalAbility(connect) &&
3988         ERR_OK != DisconnectRemoteAbility(connect->AsObject())) {
3989         eventInfo.errCode = INNER_ERR;
3990         EventReport::SendExtensionEvent(EventName::DISCONNECT_SERVICE_ERROR, HiSysEventType::FAULT, eventInfo);
3991     }
3992     return ERR_OK;
3993 }
3994 
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)3995 int AbilityManagerService::ConnectLocalAbility(const Want &want, const int32_t userId,
3996     const sptr<IAbilityConnection> &connect, const sptr<IRemoteObject> &callerToken,
3997     AppExecFwk::ExtensionAbilityType extensionType, const sptr<SessionInfo> &sessionInfo,
3998     bool isQueryExtensionOnly, sptr<UIExtensionAbilityConnectInfo> connectInfo)
3999 {
4000     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4001     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4002     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
4003     bool isEnterpriseAdmin = AAFwk::UIExtensionUtils::IsEnterpriseAdmin(extensionType);
4004     if (!isEnterpriseAdmin && !JudgeMultiUserConcurrency(userId)) {
4005         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
4006         return ERR_CROSS_USER;
4007     }
4008 
4009     AbilityRequest abilityRequest;
4010     ErrCode result = ERR_OK;
4011     if (isQueryExtensionOnly ||
4012         AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4013         result = GenerateExtensionAbilityRequest(want, abilityRequest, callerToken, userId);
4014     } else {
4015         result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, callerToken, userId);
4016     }
4017     abilityRequest.sessionInfo = sessionInfo;
4018 
4019     Want requestWant = want;
4020     CHECK_POINTER_AND_RETURN_LOG(connect, ERR_INVALID_VALUE, "connect is nullptr");
4021     TAG_LOGD(AAFwkTag::ABILITYMGR, "requestWant SetParam success");
4022 
4023     if (result != ERR_OK) {
4024         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
4025         return result;
4026     }
4027 
4028     auto abilityInfo = abilityRequest.abilityInfo;
4029     if (abilityInfo.isStageBasedModel) {
4030         bool isService = (abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::SERVICE);
4031         if (isService && extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
4032             TAG_LOGE(AAFwkTag::ABILITYMGR, "Service extension type, please use ConnectAbility.");
4033             return ERR_WRONG_INTERFACE_CALL;
4034         }
4035         // not allow app to connect other extension by using connectServiceExtensionAbility
4036         if (callerToken && extensionType == AppExecFwk::ExtensionAbilityType::SERVICE && !isService) {
4037             TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect service extension ability, but target type is not Service.");
4038             return TARGET_ABILITY_NOT_SERVICE;
4039         }
4040     }
4041     int32_t validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : userId;
4042     TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
4043         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
4044 
4045     result = CheckStaticCfgPermission(abilityRequest, false, -1);
4046     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
4047         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
4048         return ERR_STATIC_CFG_PERMISSION;
4049     }
4050 
4051     AppExecFwk::ExtensionAbilityType targetExtensionType = abilityInfo.extensionAbilityType;
4052     TAG_LOGD(AAFwkTag::ABILITYMGR, "extension type %{public}d.", targetExtensionType);
4053     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
4054         if (!AAFwk::UIExtensionUtils::IsUIExtension(targetExtensionType)
4055             && targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW) {
4056             TAG_LOGE(AAFwkTag::ABILITYMGR, "Try to connect UI extension, but target ability is not UI extension.");
4057             return ERR_WRONG_INTERFACE_CALL;
4058         }
4059 
4060         // Cause window has used this api, don't check it when type is window.
4061         if (targetExtensionType != AppExecFwk::ExtensionAbilityType::WINDOW &&
4062             !PermissionVerification::GetInstance()->VerifyCallingPermission(
4063                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY)) {
4064             TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
4065                 PermissionConstants::PERMISSION_CONNECT_UI_EXTENSION_ABILITY);
4066             return ERR_PERMISSION_DENIED;
4067         }
4068     }
4069 
4070     auto type = abilityInfo.type;
4071     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
4072         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not Service.");
4073         return TARGET_ABILITY_NOT_SERVICE;
4074     }
4075 
4076     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
4077         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo));
4078     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
4079         afterCheckExecuter_->DoProcess(afterCheckParam);
4080     if (result != ERR_OK) {
4081         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
4082         return result;
4083     }
4084 
4085     result = CheckCallServicePermission(abilityRequest);
4086     if (result != ERR_OK) {
4087         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s CheckCallServicePermission error.", __func__);
4088         return result;
4089     }
4090 
4091     if (!ExtensionPermissionsUtil::CheckSAPermission(targetExtensionType)) {
4092         TAG_LOGE(AAFwkTag::ABILITYMGR, "The SA doesn't have permission for target extension.");
4093         return CHECK_PERMISSION_FAILED;
4094     }
4095 
4096     result = PreLoadAppDataAbilities(abilityInfo.bundleName, validUserId);
4097     if (result != ERR_OK) {
4098         TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectAbility: App data ability preloading failed, '%{public}s', %{public}d",
4099             abilityInfo.bundleName.c_str(),
4100             result);
4101         return result;
4102     }
4103 
4104     auto connectManager = GetConnectManagerByUserId(validUserId);
4105     if (connectManager == nullptr) {
4106         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", validUserId);
4107         return ERR_INVALID_VALUE;
4108     }
4109 
4110     ReportEventToRSS(abilityInfo, callerToken);
4111     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(const_cast<Want &>(abilityRequest.want),
4112         abilityRequest.abilityInfo.extensionAbilityType);
4113     return connectManager->ConnectAbilityLocked(abilityRequest, connect, callerToken, sessionInfo, connectInfo);
4114 }
4115 
ConnectRemoteAbility(Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)4116 int AbilityManagerService::ConnectRemoteAbility(Want &want, const sptr<IRemoteObject> &callerToken,
4117     const sptr<IRemoteObject> &connect)
4118 {
4119     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin ConnectAbilityRemote", __func__);
4120     UpdateDmsCallerInfo(want, callerToken);
4121     if (AddStartControlParam(want, callerToken) != ERR_OK) {
4122         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
4123         return ERR_INVALID_VALUE;
4124     }
4125     DistributedClient dmsClient;
4126     return dmsClient.ConnectRemoteAbility(want, connect);
4127 }
4128 
DisconnectLocalAbility(const sptr<IAbilityConnection> & connect)4129 int AbilityManagerService::DisconnectLocalAbility(const sptr<IAbilityConnection> &connect)
4130 {
4131     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4132     auto currentConnectManager = GetCurrentConnectManager();
4133     CHECK_POINTER_AND_RETURN(currentConnectManager, ERR_NO_INIT);
4134     if (currentConnectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4135         return ERR_OK;
4136     }
4137     // If current connectManager does not exist connect, then try connectManagerU0
4138     auto connectManager = GetConnectManagerByUserId(U0_USER_ID);
4139     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4140     if (connectManager->DisconnectAbilityLocked(connect) == ERR_OK) {
4141         return ERR_OK;
4142     }
4143 
4144     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
4145     if (userId == U0_USER_ID) {
4146         auto connectManagers = GetConnectManagers();
4147         for (auto& item : connectManagers) {
4148             if (item.second && item.second->DisconnectAbilityLocked(connect) == ERR_OK) {
4149                 return ERR_OK;
4150             }
4151         }
4152     }
4153 
4154     // EnterpriseAdminExtensionAbility Scene
4155     connectManager = GetConnectManagerByUserId(USER_ID_DEFAULT);
4156     CHECK_POINTER_AND_RETURN(connectManager, ERR_NO_INIT);
4157     return connectManager->DisconnectAbilityLocked(connect);
4158 }
4159 
DisconnectRemoteAbility(const sptr<IRemoteObject> & connect)4160 int AbilityManagerService::DisconnectRemoteAbility(const sptr<IRemoteObject> &connect)
4161 {
4162     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin DisconnectAbilityRemote", __func__);
4163     int32_t callerUid = IPCSkeleton::GetCallingUid();
4164     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4165     DistributedClient dmsClient;
4166     return dmsClient.DisconnectRemoteAbility(connect, callerUid, accessToken);
4167 }
4168 
ContinueMission(const std::string & srcDeviceId,const std::string & dstDeviceId,int32_t missionId,const sptr<IRemoteObject> & callBack,AAFwk::WantParams & wantParams)4169 int AbilityManagerService::ContinueMission(const std::string &srcDeviceId, const std::string &dstDeviceId,
4170     int32_t missionId, const sptr<IRemoteObject> &callBack, AAFwk::WantParams &wantParams)
4171 {
4172     CHECK_CALLER_IS_SYSTEM_APP;
4173     TAG_LOGI(AAFwkTag::ABILITYMGR, "ContinueMission missionId: %{public}d", missionId);
4174     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4175         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4176         return CHECK_PERMISSION_FAILED;
4177     }
4178 
4179     DistributedClient dmsClient;
4180     return dmsClient.ContinueMission(srcDeviceId, dstDeviceId, missionId, callBack, wantParams);
4181 }
4182 
ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,const sptr<IRemoteObject> & callback)4183 int AbilityManagerService::ContinueMission(AAFwk::ContinueMissionInfo continueMissionInfo,
4184     const sptr<IRemoteObject> &callback)
4185 {
4186     CHECK_CALLER_IS_SYSTEM_APP;
4187     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
4188     AAFWK::ContinueRadar::GetInstance().ClickIconContinue("ContinueMission");
4189     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4190         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4191         return CHECK_PERMISSION_FAILED;
4192     }
4193 
4194     DistributedClient dmsClient;
4195     return dmsClient.ContinueMission(continueMissionInfo, callback);
4196 }
4197 
ContinueAbility(const std::string & deviceId,int32_t missionId,uint32_t versionCode)4198 int AbilityManagerService::ContinueAbility(const std::string &deviceId, int32_t missionId, uint32_t versionCode)
4199 {
4200     TAG_LOGI(AAFwkTag::ABILITYMGR,
4201         "ContinueAbility missionId = %{public}d, version = %{public}u.", missionId, versionCode);
4202     if (!CheckCallerIsDmsProcess()) {
4203         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check processName failed");
4204         return ERR_INVALID_VALUE;
4205     }
4206 
4207     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4208     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4209         auto uiAbilityManager = GetCurrentUIAbilityManager();
4210         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4211         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4212     } else {
4213         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4214         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4215         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4216     }
4217     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4218 
4219     abilityRecord->ContinueAbility(deviceId, versionCode);
4220     return ERR_OK;
4221 }
4222 
StartContinuation(const Want & want,const sptr<IRemoteObject> & abilityToken,int32_t status)4223 int AbilityManagerService::StartContinuation(const Want &want, const sptr<IRemoteObject> &abilityToken, int32_t status)
4224 {
4225     TAG_LOGI(AAFwkTag::ABILITYMGR, "Start Continuation.");
4226     if (!CheckIfOperateRemote(want)) {
4227         TAG_LOGE(AAFwkTag::ABILITYMGR, "deviceId or bundle name or abilityName empty");
4228         return ERR_INVALID_VALUE;
4229     }
4230     CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4231 
4232     int32_t appUid = IPCSkeleton::GetCallingUid();
4233     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
4234         TAG_LOGI(AAFwkTag::ABILITYMGR,
4235             "AbilityManagerService::Try to StartContinuation");
4236     int32_t missionId = -1;
4237     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4238         missionId = GetMissionIdByAbilityTokenInner(abilityToken);
4239         if (!missionId) {
4240             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
4241             return ERR_INVALID_VALUE;
4242         }
4243     } else {
4244         missionId = GetMissionIdByAbilityToken(abilityToken);
4245     }
4246     if (missionId < 0) {
4247         TAG_LOGE(AAFwkTag::ABILITYMGR, "AbilityManagerService::StartContinuation failed to get missionId.");
4248         return ERR_INVALID_VALUE;
4249     }
4250     AAFWK::ContinueRadar::GetInstance().SaveDataRemoteWant("StartContinuation");
4251     DistributedClient dmsClient;
4252     auto result =  dmsClient.StartContinuation(want, missionId, appUid, status, accessToken);
4253     if (result != ERR_OK) {
4254         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartContinuation failed, result = %{public}d, notify caller", result);
4255         NotifyContinuationResult(missionId, result);
4256     }
4257     return result;
4258 }
4259 
NotifyCompleteContinuation(const std::string & deviceId,int32_t sessionId,bool isSuccess)4260 void AbilityManagerService::NotifyCompleteContinuation(const std::string &deviceId,
4261     int32_t sessionId, bool isSuccess)
4262 {
4263     TAG_LOGI(AAFwkTag::ABILITYMGR, "NotifyCompleteContinuation.");
4264     AAFWK::ContinueRadar::GetInstance().ClickIconRecvOver("NotifyCompleteContinuation");
4265     sptr<ISystemAbilityManager> samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
4266     if (samgrProxy == nullptr) {
4267         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get samgrProxy");
4268         return;
4269     }
4270     sptr<IRemoteObject> bmsProxy = samgrProxy->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
4271     if (bmsProxy == nullptr) {
4272         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms from samgr");
4273         return;
4274     }
4275     auto bundleMgr = iface_cast<AppExecFwk::IBundleMgr>(bmsProxy);
4276     if (bundleMgr == nullptr) {
4277         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bms");
4278         return;
4279     }
4280     int32_t callerUid = IPCSkeleton::GetCallingUid();
4281     std::string callerBundleName;
4282     // reset ipc identity
4283     auto identity = IPCSkeleton::ResetCallingIdentity();
4284     bool result = bundleMgr->GetBundleNameForUid(callerUid, callerBundleName);
4285     // set ipc identity to raw
4286     IPCSkeleton::SetCallingIdentity(identity);
4287     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName: %{public}s", callerBundleName.c_str());
4288     DistributedClient dmsClient;
4289     dmsClient.NotifyCompleteContinuation(Str8ToStr16(deviceId), sessionId, isSuccess, callerBundleName);
4290 }
4291 
NotifyContinuationResult(int32_t missionId,int32_t result)4292 int AbilityManagerService::NotifyContinuationResult(int32_t missionId, int32_t result)
4293 {
4294     TAG_LOGI(AAFwkTag::ABILITYMGR, "Notify Continuation Result : %{public}d.", result);
4295 
4296     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
4297     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4298         auto uiAbilityManager = GetCurrentUIAbilityManager();
4299         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4300         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
4301     } else {
4302         sptr<IRemoteObject> abilityToken = GetAbilityTokenByMissionId(missionId);
4303         CHECK_POINTER_AND_RETURN(abilityToken, ERR_INVALID_VALUE);
4304         abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
4305     }
4306     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
4307 
4308     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
4309         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
4310         return ERR_INVALID_VALUE;
4311     }
4312     abilityRecord->NotifyContinuationResult(result);
4313     return ERR_OK;
4314 }
4315 
StartSyncRemoteMissions(const std::string & devId,bool fixConflict,int64_t tag)4316 int AbilityManagerService::StartSyncRemoteMissions(const std::string& devId, bool fixConflict, int64_t tag)
4317 {
4318     CHECK_CALLER_IS_SYSTEM_APP;
4319     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4320         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4321         return CHECK_PERMISSION_FAILED;
4322     }
4323     DistributedClient dmsClient;
4324     return dmsClient.StartSyncRemoteMissions(devId, fixConflict, tag);
4325 }
4326 
StopSyncRemoteMissions(const std::string & devId)4327 int AbilityManagerService::StopSyncRemoteMissions(const std::string& devId)
4328 {
4329     CHECK_CALLER_IS_SYSTEM_APP;
4330     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4331         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4332         return CHECK_PERMISSION_FAILED;
4333     }
4334     DistributedClient dmsClient;
4335     return dmsClient.StopSyncRemoteMissions(devId);
4336 }
4337 
RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4338 int AbilityManagerService::RegisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4339 {
4340     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4341         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
4342         return CHECK_PERMISSION_FAILED;
4343     }
4344     return DelayedSingleton<ConnectionStateManager>::GetInstance()->RegisterObserver(observer);
4345 }
4346 
UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> & observer)4347 int AbilityManagerService::UnregisterObserver(const sptr<AbilityRuntime::IConnectionObserver> &observer)
4348 {
4349     if (!PermissionVerification::GetInstance()->CheckObserverCallerPermission()) {
4350         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
4351         return CHECK_PERMISSION_FAILED;
4352     }
4353     return DelayedSingleton<ConnectionStateManager>::GetInstance()->UnregisterObserver(observer);
4354 }
4355 
4356 #ifdef WITH_DLP
GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> & infos)4357 int AbilityManagerService::GetDlpConnectionInfos(std::vector<AbilityRuntime::DlpConnectionInfo> &infos)
4358 {
4359     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4360         TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get dlp connection infos if caller is not sa.");
4361         return CHECK_PERMISSION_FAILED;
4362     }
4363     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetDlpConnectionInfos(infos);
4364 
4365     return ERR_OK;
4366 }
4367 #endif // WITH_DLP
4368 
GetConnectionData(std::vector<AbilityRuntime::ConnectionData> & connectionData)4369 int AbilityManagerService::GetConnectionData(std::vector<AbilityRuntime::ConnectionData> &connectionData)
4370 {
4371     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4372         TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get connection data if caller is not sa.");
4373         return CHECK_PERMISSION_FAILED;
4374     }
4375     DelayedSingleton<ConnectionStateManager>::GetInstance()->GetConnectionData(connectionData);
4376 
4377     return ERR_OK;
4378 }
4379 
RegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4380 int AbilityManagerService::RegisterMissionListener(const std::string &deviceId,
4381     const sptr<IRemoteMissionListener> &listener)
4382 {
4383     CHECK_CALLER_IS_SYSTEM_APP;
4384     std::string localDeviceId;
4385     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4386         TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterMissionListener: Check DeviceId failed");
4387         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4388     }
4389     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4390     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4391         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4392         return CHECK_PERMISSION_FAILED;
4393     }
4394     DistributedClient dmsClient;
4395     return dmsClient.RegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4396 }
4397 
RegisterOnListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4398 int AbilityManagerService::RegisterOnListener(const std::string &type,
4399     const sptr<IRemoteOnListener> &listener)
4400 {
4401     CHECK_CALLER_IS_SYSTEM_APP;
4402     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4403     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4404         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4405         return CHECK_PERMISSION_FAILED;
4406     }
4407     DistributedClient dmsClient;
4408     return dmsClient.RegisterOnListener(type, listener->AsObject());
4409 }
4410 
RegisterOffListener(const std::string & type,const sptr<IRemoteOnListener> & listener)4411 int AbilityManagerService::RegisterOffListener(const std::string &type,
4412     const sptr<IRemoteOnListener> &listener)
4413 {
4414     CHECK_CALLER_IS_SYSTEM_APP;
4415     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4416     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4417         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4418         return CHECK_PERMISSION_FAILED;
4419     }
4420     DistributedClient dmsClient;
4421     return dmsClient.RegisterOffListener(type, listener->AsObject());
4422 }
4423 
UnRegisterMissionListener(const std::string & deviceId,const sptr<IRemoteMissionListener> & listener)4424 int AbilityManagerService::UnRegisterMissionListener(const std::string &deviceId,
4425     const sptr<IRemoteMissionListener> &listener)
4426 {
4427     CHECK_CALLER_IS_SYSTEM_APP;
4428     std::string localDeviceId;
4429     if (!GetLocalDeviceId(localDeviceId) || localDeviceId == deviceId) {
4430         TAG_LOGE(AAFwkTag::ABILITYMGR, "RegisterMissionListener: Check DeviceId failed");
4431         return REGISTER_REMOTE_MISSION_LISTENER_FAIL;
4432     }
4433     CHECK_POINTER_AND_RETURN(listener, ERR_INVALID_VALUE);
4434     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4435         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4436         return CHECK_PERMISSION_FAILED;
4437     }
4438     DistributedClient dmsClient;
4439     return dmsClient.UnRegisterMissionListener(Str8ToStr16(deviceId), listener->AsObject());
4440 }
4441 
GetWantSender(const WantSenderInfo & wantSenderInfo,const sptr<IRemoteObject> & callerToken,int32_t uid)4442 sptr<IWantSender> AbilityManagerService::GetWantSender(
4443     const WantSenderInfo &wantSenderInfo, const sptr<IRemoteObject> &callerToken,
4444     int32_t uid)
4445 {
4446     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4447     auto pendingWantManager = GetCurrentPendingWantManager();
4448     CHECK_POINTER_AND_RETURN(pendingWantManager, nullptr);
4449 
4450     auto bms = GetBundleManager();
4451     CHECK_POINTER_AND_RETURN(bms, nullptr);
4452 
4453     int32_t callerUid = IPCSkeleton::GetCallingUid();
4454     int32_t userId = wantSenderInfo.userId;
4455     int32_t bundleMgrResult = 0;
4456 
4457     if (userId < 0) {
4458         if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4459             GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4460             TAG_LOGE(AAFwkTag::ABILITYMGR, "GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
4461             return nullptr;
4462         }
4463     }
4464     //sa caller and has uid,no need find from bms.
4465     bool isSpecifyUidBySa = (uid != -1) && (AAFwk::PermissionVerification::GetInstance()->IsSACall());
4466 
4467     int32_t appUid = 0;
4468     int32_t appIndex = 0;
4469     if (!wantSenderInfo.allWants.empty()) {
4470         AppExecFwk::BundleInfo bundleInfo;
4471         std::string bundleName = wantSenderInfo.allWants.back().want.GetElement().GetBundleName();
4472         GetRunningMultiAppIndex(bundleName, callerUid, appIndex);
4473         if (!isSpecifyUidBySa) {
4474             bundleMgrResult = IN_PROCESS_CALL(bms->GetCloneBundleInfo(bundleName,
4475                 static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
4476                 appIndex, bundleInfo, userId));
4477             if (bundleMgrResult == ERR_OK) {
4478                 appUid = bundleInfo.uid;
4479             }
4480         } else {
4481             appUid = uid;
4482         }
4483         TAG_LOGD(AAFwkTag::ABILITYMGR, "App bundleName: %{public}s, uid: %{public}d", bundleName.c_str(), appUid);
4484     }
4485     if (!CheckSenderWantInfo(callerUid, wantSenderInfo)) {
4486         TAG_LOGE(AAFwkTag::ABILITYMGR, "check bundleName failed");
4487         return nullptr;
4488     }
4489 
4490     bool isSystemApp = false;
4491     if (!wantSenderInfo.bundleName.empty() && !isSpecifyUidBySa) {
4492         AppExecFwk::BundleInfo bundleInfo;
4493         bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(wantSenderInfo.bundleName,
4494             AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
4495         if (bundleMgrResult) {
4496             isSystemApp = bundleInfo.applicationInfo.isSystemApp;
4497         }
4498     }
4499 
4500     TAG_LOGD(AAFwkTag::ABILITYMGR, "bundleName = %{public}s, appIndex:%{public}d",
4501         wantSenderInfo.bundleName.c_str(), appIndex);
4502     return pendingWantManager->GetWantSender(callerUid, appUid, isSystemApp, wantSenderInfo, callerToken, appIndex);
4503 }
4504 
SendWantSender(sptr<IWantSender> target,const SenderInfo & senderInfo)4505 int AbilityManagerService::SendWantSender(sptr<IWantSender> target, const SenderInfo &senderInfo)
4506 {
4507     TAG_LOGI(AAFwkTag::ABILITYMGR, "Send want sender.");
4508     auto pendingWantManager = GetCurrentPendingWantManager();
4509     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4510     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4511     return pendingWantManager->SendWantSender(target, senderInfo);
4512 }
4513 
CancelWantSender(const sptr<IWantSender> & sender)4514 void AbilityManagerService::CancelWantSender(const sptr<IWantSender> &sender)
4515 {
4516     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
4517     auto pendingWantManager = GetCurrentPendingWantManager();
4518     CHECK_POINTER(pendingWantManager);
4519     CHECK_POINTER(sender);
4520 
4521     sptr<IRemoteObject> obj = sender->AsObject();
4522     if (!obj || obj->IsProxyObject()) {
4523         TAG_LOGE(AAFwkTag::ABILITYMGR, "obj is nullptr or obj is a proxy obj.");
4524         return;
4525     }
4526 
4527     auto bms = GetBundleManager();
4528     CHECK_POINTER(bms);
4529 
4530     int32_t callerUid = IPCSkeleton::GetCallingUid();
4531     sptr<PendingWantRecord> record = iface_cast<PendingWantRecord>(obj);
4532 
4533     int userId = -1;
4534     if (DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
4535         GetOsAccountLocalIdFromUid(callerUid, userId) != 0) {
4536         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetOsAccountLocalIdFromUid failed. uid=%{public}d", callerUid);
4537         return;
4538     }
4539     bool isSystemApp = false;
4540     if (record->GetKey() != nullptr && !record->GetKey()->GetBundleName().empty()) {
4541         AppExecFwk::BundleInfo bundleInfo;
4542         bool bundleMgrResult = IN_PROCESS_CALL(bms->GetBundleInfo(record->GetKey()->GetBundleName(),
4543             AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId));
4544         if (!bundleMgrResult) {
4545             TAG_LOGE(AAFwkTag::ABILITYMGR, "GetBundleInfo is fail.");
4546             return;
4547         }
4548         isSystemApp = bundleInfo.applicationInfo.isSystemApp;
4549     }
4550 
4551     pendingWantManager->CancelWantSender(isSystemApp, sender);
4552 }
4553 
GetPendingWantUid(const sptr<IWantSender> & target)4554 int AbilityManagerService::GetPendingWantUid(const sptr<IWantSender> &target)
4555 {
4556     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4557     auto pendingWantManager = GetCurrentPendingWantManager();
4558     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4559     if (target == nullptr) {
4560         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4561         return -1;
4562     }
4563     return pendingWantManager->GetPendingWantUid(target);
4564 }
4565 
GetPendingWantUserId(const sptr<IWantSender> & target)4566 int AbilityManagerService::GetPendingWantUserId(const sptr<IWantSender> &target)
4567 {
4568     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4569     auto pendingWantManager = GetCurrentPendingWantManager();
4570     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4571     if (target == nullptr) {
4572         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4573         return -1;
4574     }
4575     return pendingWantManager->GetPendingWantUserId(target);
4576 }
4577 
GetPendingWantBundleName(const sptr<IWantSender> & target)4578 std::string AbilityManagerService::GetPendingWantBundleName(const sptr<IWantSender> &target)
4579 {
4580     TAG_LOGI(AAFwkTag::ABILITYMGR, "Get pending want bundle name.");
4581     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantBundleName");
4582     auto pendingWantManager = GetCurrentPendingWantManager();
4583     CHECK_POINTER_AND_RETURN(pendingWantManager, "");
4584     CHECK_POINTER_AND_RETURN(target, "");
4585     return pendingWantManager->GetPendingWantBundleName(target);
4586 }
4587 
GetPendingWantCode(const sptr<IWantSender> & target)4588 int AbilityManagerService::GetPendingWantCode(const sptr<IWantSender> &target)
4589 {
4590     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4591     auto pendingWantManager = GetCurrentPendingWantManager();
4592     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4593     if (target == nullptr) {
4594         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4595         return -1;
4596     }
4597     return pendingWantManager->GetPendingWantCode(target);
4598 }
4599 
GetPendingWantType(const sptr<IWantSender> & target)4600 int AbilityManagerService::GetPendingWantType(const sptr<IWantSender> &target)
4601 {
4602     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s:begin.", __func__);
4603     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingWantType");
4604     auto pendingWantManager = GetCurrentPendingWantManager();
4605     CHECK_POINTER_AND_RETURN(pendingWantManager, -1);
4606     if (target == nullptr) {
4607         TAG_LOGE(AAFwkTag::ABILITYMGR, "%s, target is nullptr", __func__);
4608         return -1;
4609     }
4610     return pendingWantManager->GetPendingWantType(target);
4611 }
4612 
RegisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)4613 void AbilityManagerService::RegisterCancelListener(const sptr<IWantSender> &sender,
4614     const sptr<IWantReceiver> &receiver)
4615 {
4616     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register cancel listener.");
4617     auto pendingWantManager = GetCurrentPendingWantManager();
4618     CHECK_POINTER(pendingWantManager);
4619     CHECK_POINTER(sender);
4620     CHECK_POINTER(receiver);
4621     pendingWantManager->RegisterCancelListener(sender, receiver);
4622 }
4623 
UnregisterCancelListener(const sptr<IWantSender> & sender,const sptr<IWantReceiver> & receiver)4624 void AbilityManagerService::UnregisterCancelListener(
4625     const sptr<IWantSender> &sender, const sptr<IWantReceiver> &receiver)
4626 {
4627     TAG_LOGI(AAFwkTag::ABILITYMGR, "Unregister cancel listener.");
4628     auto pendingWantManager = GetCurrentPendingWantManager();
4629     CHECK_POINTER(pendingWantManager);
4630     CHECK_POINTER(sender);
4631     CHECK_POINTER(receiver);
4632     pendingWantManager->UnregisterCancelListener(sender, receiver);
4633 }
4634 
GetPendingRequestWant(const sptr<IWantSender> & target,std::shared_ptr<Want> & want)4635 int AbilityManagerService::GetPendingRequestWant(const sptr<IWantSender> &target, std::shared_ptr<Want> &want)
4636 {
4637     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4638     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get pending request want.");
4639     AbilityManagerXCollie abilityManagerXCollie("AbilityManagerService::GetPendingRequestWant");
4640     auto pendingWantManager = GetCurrentPendingWantManager();
4641     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
4642     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
4643     CHECK_POINTER_AND_RETURN(want, ERR_INVALID_VALUE);
4644     CHECK_CALLER_IS_SYSTEM_APP;
4645     return pendingWantManager->GetPendingRequestWant(target, want);
4646 }
4647 
LockMissionForCleanup(int32_t missionId)4648 int AbilityManagerService::LockMissionForCleanup(int32_t missionId)
4649 {
4650     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock mission for clean up all, id :%{public}d", missionId);
4651     auto missionListManager = GetCurrentMissionListManager();
4652     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4653     CHECK_CALLER_IS_SYSTEM_APP;
4654 
4655     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4656         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4657         return CHECK_PERMISSION_FAILED;
4658     }
4659     return missionListManager->SetMissionLockedState(missionId, true);
4660 }
4661 
UnlockMissionForCleanup(int32_t missionId)4662 int AbilityManagerService::UnlockMissionForCleanup(int32_t missionId)
4663 {
4664     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4665     TAG_LOGI(AAFwkTag::ABILITYMGR, "request unlock mission for clean up all, id :%{public}d", missionId);
4666     auto missionListManager = GetCurrentMissionListManager();
4667     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4668     CHECK_CALLER_IS_SYSTEM_APP;
4669 
4670     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4671         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4672         return CHECK_PERMISSION_FAILED;
4673     }
4674     return missionListManager->SetMissionLockedState(missionId, false);
4675 }
4676 
SetLockedState(int32_t sessionId,bool lockedState)4677 void AbilityManagerService::SetLockedState(int32_t sessionId, bool lockedState)
4678 {
4679     TAG_LOGI(AAFwkTag::ABILITYMGR, "request lock abilityRecord, sessionId :%{public}d", sessionId);
4680     if (!IsCallerSceneBoard()) {
4681         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
4682         return;
4683     }
4684     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4685     CHECK_POINTER(uiAbilityManager);
4686     auto abilityRecord = uiAbilityManager->GetAbilityRecordsById(sessionId);
4687     if (!abilityRecord) {
4688         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
4689         return;
4690     }
4691     abilityRecord->SetLockedState(lockedState);
4692 }
4693 
RegisterMissionListener(const sptr<IMissionListener> & listener)4694 int AbilityManagerService::RegisterMissionListener(const sptr<IMissionListener> &listener)
4695 {
4696     TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
4697     auto missionListManager = GetCurrentMissionListManager();
4698     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4699     CHECK_CALLER_IS_SYSTEM_APP;
4700 
4701     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4702         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4703         return CHECK_PERMISSION_FAILED;
4704     }
4705     return missionListManager->RegisterMissionListener(listener);
4706 }
4707 
UnRegisterMissionListener(const sptr<IMissionListener> & listener)4708 int AbilityManagerService::UnRegisterMissionListener(const sptr<IMissionListener> &listener)
4709 {
4710     TAG_LOGI(AAFwkTag::ABILITYMGR, "request RegisterMissionListener ");
4711     auto missionListManager = GetCurrentMissionListManager();
4712     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4713     CHECK_CALLER_IS_SYSTEM_APP;
4714 
4715     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4716         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4717         return CHECK_PERMISSION_FAILED;
4718     }
4719     return missionListManager->UnRegisterMissionListener(listener);
4720 }
4721 
GetMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)4722 int AbilityManagerService::GetMissionInfos(const std::string& deviceId, int32_t numMax,
4723     std::vector<MissionInfo> &missionInfos)
4724 {
4725     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4726     TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfos.");
4727     auto missionListManager = GetCurrentMissionListManager();
4728     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4729     CHECK_CALLER_IS_SYSTEM_APP;
4730 
4731     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4732         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4733         return CHECK_PERMISSION_FAILED;
4734     }
4735 
4736     if (CheckIsRemote(deviceId)) {
4737         return GetRemoteMissionInfos(deviceId, numMax, missionInfos);
4738     }
4739 
4740     return missionListManager->GetMissionInfos(numMax, missionInfos);
4741 }
4742 
GetRemoteMissionInfos(const std::string & deviceId,int32_t numMax,std::vector<MissionInfo> & missionInfos)4743 int AbilityManagerService::GetRemoteMissionInfos(const std::string& deviceId, int32_t numMax,
4744     std::vector<MissionInfo> &missionInfos)
4745 {
4746     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetRemoteMissionInfos begin");
4747     DistributedClient dmsClient;
4748     int result = dmsClient.GetMissionInfos(deviceId, numMax, missionInfos);
4749     if (result != ERR_OK) {
4750         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetRemoteMissionInfos failed, result = %{public}d", result);
4751         return result;
4752     }
4753     return ERR_OK;
4754 }
4755 
GetMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)4756 int AbilityManagerService::GetMissionInfo(const std::string& deviceId, int32_t missionId,
4757     MissionInfo &missionInfo)
4758 {
4759     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4760     TAG_LOGI(AAFwkTag::ABILITYMGR, "request GetMissionInfo, missionId:%{public}d", missionId);
4761     auto missionListManager = GetCurrentMissionListManager();
4762     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4763     CHECK_CALLER_IS_SYSTEM_APP;
4764 
4765     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4766         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4767         return CHECK_PERMISSION_FAILED;
4768     }
4769 
4770     if (CheckIsRemote(deviceId)) {
4771         return GetRemoteMissionInfo(deviceId, missionId, missionInfo);
4772     }
4773 
4774     return missionListManager->GetMissionInfo(missionId, missionInfo);
4775 }
4776 
GetRemoteMissionInfo(const std::string & deviceId,int32_t missionId,MissionInfo & missionInfo)4777 int AbilityManagerService::GetRemoteMissionInfo(const std::string& deviceId, int32_t missionId,
4778     MissionInfo &missionInfo)
4779 {
4780     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4781     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetMissionInfoFromDms begin");
4782     std::vector<MissionInfo> missionVector;
4783     int result = GetRemoteMissionInfos(deviceId, MAX_NUMBER_OF_DISTRIBUTED_MISSIONS, missionVector);
4784     if (result != ERR_OK) {
4785         return result;
4786     }
4787     for (auto iter = missionVector.begin(); iter != missionVector.end(); iter++) {
4788         if (iter->id == missionId) {
4789             missionInfo = *iter;
4790             return ERR_OK;
4791         }
4792     }
4793     TAG_LOGW(AAFwkTag::ABILITYMGR, "missionId not found");
4794     return ERR_INVALID_VALUE;
4795 }
4796 
CleanMission(int32_t missionId)4797 int AbilityManagerService::CleanMission(int32_t missionId)
4798 {
4799     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4800     TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanMission, missionId:%{public}d", missionId);
4801     auto missionListManager = GetCurrentMissionListManager();
4802     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4803     CHECK_CALLER_IS_SYSTEM_APP;
4804 
4805     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4806         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4807         return CHECK_PERMISSION_FAILED;
4808     }
4809 
4810     return missionListManager->ClearMission(missionId);
4811 }
4812 
CleanAllMissions()4813 int AbilityManagerService::CleanAllMissions()
4814 {
4815     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4816     TAG_LOGI(AAFwkTag::ABILITYMGR, "request CleanAllMissions ");
4817     auto missionListManager = GetCurrentMissionListManager();
4818     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4819     CHECK_CALLER_IS_SYSTEM_APP;
4820 
4821     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4822         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4823         return CHECK_PERMISSION_FAILED;
4824     }
4825 
4826     Want want;
4827     want.SetElementName(AbilityConfig::LAUNCHER_BUNDLE_NAME, AbilityConfig::LAUNCHER_ABILITY_NAME);
4828     if (!IsAbilityControllerStart(want, AbilityConfig::LAUNCHER_BUNDLE_NAME)) {
4829         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
4830         return ERR_WOULD_BLOCK;
4831     }
4832 
4833     return missionListManager->ClearAllMissions();
4834 }
4835 
MoveMissionToFront(int32_t missionId)4836 int AbilityManagerService::MoveMissionToFront(int32_t missionId)
4837 {
4838     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4839     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
4840     CHECK_CALLER_IS_SYSTEM_APP;
4841     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4842         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4843         return CHECK_PERMISSION_FAILED;
4844     }
4845 
4846     if (!IsAbilityControllerStartById(missionId)) {
4847         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
4848         return ERR_WOULD_BLOCK;
4849     }
4850 
4851     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4852         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4853         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4854         return uiAbilityManager->MoveMissionToFront(missionId);
4855     }
4856 
4857     auto missionListManager = GetCurrentMissionListManager();
4858     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4859     return missionListManager->MoveMissionToFront(missionId);
4860 }
4861 
MoveMissionToFront(int32_t missionId,const StartOptions & startOptions)4862 int AbilityManagerService::MoveMissionToFront(int32_t missionId, const StartOptions &startOptions)
4863 {
4864     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4865     TAG_LOGI(AAFwkTag::ABILITYMGR, "request MoveMissionToFront, missionId:%{public}d", missionId);
4866     CHECK_CALLER_IS_SYSTEM_APP;
4867     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4868         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4869         return CHECK_PERMISSION_FAILED;
4870     }
4871 
4872     if (!IsAbilityControllerStartById(missionId)) {
4873         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
4874         return ERR_WOULD_BLOCK;
4875     }
4876 
4877     auto options = std::make_shared<StartOptions>(startOptions);
4878     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
4879         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
4880         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
4881         return uiAbilityManager->MoveMissionToFront(missionId, options);
4882     }
4883 
4884     auto missionListManager = GetCurrentMissionListManager();
4885     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
4886     return missionListManager->MoveMissionToFront(missionId, options);
4887 }
4888 
MoveMissionsToForeground(const std::vector<int32_t> & missionIds,int32_t topMissionId)4889 int AbilityManagerService::MoveMissionsToForeground(const std::vector<int32_t>& missionIds, int32_t topMissionId)
4890 {
4891     CHECK_CALLER_IS_SYSTEM_APP;
4892     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4893         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4894         return CHECK_PERMISSION_FAILED;
4895     }
4896     if (wmsHandler_) {
4897         auto ret = wmsHandler_->MoveMissionsToForeground(missionIds, topMissionId);
4898         if (ret) {
4899             TAG_LOGE(AAFwkTag::ABILITYMGR, "MoveMissionsToForeground failed, missiondIds may be invalid");
4900             return ERR_INVALID_VALUE;
4901         } else {
4902             return NO_ERROR;
4903         }
4904     }
4905     return ERR_NO_INIT;
4906 }
4907 
MoveMissionsToBackground(const std::vector<int32_t> & missionIds,std::vector<int32_t> & result)4908 int AbilityManagerService::MoveMissionsToBackground(const std::vector<int32_t>& missionIds,
4909     std::vector<int32_t>& result)
4910 {
4911     CHECK_CALLER_IS_SYSTEM_APP;
4912     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
4913         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
4914         return CHECK_PERMISSION_FAILED;
4915     }
4916     if (wmsHandler_) {
4917         auto ret = wmsHandler_->MoveMissionsToBackground(missionIds, result);
4918         if (ret) {
4919             TAG_LOGE(AAFwkTag::ABILITYMGR, "MoveMissionsToBackground failed, missiondIds may be invalid");
4920             return ERR_INVALID_VALUE;
4921         } else {
4922             return NO_ERROR;
4923         }
4924     }
4925     return ERR_NO_INIT;
4926 }
4927 
GetMissionIdByToken(const sptr<IRemoteObject> & token)4928 int32_t AbilityManagerService::GetMissionIdByToken(const sptr<IRemoteObject> &token)
4929 {
4930     TAG_LOGD(AAFwkTag::ABILITYMGR, "request GetMissionIdByToken.");
4931     auto abilityRecord = Token::GetAbilityRecordByToken(token);
4932     if (!abilityRecord) {
4933         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
4934         return ERR_INVALID_VALUE;
4935     }
4936     if (!JudgeSelfCalled(abilityRecord) && !CheckCallerIsDmsProcess()) {
4937         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
4938         return ERR_INVALID_VALUE;
4939     }
4940     return GetMissionIdByAbilityTokenInner(token);
4941 }
4942 
IsAbilityControllerStartById(int32_t missionId)4943 bool AbilityManagerService::IsAbilityControllerStartById(int32_t missionId)
4944 {
4945     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4946     auto missionListWrap = GetMissionListWrap();
4947     if (missionListWrap == nullptr) {
4948         TAG_LOGW(AAFwkTag::ABILITYMGR, "missionListWrap null.");
4949         return true;
4950     }
4951     InnerMissionInfo innerMissionInfo;
4952     int getMission = missionListWrap->GetInnerMissionInfoById(missionId, innerMissionInfo);
4953     if (getMission != ERR_OK) {
4954         TAG_LOGE(AAFwkTag::ABILITYMGR,
4955             "cannot find mission info from MissionInfoList by missionId: %{public}d", missionId);
4956         return true;
4957     }
4958     if (!IsAbilityControllerStart(innerMissionInfo.missionInfo.want, innerMissionInfo.missionInfo.want.GetBundle())) {
4959         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s",
4960             innerMissionInfo.missionInfo.want.GetBundle().c_str());
4961         return false;
4962     }
4963     return true;
4964 }
4965 
GetConnectRecordListByCallback(sptr<IAbilityConnection> callback)4966 std::list<std::shared_ptr<ConnectionRecord>> AbilityManagerService::GetConnectRecordListByCallback(
4967     sptr<IAbilityConnection> callback)
4968 {
4969     auto connectManager = GetCurrentConnectManager();
4970     CHECK_POINTER_AND_RETURN(connectManager, std::list<std::shared_ptr<ConnectionRecord>>());
4971     return connectManager->GetConnectRecordListByCallback(callback);
4972 }
4973 
GenerateDataAbilityRequestByUri(const std::string & dataAbilityUri,AbilityRequest & abilityRequest,sptr<IRemoteObject> callerToken,int32_t userId)4974 bool AbilityManagerService::GenerateDataAbilityRequestByUri(const std::string& dataAbilityUri,
4975     AbilityRequest &abilityRequest, sptr<IRemoteObject> callerToken, int32_t userId)
4976 {
4977     auto bms = GetBundleManager();
4978     CHECK_POINTER_AND_RETURN(bms, false);
4979     TAG_LOGI(AAFwkTag::ABILITYMGR, "called. userId %{public}d", userId);
4980     bool queryResult = IN_PROCESS_CALL(bms->QueryAbilityInfoByUri(dataAbilityUri, userId, abilityRequest.abilityInfo));
4981     if (!queryResult || abilityRequest.abilityInfo.name.empty() || abilityRequest.abilityInfo.bundleName.empty()) {
4982         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ability info for data ability acquiring.");
4983         return false;
4984     }
4985     abilityRequest.callerToken = callerToken;
4986     return true;
4987 }
4988 
AcquireDataAbility(const Uri & uri,bool tryBind,const sptr<IRemoteObject> & callerToken)4989 sptr<IAbilityScheduler> AbilityManagerService::AcquireDataAbility(
4990     const Uri &uri, bool tryBind, const sptr<IRemoteObject> &callerToken)
4991 {
4992     auto localUri(uri);
4993     if (localUri.GetScheme() != AbilityConfig::SCHEME_DATA_ABILITY) {
4994         TAG_LOGE(AAFwkTag::ABILITYMGR, "Acquire data ability with invalid uri scheme.");
4995         return nullptr;
4996     }
4997     std::vector<std::string> pathSegments;
4998     localUri.GetPathSegments(pathSegments);
4999     if (pathSegments.empty()) {
5000         TAG_LOGE(AAFwkTag::ABILITYMGR, "Acquire data ability with invalid uri path.");
5001         return nullptr;
5002     }
5003 
5004     auto userId = GetValidUserId(INVALID_USER_ID);
5005     AbilityRequest abilityRequest;
5006     if (!GenerateDataAbilityRequestByUri(localUri.ToString(), abilityRequest, callerToken, userId)) {
5007         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate data ability request by uri failed.");
5008         return nullptr;
5009     }
5010 
5011     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5012     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5013     if (!isSaCall && CheckCallDataAbilityPermission(abilityRequest, isShellCall, isSaCall) != ERR_OK) {
5014         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ability request info for data ability acquiring.");
5015         return nullptr;
5016     }
5017 
5018     TAG_LOGD(AAFwkTag::ABILITYMGR, "Query data ability info: %{public}s|%{public}s|%{public}s",
5019         abilityRequest.appInfo.name.c_str(), abilityRequest.appInfo.bundleName.c_str(),
5020         abilityRequest.abilityInfo.name.c_str());
5021 
5022     if (CheckStaticCfgPermission(abilityRequest, false, -1, true, isSaCall) !=
5023         AppExecFwk::Constants::PERMISSION_GRANTED) {
5024         TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission fail");
5025         return nullptr;
5026     }
5027 
5028     if (!VerificationAllToken(callerToken)) {
5029         TAG_LOGI(AAFwkTag::ABILITYMGR, "VerificationAllToken fail");
5030         return nullptr;
5031     }
5032 
5033     if (abilityRequest.abilityInfo.applicationInfo.singleton) {
5034         userId = U0_USER_ID;
5035     }
5036 
5037     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5038     CHECK_POINTER_AND_RETURN(dataAbilityManager, nullptr);
5039     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
5040     bool isNotHap = isSaCall || isShellCall;
5041     UpdateCallerInfo(abilityRequest.want, callerToken);
5042     return dataAbilityManager->Acquire(abilityRequest, tryBind, callerToken, isNotHap);
5043 }
5044 
ReleaseDataAbility(sptr<IAbilityScheduler> dataAbilityScheduler,const sptr<IRemoteObject> & callerToken)5045 int AbilityManagerService::ReleaseDataAbility(
5046     sptr<IAbilityScheduler> dataAbilityScheduler, const sptr<IRemoteObject> &callerToken)
5047 {
5048     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
5049     if (!dataAbilityScheduler || !callerToken) {
5050         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilitySchedule or callerToken is nullptr");
5051         return ERR_INVALID_VALUE;
5052     }
5053 
5054     std::shared_ptr<DataAbilityManager> dataAbilityManager = GetDataAbilityManager(dataAbilityScheduler);
5055     if (!dataAbilityManager) {
5056         TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityScheduler is not exists");
5057         return ERR_INVALID_VALUE;
5058     }
5059 
5060     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5061     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5062     bool isNotHap = isSaCall || isShellCall;
5063     return dataAbilityManager->Release(dataAbilityScheduler, callerToken, isNotHap);
5064 }
5065 
AttachAbilityThread(const sptr<IAbilityScheduler> & scheduler,const sptr<IRemoteObject> & token)5066 int AbilityManagerService::AttachAbilityThread(
5067     const sptr<IAbilityScheduler> &scheduler, const sptr<IRemoteObject> &token)
5068 {
5069     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5070     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s called", __func__);
5071     CHECK_POINTER_AND_RETURN(scheduler, ERR_INVALID_VALUE);
5072     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5073         return ERR_INVALID_VALUE;
5074     }
5075     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5076     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5077     if (!JudgeSelfCalled(abilityRecord)) {
5078         return CHECK_PERMISSION_FAILED;
5079     }
5080 
5081     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5082     auto abilityInfo = abilityRecord->GetAbilityInfo();
5083     auto type = abilityInfo.type;
5084     // force timeout ability for test
5085     if (IsNeedTimeoutForTest(abilityInfo.name, AbilityRecord::ConvertAbilityState(AbilityState::INITIAL))) {
5086         TAG_LOGW(AAFwkTag::ABILITYMGR,
5087             "force timeout ability for test, state:INITIAL, ability: %{public}s", abilityInfo.name.c_str());
5088         return ERR_OK;
5089     }
5090     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5091         auto connectManager = GetConnectManagerByUserId(userId);
5092         if (!connectManager) {
5093             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5094             return ERR_INVALID_VALUE;
5095         }
5096         return connectManager->AttachAbilityThreadLocked(scheduler, token);
5097     } else if (type == AppExecFwk::AbilityType::DATA) {
5098         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5099         if (!dataAbilityManager) {
5100             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
5101             return ERR_INVALID_VALUE;
5102         }
5103         return dataAbilityManager->AttachAbilityThread(scheduler, token);
5104     } else {
5105         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::LOAD };
5106         std::string entry = "AbilityManagerService::AttachAbilityThread; the end of load lifecycle.";
5107         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5108         int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5109         if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5110             auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5111             CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5112             return uiAbilityManager->AttachAbilityThread(scheduler, token);
5113         }
5114         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5115         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
5116         return missionListManager->AttachAbilityThread(scheduler, token);
5117     }
5118 }
5119 
DumpSysInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5120 void AbilityManagerService::DumpSysInner(
5121     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5122 {
5123     std::vector<std::string> argList;
5124     SplitStr(args, " ", argList);
5125     if (argList.empty()) {
5126         return;
5127     }
5128 
5129     DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5130     DumpSysStateInner(args, info, isClient, isUserID, userId);
5131     DumpSysPendingInner(args, info, isClient, isUserID, userId);
5132     DumpSysProcess(args, info, isClient, isUserID, userId);
5133 }
5134 
DumpSysMissionListInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5135 void AbilityManagerService::DumpSysMissionListInner(
5136     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5137 {
5138     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5139         DumpSysMissionListInnerBySCB(args, info, isClient, isUserID, userId);
5140         return;
5141     }
5142     std::shared_ptr<MissionListManagerInterface> targetManager;
5143     if (isUserID) {
5144         auto missionListManager = GetMissionListManagerByUserId(userId);
5145         if (missionListManager == nullptr) {
5146             info.push_back("error: No user found.");
5147             return;
5148         }
5149         targetManager = missionListManager;
5150     } else {
5151         targetManager = GetCurrentMissionListManager();
5152     }
5153 
5154     CHECK_POINTER(targetManager);
5155 
5156     std::vector<std::string> argList;
5157     SplitStr(args, " ", argList);
5158     if (argList.empty()) {
5159         return;
5160     }
5161 
5162     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5163         targetManager->DumpMissionList(info, isClient, argList[1]);
5164     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5165         targetManager->DumpMissionList(info, isClient);
5166     } else {
5167         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5168     }
5169 }
5170 
DumpSysMissionListInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5171 void AbilityManagerService::DumpSysMissionListInnerBySCB(
5172     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5173 {
5174     if (!isUserID) {
5175         userId = GetUserId();
5176     }
5177 
5178     std::vector<std::string> argList;
5179     SplitStr(args, " ", argList);
5180     if (argList.empty()) {
5181         return;
5182     }
5183 
5184     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5185     CHECK_POINTER(uiAbilityManager);
5186     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5187         uiAbilityManager->DumpMissionList(info, isClient, argList[1]);
5188     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5189         uiAbilityManager->DumpMissionList(info, isClient);
5190     } else {
5191         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5192     }
5193 }
5194 
DumpSysAbilityInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5195 void AbilityManagerService::DumpSysAbilityInner(
5196     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5197 {
5198     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5199         DumpSysAbilityInnerBySCB(args, info, isClient, isUserID, userId);
5200         return;
5201     }
5202     std::shared_ptr<MissionListManagerInterface> targetManager;
5203     if (isUserID) {
5204         auto missionListManager = GetMissionListManagerByUserId(userId);
5205         if (missionListManager == nullptr) {
5206             info.push_back("error: No user found.");
5207             return;
5208         }
5209         targetManager = missionListManager;
5210     } else {
5211         targetManager = GetCurrentMissionListManager();
5212     }
5213 
5214     CHECK_POINTER(targetManager);
5215 
5216     std::vector<std::string> argList;
5217     SplitStr(args, " ", argList);
5218     if (argList.empty()) {
5219         return;
5220     }
5221     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5222         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList = %{public}s", argList[1].c_str());
5223         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5224         try {
5225             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5226             targetManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5227         } catch (...) {
5228             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5229             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5230         }
5231     } else {
5232         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5233     }
5234 }
5235 
DumpSysAbilityInnerBySCB(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5236 void AbilityManagerService::DumpSysAbilityInnerBySCB(
5237     const std::string &args, std::vector<std::string> &info, bool isClient, bool isUserID, int userId)
5238 {
5239     if (!isUserID) {
5240         userId = GetUserId();
5241     }
5242 
5243     std::vector<std::string> argList;
5244     SplitStr(args, " ", argList);
5245     if (argList.empty()) {
5246         return;
5247     }
5248     if (argList.size() >= MIN_DUMP_ARGUMENT_NUM) {
5249         TAG_LOGI(AAFwkTag::ABILITYMGR, "argList = %{public}s", argList[1].c_str());
5250         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5251         try {
5252             auto abilityId = static_cast<int32_t>(std::stoi(argList[1]));
5253             auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
5254             CHECK_POINTER(uiAbilityManager);
5255             uiAbilityManager->DumpMissionListByRecordId(info, isClient, abilityId, params);
5256         } catch (...) {
5257             TAG_LOGW(AAFwkTag::ABILITYMGR, "stoi(%{public}s) failed", argList[1].c_str());
5258             info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5259         }
5260     } else {
5261         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5262     }
5263 }
5264 
DumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5265 void AbilityManagerService::DumpSysStateInner(
5266     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5267 {
5268     TAG_LOGI(AAFwkTag::ABILITYMGR, "DumpSysStateInner begin:%{public}s", args.c_str());
5269     std::shared_ptr<AbilityConnectManager> targetManager;
5270 
5271     if (isUserID) {
5272         auto connectManager = GetConnectManagerByUserId(userId);
5273         if (connectManager == nullptr) {
5274             info.push_back("error: No user found.");
5275             return;
5276         }
5277         targetManager = connectManager;
5278     } else {
5279         targetManager = GetCurrentConnectManager();
5280     }
5281 
5282     CHECK_POINTER(targetManager);
5283 
5284     std::vector<std::string> argList;
5285     SplitStr(args, " ", argList);
5286     if (argList.empty()) {
5287         return;
5288     }
5289 
5290     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5291         targetManager->DumpState(info, isClient, argList[1]);
5292     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5293         targetManager->DumpState(info, isClient);
5294     } else {
5295         TAG_LOGI(AAFwkTag::ABILITYMGR, "uri = %{public}s", argList[1].c_str());
5296         std::vector<std::string> params(argList.begin() + MIN_DUMP_ARGUMENT_NUM, argList.end());
5297         targetManager->DumpStateByUri(info, isClient, argList[1], params);
5298     }
5299 }
5300 
DumpSysPendingInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5301 void AbilityManagerService::DumpSysPendingInner(
5302     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5303 {
5304     std::shared_ptr<PendingWantManager> targetManager;
5305     if (isUserID) {
5306         auto pendingWantManager = GetPendingWantManagerByUserId(userId);
5307         if (pendingWantManager == nullptr) {
5308             info.push_back("error: No user found.");
5309             return;
5310         }
5311         targetManager = pendingWantManager;
5312     } else {
5313         targetManager = GetCurrentPendingWantManager();
5314     }
5315 
5316     CHECK_POINTER(targetManager);
5317 
5318     std::vector<std::string> argList;
5319     SplitStr(args, " ", argList);
5320     if (argList.empty()) {
5321         return;
5322     }
5323 
5324     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5325         targetManager->DumpByRecordId(info, argList[1]);
5326     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5327         targetManager->Dump(info);
5328     } else {
5329         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5330     }
5331 }
5332 
DumpSysProcess(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5333 void AbilityManagerService::DumpSysProcess(
5334     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5335 {
5336     std::vector<std::string> argList;
5337     SplitStr(args, " ", argList);
5338     if (argList.empty()) {
5339         return;
5340     }
5341     std::vector<AppExecFwk::RunningProcessInfo> processInfos;
5342     int ret = 0;
5343     if (isUserID) {
5344         ret = GetProcessRunningInfosByUserId(processInfos, userId);
5345     } else {
5346         ret = GetProcessRunningInfos(processInfos);
5347     }
5348 
5349     if (ret != ERR_OK || processInfos.size() == 0) {
5350         return;
5351     }
5352 
5353     std::string dumpInfo = "  AppRunningRecords:";
5354     info.push_back(dumpInfo);
5355     auto processInfoID = 0;
5356     auto hasProcessName = (argList.size() == MIN_DUMP_ARGUMENT_NUM ? true : false);
5357     for (const auto& processInfo : processInfos) {
5358         if (hasProcessName && argList[1] != processInfo.processName_) {
5359             continue;
5360         }
5361 
5362         dumpInfo = "    AppRunningRecord ID #" + std::to_string(processInfoID);
5363         processInfoID++;
5364         info.push_back(dumpInfo);
5365         dumpInfo = "      process name [" + processInfo.processName_ + "]";
5366         info.push_back(dumpInfo);
5367         dumpInfo = "      pid #" + std::to_string(processInfo.pid_) +
5368             "  uid #" + std::to_string(processInfo.uid_);
5369         info.push_back(dumpInfo);
5370         auto appState = static_cast<AppState>(processInfo.state_);
5371         dumpInfo = "      state #" + DelayedSingleton<AppScheduler>::GetInstance()->ConvertAppState(appState);
5372         info.push_back(dumpInfo);
5373         DumpUIExtensionRootHostRunningInfos(processInfo.pid_, info);
5374         DumpUIExtensionProviderRunningInfos(processInfo.pid_, info);
5375     }
5376 }
5377 
DumpUIExtensionRootHostRunningInfos(pid_t pid,std::vector<std::string> & info)5378 void AbilityManagerService::DumpUIExtensionRootHostRunningInfos(pid_t pid, std::vector<std::string> &info)
5379 {
5380     auto appMgr = GetAppMgr();
5381     if (appMgr == nullptr) {
5382         TAG_LOGW(AAFwkTag::ABILITYMGR, "Get AppMgr failed.");
5383         return;
5384     }
5385 
5386     std::vector<pid_t> hostPids;
5387     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionRootHostPid(pid, hostPids));
5388     if (ret != ERR_OK) {
5389         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get root host process info faild.");
5390         return;
5391     }
5392 
5393     if (hostPids.size() == 0) {
5394         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extenson root host of pid %{public}d.", pid);
5395         return;
5396     }
5397 
5398     std::string temp;
5399     for (size_t i = 0; i < hostPids.size(); i++) {
5400         temp = "      root caller #" + std::to_string(i);
5401         info.push_back(temp);
5402         temp = "        pid #" + std::to_string(hostPids[i]);
5403         info.push_back(temp);
5404     }
5405 }
5406 
DumpUIExtensionProviderRunningInfos(pid_t hostPid,std::vector<std::string> & info)5407 void AbilityManagerService::DumpUIExtensionProviderRunningInfos(pid_t hostPid, std::vector<std::string> &info)
5408 {
5409     auto appMgr = GetAppMgr();
5410     if (appMgr == nullptr) {
5411         TAG_LOGW(AAFwkTag::ABILITYMGR, "Get AppMgr failed.");
5412         return;
5413     }
5414 
5415     std::vector<pid_t> providerPids;
5416     auto ret = IN_PROCESS_CALL(appMgr->GetAllUIExtensionProviderPid(hostPid, providerPids));
5417     if (ret != ERR_OK) {
5418         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get provider process info faild.");
5419         return;
5420     }
5421 
5422     if (providerPids.size() == 0) {
5423         TAG_LOGD(AAFwkTag::ABILITYMGR, "There's no ui extension provider of pid %{public}d.", hostPid);
5424         return;
5425     }
5426 
5427     std::string temp;
5428     for (size_t i = 0; i < providerPids.size(); i++) {
5429         temp = "      uiextension provider #" + std::to_string(i);
5430         info.push_back(temp);
5431         temp = "        pid #" + std::to_string(providerPids[i]);
5432         info.push_back(temp);
5433     }
5434 }
5435 
DataDumpSysStateInner(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5436 void AbilityManagerService::DataDumpSysStateInner(
5437     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5438 {
5439     std::shared_ptr<DataAbilityManager> targetManager;
5440     if (isUserID) {
5441         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5442         if (dataAbilityManager == nullptr) {
5443             info.push_back("error: No user found.");
5444             return;
5445         }
5446         targetManager = dataAbilityManager;
5447     } else {
5448         targetManager = GetCurrentDataAbilityManager();
5449     }
5450 
5451     CHECK_POINTER(targetManager);
5452 
5453     std::vector<std::string> argList;
5454     SplitStr(args, " ", argList);
5455     if (argList.empty()) {
5456         return;
5457     }
5458     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5459         targetManager->DumpSysState(info, isClient, argList[1]);
5460     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5461         targetManager->DumpSysState(info, isClient);
5462     } else {
5463         info.emplace_back("error: invalid argument, please see 'hidumper -s AbilityManagerService -a '-h''.");
5464     }
5465 }
5466 
DumpInner(const std::string & args,std::vector<std::string> & info)5467 void AbilityManagerService::DumpInner(const std::string &args, std::vector<std::string> &info)
5468 {
5469     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5470         auto uiAbilityManager = GetCurrentUIAbilityManager();
5471         CHECK_POINTER(uiAbilityManager);
5472         uiAbilityManager->Dump(info);
5473         return;
5474     }
5475 
5476     auto missionListManager = GetCurrentMissionListManager();
5477     if (missionListManager) {
5478         missionListManager->Dump(info);
5479     }
5480 }
5481 
DumpMissionListInner(const std::string & args,std::vector<std::string> & info)5482 void AbilityManagerService::DumpMissionListInner(const std::string &args, std::vector<std::string> &info)
5483 {
5484     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5485         auto uiAbilityManager = GetCurrentUIAbilityManager();
5486         CHECK_POINTER(uiAbilityManager);
5487         uiAbilityManager->DumpMissionList(info, false, " ");
5488         return;
5489     }
5490     auto missionListManager = GetCurrentMissionListManager();
5491     if (missionListManager) {
5492         missionListManager->DumpMissionList(info, false, "");
5493     }
5494 }
5495 
DumpMissionInfosInner(const std::string & args,std::vector<std::string> & info)5496 void AbilityManagerService::DumpMissionInfosInner(const std::string &args, std::vector<std::string> &info)
5497 {
5498     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5499         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5500         Rosen::WindowManager::GetInstance().DumpSessionAll(info);
5501         return;
5502     }
5503     auto missionListManager = GetCurrentMissionListManager();
5504     if (missionListManager) {
5505         missionListManager->DumpMissionInfos(info);
5506     }
5507 }
5508 
DumpMissionInner(const std::string & args,std::vector<std::string> & info)5509 void AbilityManagerService::DumpMissionInner(const std::string &args, std::vector<std::string> &info)
5510 {
5511     std::vector<std::string> argList;
5512     SplitStr(args, " ", argList);
5513     if (argList.empty()) {
5514         return;
5515     }
5516     if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5517         info.push_back("error: invalid argument, please see 'ability dump -h'.");
5518         return;
5519     }
5520     int missionId = DEFAULT_INVAL_VALUE;
5521     (void)StrToInt(argList[1], missionId);
5522 
5523     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5524         TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
5525         Rosen::WindowManager::GetInstance().DumpSessionWithId(missionId, info);
5526         return;
5527     }
5528 
5529     auto missionListManager = GetCurrentMissionListManager();
5530     CHECK_POINTER_LOG(missionListManager, "Current mission manager not init.");
5531     missionListManager->DumpMission(missionId, info);
5532 }
5533 
DumpStateInner(const std::string & args,std::vector<std::string> & info)5534 void AbilityManagerService::DumpStateInner(const std::string &args, std::vector<std::string> &info)
5535 {
5536     auto connectManager = GetCurrentConnectManager();
5537     CHECK_POINTER_LOG(connectManager, "Current mission manager not init.");
5538     std::vector<std::string> argList;
5539     SplitStr(args, " ", argList);
5540     if (argList.empty()) {
5541         return;
5542     }
5543     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5544         connectManager->DumpState(info, false, argList[1]);
5545     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5546         connectManager->DumpState(info, false);
5547     } else {
5548         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5549     }
5550 }
5551 
DataDumpStateInner(const std::string & args,std::vector<std::string> & info)5552 void AbilityManagerService::DataDumpStateInner(const std::string &args, std::vector<std::string> &info)
5553 {
5554     auto dataAbilityManager = GetCurrentDataAbilityManager();
5555     CHECK_POINTER(dataAbilityManager);
5556     std::vector<std::string> argList;
5557     SplitStr(args, " ", argList);
5558     if (argList.empty()) {
5559         return;
5560     }
5561     if (argList.size() == MIN_DUMP_ARGUMENT_NUM) {
5562         dataAbilityManager->DumpState(info, argList[1]);
5563     } else if (argList.size() < MIN_DUMP_ARGUMENT_NUM) {
5564         dataAbilityManager->DumpState(info);
5565     } else {
5566         info.emplace_back("error: invalid argument, please see 'ability dump -h'.");
5567     }
5568 }
5569 
DumpState(const std::string & args,std::vector<std::string> & info)5570 void AbilityManagerService::DumpState(const std::string &args, std::vector<std::string> &info)
5571 {
5572     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5573     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5574     if (!isShellCall && !isHidumperServiceCall) {
5575         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5576         return;
5577     }
5578     std::vector<std::string> argList;
5579     SplitStr(args, " ", argList);
5580     if (argList.empty()) {
5581         return;
5582     }
5583     auto key = DumpUtils::DumpMap(argList[0]);
5584     if (!key.first) {
5585         return;
5586     }
5587     switch (key.second) {
5588         case DumpUtils::KEY_DUMP_SERVICE:
5589             DumpStateInner(args, info);
5590             break;
5591         case DumpUtils::KEY_DUMP_DATA:
5592             DataDumpStateInner(args, info);
5593             break;
5594         case DumpUtils::KEY_DUMP_ALL:
5595             DumpInner(args, info);
5596             break;
5597         case DumpUtils::KEY_DUMP_MISSION:
5598             DumpMissionInner(args, info);
5599             break;
5600         case DumpUtils::KEY_DUMP_MISSION_LIST:
5601             DumpMissionListInner(args, info);
5602             break;
5603         case DumpUtils::KEY_DUMP_MISSION_INFOS:
5604             DumpMissionInfosInner(args, info);
5605             break;
5606         default:
5607             info.push_back("error: invalid argument, please see 'ability dump -h'.");
5608             break;
5609     }
5610 }
5611 
DumpSysState(const std::string & args,std::vector<std::string> & info,bool isClient,bool isUserID,int userId)5612 void AbilityManagerService::DumpSysState(
5613     const std::string& args, std::vector<std::string>& info, bool isClient, bool isUserID, int userId)
5614 {
5615     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
5616     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5617     auto isHidumperServiceCall = (IPCSkeleton::GetCallingUid() == HIDUMPER_SERVICE_UID);
5618     if (!isShellCall && !isHidumperServiceCall) {
5619         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
5620         return;
5621     }
5622     std::vector<std::string> argList;
5623     SplitStr(args, " ", argList);
5624     if (argList.empty()) {
5625         return;
5626     }
5627     auto key = DumpUtils::DumpsysMap(argList[0]);
5628     if (!key.first) {
5629         return;
5630     }
5631     switch (key.second) {
5632         case DumpUtils::KEY_DUMP_SYS_ALL:
5633             DumpSysInner(args, info, isClient, isUserID, userId);
5634             break;
5635         case DumpUtils::KEY_DUMP_SYS_SERVICE:
5636             DumpSysStateInner(args, info, isClient, isUserID, userId);
5637             break;
5638         case DumpUtils::KEY_DUMP_SYS_PENDING:
5639             DumpSysPendingInner(args, info, isClient, isUserID, userId);
5640             break;
5641         case DumpUtils::KEY_DUMP_SYS_PROCESS:
5642             DumpSysProcess(args, info, isClient, isUserID, userId);
5643             break;
5644         case DumpUtils::KEY_DUMP_SYS_DATA:
5645             DataDumpSysStateInner(args, info, isClient, isUserID, userId);
5646             break;
5647         case DumpUtils::KEY_DUMP_SYS_MISSION_LIST:
5648             DumpSysMissionListInner(args, info, isClient, isUserID, userId);
5649             break;
5650         case DumpUtils::KEY_DUMP_SYS_ABILITY:
5651             DumpSysAbilityInner(args, info, isClient, isUserID, userId);
5652             break;
5653         default:
5654             info.push_back("error: invalid argument, please see 'ability dump -h'.");
5655             break;
5656     }
5657 }
5658 
AbilityTransitionDone(const sptr<IRemoteObject> & token,int state,const PacMap & saveData)5659 int AbilityManagerService::AbilityTransitionDone(const sptr<IRemoteObject> &token, int state, const PacMap &saveData)
5660 {
5661     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5662     TAG_LOGD(AAFwkTag::ABILITYMGR, "Lifecycle: state:%{public}d.", state);
5663     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() && !VerificationAllToken(token)) {
5664         return ERR_INVALID_VALUE;
5665     }
5666     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5667     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
5668     if (!JudgeSelfCalled(abilityRecord)) {
5669         return CHECK_PERMISSION_FAILED;
5670     }
5671 
5672     auto abilityInfo = abilityRecord->GetAbilityInfo();
5673     TAG_LOGI(AAFwkTag::ABILITYMGR, "Lifecycle: ability: %{public}s.", abilityRecord->GetURI().c_str());
5674     auto type = abilityInfo.type;
5675     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5676     // force timeout ability for test
5677     int targetState = AbilityRecord::ConvertLifeCycleToAbilityState(static_cast<AbilityLifeCycleState>(state));
5678     bool isTerminate = abilityRecord->IsAbilityState(AbilityState::TERMINATING) && targetState == AbilityState::INITIAL;
5679     std::string tempState = isTerminate ? AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) :
5680         AbilityRecord::ConvertAbilityState(static_cast<AbilityState>(targetState));
5681     if (IsNeedTimeoutForTest(abilityInfo.name, tempState)) {
5682         TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability for test, state:%{public}s, ability: %{public}s",
5683             tempState.c_str(),
5684             abilityInfo.name.c_str());
5685         return ERR_OK;
5686     }
5687     if (type == AppExecFwk::AbilityType::SERVICE || type == AppExecFwk::AbilityType::EXTENSION) {
5688         auto connectManager = GetConnectManagerByUserId(userId);
5689         if (!connectManager) {
5690             TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5691             return ERR_INVALID_VALUE;
5692         }
5693         return connectManager->AbilityTransitionDone(token, state);
5694     }
5695     if (type == AppExecFwk::AbilityType::DATA) {
5696         auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5697         if (!dataAbilityManager) {
5698             TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
5699             return ERR_INVALID_VALUE;
5700         }
5701         return dataAbilityManager->AbilityTransitionDone(token, state);
5702     }
5703 
5704     if (targetState == AbilityState::BACKGROUND) {
5705         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::BACKGROUND };
5706         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of background lifecycle.";
5707         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5708     } else if (targetState != AbilityState::INITIAL) {
5709         FreezeUtil::LifecycleFlow flow = { token, FreezeUtil::TimeoutState::FOREGROUND };
5710         std::string entry = "AbilityManagerService::AbilityTransitionDone; the end of foreground lifecycle."
5711             " the end of foreground lifecycle.";
5712         FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
5713     }
5714 
5715     int32_t ownerMissionUserId = abilityRecord->GetOwnerMissionUserId();
5716     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5717         auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerMissionUserId);
5718         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
5719         return uiAbilityManager->AbilityTransactionDone(token, state, saveData);
5720     } else {
5721         auto missionListManager = GetMissionListManagerByUserId(ownerMissionUserId);
5722         if (!missionListManager) {
5723             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", ownerMissionUserId);
5724             return ERR_INVALID_VALUE;
5725         }
5726         return missionListManager->AbilityTransactionDone(token, state, saveData);
5727     }
5728 }
5729 
ScheduleConnectAbilityDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & remoteObject)5730 int AbilityManagerService::ScheduleConnectAbilityDone(
5731     const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &remoteObject)
5732 {
5733     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5734     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5735     if (!VerificationAllToken(token)) {
5736         return ERR_INVALID_VALUE;
5737     }
5738 
5739     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5740     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5741     if (!JudgeSelfCalled(abilityRecord)) {
5742         return CHECK_PERMISSION_FAILED;
5743     }
5744 
5745     auto type = abilityRecord->GetAbilityInfo().type;
5746     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
5747         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not service.");
5748         return TARGET_ABILITY_NOT_SERVICE;
5749     }
5750     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5751     auto connectManager = GetConnectManagerByUserId(userId);
5752     if (!connectManager) {
5753         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5754         return ERR_INVALID_VALUE;
5755     }
5756     return connectManager->ScheduleConnectAbilityDoneLocked(token, remoteObject);
5757 }
5758 
ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> & token)5759 int AbilityManagerService::ScheduleDisconnectAbilityDone(const sptr<IRemoteObject> &token)
5760 {
5761     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5762     TAG_LOGI(AAFwkTag::ABILITYMGR, "Schedule disconnect ability done.");
5763     if (!VerificationAllToken(token)) {
5764         return ERR_INVALID_VALUE;
5765     }
5766 
5767     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5768     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5769     if (!JudgeSelfCalled(abilityRecord)) {
5770         return CHECK_PERMISSION_FAILED;
5771     }
5772 
5773     auto type = abilityRecord->GetAbilityInfo().type;
5774     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
5775         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not service.");
5776         return TARGET_ABILITY_NOT_SERVICE;
5777     }
5778     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5779     auto connectManager = GetConnectManagerByUserId(userId);
5780     if (!connectManager) {
5781         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5782         return ERR_INVALID_VALUE;
5783     }
5784     return connectManager->ScheduleDisconnectAbilityDoneLocked(token);
5785 }
5786 
ScheduleCommandAbilityDone(const sptr<IRemoteObject> & token)5787 int AbilityManagerService::ScheduleCommandAbilityDone(const sptr<IRemoteObject> &token)
5788 {
5789     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5790     TAG_LOGD(AAFwkTag::ABILITYMGR, "Schedule command ability done.");
5791     if (!VerificationAllToken(token)) {
5792         return ERR_INVALID_VALUE;
5793     }
5794 
5795     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5796     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5797     if (!JudgeSelfCalled(abilityRecord)) {
5798         return CHECK_PERMISSION_FAILED;
5799     }
5800     // force timeout ability for test
5801     if (IsNeedTimeoutForTest(abilityRecord->GetAbilityInfo().name, std::string("COMMAND"))) {
5802         TAG_LOGW(AAFwkTag::ABILITYMGR, "force timeout ability for test, state:COMMAND, ability: %{public}s",
5803             abilityRecord->GetAbilityInfo().name.c_str());
5804         return ERR_OK;
5805     }
5806     auto type = abilityRecord->GetAbilityInfo().type;
5807     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
5808         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect ability failed, target ability is not service.");
5809         return TARGET_ABILITY_NOT_SERVICE;
5810     }
5811     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5812     auto connectManager = GetConnectManagerByUserId(userId);
5813     if (!connectManager) {
5814         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5815         return ERR_INVALID_VALUE;
5816     }
5817     return connectManager->ScheduleCommandAbilityDoneLocked(token);
5818 }
5819 
ScheduleCommandAbilityWindowDone(const sptr<IRemoteObject> & token,const sptr<SessionInfo> & sessionInfo,WindowCommand winCmd,AbilityCommand abilityCmd)5820 int AbilityManagerService::ScheduleCommandAbilityWindowDone(
5821     const sptr<IRemoteObject> &token,
5822     const sptr<SessionInfo> &sessionInfo,
5823     WindowCommand winCmd,
5824     AbilityCommand abilityCmd)
5825 {
5826     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5827     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter.");
5828     if (!VerificationAllToken(token)) {
5829         return ERR_INVALID_VALUE;
5830     }
5831 
5832     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5833     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
5834     if (!JudgeSelfCalled(abilityRecord)) {
5835         return CHECK_PERMISSION_FAILED;
5836     }
5837 
5838     if (!UIExtensionUtils::IsUIExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)
5839         && !UIExtensionUtils::IsWindowExtension(abilityRecord->GetAbilityInfo().extensionAbilityType)) {
5840         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability is not ui or window extension.");
5841         return ERR_INVALID_VALUE;
5842     }
5843     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5844     auto connectManager = GetConnectManagerByUserId(userId);
5845     if (!connectManager) {
5846         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5847         return ERR_INVALID_VALUE;
5848     }
5849     return connectManager->ScheduleCommandAbilityWindowDone(token, sessionInfo, winCmd, abilityCmd);
5850 }
5851 
OnAbilityRequestDone(const sptr<IRemoteObject> & token,const int32_t state)5852 void AbilityManagerService::OnAbilityRequestDone(const sptr<IRemoteObject> &token, const int32_t state)
5853 {
5854     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5855     auto abilityRecord = Token::GetAbilityRecordByToken(token);
5856     CHECK_POINTER(abilityRecord);
5857     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnAbilityRequestDone, bundleName: %{public}s, abilityName: %{public}s",
5858         abilityRecord->GetAbilityInfo().bundleName.c_str(), abilityRecord->GetAbilityInfo().name.c_str());
5859     auto userId = abilityRecord->GetApplicationInfo().uid / BASE_USER_RANGE;
5860 
5861     auto type = abilityRecord->GetAbilityInfo().type;
5862     switch (type) {
5863         case AppExecFwk::AbilityType::DATA: {
5864             auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
5865             if (!dataAbilityManager) {
5866                 TAG_LOGE(AAFwkTag::ABILITYMGR, "dataAbilityManager is Null. userId=%{public}d", userId);
5867                 return;
5868             }
5869             dataAbilityManager->OnAbilityRequestDone(token, state);
5870             break;
5871         }
5872         case AppExecFwk::AbilityType::SERVICE:
5873         case AppExecFwk::AbilityType::EXTENSION: {
5874             auto connectManager = GetConnectManagerByUserId(userId);
5875             if (!connectManager) {
5876                 TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
5877                 return;
5878             }
5879             connectManager->OnAbilityRequestDone(token, state);
5880             break;
5881         }
5882         default: {
5883             int32_t ownerUserId = abilityRecord->GetOwnerMissionUserId();
5884             if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5885                 auto uiAbilityManager = GetUIAbilityManagerByUserId(ownerUserId);
5886                 CHECK_POINTER(uiAbilityManager);
5887                 uiAbilityManager->OnAbilityRequestDone(token, state);
5888             } else {
5889                 auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
5890                 if (!missionListManager) {
5891                     TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. userId=%{public}d", ownerUserId);
5892                     return;
5893                 }
5894                 missionListManager->OnAbilityRequestDone(token, state);
5895             }
5896             break;
5897         }
5898     }
5899 }
5900 
OnAppStateChanged(const AppInfo & info)5901 void AbilityManagerService::OnAppStateChanged(const AppInfo &info)
5902 {
5903     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
5904     auto connectManager = GetCurrentConnectManager();
5905     CHECK_POINTER_LOG(connectManager, "Connect manager not init.");
5906     connectManager->OnAppStateChanged(info);
5907     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
5908         auto uiAbilityManager = GetCurrentUIAbilityManager();
5909         CHECK_POINTER(uiAbilityManager);
5910         uiAbilityManager->OnAppStateChanged(info);
5911     } else {
5912         auto missionListManager = GetCurrentMissionListManager();
5913         CHECK_POINTER_LOG(missionListManager, "Current mission list manager not init.");
5914         missionListManager->OnAppStateChanged(info);
5915     }
5916     auto dataAbilityManager = GetCurrentDataAbilityManager();
5917     CHECK_POINTER(dataAbilityManager);
5918     dataAbilityManager->OnAppStateChanged(info);
5919 
5920     auto residentProcessMgr = DelayedSingleton<ResidentProcessManager>::GetInstance();
5921     CHECK_POINTER(residentProcessMgr);
5922     residentProcessMgr->OnAppStateChanged(info);
5923 }
5924 
GetEventHandler()5925 std::shared_ptr<AbilityEventHandler> AbilityManagerService::GetEventHandler()
5926 {
5927     return eventHandler_;
5928 }
5929 
5930 // multi user scene
GetUserId() const5931 int32_t AbilityManagerService::GetUserId() const
5932 {
5933     if (userController_) {
5934         auto userId = userController_->GetCurrentUserId();
5935         TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is %{public}d", userId);
5936         return userId;
5937     }
5938     return U0_USER_ID;
5939 }
5940 
StartHighestPriorityAbility(int32_t userId,bool isBoot)5941 void AbilityManagerService::StartHighestPriorityAbility(int32_t userId, bool isBoot)
5942 {
5943     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
5944     auto bms = GetBundleManager();
5945     CHECK_POINTER(bms);
5946 
5947     /* Query the highest priority ability or extension ability, and start it. usually, it is OOBE or launcher */
5948     Want want;
5949     want.AddEntity(HIGHEST_PRIORITY_ABILITY_ENTITY);
5950     AppExecFwk::AbilityInfo abilityInfo;
5951     AppExecFwk::ExtensionAbilityInfo extensionAbilityInfo;
5952     int attemptNums = 0;
5953     while (!IN_PROCESS_CALL(bms->ImplicitQueryInfoByPriority(want,
5954         AppExecFwk::AbilityInfoFlag::GET_ABILITY_INFO_DEFAULT, userId,
5955         abilityInfo, extensionAbilityInfo))) {
5956         TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting query highest priority ability info completed.");
5957         ++attemptNums;
5958         if (!isBoot && attemptNums > SWITCH_ACCOUNT_TRY) {
5959             TAG_LOGE(AAFwkTag::ABILITYMGR, "Query highest priority ability failed.");
5960             return;
5961         }
5962         AbilityRequest abilityRequest;
5963         usleep(REPOLL_TIME_MICRO_SECONDS);
5964     }
5965 
5966     if (abilityInfo.name.empty() && extensionAbilityInfo.name.empty()) {
5967         TAG_LOGE(AAFwkTag::ABILITYMGR, "Query highest priority ability failed");
5968         return;
5969     }
5970 
5971     Want abilityWant; // donot use 'want' here, because the entity of 'want' is not empty
5972     if (!abilityInfo.name.empty()) {
5973         /* highest priority ability */
5974         TAG_LOGI(AAFwkTag::ABILITYMGR, "Start the highest priority ability. bundleName: %{public}s, ability:%{public}s",
5975             abilityInfo.bundleName.c_str(), abilityInfo.name.c_str());
5976         abilityWant.SetElementName(abilityInfo.bundleName, abilityInfo.name);
5977     } else {
5978         /* highest priority extension ability */
5979         TAG_LOGI(AAFwkTag::ABILITYMGR,
5980             "Start the highest priority extension ability. bundleName: %{public}s, ability:%{public}s",
5981             extensionAbilityInfo.bundleName.c_str(), extensionAbilityInfo.name.c_str());
5982         abilityWant.SetElementName(extensionAbilityInfo.bundleName, extensionAbilityInfo.name);
5983     }
5984 
5985 #ifdef SUPPORT_GRAPHICS
5986     abilityWant.SetParam(NEED_STARTINGWINDOW, false);
5987     // wait BOOT_ANIMATION_STARTED to start LAUNCHER
5988     WaitBootAnimationStart();
5989 #endif
5990 
5991     /* note: OOBE APP need disable itself, otherwise, it will be started when restart system everytime */
5992     (void)StartAbility(abilityWant, userId, DEFAULT_INVAL_VALUE);
5993 }
5994 
GenerateAbilityRequest(const Want & want,int requestCode,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)5995 int AbilityManagerService::GenerateAbilityRequest(const Want &want, int requestCode, AbilityRequest &request,
5996     const sptr<IRemoteObject> &callerToken, int32_t userId)
5997 {
5998     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5999     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6000     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6001         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6002         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6003         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6004     }
6005 
6006     int32_t appIndex = 0;
6007     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
6008     if (abilityRecord != nullptr &&
6009         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName() &&
6010         abilityRecord->GetAppIndex() == appIndex) {
6011         (const_cast<Want &>(want)).SetParam(DEBUG_APP, abilityRecord->IsDebugApp());
6012     }
6013 
6014     request.want = want;
6015     request.requestCode = requestCode;
6016     request.callerToken = callerToken;
6017     request.startSetting = nullptr;
6018 
6019     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6020     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6021         int32_t appIndex = 0;
6022         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6023             return ERR_APP_CLONE_INDEX_INVALID;
6024         }
6025         Want localWant = want;
6026         if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
6027             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
6028             localWant.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
6029         }
6030         abilityInfo = StartAbilityInfo::CreateStartAbilityInfo(localWant, userId, appIndex);
6031     }
6032     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6033     if (abilityInfo->status != ERR_OK) {
6034         return abilityInfo->status;
6035     }
6036     request.abilityInfo = abilityInfo->abilityInfo;
6037     request.extensionProcessMode = abilityInfo->extensionProcessMode;
6038 
6039     if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::RESERVE_TYPE)) {
6040         request.collaboratorType = CollaboratorType::RESERVE_TYPE;
6041     } else if (request.abilityInfo.applicationInfo.codePath == std::to_string(CollaboratorType::OTHERS_TYPE)) {
6042         request.collaboratorType = CollaboratorType::OTHERS_TYPE;
6043     }
6044 
6045     if (request.abilityInfo.type == AppExecFwk::AbilityType::SERVICE && request.abilityInfo.isStageBasedModel) {
6046         TAG_LOGI(AAFwkTag::ABILITYMGR, "Stage mode, abilityInfo SERVICE type reset EXTENSION.");
6047         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
6048     }
6049 
6050     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6051         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app info failed.");
6052         return RESOLVE_APP_ERR;
6053     }
6054     if (want.GetIntParam(AAFwk::SCREEN_MODE_KEY, ScreenMode::IDLE_SCREEN_MODE) == ScreenMode::JUMP_SCREEN_MODE &&
6055         (request.abilityInfo.applicationInfo.bundleType != AppExecFwk::BundleType::ATOMIC_SERVICE ||
6056         request.abilityInfo.launchMode != AppExecFwk::LaunchMode::SINGLETON)) {
6057         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface of starting atomicService can start only atomicService.");
6058         return TARGET_ABILITY_NOT_SERVICE;
6059     }
6060     request.appInfo = request.abilityInfo.applicationInfo;
6061     request.uid = request.appInfo.uid;
6062     TAG_LOGD(AAFwkTag::ABILITYMGR,
6063         "GenerateAbilityRequest end, app name: %{public}s, moduleName name: %{public}s, uid: %{public}d.",
6064         request.appInfo.name.c_str(), request.abilityInfo.moduleName.c_str(), request.uid);
6065 
6066     request.want.SetModuleName(request.abilityInfo.moduleName);
6067 
6068     if (want.GetBoolParam(Want::PARAM_RESV_START_RECENT, false) &&
6069         AAFwk::PermissionVerification::GetInstance()->VerifyStartRecentAbilityPermission()) {
6070         request.startRecent = true;
6071     }
6072 
6073     return ERR_OK;
6074 }
6075 
GenerateExtensionAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)6076 int AbilityManagerService::GenerateExtensionAbilityRequest(
6077     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
6078 {
6079     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
6080     if (abilityRecord && abilityRecord->GetAppIndex() > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX &&
6081         abilityRecord->GetApplicationInfo().bundleName == want.GetElement().GetBundleName()) {
6082         (const_cast<Want &>(want)).SetParam(AbilityRuntime::ServerConstant::DLP_INDEX, abilityRecord->GetAppIndex());
6083         (const_cast<Want &>(want)).SetParam(DLP_PARAMS_SECURITY_FLAG, abilityRecord->GetSecurityFlag());
6084     }
6085     request.want = want;
6086     request.callerToken = callerToken;
6087     request.startSetting = nullptr;
6088 
6089     auto abilityInfo = StartAbilityUtils::startAbilityInfo;
6090     if (abilityInfo == nullptr || abilityInfo->GetAppBundleName() != want.GetElement().GetBundleName()) {
6091         int32_t appIndex = 0;
6092         if (!AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex)) {
6093             return ERR_APP_CLONE_INDEX_INVALID;
6094         }
6095         abilityInfo = StartAbilityInfo::CreateStartExtensionInfo(want, userId, appIndex);
6096     }
6097     CHECK_POINTER_AND_RETURN(abilityInfo, GET_ABILITY_SERVICE_FAILED);
6098     if (abilityInfo->status != ERR_OK) {
6099         return abilityInfo->status;
6100     }
6101 
6102     auto result = InitialAbilityRequest(request, *abilityInfo);
6103     return result;
6104 }
6105 
InitialAbilityRequest(AbilityRequest & request,const StartAbilityInfo & abilityInfo) const6106 int32_t AbilityManagerService::InitialAbilityRequest(AbilityRequest &request,
6107     const StartAbilityInfo &abilityInfo) const
6108 {
6109     request.abilityInfo = abilityInfo.abilityInfo;
6110     request.extensionProcessMode = abilityInfo.extensionProcessMode;
6111     if (request.abilityInfo.applicationInfo.name.empty() || request.abilityInfo.applicationInfo.bundleName.empty()) {
6112         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get app info failed.");
6113         return RESOLVE_APP_ERR;
6114     }
6115     request.appInfo = request.abilityInfo.applicationInfo;
6116     request.uid = request.appInfo.uid;
6117     TAG_LOGD(AAFwkTag::ABILITYMGR,
6118         "GenerateAbilityRequest end, app name: %{public}s, bundle name: %{public}s, uid: %{public}d.",
6119         request.appInfo.name.c_str(), request.appInfo.bundleName.c_str(), request.uid);
6120 
6121     TAG_LOGD(AAFwkTag::ABILITYMGR,
6122         "GenerateExtensionAbilityRequest, moduleName: %{public}s.", request.abilityInfo.moduleName.c_str());
6123     request.want.SetModuleName(request.abilityInfo.moduleName);
6124 
6125     return ERR_OK;
6126 }
6127 
StopServiceAbility(const Want & want,int32_t userId,const sptr<IRemoteObject> & token)6128 int AbilityManagerService::StopServiceAbility(const Want &want, int32_t userId, const sptr<IRemoteObject> &token)
6129 {
6130     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6131     TAG_LOGD(AAFwkTag::ABILITYMGR, "call.");
6132 
6133     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6134     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6135     if (!isSaCall && !isShellCall) {
6136         auto abilityRecord = Token::GetAbilityRecordByToken(token);
6137         if (abilityRecord == nullptr) {
6138             TAG_LOGE(AAFwkTag::ABILITYMGR, "callerRecord is nullptr");
6139             return ERR_INVALID_VALUE;
6140         }
6141     }
6142 
6143     int32_t validUserId = GetValidUserId(userId);
6144     if (!JudgeMultiUserConcurrency(validUserId)) {
6145         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
6146         return ERR_CROSS_USER;
6147     }
6148 
6149     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
6150     AbilityRequest abilityRequest;
6151     auto result = GenerateAbilityRequest(want, DEFAULT_INVAL_VALUE, abilityRequest, nullptr, validUserId);
6152     if (result != ERR_OK) {
6153         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
6154         return result;
6155     }
6156 
6157     auto abilityInfo = abilityRequest.abilityInfo;
6158     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
6159     TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId : %{public}d, singleton is : %{public}d",
6160         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
6161 
6162     auto type = abilityInfo.type;
6163     if (type != AppExecFwk::AbilityType::SERVICE && type != AppExecFwk::AbilityType::EXTENSION) {
6164         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is not service type.");
6165         return TARGET_ABILITY_NOT_SERVICE;
6166     }
6167 
6168     auto res = JudgeAbilityVisibleControl(abilityInfo);
6169     if (res != ERR_OK) {
6170         TAG_LOGE(AAFwkTag::ABILITYMGR, "Target ability is invisible");
6171         return res;
6172     }
6173 
6174     auto connectManager = GetConnectManagerByUserId(validUserId);
6175     if (connectManager == nullptr) {
6176         return ERR_INVALID_VALUE;
6177     }
6178 
6179     return connectManager->StopServiceAbility(abilityRequest);
6180 }
6181 
OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)6182 void AbilityManagerService::OnAbilityDied(std::shared_ptr<AbilityRecord> abilityRecord)
6183 {
6184     CHECK_POINTER(abilityRecord);
6185     if (abilityRecord->GetToken()) {
6186         FreezeUtil::GetInstance().DeleteLifecycleEvent(abilityRecord->GetToken()->AsObject());
6187     }
6188     FreezeUtil::GetInstance().DeleteAppLifecycleEvent(abilityRecord->GetPid());
6189     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6190         if (abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6191             auto uiAbilityManager = GetUIAbilityManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6192             CHECK_POINTER(uiAbilityManager);
6193             uiAbilityManager->OnAbilityDied(abilityRecord);
6194             return;
6195         }
6196     } else {
6197         auto manager = GetMissionListManagerByUserId(abilityRecord->GetOwnerMissionUserId());
6198         if (manager && abilityRecord->GetAbilityInfo().type == AbilityType::PAGE) {
6199             ReleaseAbilityTokenMap(abilityRecord->GetToken());
6200             manager->OnAbilityDied(abilityRecord, GetUserId());
6201             return;
6202         }
6203     }
6204 
6205     auto connectManager = GetConnectManagerByToken(abilityRecord->GetToken());
6206     if (connectManager) {
6207         connectManager->OnAbilityDied(abilityRecord, GetUserId());
6208         return;
6209     }
6210 
6211     auto dataAbilityManager = GetDataAbilityManagerByToken(abilityRecord->GetToken());
6212     if (dataAbilityManager) {
6213         dataAbilityManager->OnAbilityDied(abilityRecord);
6214     }
6215 }
6216 
OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)6217 void AbilityManagerService::OnCallConnectDied(std::shared_ptr<CallRecord> callRecord)
6218 {
6219     CHECK_POINTER(callRecord);
6220     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6221         auto uiAbilityManager = GetCurrentUIAbilityManager();
6222         CHECK_POINTER(uiAbilityManager);
6223         uiAbilityManager->OnCallConnectDied(callRecord);
6224         return;
6225     }
6226     auto missionListManager = GetCurrentMissionListManager();
6227     if (missionListManager) {
6228         missionListManager->OnCallConnectDied(callRecord);
6229     }
6230 }
6231 
ReleaseAbilityTokenMap(const sptr<IRemoteObject> & token)6232 void AbilityManagerService::ReleaseAbilityTokenMap(const sptr<IRemoteObject> &token)
6233 {
6234     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
6235     for (auto iter = callStubTokenMap_.begin(); iter != callStubTokenMap_.end(); iter++) {
6236         if (iter->second == token) {
6237             callStubTokenMap_.erase(iter);
6238             break;
6239         }
6240     }
6241 }
6242 
KillProcess(const std::string & bundleName)6243 int AbilityManagerService::KillProcess(const std::string &bundleName)
6244 {
6245     TAG_LOGI(AAFwkTag::ABILITYMGR, "Kill process, bundleName: %{public}s", bundleName.c_str());
6246     CHECK_CALLER_IS_SYSTEM_APP;
6247     auto bms = GetBundleManager();
6248     CHECK_POINTER_AND_RETURN(bms, KILL_PROCESS_FAILED);
6249     int32_t userId = GetUserId();
6250     AppExecFwk::BundleInfo bundleInfo;
6251     if (!IN_PROCESS_CALL(
6252         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
6253         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info when kill process.");
6254         return GET_BUNDLE_INFO_FAILED;
6255     }
6256 
6257     bool keepAliveEnable = bundleInfo.isKeepAlive;
6258     AmsResidentProcessRdb::GetInstance().GetResidentProcessEnable(bundleName, keepAliveEnable);
6259     if (keepAliveEnable && DelayedSingleton<AppScheduler>::GetInstance()->IsMemorySizeSufficent()) {
6260         TAG_LOGE(AAFwkTag::ABILITYMGR, "Can not kill keep alive process.");
6261         return KILL_PROCESS_KEEP_ALIVE;
6262     }
6263 
6264     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplication(bundleName);
6265     if (ret != ERR_OK) {
6266         return KILL_PROCESS_FAILED;
6267     }
6268 
6269     return ERR_OK;
6270 }
6271 
UninstallApp(const std::string & bundleName,int32_t uid)6272 int AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid)
6273 {
6274     return UninstallApp(bundleName, uid, 0);
6275 }
6276 
UninstallApp(const std::string & bundleName,int32_t uid,int32_t appIndex)6277 int32_t AbilityManagerService::UninstallApp(const std::string &bundleName, int32_t uid, int32_t appIndex)
6278 {
6279     TAG_LOGI(AAFwkTag::ABILITYMGR, "Uninstall app, bundleName: %{public}s, uid=%{public}d, appIndex:%{public}d",
6280         bundleName.c_str(), uid, appIndex);
6281     return UninstallAppInner(bundleName, uid, appIndex, false, "");
6282 }
6283 
UpgradeApp(const std::string & bundleName,const int32_t uid,const std::string & exitMsg,int32_t appIndex)6284 int32_t AbilityManagerService::UpgradeApp(const std::string &bundleName, const int32_t uid, const std::string &exitMsg,
6285     int32_t appIndex)
6286 {
6287     TAG_LOGI(AAFwkTag::ABILITYMGR,
6288         "UpgradeApp app, bundleName: %{public}s, uid=%{public}d, exitMsg: %{public}s, appIndex:%{public}d",
6289         bundleName.c_str(), uid, exitMsg.c_str(), appIndex);
6290     return UninstallAppInner(bundleName, uid, appIndex, true, exitMsg);
6291 }
6292 
UninstallAppInner(const std::string & bundleName,const int32_t uid,int32_t appIndex,const bool isUpgrade,const std::string & exitMsg)6293 int32_t AbilityManagerService::UninstallAppInner(const std::string &bundleName, const int32_t uid, int32_t appIndex,
6294     const bool isUpgrade, const std::string &exitMsg)
6295 {
6296     pid_t callingPid = IPCSkeleton::GetCallingPid();
6297     pid_t pid = getprocpid();
6298     if (callingPid != pid) {
6299         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Not bundleMgr call.", __func__);
6300         return CHECK_PERMISSION_FAILED;
6301     }
6302 
6303     if (isUpgrade) {
6304         CHECK_POINTER_AND_RETURN(appExitReasonHelper_, ERR_NULL_OBJECT);
6305         AAFwk::ExitReason exitReason = { REASON_UPGRADE, exitMsg };
6306         appExitReasonHelper_->RecordAppExitReason(bundleName, uid, appIndex, exitReason);
6307     } else {
6308         IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppExecFwk::AppMgrClient>::
6309             GetInstance()->SetKeepAliveEnableState(bundleName, false, uid));
6310         auto userId = uid / BASE_USER_RANGE;
6311         auto connectManager = GetConnectManagerByUserId(userId);
6312         if (connectManager) {
6313             connectManager->UninstallApp(bundleName);
6314         }
6315     }
6316 
6317     CHECK_POINTER_AND_RETURN(subManagersHelper_, ERR_NULL_OBJECT);
6318     subManagersHelper_->UninstallApp(bundleName, uid);
6319     int ret = DelayedSingleton<AppScheduler>::GetInstance()->KillApplicationByUid(bundleName, uid, "UninstallApp");
6320     if (ret != ERR_OK) {
6321         return UNINSTALL_APP_FAILED;
6322     }
6323     if (!isUpgrade) {
6324         DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->DeleteAppExitReason(bundleName, uid,
6325             appIndex);
6326     }
6327     return ERR_OK;
6328 }
6329 
GetBundleManager()6330 std::shared_ptr<AppExecFwk::BundleMgrHelper> AbilityManagerService::GetBundleManager()
6331 {
6332     if (bundleMgrHelper_ == nullptr) {
6333         bundleMgrHelper_ = AbilityUtil::GetBundleManagerHelper();
6334     }
6335     return bundleMgrHelper_;
6336 }
6337 
PreLoadAppDataAbilities(const std::string & bundleName,const int32_t userId)6338 int AbilityManagerService::PreLoadAppDataAbilities(const std::string &bundleName, const int32_t userId)
6339 {
6340     if (bundleName.empty()) {
6341         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name when app data abilities preloading.");
6342         return ERR_INVALID_VALUE;
6343     }
6344 
6345     if (taskHandler_ == nullptr) {
6346         TAG_LOGE(AAFwkTag::ABILITYMGR, "taskHandler nullptr.");
6347         return ERR_INVALID_STATE;
6348     }
6349 
6350     taskHandler_->SubmitTask([weak = weak_from_this(), bundleName, userId]() {
6351         auto pthis = weak.lock();
6352         if (pthis == nullptr) {
6353             TAG_LOGE(AAFwkTag::ABILITYMGR, "pthis nullptr.");
6354             return;
6355         }
6356         pthis->PreLoadAppDataAbilitiesTask(bundleName, userId);
6357         });
6358 
6359     return ERR_OK;
6360 }
6361 
PreLoadAppDataAbilitiesTask(const std::string & bundleName,const int32_t userId)6362 void AbilityManagerService::PreLoadAppDataAbilitiesTask(const std::string &bundleName, const int32_t userId)
6363 {
6364     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6365     auto dataAbilityManager = GetDataAbilityManagerByUserId(userId);
6366     if (dataAbilityManager == nullptr) {
6367         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid data ability manager when app data abilities preloading.");
6368         return;
6369     }
6370 
6371     auto bms = GetBundleManager();
6372     CHECK_POINTER(bms);
6373 
6374     AppExecFwk::BundleInfo bundleInfo;
6375     bool ret = IN_PROCESS_CALL(
6376         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo, userId));
6377     if (!ret) {
6378         TAG_LOGE(AAFwkTag::ABILITYMGR,
6379             "Failed to get bundle info when app data abilities preloading, userId is %{public}d", userId);
6380         return;
6381     }
6382 
6383     auto begin = system_clock::now();
6384     AbilityRequest dataAbilityRequest;
6385     UpdateCallerInfo(dataAbilityRequest.want, nullptr);
6386     dataAbilityRequest.appInfo = bundleInfo.applicationInfo;
6387     for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
6388         if (it->type != AppExecFwk::AbilityType::DATA) {
6389             continue;
6390         }
6391         if ((system_clock::now() - begin) >= DATA_ABILITY_START_TIMEOUT) {
6392             TAG_LOGE(AAFwkTag::ABILITYMGR, "App data ability preloading for '%{public}s' timeout.", bundleName.c_str());
6393             return;
6394         }
6395         dataAbilityRequest.abilityInfo = *it;
6396         dataAbilityRequest.uid = bundleInfo.uid;
6397         TAG_LOGD(AAFwkTag::ABILITYMGR, "App data ability preloading: '%{public}s.%{public}s'...",
6398             it->bundleName.c_str(), it->name.c_str());
6399 
6400         auto dataAbility = dataAbilityManager->Acquire(dataAbilityRequest, false, nullptr, false);
6401         if (dataAbility == nullptr) {
6402             TAG_LOGE(AAFwkTag::ABILITYMGR,
6403                 "Failed to preload data ability '%{public}s.%{public}s'.", it->bundleName.c_str(), it->name.c_str());
6404             return;
6405         }
6406     }
6407 }
6408 
IsSystemUiApp(const AppExecFwk::AbilityInfo & info) const6409 bool AbilityManagerService::IsSystemUiApp(const AppExecFwk::AbilityInfo &info) const
6410 {
6411     if (info.bundleName != AbilityConfig::SYSTEM_UI_BUNDLE_NAME) {
6412         return false;
6413     }
6414     return (info.name == AbilityConfig::SYSTEM_UI_NAVIGATION_BAR ||
6415         info.name == AbilityConfig::SYSTEM_UI_STATUS_BAR ||
6416         info.name == AbilityConfig::SYSTEM_UI_ABILITY_NAME);
6417 }
6418 
IsSystemUI(const std::string & bundleName) const6419 bool AbilityManagerService::IsSystemUI(const std::string &bundleName) const
6420 {
6421     return bundleName == AbilityConfig::SYSTEM_UI_BUNDLE_NAME;
6422 }
6423 
HandleLoadTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)6424 void AbilityManagerService::HandleLoadTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6425 {
6426     TAG_LOGD(AAFwkTag::ABILITYMGR, "load timeout %{public}" PRId64, abilityRecordId);
6427     if (isExtension) {
6428         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6429         if (connectManager != nullptr) {
6430             connectManager->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6431         }
6432         return;
6433     }
6434 
6435     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6436         auto uiAbilityManagers = GetUIAbilityManagers();
6437         for (auto& item : uiAbilityManagers) {
6438             if (item.second) {
6439                 item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6440             }
6441         }
6442         return;
6443     }
6444     auto missionListManagers = GetMissionListManagers();
6445     for (auto& item : missionListManagers) {
6446         if (item.second) {
6447             item.second->OnTimeOut(AbilityManagerService::LOAD_TIMEOUT_MSG, abilityRecordId, isHalf);
6448         }
6449     }
6450 }
6451 
HandleActiveTimeOut(int64_t abilityRecordId)6452 void AbilityManagerService::HandleActiveTimeOut(int64_t abilityRecordId)
6453 {
6454     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle active timeout.");
6455     auto missionListManagers = GetMissionListManagers();
6456     for (auto& item : missionListManagers) {
6457         if (item.second) {
6458             item.second->OnTimeOut(AbilityManagerService::ACTIVE_TIMEOUT_MSG, abilityRecordId);
6459         }
6460     }
6461 }
6462 
HandleInactiveTimeOut(int64_t abilityRecordId)6463 void AbilityManagerService::HandleInactiveTimeOut(int64_t abilityRecordId)
6464 {
6465     TAG_LOGD(AAFwkTag::ABILITYMGR, "Handle inactive timeout.");
6466     auto missionListManagers = GetMissionListManagers();
6467     for (auto& item : missionListManagers) {
6468         if (item.second) {
6469             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6470         }
6471     }
6472     auto connectManagers = GetConnectManagers();
6473     for (auto& item : connectManagers) {
6474         if (item.second) {
6475             item.second->OnTimeOut(AbilityManagerService::INACTIVE_TIMEOUT_MSG, abilityRecordId);
6476         }
6477     }
6478 }
6479 
HandleForegroundTimeOut(int64_t abilityRecordId,bool isHalf,bool isExtension)6480 void AbilityManagerService::HandleForegroundTimeOut(int64_t abilityRecordId, bool isHalf, bool isExtension)
6481 {
6482     TAG_LOGD(AAFwkTag::ABILITYMGR, "foreground timeout %{public}" PRId64, abilityRecordId);
6483     if (isExtension) {
6484         auto connectManager = GetConnectManagerByAbilityRecordId(abilityRecordId);
6485         if (connectManager != nullptr) {
6486             connectManager->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6487         }
6488         return;
6489     }
6490 
6491     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6492         auto uiAbilityManagers = GetUIAbilityManagers();
6493         for (auto& item : uiAbilityManagers) {
6494             if (item.second) {
6495                 item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6496             }
6497         }
6498         return;
6499     }
6500     auto missionListManagers = GetMissionListManagers();
6501     for (auto& item : missionListManagers) {
6502         if (item.second) {
6503             item.second->OnTimeOut(AbilityManagerService::FOREGROUND_TIMEOUT_MSG, abilityRecordId, isHalf);
6504         }
6505     }
6506 }
6507 
HandleShareDataTimeOut(int64_t uniqueId)6508 void AbilityManagerService::HandleShareDataTimeOut(int64_t uniqueId)
6509 {
6510     WantParams wantParam;
6511     int32_t ret = GetShareDataPairAndReturnData(nullptr, ERR_TIMED_OUT, uniqueId, wantParam);
6512     if (ret) {
6513         TAG_LOGE(AAFwkTag::ABILITYMGR, "acqurieShareData failed.");
6514     }
6515 }
6516 
GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)6517 int32_t AbilityManagerService::GetShareDataPairAndReturnData(std::shared_ptr<AbilityRecord> abilityRecord,
6518     const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
6519 {
6520     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d, wantParam size:%{public}d.",
6521         resultCode, uniqueId, wantParam.Size());
6522     {
6523         std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
6524         auto it = iAcquireShareDataMap_.find(uniqueId);
6525         if (it != iAcquireShareDataMap_.end()) {
6526             auto shareDataPair = it->second;
6527             if (abilityRecord && shareDataPair.first != abilityRecord->GetAbilityRecordId()) {
6528                 TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is not the abilityRecord from request.");
6529                 return ERR_INVALID_VALUE;
6530             }
6531             auto callback = shareDataPair.second;
6532             if (!callback) {
6533                 TAG_LOGE(AAFwkTag::ABILITYMGR, "callback object is nullptr.");
6534                 return ERR_INVALID_VALUE;
6535             }
6536             auto ret = callback->AcquireShareDataDone(resultCode, wantParam);
6537             iAcquireShareDataMap_.erase(it);
6538             return ret;
6539         }
6540     }
6541     TAG_LOGE(AAFwkTag::ABILITYMGR, "iAcquireShareData is null.");
6542     return ERR_INVALID_VALUE;
6543 }
6544 
VerificationToken(const sptr<IRemoteObject> & token)6545 bool AbilityManagerService::VerificationToken(const sptr<IRemoteObject> &token)
6546 {
6547     TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token.");
6548     auto dataAbilityManager = GetCurrentDataAbilityManager();
6549     CHECK_POINTER_RETURN_BOOL(dataAbilityManager);
6550     auto connectManager = GetCurrentConnectManager();
6551     CHECK_POINTER_RETURN_BOOL(connectManager);
6552     auto missionListManager = GetCurrentMissionListManager();
6553     CHECK_POINTER_RETURN_BOOL(missionListManager);
6554 
6555     if (missionListManager->GetAbilityRecordByToken(token)) {
6556         return true;
6557     }
6558     if (missionListManager->GetAbilityFromTerminateList(token)) {
6559         return true;
6560     }
6561 
6562     if (dataAbilityManager->GetAbilityRecordByToken(token)) {
6563         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token4.");
6564         return true;
6565     }
6566 
6567     if (connectManager->GetExtensionByTokenFromServiceMap(token)) {
6568         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6569         return true;
6570     }
6571 
6572     if (connectManager->GetExtensionByTokenFromAbilityCache(token)) {
6573         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6574         return true;
6575     }
6576 
6577     if (connectManager->GetExtensionByTokenFromTerminatingMap(token)) {
6578         TAG_LOGI(AAFwkTag::ABILITYMGR, "Verification token5.");
6579         return true;
6580     }
6581 
6582     TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to verify token.");
6583     return false;
6584 }
6585 
VerificationAllToken(const sptr<IRemoteObject> & token)6586 bool AbilityManagerService::VerificationAllToken(const sptr<IRemoteObject> &token)
6587 {
6588     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6589     CHECK_POINTER_AND_RETURN(subManagersHelper_, false);
6590     return subManagersHelper_->VerificationAllToken(token);
6591 }
6592 
GetCurrentDataAbilityManager()6593 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetCurrentDataAbilityManager()
6594 {
6595     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6596     return subManagersHelper_->GetCurrentDataAbilityManager();
6597 }
6598 
GetDataAbilityManager(const sptr<IAbilityScheduler> & scheduler)6599 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManager(
6600     const sptr<IAbilityScheduler> &scheduler)
6601 {
6602     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6603     return subManagersHelper_->GetDataAbilityManager(scheduler);
6604 }
6605 
GetDataAbilityManagerByUserId(int32_t userId)6606 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByUserId(int32_t userId)
6607 {
6608     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6609     return subManagersHelper_->GetDataAbilityManagerByUserId(userId);
6610 }
6611 
GetDataAbilityManagerByToken(const sptr<IRemoteObject> & token)6612 std::shared_ptr<DataAbilityManager> AbilityManagerService::GetDataAbilityManagerByToken(
6613     const sptr<IRemoteObject> &token)
6614 {
6615     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6616     return subManagersHelper_->GetDataAbilityManagerByToken(token);
6617 }
6618 
GetConnectManagers()6619 std::unordered_map<int, std::shared_ptr<AbilityConnectManager>> AbilityManagerService::GetConnectManagers()
6620 {
6621     if (subManagersHelper_ == nullptr) {
6622         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6623         return std::unordered_map<int, std::shared_ptr<AbilityConnectManager>>();
6624     }
6625     return subManagersHelper_->GetConnectManagers();
6626 }
6627 
GetCurrentConnectManager()6628 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetCurrentConnectManager()
6629 {
6630     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6631     return subManagersHelper_->GetCurrentConnectManager();
6632 }
6633 
GetConnectManagerByUserId(int32_t userId)6634 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByUserId(int32_t userId)
6635 {
6636     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6637     return subManagersHelper_->GetConnectManagerByUserId(userId);
6638 }
6639 
GetConnectManagerByToken(const sptr<IRemoteObject> & token)6640 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByToken(
6641     const sptr<IRemoteObject> &token)
6642 {
6643     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6644     return subManagersHelper_->GetConnectManagerByToken(token);
6645 }
6646 
GetConnectManagerByAbilityRecordId(const int64_t & abilityRecordId)6647 std::shared_ptr<AbilityConnectManager> AbilityManagerService::GetConnectManagerByAbilityRecordId(
6648     const int64_t &abilityRecordId)
6649 {
6650     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6651     return subManagersHelper_->GetConnectManagerByAbilityRecordId(abilityRecordId);
6652 }
6653 
GetCurrentPendingWantManager()6654 std::shared_ptr<PendingWantManager> AbilityManagerService::GetCurrentPendingWantManager()
6655 {
6656     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6657     return subManagersHelper_->GetCurrentPendingWantManager();
6658 }
6659 
GetPendingWantManagerByUserId(int32_t userId)6660 std::shared_ptr<PendingWantManager> AbilityManagerService::GetPendingWantManagerByUserId(int32_t userId)
6661 {
6662     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6663     return subManagersHelper_->GetPendingWantManagerByUserId(userId);
6664 }
6665 
GetMissionListManagers()6666 std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>> AbilityManagerService::GetMissionListManagers()
6667 {
6668     if (subManagersHelper_ == nullptr) {
6669         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6670         return std::unordered_map<int, std::shared_ptr<MissionListManagerInterface>>();
6671     }
6672     return subManagersHelper_->GetMissionListManagers();
6673 }
6674 
GetCurrentMissionListManager()6675 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetCurrentMissionListManager()
6676 {
6677     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6678     return subManagersHelper_->GetCurrentMissionListManager();
6679 }
6680 
GetMissionListManagerByUserId(int32_t userId)6681 std::shared_ptr<MissionListManagerInterface> AbilityManagerService::GetMissionListManagerByUserId(int32_t userId)
6682 {
6683     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6684     return subManagersHelper_->GetMissionListManagerByUserId(userId);
6685 }
6686 
GetMissionListWrap()6687 std::shared_ptr<MissionListWrap> AbilityManagerService::GetMissionListWrap()
6688 {
6689     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6690     return subManagersHelper_->GetMissionListWrap();
6691 }
6692 
GetUIAbilityManagers()6693 std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>> AbilityManagerService::GetUIAbilityManagers()
6694 {
6695     if (subManagersHelper_ == nullptr) {
6696         TAG_LOGE(AAFwkTag::ABILITYMGR, "pointer is nullptr.");
6697         return std::unordered_map<int, std::shared_ptr<UIAbilityLifecycleManager>>();
6698     }
6699     return subManagersHelper_->GetUIAbilityManagers();
6700 }
6701 
GetCurrentUIAbilityManager()6702 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetCurrentUIAbilityManager()
6703 {
6704     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6705     return subManagersHelper_->GetCurrentUIAbilityManager();
6706 }
6707 
GetUIAbilityManagerByUserId(int32_t userId) const6708 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUserId(int32_t userId) const
6709 {
6710     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6711     return subManagersHelper_->GetUIAbilityManagerByUserId(userId);
6712 }
6713 
GetUIAbilityManagerByUid(int32_t uid)6714 std::shared_ptr<UIAbilityLifecycleManager> AbilityManagerService::GetUIAbilityManagerByUid(int32_t uid)
6715 {
6716     CHECK_POINTER_AND_RETURN(subManagersHelper_, nullptr);
6717     return subManagersHelper_->GetUIAbilityManagerByUid(uid);
6718 }
6719 
StartResidentApps(int32_t userId)6720 void AbilityManagerService::StartResidentApps(int32_t userId)
6721 {
6722     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps %{public}d", userId);
6723     ConnectBmsService();
6724     auto bms = GetBundleManager();
6725     CHECK_POINTER_IS_NULLPTR(bms);
6726     std::vector<AppExecFwk::BundleInfo> bundleInfos;
6727     if (!DelayedSingleton<ResidentProcessManager>::GetInstance()->GetResidentBundleInfosForUser(bundleInfos, userId)) {
6728         TAG_LOGE(AAFwkTag::ABILITYMGR, "get resident bundleinfos failed");
6729         return;
6730     }
6731     DelayedSingleton<ResidentProcessManager>::GetInstance()->Init();
6732     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps GetBundleInfos size: %{public}zu", bundleInfos.size());
6733 
6734     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(bundleInfos, userId);
6735     if (!bundleInfos.empty()) {
6736 #ifdef SUPPORT_GRAPHICS
6737         if (userId == U0_USER_ID) {
6738             WaitBootAnimationStart();
6739         }
6740 #endif
6741         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfos);
6742     }
6743 }
6744 
StartAutoStartupApps()6745 void AbilityManagerService::StartAutoStartupApps()
6746 {
6747     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6748     if (abilityAutoStartupService_ == nullptr) {
6749         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
6750         return;
6751     }
6752     std::vector<AutoStartupInfo> infoList;
6753     int32_t result = abilityAutoStartupService_->QueryAllAutoStartupApplicationsWithoutPermission(infoList,
6754         GetUserId());
6755     if (result != ERR_OK) {
6756         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to query data.");
6757         return;
6758     }
6759 
6760     constexpr int retryCount = 5;
6761     RetryStartAutoStartupApps(infoList, retryCount);
6762 }
6763 
RetryStartAutoStartupApps(const std::vector<AutoStartupInfo> & infoList,int32_t retryCount)6764 void AbilityManagerService::RetryStartAutoStartupApps(
6765     const std::vector<AutoStartupInfo> &infoList, int32_t retryCount)
6766 {
6767     TAG_LOGD(AAFwkTag::ABILITYMGR,
6768         "Called, retryCount: %{public}d, infoList.size:%{public}zu", retryCount, infoList.size());
6769     std::vector<AutoStartupInfo> failedList;
6770     for (auto info : infoList) {
6771         AppExecFwk::ElementName element;
6772         element.SetBundleName(info.bundleName);
6773         element.SetAbilityName(info.abilityName);
6774         element.SetModuleName(info.moduleName);
6775         Want want;
6776         want.SetElement(element);
6777         want.SetParam(Want::PARAM_APP_AUTO_STARTUP_LAUNCH_REASON, true);
6778         if (info.appCloneIndex > 0 && info.appCloneIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
6779             want.SetParam(Want::PARAM_APP_CLONE_INDEX_KEY, info.appCloneIndex);
6780         }
6781         if (StartAbility(want) != ERR_OK) {
6782             failedList.push_back(info);
6783         }
6784     }
6785 
6786     TAG_LOGD(AAFwkTag::ABILITYMGR,
6787         "RetryCount: %{public}d, failedList.size:%{public}zu", retryCount, failedList.size());
6788     if (!failedList.empty() && retryCount > 0) {
6789         auto retryStartAutoStartupAppsTask = [aams = weak_from_this(), list = failedList, retryCount]() {
6790             auto obj = aams.lock();
6791             if (obj == nullptr) {
6792                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Retry start auto startup app error, obj is nullptr");
6793                 return;
6794             }
6795             obj->RetryStartAutoStartupApps(list, retryCount - 1);
6796         };
6797         constexpr int delaytime = 2000;
6798         taskHandler_->SubmitTask(retryStartAutoStartupAppsTask, "RetryStartAutoStartupApps", delaytime);
6799     }
6800 }
6801 
SubscribeScreenUnlockedEvent()6802 void AbilityManagerService::SubscribeScreenUnlockedEvent()
6803 {
6804     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6805     // add listen screen unlocked.
6806     EventFwk::MatchingSkills matchingSkills;
6807     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_UNLOCKED);
6808     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_USER_UNLOCKED);
6809     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
6810     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
6811     auto callback = [abilityManager = weak_from_this()]() {
6812         TAG_LOGD(AAFwkTag::ABILITYMGR, "On screen unlocked.");
6813         auto abilityMgr = abilityManager.lock();
6814         if (abilityMgr == nullptr) {
6815             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
6816             return;
6817         }
6818         auto taskHandler = abilityMgr->GetTaskHandler();
6819         if (taskHandler == nullptr) {
6820             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid taskHandler pointer.");
6821             return;
6822         }
6823         auto startAutoStartupAppsTask = [abilityManager]() {
6824             auto abilityMgr = abilityManager.lock();
6825             if (abilityMgr == nullptr) {
6826                 TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
6827                 return;
6828             }
6829             abilityMgr->RemoveScreenUnlockInterceptor();
6830             abilityMgr->StartAutoStartupApps();
6831             abilityMgr->UnSubscribeScreenUnlockedEvent();
6832         };
6833         taskHandler->SubmitTask(startAutoStartupAppsTask, "StartAutoStartupApps");
6834     };
6835     auto userScreenUnlockCallback = [abilityManager = weak_from_this()]() {
6836         TAG_LOGD(AAFwkTag::ABILITYMGR, "On user screen unlocked.");
6837         auto abilityMgr = abilityManager.lock();
6838         if (abilityMgr == nullptr) {
6839             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid abilityMgr pointer.");
6840             return;
6841         }
6842         abilityMgr->RemoveScreenUnlockInterceptor();
6843     };
6844     screenSubscriber_ = std::make_shared<AbilityRuntime::AbilityManagerEventSubscriber>(subscribeInfo, callback,
6845         userScreenUnlockCallback);
6846     bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber_);
6847     if (!subResult) {
6848         constexpr int retryCount = 20;
6849         RetrySubscribeScreenUnlockedEvent(retryCount);
6850     }
6851 }
6852 
UnSubscribeScreenUnlockedEvent()6853 void AbilityManagerService::UnSubscribeScreenUnlockedEvent()
6854 {
6855     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
6856     bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenSubscriber_);
6857     TAG_LOGD(AAFwkTag::ABILITYMGR, "Screen unlocked event subscriber unsubscribe result is %{public}d.", subResult);
6858 }
6859 
RetrySubscribeScreenUnlockedEvent(int32_t retryCount)6860 void AbilityManagerService::RetrySubscribeScreenUnlockedEvent(int32_t retryCount)
6861 {
6862     TAG_LOGD(AAFwkTag::ABILITYMGR, "RetryCount: %{public}d.", retryCount);
6863     auto retrySubscribeScreenUnlockedEventTask = [aams = weak_from_this(), screenSubscriber = screenSubscriber_,
6864                                                      retryCount]() {
6865         bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenSubscriber);
6866         auto obj = aams.lock();
6867         if (obj == nullptr) {
6868             TAG_LOGE(AAFwkTag::ABILITYMGR, "Retry subscribe screen unlocked event, obj is nullptr.");
6869             return;
6870         }
6871         if (!subResult && retryCount > 0) {
6872             obj->RetrySubscribeScreenUnlockedEvent(retryCount - 1);
6873         }
6874     };
6875     constexpr int delaytime = 200;
6876     taskHandler_->SubmitTask(retrySubscribeScreenUnlockedEventTask, "RetrySubscribeScreenUnlockedEvent", delaytime);
6877 }
6878 
RemoveScreenUnlockInterceptor()6879 void AbilityManagerService::RemoveScreenUnlockInterceptor()
6880 {
6881     interceptorExecuter_->RemoveInterceptor("ScreenUnlock");
6882 }
6883 
ConnectBmsService()6884 void AbilityManagerService::ConnectBmsService()
6885 {
6886     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
6887     TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting AppMgr Service run completed.");
6888     while (!DelayedSingleton<AppScheduler>::GetInstance()->Init(shared_from_this())) {
6889         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to init AppScheduler");
6890         usleep(REPOLL_TIME_MICRO_SECONDS);
6891     }
6892 
6893     TAG_LOGI(AAFwkTag::ABILITYMGR, "Waiting BundleMgr Service run completed.");
6894     /* wait until connected to bundle manager service */
6895     std::lock_guard<ffrt::mutex> guard(globalLock_);
6896     while (iBundleManager_ == nullptr) {
6897         sptr<IRemoteObject> bundle_obj =
6898             OHOS::DelayedSingleton<SaMgrClient>::GetInstance()->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID);
6899         if (bundle_obj == nullptr) {
6900             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to get bundle manager service");
6901             usleep(REPOLL_TIME_MICRO_SECONDS);
6902             continue;
6903         }
6904         iBundleManager_ = iface_cast<AppExecFwk::IBundleMgr>(bundle_obj);
6905     }
6906 
6907     TAG_LOGI(AAFwkTag::ABILITYMGR, "Connect bms success!");
6908 }
6909 
GetWantSenderInfo(const sptr<IWantSender> & target,std::shared_ptr<WantSenderInfo> & info)6910 int AbilityManagerService::GetWantSenderInfo(const sptr<IWantSender> &target, std::shared_ptr<WantSenderInfo> &info)
6911 {
6912     TAG_LOGI(AAFwkTag::ABILITYMGR, "Get pending request info.");
6913     auto pendingWantManager = GetCurrentPendingWantManager();
6914     CHECK_POINTER_AND_RETURN(pendingWantManager, ERR_INVALID_VALUE);
6915     CHECK_POINTER_AND_RETURN(target, ERR_INVALID_VALUE);
6916     CHECK_POINTER_AND_RETURN(info, ERR_INVALID_VALUE);
6917     return pendingWantManager->GetWantSenderInfo(target, info);
6918 }
6919 
GetAppMemorySize()6920 int AbilityManagerService::GetAppMemorySize()
6921 {
6922     TAG_LOGI(AAFwkTag::ABILITYMGR, "service GetAppMemorySize start");
6923     const char *key = "const.product.arkheaplimit";
6924     const char *def = "512m";
6925     char *valueGet = nullptr;
6926     unsigned int len = 128;
6927     int ret = GetParameter(key, def, valueGet, len);
6928     int resultInt = 0;
6929     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
6930         if (valueGet == nullptr) {
6931             TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s, valueGet is nullptr", __func__);
6932             return APP_MEMORY_SIZE;
6933         }
6934         int len = strlen(valueGet);
6935         for (int i = 0; i < len; i++) {
6936             if (valueGet[i] >= '0' && valueGet[i] <= '9') {
6937                 resultInt *= SIZE_10;
6938                 resultInt += valueGet[i] - '0';
6939             }
6940         }
6941         if (resultInt == 0) {
6942             return APP_MEMORY_SIZE;
6943         }
6944         return resultInt;
6945     }
6946     return APP_MEMORY_SIZE;
6947 }
6948 
IsRamConstrainedDevice()6949 bool AbilityManagerService::IsRamConstrainedDevice()
6950 {
6951     TAG_LOGI(AAFwkTag::ABILITYMGR, "service IsRamConstrainedDevice start");
6952     const char *key = "const.product.islowram";
6953     const char *def = "0";
6954     char *valueGet = nullptr;
6955     unsigned int len = 128;
6956     int ret = GetParameter(key, def, valueGet, len);
6957     if ((ret != GET_PARAMETER_OTHER) && (ret != GET_PARAMETER_INCORRECT)) {
6958         int value = atoi(valueGet);
6959         if (value) {
6960             return true;
6961         }
6962         return false;
6963     }
6964     return false;
6965 }
6966 
GetMissionIdByAbilityToken(const sptr<IRemoteObject> & token)6967 int32_t AbilityManagerService::GetMissionIdByAbilityToken(const sptr<IRemoteObject> &token)
6968 {
6969     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6970     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6971     if (!abilityRecord) {
6972         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
6973         return -1;
6974     }
6975     if (!JudgeSelfCalled(abilityRecord)) {
6976         return -1;
6977     }
6978     return GetMissionIdByAbilityTokenInner(token);
6979 }
6980 
GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> & token)6981 int32_t AbilityManagerService::GetMissionIdByAbilityTokenInner(const sptr<IRemoteObject> &token)
6982 {
6983     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6984     auto abilityRecord = Token::GetAbilityRecordByToken(token);
6985     if (!abilityRecord) {
6986         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is Null.");
6987         return -1;
6988     }
6989     auto userId = abilityRecord->GetOwnerMissionUserId();
6990     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
6991         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
6992         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
6993         return uiAbilityManager->GetSessionIdByAbilityToken(token);
6994     }
6995     auto missionListManager = GetMissionListManagerByUserId(userId);
6996     if (!missionListManager) {
6997         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is Null. owner mission userId=%{public}d", userId);
6998         return -1;
6999     }
7000     return missionListManager->GetMissionIdByAbilityToken(token);
7001 }
7002 
GetAbilityTokenByMissionId(int32_t missionId)7003 sptr<IRemoteObject> AbilityManagerService::GetAbilityTokenByMissionId(int32_t missionId)
7004 {
7005     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7006     auto missionListManager = GetCurrentMissionListManager();
7007     if (!missionListManager) {
7008         return nullptr;
7009     }
7010     return missionListManager->GetAbilityTokenByMissionId(missionId);
7011 }
7012 
StartRemoteAbilityByCall(const Want & want,const sptr<IRemoteObject> & callerToken,const sptr<IRemoteObject> & connect)7013 int AbilityManagerService::StartRemoteAbilityByCall(const Want &want, const sptr<IRemoteObject> &callerToken,
7014     const sptr<IRemoteObject> &connect)
7015 {
7016     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s begin StartRemoteAbilityByCall", __func__);
7017     Want remoteWant = want;
7018     UpdateDmsCallerInfo(remoteWant, callerToken);
7019     if (AddStartControlParam(remoteWant, callerToken) != ERR_OK) {
7020         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AddStartControlParam failed.", __func__);
7021         return ERR_INVALID_VALUE;
7022     }
7023     int32_t missionId = -1;
7024     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7025         missionId = GetMissionIdByAbilityTokenInner(callerToken);
7026         if (!missionId) {
7027             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid missionId id.");
7028             return ERR_INVALID_VALUE;
7029         }
7030     } else {
7031         missionId = GetMissionIdByAbilityToken(callerToken);
7032 }
7033     if (missionId < 0) {
7034         return ERR_INVALID_VALUE;
7035     }
7036     remoteWant.SetParam(DMS_MISSION_ID, missionId);
7037     DistributedClient dmsClient;
7038     return dmsClient.StartRemoteAbilityByCall(remoteWant, connect);
7039 }
7040 
ReleaseRemoteAbility(const sptr<IRemoteObject> & connect,const AppExecFwk::ElementName & element)7041 int AbilityManagerService::ReleaseRemoteAbility(const sptr<IRemoteObject> &connect,
7042     const AppExecFwk::ElementName &element)
7043 {
7044     DistributedClient dmsClient;
7045     return dmsClient.ReleaseRemoteAbility(connect, element);
7046 }
7047 
StartAbilityByCall(const Want & want,const sptr<IAbilityConnection> & connect,const sptr<IRemoteObject> & callerToken,int32_t accountId)7048 int AbilityManagerService::StartAbilityByCall(const Want &want, const sptr<IAbilityConnection> &connect,
7049     const sptr<IRemoteObject> &callerToken, int32_t accountId)
7050 {
7051     TAG_LOGI(AAFwkTag::ABILITYMGR, "call ability.");
7052     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7053     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7054     if (IsCrossUserCall(accountId)) {
7055         CHECK_CALLER_IS_SYSTEM_APP;
7056     }
7057 
7058     if (VerifyAccountPermission(accountId) == CHECK_PERMISSION_FAILED) {
7059         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s: Permission verification failed.", __func__);
7060         return CHECK_PERMISSION_FAILED;
7061     }
7062 
7063     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
7064     if (abilityRecord && !JudgeSelfCalled(abilityRecord)) {
7065         return CHECK_PERMISSION_FAILED;
7066     }
7067 
7068     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
7069     int32_t appIndex = 0;
7070     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
7071         return ERR_APP_CLONE_INDEX_INVALID;
7072     }
7073     StartAbilityInfoWrap threadLocalInfo(want, GetUserId(), appIndex, callerToken);
7074     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, 0, GetUserId(), true, nullptr);
7075     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
7076         interceptorExecuter_->DoProcess(interceptorParam);
7077     if (result != ERR_OK) {
7078         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
7079         return result;
7080     }
7081 
7082     if (CheckIfOperateRemote(want)) {
7083         TAG_LOGI(AAFwkTag::ABILITYMGR, "start remote ability by call");
7084         return StartRemoteAbilityByCall(want, callerToken, connect->AsObject());
7085     }
7086 
7087     if (accountId == U0_USER_ID) {
7088         accountId = DEFAULT_INVAL_VALUE;
7089     }
7090     int32_t oriValidUserId = GetValidUserId(accountId);
7091     if (!JudgeMultiUserConcurrency(oriValidUserId)) {
7092         TAG_LOGE(AAFwkTag::ABILITYMGR, "Multi-user non-concurrent mode is not satisfied.");
7093         return ERR_CROSS_USER;
7094     }
7095 
7096     AbilityRequest abilityRequest;
7097     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
7098     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
7099     abilityRequest.callerToken = callerToken;
7100     abilityRequest.startSetting = nullptr;
7101     abilityRequest.want = want;
7102     abilityRequest.connect = connect;
7103     result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
7104     if (result != ERR_OK) {
7105         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
7106         return result;
7107     }
7108 
7109     if (!abilityRequest.abilityInfo.isStageBasedModel) {
7110         TAG_LOGE(AAFwkTag::ABILITYMGR, "target ability is not stage base model.");
7111         return RESOLVE_CALL_ABILITY_VERSION_ERR;
7112     }
7113 
7114     result = CheckStartByCallPermission(abilityRequest);
7115     if (result != ERR_OK) {
7116         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStartByCallPermission fail, result: %{public}d", result);
7117         return result;
7118     }
7119 
7120     TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityInfo.applicationInfo.singleton is %{public}s",
7121         abilityRequest.abilityInfo.applicationInfo.singleton ? "true" : "false");
7122     UpdateCallerInfo(abilityRequest.want, callerToken);
7123     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(abilityRequest.want, 0, GetUserId(),
7124         false, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityRequest.abilityInfo), false, appIndex);
7125     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
7126         afterCheckExecuter_->DoProcess(afterCheckParam);
7127     if (result != ERR_OK) {
7128         TAG_LOGE(AAFwkTag::ABILITYMGR, "afterCheckExecuter_ is nullptr or DoProcess return error.");
7129         return result;
7130     }
7131     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7132         ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7133         abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
7134         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
7135         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7136         return uiAbilityManager->ResolveLocked(abilityRequest);
7137     }
7138 
7139     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
7140     if (missionListMgr == nullptr) {
7141         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is Null. Designated User Id=%{public}d", oriValidUserId);
7142         return ERR_INVALID_VALUE;
7143     }
7144     ReportEventToRSS(abilityRequest.abilityInfo, callerToken);
7145 
7146     return missionListMgr->ResolveLocked(abilityRequest);
7147 }
7148 
StartAbilityJust(AbilityRequest & abilityRequest,int32_t validUserId)7149 int AbilityManagerService::StartAbilityJust(AbilityRequest &abilityRequest, int32_t validUserId)
7150 {
7151     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7152     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
7153     UpdateCallerInfo(abilityRequest.want, abilityRequest.callerToken);
7154     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7155         ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7156         auto uiAbilityManager = GetUIAbilityManagerByUserId(validUserId);
7157         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7158         return uiAbilityManager->ResolveLocked(abilityRequest);
7159     }
7160 
7161     auto missionListMgr = GetMissionListManagerByUserId(validUserId);
7162     if (missionListMgr == nullptr) {
7163         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is Null. Designated User Id=%{public}d", validUserId);
7164         return ERR_INVALID_VALUE;
7165     }
7166     ReportEventToRSS(abilityRequest.abilityInfo, abilityRequest.callerToken);
7167 
7168     return missionListMgr->ResolveLocked(abilityRequest);
7169 }
7170 
ReleaseCall(const sptr<IAbilityConnection> & connect,const AppExecFwk::ElementName & element)7171 int AbilityManagerService::ReleaseCall(
7172     const sptr<IAbilityConnection> &connect, const AppExecFwk::ElementName &element)
7173 {
7174     TAG_LOGD(AAFwkTag::ABILITYMGR, "Release called ability.");
7175 
7176     CHECK_POINTER_AND_RETURN(connect, ERR_INVALID_VALUE);
7177     CHECK_POINTER_AND_RETURN(connect->AsObject(), ERR_INVALID_VALUE);
7178 
7179     std::string elementName = element.GetURI();
7180     TAG_LOGD(AAFwkTag::ABILITYMGR, "try to release called ability, name: %{public}s.", elementName.c_str());
7181 
7182     if (CheckIsRemote(element.GetDeviceID())) {
7183         TAG_LOGI(AAFwkTag::ABILITYMGR, "release remote ability");
7184         return ReleaseRemoteAbility(connect->AsObject(), element);
7185     }
7186 
7187     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7188         auto uiAbilityManager = GetCurrentUIAbilityManager();
7189         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7190         return uiAbilityManager->ReleaseCallLocked(connect, element);
7191     }
7192     auto missionListManager = GetCurrentMissionListManager();
7193     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
7194     return missionListManager->ReleaseCallLocked(connect, element);
7195 }
7196 
JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo & abilityInfo)7197 int AbilityManagerService::JudgeAbilityVisibleControl(const AppExecFwk::AbilityInfo &abilityInfo)
7198 {
7199     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
7200     if (abilityInfo.visible) {
7201         return ERR_OK;
7202     }
7203     auto callerTokenId = IPCSkeleton::GetCallingTokenID();
7204     if (callerTokenId == abilityInfo.applicationInfo.accessTokenId ||
7205         callerTokenId == static_cast<uint32_t>(IPCSkeleton::GetSelfTokenID())) {  // foundation call is allowed
7206         return ERR_OK;
7207     }
7208     if (AccessTokenKit::VerifyAccessToken(callerTokenId,
7209         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == AppExecFwk::Constants::PERMISSION_GRANTED) {
7210         return ERR_OK;
7211     }
7212     TAG_LOGE(AAFwkTag::ABILITYMGR, "callerToken: %{private}u, targetToken: %{private}u, caller doesn's have permission",
7213         callerTokenId, abilityInfo.applicationInfo.accessTokenId);
7214     return ABILITY_VISIBLE_FALSE_DENY_REQUEST;
7215 }
7216 
StartUser(int userId,sptr<IUserCallback> callback)7217 int AbilityManagerService::StartUser(int userId, sptr<IUserCallback> callback)
7218 {
7219     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartUser in service:%{public}d.", userId);
7220     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7221         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUser permission verification failed, not account process.");
7222         if (callback != nullptr) {
7223             callback->OnStartUserDone(userId, CHECK_PERMISSION_FAILED);
7224         }
7225         return CHECK_PERMISSION_FAILED;
7226     }
7227 
7228     if (userController_) {
7229         userController_->StartUser(userId, callback);
7230     }
7231     return 0;
7232 }
7233 
StopUser(int userId,const sptr<IUserCallback> & callback)7234 int AbilityManagerService::StopUser(int userId, const sptr<IUserCallback> &callback)
7235 {
7236     TAG_LOGI(AAFwkTag::ABILITYMGR, "StopUser in service:%{public}d", userId);
7237     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7238         TAG_LOGE(AAFwkTag::ABILITYMGR, "StopUser permission verification failed, not account process");
7239         if (callback != nullptr) {
7240             callback->OnStopUserDone(userId, CHECK_PERMISSION_FAILED);
7241         }
7242         return CHECK_PERMISSION_FAILED;
7243     }
7244 
7245     auto ret = -1;
7246     if (userController_) {
7247         ret = userController_->StopUser(userId);
7248         TAG_LOGD(AAFwkTag::ABILITYMGR, "ret = %{public}d", ret);
7249     }
7250     if (callback) {
7251         callback->OnStopUserDone(userId, ret);
7252     }
7253     return 0;
7254 }
7255 
LogoutUser(int32_t userId)7256 int AbilityManagerService::LogoutUser(int32_t userId)
7257 {
7258     TAG_LOGI(AAFwkTag::ABILITYMGR, "LogoutUser in service:%{public}d", userId);
7259     if (IPCSkeleton::GetCallingUid() != ACCOUNT_MGR_SERVICE_UID) {
7260         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed, not account process");
7261         return CHECK_PERMISSION_FAILED;
7262     }
7263 
7264     // Lister screen unlock for auto startup apps.
7265     if (system::GetBoolParameter(PRODUCT_APPBOOT_SETTING_ENABLED, false)) {
7266         InitInterceptorForScreenUnlock();
7267         SubscribeScreenUnlockedEvent();
7268     }
7269 
7270     if (userController_) {
7271         auto ret = userController_->LogoutUser(userId);
7272         TAG_LOGD(AAFwkTag::ABILITYMGR, "logout user return = %{public}d", ret);
7273         return ret;
7274     }
7275     return ERR_OK;
7276 }
7277 
OnAcceptWantResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)7278 void AbilityManagerService::OnAcceptWantResponse(
7279     const AAFwk::Want &want, const std::string &flag, int32_t requestId)
7280 {
7281     TAG_LOGD(AAFwkTag::ABILITYMGR, "On accept want response");
7282     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7283         auto uiAbilityManager = GetCurrentUIAbilityManager();
7284         CHECK_POINTER(uiAbilityManager);
7285         uiAbilityManager->OnAcceptWantResponse(want, flag, requestId);
7286         return;
7287     }
7288     auto missionListManager = GetCurrentMissionListManager();
7289     if (!missionListManager) {
7290         return;
7291     }
7292     missionListManager->OnAcceptWantResponse(want, flag);
7293 }
7294 
OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want & want,int32_t requestId)7295 void AbilityManagerService::OnStartSpecifiedAbilityTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7296 {
7297     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str());
7298     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7299         auto uiAbilityManager = GetCurrentUIAbilityManager();
7300         CHECK_POINTER(uiAbilityManager);
7301         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7302         return;
7303     }
7304     auto missionListManager = GetCurrentMissionListManager();
7305     if (!missionListManager) {
7306         return;
7307     }
7308     missionListManager->OnStartSpecifiedAbilityTimeoutResponse(want);
7309 }
7310 
OnStartSpecifiedProcessResponse(const AAFwk::Want & want,const std::string & flag,int32_t requestId)7311 void AbilityManagerService::OnStartSpecifiedProcessResponse(const AAFwk::Want &want, const std::string &flag,
7312     int32_t requestId)
7313 {
7314     TAG_LOGD(AAFwkTag::ABILITYMGR, "flag = %{public}s", flag.c_str());
7315     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7316         auto uiAbilityManager = GetCurrentUIAbilityManager();
7317         CHECK_POINTER(uiAbilityManager);
7318         uiAbilityManager->OnStartSpecifiedProcessResponse(want, flag, requestId);
7319         return;
7320     }
7321 }
7322 
OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want & want,int32_t requestId)7323 void AbilityManagerService::OnStartSpecifiedProcessTimeoutResponse(const AAFwk::Want &want, int32_t requestId)
7324 {
7325     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s.", want.GetElement().GetURI().c_str());
7326     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7327         auto uiAbilityManager = GetCurrentUIAbilityManager();
7328         CHECK_POINTER(uiAbilityManager);
7329         uiAbilityManager->OnStartSpecifiedAbilityTimeoutResponse(want, requestId);
7330         return;
7331     }
7332 }
7333 
GetAbilityRunningInfos(std::vector<AbilityRunningInfo> & info)7334 int AbilityManagerService::GetAbilityRunningInfos(std::vector<AbilityRunningInfo> &info)
7335 {
7336     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7337     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get running ability infos.");
7338     CHECK_CALLER_IS_SYSTEM_APP;
7339     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7340     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7341         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
7342         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
7343         uiAbilityManager->GetAbilityRunningInfos(info, isPerm);
7344     } else {
7345         auto missionListManager = GetCurrentMissionListManager();
7346         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
7347         missionListManager->GetAbilityRunningInfos(info, isPerm);
7348     }
7349 
7350     UpdateFocusState(info);
7351 
7352     return ERR_OK;
7353 }
7354 
UpdateFocusState(std::vector<AbilityRunningInfo> & info)7355 void AbilityManagerService::UpdateFocusState(std::vector<AbilityRunningInfo> &info)
7356 {
7357     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7358     if (info.empty()) {
7359         return;
7360     }
7361 
7362 #ifdef SUPPORT_GRAPHICS
7363     sptr<IRemoteObject> token;
7364     int ret = IN_PROCESS_CALL(GetTopAbility(token));
7365     if (ret != ERR_OK || token == nullptr) {
7366         return;
7367     }
7368 
7369     auto abilityRecord = Token::GetAbilityRecordByToken(token);
7370     if (abilityRecord == nullptr) {
7371         TAG_LOGW(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
7372         return;
7373     }
7374 
7375     for (auto &item : info) {
7376         if (item.uid == abilityRecord->GetUid() && item.pid == abilityRecord->GetPid() &&
7377             item.ability == abilityRecord->GetElementName()) {
7378             item.abilityState = static_cast<int>(AbilityState::ACTIVE);
7379             break;
7380         }
7381     }
7382 #endif
7383 }
7384 
GetExtensionRunningInfos(int upperLimit,std::vector<ExtensionRunningInfo> & info)7385 int AbilityManagerService::GetExtensionRunningInfos(int upperLimit, std::vector<ExtensionRunningInfo> &info)
7386 {
7387     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7388     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get extension infos, upperLimit : %{public}d", upperLimit);
7389     CHECK_CALLER_IS_SYSTEM_APP;
7390     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
7391     auto connectManager = GetCurrentConnectManager();
7392     CHECK_POINTER_AND_RETURN(connectManager, ERR_INVALID_VALUE);
7393     connectManager->GetExtensionRunningInfos(upperLimit, info, GetUserId(), isPerm);
7394     return ERR_OK;
7395 }
7396 
GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> & info)7397 int AbilityManagerService::GetProcessRunningInfos(std::vector<AppExecFwk::RunningProcessInfo> &info)
7398 {
7399     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfos(info);
7400 }
7401 
GetProcessRunningInfosByUserId(std::vector<AppExecFwk::RunningProcessInfo> & info,int32_t userId)7402 int AbilityManagerService::GetProcessRunningInfosByUserId(
7403     std::vector<AppExecFwk::RunningProcessInfo> &info, int32_t userId)
7404 {
7405     return DelayedSingleton<AppScheduler>::GetInstance()->GetProcessRunningInfosByUserId(info, userId);
7406 }
7407 
ClearUserData(int32_t userId)7408 void AbilityManagerService::ClearUserData(int32_t userId)
7409 {
7410     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7411     CHECK_POINTER(subManagersHelper_);
7412     subManagersHelper_->ClearSubManagers(userId);
7413 }
7414 
RegisterSnapshotHandler(const sptr<ISnapshotHandler> & handler)7415 int AbilityManagerService::RegisterSnapshotHandler(const sptr<ISnapshotHandler>& handler)
7416 {
7417     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7418     if (!isSaCall) {
7419         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
7420         return 0;
7421     }
7422 
7423     auto missionListManager = GetCurrentMissionListManager();
7424     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7425     missionListManager->RegisterSnapshotHandler(handler);
7426     TAG_LOGI(AAFwkTag::ABILITYMGR, "snapshot: AbilityManagerService register snapshot handler success.");
7427     return ERR_OK;
7428 }
7429 
GetMissionSnapshot(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot,bool isLowResolution)7430 int32_t AbilityManagerService::GetMissionSnapshot(const std::string& deviceId, int32_t missionId,
7431     MissionSnapshot& missionSnapshot, bool isLowResolution)
7432 {
7433     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7434     CHECK_CALLER_IS_SYSTEM_APP;
7435     if (!PermissionVerification::GetInstance()->VerifyMissionPermission()) {
7436         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
7437         return CHECK_PERMISSION_FAILED;
7438     }
7439 
7440     if (CheckIsRemote(deviceId)) {
7441         TAG_LOGI(AAFwkTag::ABILITYMGR, "get remote mission snapshot.");
7442         return GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshot);
7443     }
7444     TAG_LOGI(AAFwkTag::ABILITYMGR, "get local mission snapshot.");
7445     auto missionListManager = GetCurrentMissionListManager();
7446     CHECK_POINTER_AND_RETURN(missionListManager, INNER_ERR);
7447     auto token = GetAbilityTokenByMissionId(missionId);
7448     bool result = missionListManager->GetMissionSnapshot(missionId, token, missionSnapshot, isLowResolution);
7449     if (!result) {
7450         return INNER_ERR;
7451     }
7452     return ERR_OK;
7453 }
7454 
UpdateMissionSnapShot(const sptr<IRemoteObject> & token,const std::shared_ptr<Media::PixelMap> & pixelMap)7455 void AbilityManagerService::UpdateMissionSnapShot(const sptr<IRemoteObject> &token,
7456     const std::shared_ptr<Media::PixelMap> &pixelMap)
7457 {
7458     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(FOUNDATION_PROCESS_NAME)) {
7459         return;
7460     }
7461     auto missionListManager = GetCurrentMissionListManager();
7462     if (missionListManager) {
7463         missionListManager->UpdateSnapShot(token, pixelMap);
7464     }
7465 }
7466 
EnableRecoverAbility(const sptr<IRemoteObject> & token)7467 void AbilityManagerService::EnableRecoverAbility(const sptr<IRemoteObject>& token)
7468 {
7469     if (token == nullptr) {
7470         return;
7471     }
7472     auto record = Token::GetAbilityRecordByToken(token);
7473     if (record == nullptr) {
7474         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
7475         return;
7476     }
7477     if (record->IsClearMissionFlag()) {
7478         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::not allow EnableRecoverAbility before clearMission.",
7479             __func__);
7480         return;
7481     }
7482 
7483     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7484     auto tokenID = record->GetApplicationInfo().accessTokenId;
7485     if (callingTokenId != tokenID) {
7486         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery ScheduleRecoverAbility not self, not enabled");
7487         return;
7488     }
7489     {
7490         std::lock_guard<ffrt::mutex> guard(globalLock_);
7491         auto it = appRecoveryHistory_.find(record->GetUid());
7492         if (it == appRecoveryHistory_.end()) {
7493             appRecoveryHistory_.emplace(record->GetUid(), 0);
7494         }
7495     }
7496     auto userId = record->GetOwnerMissionUserId();
7497     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7498         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
7499         CHECK_POINTER(uiAbilityManager);
7500         const auto& abilityInfo = record->GetAbilityInfo();
7501         (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->AddAbilityRecoverInfo(
7502             abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityInfo.name,
7503             uiAbilityManager->GetSessionIdByAbilityToken(token));
7504     } else {
7505         auto missionListMgr = GetMissionListManagerByUserId(userId);
7506         if (missionListMgr == nullptr) {
7507             TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListMgr is nullptr");
7508             return;
7509         }
7510         missionListMgr->EnableRecoverAbility(record->GetMissionId());
7511     }
7512 }
7513 
ReportAppRecoverResult(const int32_t appId,const AppExecFwk::ApplicationInfo & appInfo,const std::string & abilityName,const std::string & result)7514 void AbilityManagerService::ReportAppRecoverResult(const int32_t appId, const AppExecFwk::ApplicationInfo &appInfo,
7515     const std::string& abilityName, const std::string& result)
7516 {
7517     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "APP_RECOVERY", HiSysEvent::EventType::BEHAVIOR,
7518         "APP_UID", appId,
7519         "VERSION_CODE", std::to_string(appInfo.versionCode),
7520         "VERSION_NAME", appInfo.versionName,
7521         "BUNDLE_NAME", appInfo.bundleName,
7522         "ABILITY_NAME", abilityName,
7523         "RECOVERY_RESULT", result);
7524 }
7525 
AppRecoverKill(pid_t pid,int32_t reason)7526 void AbilityManagerService::AppRecoverKill(pid_t pid, int32_t reason)
7527 {
7528     AppExecFwk::AppFaultDataBySA faultDataSA;
7529     faultDataSA.errorObject.name = "appRecovery";
7530     switch (reason) {
7531         case AppExecFwk::StateReason::CPP_CRASH:
7532             faultDataSA.faultType = AppExecFwk::FaultDataType::CPP_CRASH;
7533             break;
7534         case AppExecFwk::StateReason::JS_ERROR:
7535             faultDataSA.faultType = AppExecFwk::FaultDataType::JS_ERROR;
7536             break;
7537         case AppExecFwk::StateReason::LIFECYCLE:
7538         case AppExecFwk::StateReason::APP_FREEZE:
7539             faultDataSA.faultType = AppExecFwk::FaultDataType::APP_FREEZE;
7540             break;
7541         default:
7542             faultDataSA.faultType = AppExecFwk::FaultDataType::UNKNOWN;
7543     }
7544     faultDataSA.pid = pid;
7545     IN_PROCESS_CALL(DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->NotifyAppFaultBySA(faultDataSA));
7546 }
7547 
ScheduleRecoverAbility(const sptr<IRemoteObject> & token,int32_t reason,const Want * want)7548 void AbilityManagerService::ScheduleRecoverAbility(const sptr<IRemoteObject>& token, int32_t reason, const Want *want)
7549 {
7550     if (token == nullptr) {
7551         return;
7552     }
7553     auto record = Token::GetAbilityRecordByToken(token);
7554     if (record == nullptr) {
7555         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed find abilityRecord by given token.", __func__);
7556         return;
7557     }
7558     if (!record->IsForeground() && !record->GetAbilityForegroundingFlag()) {
7559         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::failed to recoveryAbility."
7560             "due to it is background", __func__);
7561         return;
7562     }
7563 
7564     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
7565     auto tokenID = record->GetApplicationInfo().accessTokenId;
7566     if (callingTokenId != tokenID) {
7567         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery ScheduleRecoverAbility not self, not enabled");
7568         return;
7569     }
7570 
7571     AAFwk::Want curWant;
7572     {
7573         std::lock_guard<ffrt::mutex> guard(globalLock_);
7574         auto type = record->GetAbilityInfo().type;
7575         if (type != AppExecFwk::AbilityType::PAGE) {
7576             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s AppRecovery::only do recover for page ability.", __func__);
7577             return;
7578         }
7579 
7580         constexpr int64_t MIN_RECOVERY_TIME = 60;
7581         int64_t now = time(nullptr);
7582         auto it = appRecoveryHistory_.find(record->GetUid());
7583         auto appInfo = record->GetApplicationInfo();
7584         auto abilityInfo = record->GetAbilityInfo();
7585 
7586         if ((it != appRecoveryHistory_.end()) &&
7587             (it->second + MIN_RECOVERY_TIME > now)) {
7588             TAG_LOGE(AAFwkTag::ABILITYMGR,
7589                 "%{public}s AppRecovery recover app more than once in one minute, just kill app(%{public}d).",
7590                 __func__, record->GetPid());
7591             ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_WITHIN_ONE_MINUTE");
7592             AppRecoverKill(record->GetPid(), reason);
7593             return;
7594         }
7595 
7596         if (want != nullptr) {
7597             TAG_LOGD(AAFwkTag::ABILITYMGR, "BundleName:%{public}s targetBundleName:%{public}s.",
7598                 appInfo.bundleName.c_str(), want->GetElement().GetBundleName().c_str());
7599             if (want->GetElement().GetBundleName().empty() ||
7600                 (appInfo.bundleName.compare(want->GetElement().GetBundleName()) != 0)) {
7601                 TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery BundleName not match, Not recovery ability!");
7602                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_BUNDLE_NAME_NOT_MATCH");
7603                 return;
7604             } else if (want->GetElement().GetAbilityName().empty()) {
7605                 TAG_LOGD(AAFwkTag::ABILITYMGR, "AppRecovery recovery target ability is empty");
7606                 ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "FAIL_TARGET_ABILITY_EMPTY");
7607                 return;
7608             } else {
7609                 auto bms = GetBundleManager();
7610                 if (bms == nullptr) {
7611                     TAG_LOGE(AAFwkTag::ABILITYMGR, "bms is nullptr");
7612                     return;
7613                 }
7614                 AppExecFwk::BundleInfo bundleInfo;
7615                 auto bundleName = want->GetElement().GetBundleName();
7616                 int32_t userId = GetUserId();
7617                 bool ret = IN_PROCESS_CALL(
7618                     bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, bundleInfo,
7619                     userId));
7620                 if (!ret) {
7621                     TAG_LOGE(AAFwkTag::ABILITYMGR, "AppRecovery Failed to get bundle info, not do recovery!");
7622                     return;
7623                 }
7624                 bool isRestartPage = false;
7625                 auto abilityName = want->GetElement().GetAbilityName();
7626                 for (auto it = bundleInfo.abilityInfos.begin(); it != bundleInfo.abilityInfos.end(); ++it) {
7627                     if ((abilityName.compare(it->name) == 0) && it->type == AppExecFwk::AbilityType::PAGE) {
7628                         isRestartPage = true;
7629                         break;
7630                     }
7631                 }
7632                 if (!isRestartPage) {
7633                     TAG_LOGI(AAFwkTag::ABILITYMGR, "AppRecovery the target ability type is not PAGE!");
7634                     ReportAppRecoverResult(record->GetUid(), appInfo, abilityName, "FAIL_TARGET_ABILITY_NOT_PAGE");
7635                     return;
7636                 }
7637             }
7638         }
7639 
7640         appRecoveryHistory_[record->GetUid()] = now;
7641         curWant = (want == nullptr) ? record->GetWant() : *want;
7642         curWant.SetParam(AAFwk::Want::PARAM_ABILITY_RECOVERY_RESTART, true);
7643 
7644         ReportAppRecoverResult(record->GetUid(), appInfo, abilityInfo.name, "SUCCESS");
7645     }
7646     RestartApp(curWant, true);
7647 }
7648 
GetRemoteMissionSnapshotInfo(const std::string & deviceId,int32_t missionId,MissionSnapshot & missionSnapshot)7649 int32_t AbilityManagerService::GetRemoteMissionSnapshotInfo(const std::string& deviceId, int32_t missionId,
7650     MissionSnapshot& missionSnapshot)
7651 {
7652     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7653     TAG_LOGI(AAFwkTag::ABILITYMGR, "GetRemoteMissionSnapshotInfo begin");
7654     std::unique_ptr<MissionSnapshot> missionSnapshotPtr = std::make_unique<MissionSnapshot>();
7655     DistributedClient dmsClient;
7656     int result = dmsClient.GetRemoteMissionSnapshotInfo(deviceId, missionId, missionSnapshotPtr);
7657     if (result != ERR_OK) {
7658         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetRemoteMissionSnapshotInfo failed, result = %{public}d", result);
7659         return result;
7660     }
7661     missionSnapshot = *missionSnapshotPtr;
7662     return ERR_OK;
7663 }
7664 
StartSwitchUserDialog()7665 void AbilityManagerService::StartSwitchUserDialog()
7666 {
7667     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog extension ability come");
7668     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7669         TAG_LOGE(AAFwkTag::ABILITYMGR, "Scene board enabled, dialog not show.");
7670         return;
7671     }
7672 
7673     if (userController_ == nullptr) {
7674         TAG_LOGE(AAFwkTag::ABILITYMGR, "User Controller instance is nullptr.");
7675         return;
7676     }
7677 
7678     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
7679     if (sysDialog == nullptr) {
7680         TAG_LOGE(AAFwkTag::ABILITYMGR, "System dialog scheduler instance is nullptr.");
7681         return;
7682     }
7683 
7684     Want dialogWant = sysDialog->GetSwitchUserDialogWant();
7685     StartSwitchUserDialogInner(dialogWant, userController_->GetFreezingNewUserId());
7686 }
7687 
7688 
StartSwitchUserDialogInner(const Want & want,int32_t lastUserId)7689 void AbilityManagerService::StartSwitchUserDialogInner(const Want &want, int32_t lastUserId)
7690 {
7691     TAG_LOGD(AAFwkTag::ABILITYMGR, "Start switch user dialog inner come");
7692     EventInfo eventInfo = BuildEventInfo(want, lastUserId);
7693     eventInfo.extensionType = static_cast<int32_t>(AppExecFwk::ExtensionAbilityType::SERVICE);
7694     AbilityRequest abilityRequest;
7695     auto result = GenerateExtensionAbilityRequest(want, abilityRequest, nullptr, lastUserId);
7696     if (result != ERR_OK) {
7697         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
7698         eventInfo.errCode = result;
7699         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
7700         return;
7701     }
7702 
7703     auto abilityInfo = abilityRequest.abilityInfo;
7704     auto startUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : lastUserId;
7705     result = CheckOptExtensionAbility(want, abilityRequest, startUserId, AppExecFwk::ExtensionAbilityType::SERVICE);
7706     if (result != ERR_OK) {
7707         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check extensionAbility type error.");
7708         eventInfo.errCode = result;
7709         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
7710         return;
7711     }
7712 
7713     auto connectManager = GetConnectManagerByUserId(startUserId);
7714     if (connectManager == nullptr) {
7715         CHECK_POINTER(subManagersHelper_);
7716         subManagersHelper_->InitConnectManager(startUserId, false);
7717         connectManager = GetConnectManagerByUserId(startUserId);
7718         if (connectManager == nullptr) {
7719             TAG_LOGE(AAFwkTag::ABILITYMGR, "ConnectManager is nullptr. userId=%{public}d", startUserId);
7720             eventInfo.errCode = ERR_INVALID_VALUE;
7721             EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
7722             return;
7723         }
7724     }
7725 
7726     UriUtils::GetInstance().CheckUriPermissionForServiceExtension(abilityRequest.want,
7727         abilityRequest.abilityInfo.extensionAbilityType);
7728     eventInfo.errCode = connectManager->StartAbility(abilityRequest);
7729     if (eventInfo.errCode != ERR_OK) {
7730         TAG_LOGE(AAFwkTag::ABILITYMGR, "EventInfo errCode is %{public}d", eventInfo.errCode);
7731         EventReport::SendExtensionEvent(EventName::START_EXTENSION_ERROR, HiSysEventType::FAULT, eventInfo);
7732     }
7733 }
7734 
StartFreezingScreen()7735 void AbilityManagerService::StartFreezingScreen()
7736 {
7737     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7738 #ifdef SUPPORT_GRAPHICS
7739     StartSwitchUserDialog();
7740     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
7741     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Freeze(displayIds));
7742 #endif
7743 }
7744 
StopFreezingScreen()7745 void AbilityManagerService::StopFreezingScreen()
7746 {
7747     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7748 #ifdef SUPPORT_GRAPHICS
7749     std::vector<Rosen::DisplayId> displayIds = Rosen::DisplayManager::GetInstance().GetAllDisplayIds();
7750     IN_PROCESS_CALL_WITHOUT_RET(Rosen::DisplayManager::GetInstance().Unfreeze(displayIds));
7751     StopSwitchUserDialog();
7752 #endif
7753 }
7754 
UserStarted(int32_t userId)7755 void AbilityManagerService::UserStarted(int32_t userId)
7756 {
7757     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
7758     CHECK_POINTER(subManagersHelper_);
7759     subManagersHelper_->InitSubManagers(userId, false);
7760 }
7761 
SwitchToUser(int32_t oldUserId,int32_t userId,sptr<IUserCallback> callback)7762 void AbilityManagerService::SwitchToUser(int32_t oldUserId, int32_t userId, sptr<IUserCallback> callback)
7763 {
7764     TAG_LOGI(AAFwkTag::ABILITYMGR,
7765         "%{public}s, oldUserId:%{public}d, newUserId:%{public}d", __func__, oldUserId, userId);
7766     SwitchManagers(userId);
7767     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7768         PauseOldUser(oldUserId);
7769         ConnectBmsService();
7770         StartUserApps();
7771     }
7772     callback->OnStartUserDone(userId, ERR_OK);
7773     bool isBoot = oldUserId == U0_USER_ID ? true : false;
7774     StartHighestPriorityAbility(userId, isBoot);
7775      if (taskHandler_) {
7776         taskHandler_->SubmitTask([abilityMs = shared_from_this(), userId]() {
7777             TAG_LOGI(AAFwkTag::ABILITYMGR, "StartResidentApps userId:%{public}d", userId);
7778             abilityMs->StartResidentApps(userId);
7779             });
7780     }
7781     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled() &&
7782         AmsConfigurationParameter::GetInstance().MultiUserType() != 0) {
7783         TAG_LOGI(AAFwkTag::ABILITYMGR, "no need to terminate old scb.");
7784         return;
7785     }
7786     PauseOldConnectManager(oldUserId);
7787 }
7788 
SwitchManagers(int32_t userId,bool switchUser)7789 void AbilityManagerService::SwitchManagers(int32_t userId, bool switchUser)
7790 {
7791     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----begin", __func__, userId);
7792     CHECK_POINTER(subManagersHelper_);
7793     subManagersHelper_->InitSubManagers(userId, switchUser);
7794     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, SwitchManagers:%{public}d-----end", __func__, userId);
7795 }
7796 
PauseOldUser(int32_t userId)7797 void AbilityManagerService::PauseOldUser(int32_t userId)
7798 {
7799     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----begin", __func__, userId);
7800     PauseOldMissionListManager(userId);
7801     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldUser:%{public}d-----end", __func__, userId);
7802 }
7803 
PauseOldMissionListManager(int32_t userId)7804 void AbilityManagerService::PauseOldMissionListManager(int32_t userId)
7805 {
7806     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----begin", __func__, userId);
7807     auto manager = GetMissionListManagerByUserId(userId);
7808     CHECK_POINTER(manager);
7809     manager->PauseManager();
7810     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldMissionListManager:%{public}d-----end", __func__, userId);
7811 }
7812 
PauseOldConnectManager(int32_t userId)7813 void AbilityManagerService::PauseOldConnectManager(int32_t userId)
7814 {
7815     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----begin", __func__, userId);
7816     if (userId == U0_USER_ID) {
7817         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, u0 not stop, id:%{public}d-----nullptr", __func__, userId);
7818         return;
7819     }
7820 
7821     auto manager = GetConnectManagerByUserId(userId);
7822     CHECK_POINTER(manager);
7823     manager->PauseExtensions();
7824     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, PauseOldConnectManager:%{public}d-----end", __func__, userId);
7825 }
7826 
StartUserApps()7827 void AbilityManagerService::StartUserApps()
7828 {
7829     auto missionListManager = GetCurrentMissionListManager();
7830     if (missionListManager && missionListManager->IsStarted()) {
7831         TAG_LOGI(AAFwkTag::ABILITYMGR, "missionListManager ResumeManager");
7832         missionListManager->ResumeManager();
7833     }
7834 }
7835 
GetValidUserId(const int32_t userId)7836 int32_t AbilityManagerService::GetValidUserId(const int32_t userId)
7837 {
7838     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId = %{public}d.", userId);
7839     int32_t validUserId = userId;
7840 
7841     if (DEFAULT_INVAL_VALUE == userId) {
7842         validUserId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
7843         TAG_LOGD(AAFwkTag::ABILITYMGR, "validUserId = %{public}d, CallingUid = %{public}d.", validUserId,
7844             IPCSkeleton::GetCallingUid());
7845         if (validUserId == U0_USER_ID) {
7846             validUserId = GetUserId();
7847         }
7848     }
7849     return validUserId;
7850 }
7851 
SetAbilityController(const sptr<IAbilityController> & abilityController,bool imAStabilityTest)7852 int AbilityManagerService::SetAbilityController(const sptr<IAbilityController> &abilityController,
7853     bool imAStabilityTest)
7854 {
7855     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, imAStabilityTest: %{public}d", __func__, imAStabilityTest);
7856     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyControllerPerm();
7857     if (!isPerm) {
7858         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
7859         return CHECK_PERMISSION_FAILED;
7860     }
7861 
7862     std::lock_guard<ffrt::mutex> guard(globalLock_);
7863     abilityController_ = abilityController;
7864     controllerIsAStabilityTest_ = imAStabilityTest;
7865     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, end", __func__);
7866     return ERR_OK;
7867 }
7868 
IsRunningInStabilityTest()7869 bool AbilityManagerService::IsRunningInStabilityTest()
7870 {
7871     std::lock_guard<ffrt::mutex> guard(globalLock_);
7872     bool ret = abilityController_ != nullptr && controllerIsAStabilityTest_;
7873     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, IsRunningInStabilityTest: %{public}d", __func__, ret);
7874     return ret;
7875 }
7876 
IsAbilityControllerStart(const Want & want,const std::string & bundleName)7877 bool AbilityManagerService::IsAbilityControllerStart(const Want &want, const std::string &bundleName)
7878 {
7879     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7880     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
7881     if (abilityController_ == nullptr) {
7882         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
7883         return true;
7884     }
7885 
7886     if (controllerIsAStabilityTest_) {
7887         bool isStart = abilityController_->AllowAbilityStart(want, bundleName);
7888         if (!isStart) {
7889             TAG_LOGI(AAFwkTag::ABILITYMGR,
7890                 "Not finishing start ability because controller starting: %{public}s", bundleName.c_str());
7891             return false;
7892         }
7893     }
7894     return true;
7895 }
7896 
IsAbilityControllerForeground(const std::string & bundleName)7897 bool AbilityManagerService::IsAbilityControllerForeground(const std::string &bundleName)
7898 {
7899     TAG_LOGD(AAFwkTag::ABILITYMGR, "method call, controllerIsAStabilityTest_: %{public}d", controllerIsAStabilityTest_);
7900     if (abilityController_ == nullptr) {
7901         TAG_LOGD(AAFwkTag::ABILITYMGR, "abilityController_ is nullptr");
7902         return true;
7903     }
7904 
7905     if (controllerIsAStabilityTest_) {
7906         bool isResume = abilityController_->AllowAbilityBackground(bundleName);
7907         if (!isResume) {
7908             TAG_LOGI(AAFwkTag::ABILITYMGR,
7909                 "Not finishing terminate ability because controller resuming: %{public}s", bundleName.c_str());
7910             return false;
7911         }
7912     }
7913     return true;
7914 }
7915 
StartUserTest(const Want & want,const sptr<IRemoteObject> & observer)7916 int AbilityManagerService::StartUserTest(const Want &want, const sptr<IRemoteObject> &observer)
7917 {
7918     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
7919     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
7920         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
7921         return ERR_NOT_DEVELOPER_MODE;
7922     }
7923 
7924     if (observer == nullptr) {
7925         TAG_LOGE(AAFwkTag::ABILITYMGR, "observer is nullptr");
7926         return ERR_INVALID_VALUE;
7927     }
7928 
7929     std::string bundleName = want.GetStringParam("-b");
7930     if (bundleName.empty()) {
7931         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name");
7932         return ERR_INVALID_VALUE;
7933     }
7934 
7935     auto bms = GetBundleManager();
7936     CHECK_POINTER_AND_RETURN(bms, START_USER_TEST_FAIL);
7937     AppExecFwk::BundleInfo bundleInfo;
7938     if (!IN_PROCESS_CALL(
7939         bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, U0_USER_ID))) {
7940         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info by U0_USER_ID %{public}d.", U0_USER_ID);
7941         int32_t userId = GetUserId();
7942         if (!IN_PROCESS_CALL(
7943             bms->GetBundleInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT, bundleInfo, userId))) {
7944             TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to get bundle info by userId %{public}d.", userId);
7945             return GET_BUNDLE_INFO_FAILED;
7946         }
7947     }
7948 
7949     return DelayedSingleton<AppScheduler>::GetInstance()->StartUserTest(want, observer, bundleInfo, GetUserId());
7950 }
7951 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName)7952 int AbilityManagerService::FinishUserTest(
7953     const std::string &msg, const int64_t &resultCode, const std::string &bundleName)
7954 {
7955     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
7956     if (bundleName.empty()) {
7957         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid bundle name.");
7958         return ERR_INVALID_VALUE;
7959     }
7960 
7961     return DelayedSingleton<AppScheduler>::GetInstance()->FinishUserTest(msg, resultCode, bundleName);
7962 }
7963 
GetTopAbility(sptr<IRemoteObject> & token)7964 int AbilityManagerService::GetTopAbility(sptr<IRemoteObject> &token)
7965 {
7966     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7967     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
7968     if (!isSaCall) {
7969         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
7970         return CHECK_PERMISSION_FAILED;
7971     }
7972 #ifdef SUPPORT_GRAPHICS
7973     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
7974         Rosen::FocusChangeInfo focusChangeInfo;
7975         Rosen::WindowManager::GetInstance().GetFocusWindowInfo(focusChangeInfo);
7976         token = focusChangeInfo.abilityToken_;
7977     } else {
7978         if (!wmsHandler_) {
7979             TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
7980             return ERR_INVALID_VALUE;
7981         }
7982         wmsHandler_->GetFocusWindow(token);
7983     }
7984 
7985     if (!token) {
7986         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
7987         return ERR_INVALID_VALUE;
7988     }
7989 #endif
7990     return ERR_OK;
7991 }
7992 
DelegatorDoAbilityForeground(const sptr<IRemoteObject> & token)7993 int AbilityManagerService::DelegatorDoAbilityForeground(const sptr<IRemoteObject> &token)
7994 {
7995     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
7996     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
7997     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
7998     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
7999     int32_t callerPid = IPCSkeleton::GetCallingPid();
8000     int32_t appPid = abilityRecord->GetPid();
8001     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8002     if (callerPid != appPid) {
8003         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not the application itself");
8004         return ERR_INVALID_VALUE;
8005     }
8006     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8007         auto sessionId = GetMissionIdByAbilityTokenInner(token);
8008         if (!sessionId) {
8009             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid session id.");
8010             return ERR_INVALID_VALUE;
8011         }
8012         auto want = abilityRecord->GetWant();
8013         if (!IsAbilityControllerStart(want, want.GetBundle())) {
8014             TAG_LOGE(AAFwkTag::ABILITYMGR,
8015                 "SceneBoard IsAbilityControllerStart failed: %{public}s", want.GetBundle().c_str());
8016             return ERR_WOULD_BLOCK;
8017         }
8018         return ERR_OK;
8019     }
8020     auto missionId = GetMissionIdByAbilityToken(token);
8021     if (missionId < 0) {
8022         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid mission id.");
8023         return ERR_INVALID_VALUE;
8024     }
8025     return DelegatorMoveMissionToFront(missionId);
8026 }
8027 
DelegatorDoAbilityBackground(const sptr<IRemoteObject> & token)8028 int AbilityManagerService::DelegatorDoAbilityBackground(const sptr<IRemoteObject> &token)
8029 {
8030     TAG_LOGD(AAFwkTag::ABILITYMGR, "enter");
8031     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8032     auto &&abilityRecord = Token::GetAbilityRecordByToken(token);
8033     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8034     int32_t appPid = abilityRecord->GetPid();
8035     int32_t callerPid = IPCSkeleton::GetCallingPid();
8036     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerPid: %{public}d, appPid: %{public}d", callerPid, appPid);
8037     if (callerPid != appPid) {
8038         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not the application itself");
8039         return ERR_INVALID_VALUE;
8040     }
8041     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8042         return ERR_OK;
8043     }
8044     return MinimizeAbility(token, true);
8045 }
8046 
DoAbilityForeground(const sptr<IRemoteObject> & token,uint32_t flag)8047 int AbilityManagerService::DoAbilityForeground(const sptr<IRemoteObject> &token, uint32_t flag)
8048 {
8049     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityForeground, sceneFlag:%{public}u", flag);
8050     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8051     if (!VerificationToken(token) && !VerificationAllToken(token)) {
8052         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s token error.", __func__);
8053         return ERR_INVALID_VALUE;
8054     }
8055 
8056     std::lock_guard<ffrt::mutex> guard(globalLock_);
8057     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8058     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8059     if (!JudgeSelfCalled(abilityRecord)) {
8060         return CHECK_PERMISSION_FAILED;
8061     }
8062 
8063     auto type = abilityRecord->GetAbilityInfo().type;
8064     if (type != AppExecFwk::AbilityType::PAGE) {
8065         TAG_LOGE(AAFwkTag::ABILITYMGR, "Cannot minimize except page ability.");
8066         return ERR_WRONG_INTERFACE_CALL;
8067     }
8068 
8069     if (!IsAbilityControllerForeground(abilityRecord->GetAbilityInfo().bundleName)) {
8070         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerForeground false.");
8071         return ERR_WOULD_BLOCK;
8072     }
8073 
8074     auto missionListManager = GetCurrentMissionListManager();
8075     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8076     return missionListManager->DoAbilityForeground(abilityRecord, flag);
8077 }
8078 
DoAbilityBackground(const sptr<IRemoteObject> & token,uint32_t flag)8079 int AbilityManagerService::DoAbilityBackground(const sptr<IRemoteObject> &token, uint32_t flag)
8080 {
8081     TAG_LOGD(AAFwkTag::ABILITYMGR, "DoAbilityBackground, sceneFlag:%{public}u", flag);
8082     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8083 
8084     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8085     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
8086 
8087     abilityRecord->lifeCycleStateInfo_.sceneFlag = flag;
8088     int ret = MinimizeAbility(token);
8089     abilityRecord->lifeCycleStateInfo_.sceneFlag = SCENE_FLAG_NORMAL;
8090     return ret;
8091 }
8092 
DelegatorMoveMissionToFront(int32_t missionId)8093 int AbilityManagerService::DelegatorMoveMissionToFront(int32_t missionId)
8094 {
8095     TAG_LOGI(AAFwkTag::ABILITYMGR, "enter missionId : %{public}d", missionId);
8096     auto missionListManager = GetCurrentMissionListManager();
8097     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
8098 
8099     if (!IsAbilityControllerStartById(missionId)) {
8100         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart false");
8101         return ERR_WOULD_BLOCK;
8102     }
8103 
8104     return missionListManager->MoveMissionToFront(missionId);
8105 }
8106 
UpdateCallerInfo(Want & want,const sptr<IRemoteObject> & callerToken)8107 void AbilityManagerService::UpdateCallerInfo(Want& want, const sptr<IRemoteObject> &callerToken)
8108 {
8109     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8110     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
8111         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8112         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8113         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8114     }
8115     int32_t tokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
8116     int32_t callerUid = IPCSkeleton::GetCallingUid();
8117     int32_t callerPid = IPCSkeleton::GetCallingPid();
8118     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8119     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8120     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8121     want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
8122     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8123     want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
8124     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8125     want.RemoveParam(IS_SHELL_CALL);
8126 
8127     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8128     if (!abilityRecord) {
8129         std::string bundleName;
8130         auto bundleMgr = GetBundleManager();
8131         if (bundleMgr != nullptr) {
8132             IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, bundleName));
8133         }
8134         if (bundleName == "") {
8135             std::string nativeName;
8136             Security::AccessToken::NativeTokenInfo nativeTokenInfo;
8137             int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
8138             if (result == ERR_OK) {
8139                 nativeName = "_" + nativeTokenInfo.processName;
8140             }
8141             want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8142             want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME, nativeName);
8143         }
8144         want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8145         want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, bundleName);
8146         want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8147         want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, std::string(""));
8148         return;
8149     }
8150     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8151     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8152     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8153     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8154     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8155     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8156     UpdateSignatureInfo(callerBundleName, want);
8157 }
8158 
UpdateCallerInfoFromToken(Want & want,const sptr<IRemoteObject> & token)8159 void AbilityManagerService::UpdateCallerInfoFromToken(Want& want, const sptr<IRemoteObject> &token)
8160 {
8161     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8162     if (!abilityRecord) {
8163         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller abilityRecord is null.");
8164         return;
8165     }
8166 
8167     int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
8168     int32_t callerUid = abilityRecord->GetUid();
8169     int32_t callerPid = abilityRecord->GetPid();
8170     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8171     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8172     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8173     want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
8174     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8175     want.SetParam(Want::PARAM_RESV_CALLER_PID, callerPid);
8176     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8177     want.RemoveParam(IS_SHELL_CALL);
8178 
8179     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8180     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8181     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8182     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8183     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8184     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8185     UpdateSignatureInfo(callerBundleName, want);
8186 }
8187 
UpdateSignatureInfo(std::string bundleName,Want & want,bool isRemote)8188 void AbilityManagerService::UpdateSignatureInfo(std::string bundleName, Want& want, bool isRemote)
8189 {
8190     auto bundleMgr = GetBundleManager();
8191     if (bundleMgr != nullptr) {
8192         AppExecFwk::SignatureInfo signatureInfo;
8193         IN_PROCESS_CALL(bundleMgr->GetSignatureInfoByBundleName(bundleName, signatureInfo));
8194         std::string callerAppId = isRemote ? DMS_CALLER_APP_ID : Want::PARAM_RESV_CALLER_APP_ID;
8195         std::string callerAppIdentifier = isRemote ? DMS_CALLER_APP_IDENTIFIER : Want::PARAM_RESV_CALLER_APP_IDENTIFIER;
8196         want.RemoveParam(callerAppId);
8197         want.SetParam(callerAppId, signatureInfo.appId);
8198         want.RemoveParam(callerAppIdentifier);
8199         want.SetParam(callerAppIdentifier, signatureInfo.appIdentifier);
8200     }
8201 }
8202 
UpdateDmsCallerInfo(Want & want,const sptr<IRemoteObject> & callerToken)8203 void AbilityManagerService::UpdateDmsCallerInfo(Want& want, const sptr<IRemoteObject> &callerToken)
8204 {
8205     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8206     int32_t tokenId = static_cast<int32_t>(IPCSkeleton::GetCallingTokenID());
8207     int32_t callerUid = IPCSkeleton::GetCallingUid();
8208 
8209     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8210     if (!abilityRecord) {
8211         std::string bundleName;
8212         auto bundleMgr = AbilityUtil::GetBundleManagerHelper();
8213         if (bundleMgr != nullptr) {
8214             IN_PROCESS_CALL(bundleMgr->GetNameForUid(callerUid, bundleName));
8215         }
8216         if (bundleName == "") {
8217             std::string nativeName;
8218             Security::AccessToken::NativeTokenInfo nativeTokenInfo;
8219             int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(tokenId, nativeTokenInfo);
8220             if (result == ERR_OK) {
8221                 nativeName = "_" + nativeTokenInfo.processName;
8222             }
8223             want.RemoveParam(DMS_CALLER_NATIVE_NAME);
8224             want.SetParam(DMS_CALLER_NATIVE_NAME, nativeName);
8225         }
8226         want.RemoveParam(DMS_CALLER_BUNDLE_NAME);
8227         want.SetParam(DMS_CALLER_BUNDLE_NAME, bundleName);
8228         want.RemoveParam(DMS_CALLER_ABILITY_NAME);
8229         want.SetParam(DMS_CALLER_ABILITY_NAME, std::string(""));
8230         return;
8231     }
8232     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8233     want.RemoveParam(DMS_CALLER_BUNDLE_NAME);
8234     want.SetParam(DMS_CALLER_BUNDLE_NAME, callerBundleName);
8235     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8236     want.RemoveParam(DMS_CALLER_ABILITY_NAME);
8237     want.SetParam(DMS_CALLER_ABILITY_NAME, callerAbilityName);
8238     UpdateSignatureInfo(callerBundleName, want, true);
8239 }
8240 
JudgeMultiUserConcurrency(const int32_t userId)8241 bool AbilityManagerService::JudgeMultiUserConcurrency(const int32_t userId)
8242 {
8243     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8244     if (userId == U0_USER_ID) {
8245         TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s, userId is 0.", __func__);
8246         return true;
8247     }
8248 
8249     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId : %{public}d, current userId : %{public}d", userId, GetUserId());
8250 
8251     // Only non-concurrent mode is supported
8252     bool concurrencyMode = CONCURRENCY_MODE_FALSE;
8253     if (!concurrencyMode) {
8254         return (userId == GetUserId());
8255     }
8256 
8257     return true;
8258 }
8259 
8260 #ifdef ABILITY_COMMAND_FOR_TEST
ForceTimeoutForTest(const std::string & abilityName,const std::string & state)8261 int AbilityManagerService::ForceTimeoutForTest(const std::string &abilityName, const std::string &state)
8262 {
8263     if (abilityName.empty()) {
8264         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityName is empty.");
8265         return INVALID_DATA;
8266     }
8267     if (abilityName == "clean") {
8268         timeoutMap_.clear();
8269         return ERR_OK;
8270     }
8271     if (state != AbilityRecord::ConvertAbilityState(AbilityState::INITIAL) &&
8272         state != AbilityRecord::ConvertAbilityState(AbilityState::INACTIVE) &&
8273         state != AbilityRecord::ConvertAbilityState(AbilityState::FOREGROUND) &&
8274         state != AbilityRecord::ConvertAbilityState(AbilityState::BACKGROUND) &&
8275         state != AbilityRecord::ConvertAbilityState(AbilityState::TERMINATING) &&
8276         state != std::string("COMMAND")) {
8277         TAG_LOGE(AAFwkTag::ABILITYMGR, "lifecycle state is invalid.");
8278         return INVALID_DATA;
8279     }
8280     timeoutMap_.insert(std::make_pair(state, abilityName));
8281     return ERR_OK;
8282 }
8283 #endif
8284 
UpdateAsCallerSourceInfo(Want & want,sptr<IRemoteObject> asCallerSourceToken,sptr<IRemoteObject> callerToken)8285 void AbilityManagerService::UpdateAsCallerSourceInfo(Want& want, sptr<IRemoteObject> asCallerSourceToken,
8286     sptr<IRemoteObject> callerToken)
8287 {
8288 #ifdef SUPPORT_SCREEN
8289     if (UpdateAsCallerInfoFromDialog(want)) {
8290         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from dialog.");
8291         return;
8292     }
8293 #endif // SUPPORT_SCREEN
8294     if (asCallerSourceToken != nullptr) {
8295         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from token.");
8296         UpdateAsCallerInfoFromToken(want, asCallerSourceToken);
8297     } else if (callerToken != nullptr) {
8298         TAG_LOGD(AAFwkTag::ABILITYMGR, "Update as caller source info from callerRecord.");
8299         UpdateAsCallerInfoFromCallerRecord(want, callerToken);
8300     }
8301 }
8302 
UpdateAsCallerInfoFromToken(Want & want,sptr<IRemoteObject> asCallerSourceToken)8303 void AbilityManagerService::UpdateAsCallerInfoFromToken(Want& want, sptr<IRemoteObject> asCallerSourceToken)
8304 {
8305     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(asCallerSourceToken)) {
8306         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8307         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8308         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8309     }
8310     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8311     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8312     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8313     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8314     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8315     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8316     want.RemoveParam(IS_SHELL_CALL);
8317 
8318     auto abilityRecord = Token::GetAbilityRecordByToken(asCallerSourceToken);
8319     if (abilityRecord == nullptr) {
8320         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to update as caller info from token");
8321         return;
8322     }
8323     AppExecFwk::RunningProcessInfo processInfo = {};
8324     DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByToken(asCallerSourceToken, processInfo);
8325     int32_t tokenId = abilityRecord->GetApplicationInfo().accessTokenId;
8326     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8327     want.SetParam(Want::PARAM_RESV_CALLER_UID, processInfo.uid_);
8328     want.SetParam(Want::PARAM_RESV_CALLER_PID, processInfo.pid_);
8329 
8330     std::string callerBundleName = abilityRecord->GetAbilityInfo().bundleName;
8331     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8332     std::string callerAbilityName = abilityRecord->GetAbilityInfo().name;
8333     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8334     UpdateSignatureInfo(callerBundleName, want);
8335 }
8336 
UpdateAsCallerInfoFromCallerRecord(Want & want,sptr<IRemoteObject> callerToken)8337 void AbilityManagerService::UpdateAsCallerInfoFromCallerRecord(Want& want, sptr<IRemoteObject> callerToken)
8338 {
8339     if (!StartAbilityUtils::IsCallFromAncoShellOrBroker(callerToken)) {
8340         TAG_LOGD(AAFwkTag::ABILITYMGR, "not call from anco or broker.");
8341         want.RemoveParam(PARAM_RESV_ANCO_CALLER_UID);
8342         want.RemoveParam(PARAM_RESV_ANCO_CALLER_BUNDLENAME);
8343     }
8344     want.RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
8345     want.RemoveParam(Want::PARAM_RESV_CALLER_UID);
8346     want.RemoveParam(Want::PARAM_RESV_CALLER_PID);
8347     want.RemoveParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8348     want.RemoveParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8349     want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8350     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8351     want.RemoveParam(IS_SHELL_CALL);
8352     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
8353     CHECK_POINTER(callerRecord);
8354     auto sourceInfo = callerRecord->GetCallerInfo();
8355     CHECK_POINTER(sourceInfo);
8356     std::string callerBundleName = sourceInfo->callerBundleName;
8357     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, sourceInfo->callerTokenId);
8358     want.SetParam(Want::PARAM_RESV_CALLER_UID, sourceInfo->callerUid);
8359     want.SetParam(Want::PARAM_RESV_CALLER_PID, sourceInfo->callerPid);
8360     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8361     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, sourceInfo->callerAbilityName);
8362     if (callerBundleName == "") {
8363         want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME, sourceInfo->callerNativeName);
8364         return;
8365     }
8366     UpdateSignatureInfo(callerBundleName, want);
8367 }
8368 
UpdateAsCallerInfoFromDialog(Want & want)8369 bool AbilityManagerService::UpdateAsCallerInfoFromDialog(Want& want)
8370 {
8371     std::string dialogSessionId = want.GetStringParam("dialogSessionId");
8372     auto dialogCallerInfo = DialogSessionManager::GetInstance().GetDialogCallerInfo(dialogSessionId);
8373     if (dialogCallerInfo == nullptr) {
8374         TAG_LOGW(AAFwkTag::ABILITYMGR, "failed to get dialog caller info.");
8375         return false;
8376     }
8377     Want dialogCallerWant = dialogCallerInfo->targetWant;
8378     int32_t tokenId = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0);
8379     int32_t uid = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_UID, 0);
8380     int32_t pid = dialogCallerWant.GetIntParam(Want::PARAM_RESV_CALLER_PID, 0);
8381     std::string callerBundleName = dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
8382     std::string callerAbilityName = dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_ABILITY_NAME);
8383     want.SetParam(Want::PARAM_RESV_CALLER_TOKEN, tokenId);
8384     want.SetParam(Want::PARAM_RESV_CALLER_UID, uid);
8385     want.SetParam(Want::PARAM_RESV_CALLER_PID, pid);
8386     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
8387     want.SetParam(Want::PARAM_RESV_CALLER_ABILITY_NAME, callerAbilityName);
8388     want.RemoveParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
8389     want.RemoveParam(WANT_PARAMS_APP_RESTART_FLAG);
8390     want.RemoveParam(IS_SHELL_CALL);
8391     if (callerBundleName == "") {
8392         want.SetParam(Want::PARAM_RESV_CALLER_NATIVE_NAME,
8393             dialogCallerWant.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME));
8394         return true;
8395     }
8396     UpdateSignatureInfo(callerBundleName, want);
8397     return true;
8398 }
8399 
UpdateBackToCallerFlag(const sptr<IRemoteObject> & callerToken,Want & want,int32_t requestCode,bool backFlag)8400 void AbilityManagerService::UpdateBackToCallerFlag(const sptr<IRemoteObject> &callerToken, Want &want,
8401     int32_t requestCode, bool backFlag)
8402 {
8403     if (want.HasParameter(CALLER_REQUEST_CODE)) {
8404         want.RemoveParam(CALLER_REQUEST_CODE);
8405     }
8406     auto callerAbilityRecord = Token::GetAbilityRecordByToken(callerToken);
8407     if (requestCode > 0 && callerAbilityRecord != nullptr) {
8408         // default return true on oh
8409         if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
8410             backFlag = AmsConfigurationParameter::GetInstance().IsSupportBackToCaller();
8411         }
8412         auto fullRequestCode = StartupUtil::GenerateFullRequestCode(
8413             callerAbilityRecord->GetPid(), backFlag, requestCode);
8414         want.SetParam(CALLER_REQUEST_CODE, std::to_string(fullRequestCode));
8415         TAG_LOGI(AAFwkTag::ABILITYMGR,
8416             "pid: %{public}d, backFlag:%{private}d, requestCode: %{private}d, fullRequestCode: %{private}s",
8417             callerAbilityRecord->GetPid(), backFlag, requestCode, std::to_string(fullRequestCode).c_str());
8418     }
8419 }
8420 
CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo & abilityInfo,uint32_t tokenId)8421 int AbilityManagerService::CheckStaticCfgPermissionForAbility(const AppExecFwk::AbilityInfo &abilityInfo,
8422     uint32_t tokenId)
8423 {
8424     if (abilityInfo.permissions.empty() || AccessTokenKit::VerifyAccessToken(tokenId,
8425         PermissionConstants::PERMISSION_START_INVISIBLE_ABILITY, false) == ERR_OK) {
8426         return AppExecFwk::Constants::PERMISSION_GRANTED;
8427     }
8428 
8429     for (auto permission : abilityInfo.permissions) {
8430         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8431             AppExecFwk::Constants::PERMISSION_GRANTED) {
8432             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Ability permission: %{public}s",
8433                 permission.c_str());
8434             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8435         }
8436     }
8437 
8438     return AppExecFwk::Constants::PERMISSION_GRANTED;
8439 }
8440 
CheckOneSkillPermission(const AppExecFwk::Skill & skill,uint32_t tokenId)8441 bool AbilityManagerService::CheckOneSkillPermission(const AppExecFwk::Skill &skill, uint32_t tokenId)
8442 {
8443     for (auto permission : skill.permissions) {
8444         if (AccessTokenKit::VerifyAccessToken(tokenId, permission, false) !=
8445             AppExecFwk::Constants::PERMISSION_GRANTED) {
8446             TAG_LOGE(AAFwkTag::ABILITYMGR, "verify access token fail, Skill permission: %{public}s",
8447                 permission.c_str());
8448             return false;
8449         }
8450     }
8451 
8452     return true;
8453 }
8454 
CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest & abilityRequest,uint32_t tokenId)8455 int AbilityManagerService::CheckStaticCfgPermissionForSkill(const AppExecFwk::AbilityRequest &abilityRequest,
8456     uint32_t tokenId)
8457 {
8458     auto abilityInfo = abilityRequest.abilityInfo;
8459     auto resultAbilityPermission = CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8460     if (resultAbilityPermission != AppExecFwk::Constants::PERMISSION_GRANTED) {
8461         return resultAbilityPermission;
8462     }
8463 
8464     if (abilityInfo.skills.empty()) {
8465         return AppExecFwk::Constants::PERMISSION_GRANTED;
8466     }
8467     int32_t result = AppExecFwk::Constants::PERMISSION_GRANTED;
8468     for (auto skill : abilityInfo.skills) {
8469         if (skill.Match(abilityRequest.want)) {
8470             if (CheckOneSkillPermission(skill, tokenId)) {
8471                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8472             } else {
8473                 result = AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8474             }
8475         }
8476     }
8477     return result;
8478 }
8479 
CheckStaticCfgPermission(const AppExecFwk::AbilityRequest & abilityRequest,bool isStartAsCaller,uint32_t callerTokenId,bool isData,bool isSaCall,bool isImplicit)8480 int AbilityManagerService::CheckStaticCfgPermission(const AppExecFwk::AbilityRequest &abilityRequest,
8481     bool isStartAsCaller, uint32_t callerTokenId, bool isData, bool isSaCall, bool isImplicit)
8482 {
8483     auto abilityInfo = abilityRequest.abilityInfo;
8484     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8485     if (AppUtils::GetInstance().IsSupportAncoApp() &&
8486         StartAbilityUtils::IsCallFromAncoShellOrBroker(abilityRequest.callerToken)) {
8487         TAG_LOGD(AAFwkTag::ABILITYMGR,
8488             "Check static permission, name is %{public}s.", abilityInfo.name.c_str());
8489         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
8490         if (collaborator == nullptr) {
8491             TAG_LOGE(AAFwkTag::ABILITYMGR, "Collaborator is nullptr.");
8492             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8493         }
8494         int result = collaborator->CheckStaticCfgPermission(abilityRequest.want, isImplicit);
8495         if (result != ERR_OK) {
8496             TAG_LOGE(AAFwkTag::ABILITYMGR, "Check permission failed from broker.");
8497             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8498         }
8499     }
8500     if (!isData) {
8501         isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8502     }
8503     if (isSaCall) {
8504         // do not need check static config permission when start ability by SA
8505         return AppExecFwk::Constants::PERMISSION_GRANTED;
8506     }
8507 
8508     uint32_t tokenId;
8509     if (isStartAsCaller) {
8510         tokenId = callerTokenId;
8511     } else {
8512         tokenId = IPCSkeleton::GetCallingTokenID();
8513     }
8514 
8515     if (abilityInfo.applicationInfo.accessTokenId == tokenId) {
8516         return ERR_OK;
8517     }
8518 
8519     if ((abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
8520         abilityInfo.extensionAbilityType == AppExecFwk::ExtensionAbilityType::DATASHARE) ||
8521         (abilityInfo.type == AppExecFwk::AbilityType::DATA)) {
8522         // just need check the read permission and write permission of extension ability or data ability
8523         if (!abilityInfo.readPermission.empty()) {
8524             int checkReadPermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.readPermission, false);
8525             if (checkReadPermission == ERR_OK) {
8526                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8527             }
8528             TAG_LOGW(AAFwkTag::ABILITYMGR,
8529                 "verify access token fail, read permission: %{public}s", abilityInfo.readPermission.c_str());
8530         }
8531         if (!abilityInfo.writePermission.empty()) {
8532             int checkWritePermission = AccessTokenKit::VerifyAccessToken(tokenId, abilityInfo.writePermission, false);
8533             if (checkWritePermission == ERR_OK) {
8534                 return AppExecFwk::Constants::PERMISSION_GRANTED;
8535             }
8536             TAG_LOGW(AAFwkTag::ABILITYMGR,
8537                 "verify access token fail, write permission: %{public}s", abilityInfo.writePermission.c_str());
8538         }
8539 
8540         if (!abilityInfo.readPermission.empty() || !abilityInfo.writePermission.empty()) {
8541             // 'readPermission' and 'writePermission' take precedence over 'permission'
8542             // when 'readPermission' or 'writePermission' is not empty, no need check 'permission'
8543             return AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
8544         }
8545     }
8546 
8547     if (!isImplicit) {
8548         return CheckStaticCfgPermissionForAbility(abilityInfo, tokenId);
8549     }
8550     return CheckStaticCfgPermissionForSkill(abilityRequest, tokenId);
8551 }
8552 
IsNeedTimeoutForTest(const std::string & abilityName,const std::string & state) const8553 bool AbilityManagerService::IsNeedTimeoutForTest(const std::string &abilityName, const std::string &state) const
8554 {
8555     for (auto iter = timeoutMap_.begin(); iter != timeoutMap_.end(); iter++) {
8556         if (iter->first == state && iter->second == abilityName) {
8557             return true;
8558         }
8559     }
8560     return false;
8561 }
8562 
GetValidDataAbilityUri(const std::string & abilityInfoUri,std::string & adjustUri)8563 bool AbilityManagerService::GetValidDataAbilityUri(const std::string &abilityInfoUri, std::string &adjustUri)
8564 {
8565     // note: do not use abilityInfo.uri directly, need check uri first.
8566     size_t firstSeparator = abilityInfoUri.find_first_of('/');
8567     size_t lastSeparator = abilityInfoUri.find_last_of('/');
8568     if (lastSeparator - firstSeparator != 1) {
8569         TAG_LOGE(AAFwkTag::ABILITYMGR, "ability info uri error, uri: %{public}s", abilityInfoUri.c_str());
8570         return false;
8571     }
8572 
8573     adjustUri = abilityInfoUri;
8574     adjustUri.insert(lastSeparator, "/");
8575     return true;
8576 }
8577 
GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> & abilityInfos,const std::string & mainAbility,std::string & uri)8578 bool AbilityManagerService::GetDataAbilityUri(const std::vector<AppExecFwk::AbilityInfo> &abilityInfos,
8579     const std::string &mainAbility, std::string &uri)
8580 {
8581     if (abilityInfos.empty() || mainAbility.empty()) {
8582         TAG_LOGE(AAFwkTag::ABILITYMGR,
8583             "abilityInfos or mainAbility is empty. mainAbility: %{public}s", mainAbility.c_str());
8584         return false;
8585     }
8586 
8587     std::string dataAbilityUri;
8588     for (auto abilityInfo : abilityInfos) {
8589         if (abilityInfo.type == AppExecFwk::AbilityType::DATA &&
8590             abilityInfo.name == mainAbility) {
8591             dataAbilityUri = abilityInfo.uri;
8592             TAG_LOGI(AAFwkTag::ABILITYMGR, "get data ability uri: %{public}s", dataAbilityUri.c_str());
8593             break;
8594         }
8595     }
8596 
8597     return GetValidDataAbilityUri(dataAbilityUri, uri);
8598 }
8599 
GetAbilityRunningInfo(std::vector<AbilityRunningInfo> & info,std::shared_ptr<AbilityRecord> & abilityRecord)8600 void AbilityManagerService::GetAbilityRunningInfo(std::vector<AbilityRunningInfo> &info,
8601     std::shared_ptr<AbilityRecord> &abilityRecord)
8602 {
8603     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8604     AbilityRunningInfo runningInfo;
8605     AppExecFwk::RunningProcessInfo processInfo;
8606 
8607     runningInfo.ability = abilityRecord->GetElementName();
8608     runningInfo.startTime = abilityRecord->GetStartTime();
8609     runningInfo.abilityState = static_cast<int>(abilityRecord->GetAbilityState());
8610 
8611     DelayedSingleton<AppScheduler>::GetInstance()->
8612         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
8613     runningInfo.pid = processInfo.pid_;
8614     runningInfo.uid = processInfo.uid_;
8615     runningInfo.processName = processInfo.processName_;
8616     runningInfo.appCloneIndex = processInfo.appCloneIndex;
8617     info.emplace_back(runningInfo);
8618 }
8619 
VerifyAccountPermission(int32_t userId)8620 int AbilityManagerService::VerifyAccountPermission(int32_t userId)
8621 {
8622     if ((userId < 0) || (userController_ && (userController_->GetCurrentUserId() == userId))) {
8623         return ERR_OK;
8624     }
8625     return AAFwk::PermissionVerification::GetInstance()->VerifyAccountPermission();
8626 }
8627 
FreeInstallAbilityFromRemote(const Want & want,const sptr<IRemoteObject> & callback,int32_t userId,int requestCode)8628 int AbilityManagerService::FreeInstallAbilityFromRemote(const Want &want, const sptr<IRemoteObject> &callback,
8629     int32_t userId, int requestCode)
8630 {
8631     auto callingUid = IPCSkeleton::GetCallingUid();
8632     if (callingUid != DMS_UID) {
8633         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for DMS");
8634         return CHECK_PERMISSION_FAILED;
8635     }
8636     int32_t validUserId = GetValidUserId(userId);
8637     if (freeInstallManager_ == nullptr) {
8638         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr");
8639         return ERR_INVALID_VALUE;
8640     }
8641     return freeInstallManager_->FreeInstallAbilityFromRemote(want, callback, validUserId, requestCode);
8642 }
8643 
GetTopAbility(bool isNeedLocalDeviceId)8644 AppExecFwk::ElementName AbilityManagerService::GetTopAbility(bool isNeedLocalDeviceId)
8645 {
8646     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8647     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
8648     AppExecFwk::ElementName elementName = {};
8649     if (!PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) {
8650         auto callerPid = IPCSkeleton::GetCallingPid();
8651         AppExecFwk::RunningProcessInfo processInfo;
8652         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
8653         if (!processInfo.isTestProcess) {
8654             TAG_LOGE(AAFwkTag::ABILITYMGR, "caller can not use system-api or not test process.");
8655             return elementName;
8656         }
8657     }
8658 #ifdef SUPPORT_GRAPHICS
8659     sptr<IRemoteObject> token;
8660     int ret = IN_PROCESS_CALL(GetTopAbility(token));
8661     if (ret) {
8662         return elementName;
8663     }
8664     if (!token) {
8665         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
8666         return elementName;
8667     }
8668     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8669     if (abilityRecord == nullptr) {
8670         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
8671         return elementName;
8672     }
8673     elementName = abilityRecord->GetElementName();
8674     bool isDeviceEmpty = elementName.GetDeviceID().empty();
8675     std::string localDeviceId;
8676     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
8677         elementName.SetDeviceID(localDeviceId);
8678     }
8679 #endif
8680     return elementName;
8681 }
8682 
GetElementNameByToken(sptr<IRemoteObject> token,bool isNeedLocalDeviceId)8683 AppExecFwk::ElementName AbilityManagerService::GetElementNameByToken(sptr<IRemoteObject> token,
8684     bool isNeedLocalDeviceId)
8685 {
8686     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
8687     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s start.", __func__);
8688     AppExecFwk::ElementName elementName = {};
8689 #ifdef SUPPORT_GRAPHICS
8690     if (!token) {
8691         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
8692         return elementName;
8693     }
8694     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8695     if (abilityRecord == nullptr) {
8696         TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s abilityRecord is null.", __func__);
8697         return elementName;
8698     }
8699     elementName = abilityRecord->GetElementName();
8700     bool isDeviceEmpty = elementName.GetDeviceID().empty();
8701     std::string localDeviceId;
8702     if (isDeviceEmpty && isNeedLocalDeviceId && GetLocalDeviceId(localDeviceId)) {
8703         elementName.SetDeviceID(localDeviceId);
8704     }
8705 #endif
8706     return elementName;
8707 }
8708 
Dump(int fd,const std::vector<std::u16string> & args)8709 int AbilityManagerService::Dump(int fd, const std::vector<std::u16string>& args)
8710 {
8711     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump begin fd: %{public}d", fd);
8712     std::string result;
8713     auto errCode = Dump(args, result);
8714     int ret = dprintf(fd, "%s\n", result.c_str());
8715     if (ret < 0) {
8716         TAG_LOGE(AAFwkTag::ABILITYMGR, "dprintf error");
8717         return ERR_AAFWK_HIDUMP_ERROR;
8718     }
8719     TAG_LOGD(AAFwkTag::ABILITYMGR, "Dump end");
8720     return errCode;
8721 }
8722 
Dump(const std::vector<std::u16string> & args,std::string & result)8723 int AbilityManagerService::Dump(const std::vector<std::u16string>& args, std::string& result)
8724 {
8725     ErrCode errCode = ERR_OK;
8726     auto size = args.size();
8727     if (size == 0) {
8728         ShowHelp(result);
8729         return errCode;
8730     }
8731 
8732     std::vector<std::string> argsStr;
8733     for (auto arg : args) {
8734         argsStr.emplace_back(Str16ToStr8(arg));
8735     }
8736 
8737     if (argsStr[0] == "-h") {
8738         ShowHelp(result);
8739     } else {
8740         errCode = ProcessMultiParam(argsStr, result);
8741         if (errCode == ERR_AAFWK_HIDUMP_INVALID_ARGS) {
8742             ShowIllegalInfomation(result);
8743         }
8744     }
8745     return errCode;
8746 }
8747 
ProcessMultiParam(std::vector<std::string> & argsStr,std::string & result)8748 ErrCode AbilityManagerService::ProcessMultiParam(std::vector<std::string>& argsStr, std::string& result)
8749 {
8750     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s begin", __func__);
8751     bool isClient = false;
8752     bool isUser = false;
8753     int userID = DEFAULT_INVAL_VALUE;
8754     std::vector<std::string>::iterator it;
8755     for (it = argsStr.begin(); it != argsStr.end();) {
8756         if (*it == ARGS_CLIENT) {
8757             isClient = true;
8758             it = argsStr.erase(it);
8759             continue;
8760         }
8761         if (*it == ARGS_USER_ID) {
8762             it = argsStr.erase(it);
8763             if (it == argsStr.end()) {
8764                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
8765                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
8766             }
8767             (void)StrToInt(*it, userID);
8768             if (userID < 0) {
8769                 TAG_LOGE(AAFwkTag::ABILITYMGR, "ARGS_USER_ID id invalid");
8770                 return ERR_AAFWK_HIDUMP_INVALID_ARGS;
8771             }
8772             isUser = true;
8773             it = argsStr.erase(it);
8774             continue;
8775         }
8776         it++;
8777     }
8778     std::string cmd;
8779     for (unsigned int i = 0; i < argsStr.size(); i++) {
8780         cmd.append(argsStr[i]);
8781         if (i != argsStr.size() - 1) {
8782             cmd.append(" ");
8783         }
8784     }
8785     TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s, isClient:%{public}d, userID is : %{public}d, cmd is : %{public}s",
8786         __func__, isClient, userID, cmd.c_str());
8787 
8788     std::vector<std::string> dumpResults;
8789     DumpSysState(cmd, dumpResults, isClient, isUser, userID);
8790     for (auto it : dumpResults) {
8791         result += it + "\n";
8792     }
8793     return ERR_OK;
8794 }
8795 
ShowHelp(std::string & result)8796 void AbilityManagerService::ShowHelp(std::string& result)
8797 {
8798     result.append("Usage:\n")
8799         .append("-h                          ")
8800         .append("help text for the tool\n")
8801         .append("-a [-c | -u {UserId}]       ")
8802         .append("dump all ability infomation in the system or all ability infomation of client/UserId\n")
8803         .append("-l                          ")
8804         .append("dump all mission list information in the system\n")
8805         .append("-i {AbilityRecordId}        ")
8806         .append("dump an ability infomation by ability record id\n")
8807         .append("-e                          ")
8808         .append("dump all extension infomation in the system(FA: ServiceAbilityRecords, Stage: ExtensionRecords)\n")
8809         .append("-p [PendingWantRecordId]    ")
8810         .append("dump all pendingwant record infomation in the system\n")
8811         .append("-r                          ")
8812         .append("dump all process in the system\n")
8813         .append("-d                          ")
8814         .append("dump all data ability infomation in the system");
8815 }
8816 
ShowIllegalInfomation(std::string & result)8817 void AbilityManagerService::ShowIllegalInfomation(std::string& result)
8818 {
8819     result.append(ILLEGAL_INFOMATION);
8820 }
8821 
DumpAbilityInfoDone(std::vector<std::string> & infos,const sptr<IRemoteObject> & callerToken)8822 int AbilityManagerService::DumpAbilityInfoDone(std::vector<std::string> &infos, const sptr<IRemoteObject> &callerToken)
8823 {
8824     TAG_LOGD(AAFwkTag::ABILITYMGR, "DumpAbilityInfoDone begin");
8825     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
8826     if (abilityRecord == nullptr) {
8827         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord nullptr");
8828         return ERR_INVALID_VALUE;
8829     }
8830     if (!JudgeSelfCalled(abilityRecord)) {
8831         return CHECK_PERMISSION_FAILED;
8832     }
8833     abilityRecord->DumpAbilityInfoDone(infos);
8834     return ERR_OK;
8835 }
8836 
SetMissionContinueState(const sptr<IRemoteObject> & token,const AAFwk::ContinueState & state)8837 int AbilityManagerService::SetMissionContinueState(const sptr<IRemoteObject> &token, const AAFwk::ContinueState &state)
8838 {
8839     TAG_LOGD(AAFwkTag::ABILITYMGR, "SetMissionContinueState begin. State: %{public}d", state);
8840 
8841     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
8842 
8843     int32_t missionId = GetMissionIdByAbilityToken(token);
8844     if (missionId == -1) {
8845         TAG_LOGE(AAFwkTag::ABILITYMGR, "SetMissionContinueState failed to get missionId. State: %{public}d", state);
8846         return ERR_INVALID_VALUE;
8847     }
8848 
8849     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8850     if (!abilityRecord) {
8851         TAG_LOGE(AAFwkTag::ABILITYMGR,
8852             "SetMissionContinueState: No such ability record. Mission id: %{public}d, state: %{public}d",
8853             missionId, state);
8854         return -1;
8855     }
8856 
8857     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8858     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
8859     if (callingTokenId != tokenID) {
8860         TAG_LOGE(AAFwkTag::ABILITYMGR,
8861             "SetMissionContinueState not self, not enabled. Mission id: %{public}d, state: %{public}d",
8862             missionId, state);
8863         return -1;
8864     }
8865 
8866     auto userId = abilityRecord->GetOwnerMissionUserId();
8867     auto missionListManager = GetMissionListManagerByUserId(userId);
8868     if (!missionListManager) {
8869         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager. Mission id: %{public}d, state: %{public}d",
8870             missionId, state);
8871         return -1;
8872     }
8873 
8874     auto setResult = missionListManager->SetMissionContinueState(token, missionId, state);
8875     if (setResult != ERR_OK) {
8876         TAG_LOGE(AAFwkTag::ABILITYMGR,
8877             "missionListManager set failed, result: %{public}d, mission id: %{public}d, state: %{public}d",
8878             setResult, missionId, state);
8879         return setResult;
8880     }
8881 
8882     DistributedClient dmsClient;
8883     auto result =  dmsClient.SetMissionContinueState(missionId, state);
8884     if (result != ERR_OK) {
8885         TAG_LOGE(AAFwkTag::ABILITYMGR,
8886             "Notify DMS client failed, result: %{public}d. Mission id: %{public}d, state: %{public}d",
8887             result, missionId, state);
8888     }
8889 
8890     TAG_LOGD(AAFwkTag::ABILITYMGR,
8891         "SetMissionContinueState end. Mission id: %{public}d, state: %{public}d", missionId, state);
8892     return ERR_OK;
8893 }
8894 
8895 #ifdef SUPPORT_GRAPHICS
SetMissionLabel(const sptr<IRemoteObject> & token,const std::string & label)8896 int AbilityManagerService::SetMissionLabel(const sptr<IRemoteObject> &token, const std::string &label)
8897 {
8898     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8899     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8900     if (!abilityRecord) {
8901         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
8902         return -1;
8903     }
8904 
8905     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8906     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
8907     if (callingTokenId != tokenID) {
8908         TAG_LOGE(AAFwkTag::ABILITYMGR, "SetMissionLabel not self, not enabled");
8909         return -1;
8910     }
8911 
8912     auto userId = abilityRecord->GetOwnerMissionUserId();
8913     auto missionListManager = GetMissionListManagerByUserId(userId);
8914     if (!missionListManager) {
8915         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager when set mission label.");
8916         return -1;
8917     }
8918 
8919     return missionListManager->SetMissionLabel(token, label);
8920 }
8921 
SetMissionIcon(const sptr<IRemoteObject> & token,const std::shared_ptr<OHOS::Media::PixelMap> & icon)8922 int AbilityManagerService::SetMissionIcon(const sptr<IRemoteObject> &token,
8923     const std::shared_ptr<OHOS::Media::PixelMap> &icon)
8924 {
8925     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s", __func__);
8926     CHECK_CALLER_IS_SYSTEM_APP;
8927     auto abilityRecord = Token::GetAbilityRecordByToken(token);
8928     if (!abilityRecord) {
8929         TAG_LOGE(AAFwkTag::ABILITYMGR, "no such ability record");
8930         return -1;
8931     }
8932 
8933     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8934     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
8935     if (callingTokenId != tokenID) {
8936         TAG_LOGE(AAFwkTag::ABILITYMGR, "not self, not enable to set mission icon");
8937         return -1;
8938     }
8939 
8940     auto userId = abilityRecord->GetOwnerMissionUserId();
8941     auto missionListManager = GetMissionListManagerByUserId(userId);
8942     if (!missionListManager) {
8943         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find mission list manager.");
8944         return -1;
8945     }
8946 
8947     return missionListManager->SetMissionIcon(token, icon);
8948 }
8949 
RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> & handler,bool animationEnabled)8950 int AbilityManagerService::RegisterWindowManagerServiceHandler(const sptr<IWindowManagerServiceHandler> &handler,
8951     bool animationEnabled)
8952 {
8953     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8954     if (!isSaCall) {
8955         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
8956         return CHECK_PERMISSION_FAILED;
8957     }
8958     wmsHandler_ = handler;
8959     isAnimationEnabled_ = animationEnabled;
8960     TAG_LOGD(AAFwkTag::ABILITYMGR, "%{public}s: WMS handler registered successfully.", __func__);
8961     return ERR_OK;
8962 }
8963 
GetWMSHandler() const8964 sptr<IWindowManagerServiceHandler> AbilityManagerService::GetWMSHandler() const
8965 {
8966     return wmsHandler_;
8967 }
8968 
CompleteFirstFrameDrawing(const sptr<IRemoteObject> & abilityToken)8969 void AbilityManagerService::CompleteFirstFrameDrawing(const sptr<IRemoteObject> &abilityToken)
8970 {
8971     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
8972     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
8973         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not foundation call.");
8974         return;
8975     }
8976     auto abilityRecord = Token::GetAbilityRecordByToken(abilityToken);
8977     CHECK_POINTER(abilityRecord);
8978 
8979     auto ownerUserId = abilityRecord->GetOwnerMissionUserId();
8980     auto missionListManager = GetMissionListManagerByUserId(ownerUserId);
8981     CHECK_POINTER(missionListManager);
8982     missionListManager->CompleteFirstFrameDrawing(abilityToken);
8983 }
8984 
CompleteFirstFrameDrawing(int32_t sessionId)8985 void AbilityManagerService::CompleteFirstFrameDrawing(int32_t sessionId)
8986 {
8987     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
8988     if (!IsCallerSceneBoard()) {
8989         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
8990         return;
8991     }
8992     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
8993     CHECK_POINTER(uiAbilityManager);
8994     uiAbilityManager->CompleteFirstFrameDrawing(sessionId);
8995 }
8996 
ShowPickerDialog(const Want & want,int32_t userId,const sptr<IRemoteObject> & callerToken)8997 int32_t AbilityManagerService::ShowPickerDialog(
8998     const Want& want, int32_t userId, const sptr<IRemoteObject> &callerToken)
8999 {
9000     AAFwk::Want newWant = want;
9001     std::string sharePickerBundleName =
9002         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_BUNDLE_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_BUNDLE_NAME);
9003     std::string sharePickerAbilityName =
9004         OHOS::system::GetParameter(SHARE_PICKER_DIALOG_ABILITY_NAME_KEY, SHARE_PICKER_DIALOG_DEFAULY_ABILITY_NAME);
9005     newWant.SetElementName(sharePickerBundleName, sharePickerAbilityName);
9006     newWant.SetParam(TOKEN_KEY, callerToken);
9007     // note: clear actions
9008     newWant.SetAction("");
9009     return IN_PROCESS_CALL(StartAbility(newWant, DEFAULT_INVAL_VALUE, userId));
9010 }
9011 
CheckWindowMode(int32_t windowMode,const std::vector<AppExecFwk::SupportWindowMode> & windowModes) const9012 bool AbilityManagerService::CheckWindowMode(int32_t windowMode,
9013     const std::vector<AppExecFwk::SupportWindowMode>& windowModes) const
9014 {
9015     TAG_LOGI(AAFwkTag::ABILITYMGR, "Window mode is %{public}d.", windowMode);
9016     if (windowMode == AbilityWindowConfiguration::MULTI_WINDOW_DISPLAY_UNDEFINED) {
9017         return true;
9018     }
9019 
9020     auto bmsWindowMode = WindowOptionsUtils::WindowModeMap(windowMode);
9021     if (bmsWindowMode.first) {
9022         for (const auto& mode : windowModes) {
9023             if (mode == bmsWindowMode.second) {
9024                 return true;
9025             }
9026         }
9027     }
9028     return false;
9029 }
9030 
PrepareTerminateAbility(const sptr<IRemoteObject> & token,sptr<IPrepareTerminateCallback> & callback)9031 int AbilityManagerService::PrepareTerminateAbility(const sptr<IRemoteObject> &token,
9032     sptr<IPrepareTerminateCallback> &callback)
9033 {
9034     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
9035     if (callback == nullptr) {
9036         TAG_LOGE(AAFwkTag::ABILITYMGR, "callback is nullptr.");
9037         return ERR_INVALID_VALUE;
9038     }
9039     if (!CheckPrepareTerminateEnable()) {
9040         callback->DoPrepareTerminate();
9041         return ERR_INVALID_VALUE;
9042     }
9043 
9044     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9045     if (abilityRecord == nullptr) {
9046         TAG_LOGE(AAFwkTag::ABILITYMGR, "record is nullptr.");
9047         callback->DoPrepareTerminate();
9048         return ERR_INVALID_VALUE;
9049     }
9050 
9051     if (!JudgeSelfCalled(abilityRecord)) {
9052         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not self call.");
9053         callback->DoPrepareTerminate();
9054         return CHECK_PERMISSION_FAILED;
9055     }
9056 
9057     auto type = abilityRecord->GetAbilityInfo().type;
9058     if (type != AppExecFwk::AbilityType::PAGE) {
9059         TAG_LOGE(AAFwkTag::ABILITYMGR, "Only support PAGE.");
9060         callback->DoPrepareTerminate();
9061         return RESOLVE_CALL_ABILITY_TYPE_ERR;
9062     }
9063 
9064     auto timeoutTask = [&callback]() {
9065         callback->DoPrepareTerminate();
9066     };
9067     int prepareTerminateTimeout =
9068         AmsConfigurationParameter::GetInstance().GetAppStartTimeoutTime() * PREPARE_TERMINATE_TIMEOUT_MULTIPLE;
9069     if (taskHandler_) {
9070         taskHandler_->SubmitTask(timeoutTask, "PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()),
9071             prepareTerminateTimeout);
9072     }
9073 
9074     bool res = abilityRecord->PrepareTerminateAbility();
9075     if (!res) {
9076         callback->DoPrepareTerminate();
9077     }
9078     if (taskHandler_) {
9079         taskHandler_->CancelTask("PrepareTermiante_" + std::to_string(abilityRecord->GetAbilityRecordId()));
9080     }
9081     return ERR_OK;
9082 }
9083 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9084 void AbilityManagerService::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9085 {
9086     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle focused event");
9087     auto missionListManager = GetCurrentMissionListManager();
9088     CHECK_POINTER(missionListManager);
9089 
9090     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9091     missionListManager->NotifyMissionFocused(missionId);
9092 }
9093 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)9094 void AbilityManagerService::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
9095 {
9096     TAG_LOGI(AAFwkTag::ABILITYMGR, "handle unfocused event");
9097     auto missionListManager = GetCurrentMissionListManager();
9098     CHECK_POINTER(missionListManager);
9099 
9100     int32_t missionId = GetMissionIdByAbilityToken(focusChangeInfo->abilityToken_);
9101     missionListManager->NotifyMissionUnfocused(missionId);
9102 }
9103 
InitFocusListener()9104 void AbilityManagerService::InitFocusListener()
9105 {
9106     TAG_LOGI(AAFwkTag::ABILITYMGR, "Init ability focus listener");
9107     if (focusListener_) {
9108         return;
9109     }
9110 
9111     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
9112     auto registerTask = [innerService = shared_from_this()]() {
9113         if (innerService) {
9114             TAG_LOGI(AAFwkTag::ABILITYMGR, "RegisterFocusListener task");
9115             innerService->RegisterFocusListener();
9116         }
9117     };
9118     if (taskHandler_) {
9119         taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
9120     }
9121 }
9122 
RegisterFocusListener()9123 void AbilityManagerService::RegisterFocusListener()
9124 {
9125     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register focus listener");
9126     if (!focusListener_) {
9127         TAG_LOGE(AAFwkTag::ABILITYMGR, "no listener obj");
9128         return;
9129     }
9130     Rosen::WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
9131     TAG_LOGI(AAFwkTag::ABILITYMGR, "Register focus listener success");
9132 }
9133 
InitPrepareTerminateConfig()9134 void AbilityManagerService::InitPrepareTerminateConfig()
9135 {
9136     char value[PREPARE_TERMINATE_ENABLE_SIZE] = "false";
9137     int retSysParam = GetParameter(PREPARE_TERMINATE_ENABLE_PARAMETER, "false", value, PREPARE_TERMINATE_ENABLE_SIZE);
9138     TAG_LOGI(AAFwkTag::ABILITYMGR,
9139         "CheckPrepareTerminateEnable, %{public}s value is %{public}s.", PREPARE_TERMINATE_ENABLE_PARAMETER,
9140         value);
9141     if (retSysParam > 0 && !std::strcmp(value, "true")) {
9142         isPrepareTerminateEnable_ = true;
9143     }
9144 }
9145 
RegisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer,const std::string & targetBundleName)9146 int AbilityManagerService::RegisterAbilityFirstFrameStateObserver(
9147     const sptr<IAbilityFirstFrameStateObserver> &observer, const std::string &targetBundleName)
9148 {
9149     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9150         RegisterAbilityFirstFrameStateObserver(observer, targetBundleName);
9151 }
9152 
UnregisterAbilityFirstFrameStateObserver(const sptr<IAbilityFirstFrameStateObserver> & observer)9153 int AbilityManagerService::UnregisterAbilityFirstFrameStateObserver(
9154     const sptr<IAbilityFirstFrameStateObserver> &observer)
9155 {
9156     return AppExecFwk::AbilityFirstFrameStateObserverManager::GetInstance().
9157         UnregisterAbilityFirstFrameStateObserver(observer);
9158 }
9159 
GetAnimationFlag()9160 bool AbilityManagerService::GetAnimationFlag()
9161 {
9162     return isAnimationEnabled_;
9163 }
9164 
9165 #endif
9166 
CheckCallServicePermission(const AbilityRequest & abilityRequest)9167 int AbilityManagerService::CheckCallServicePermission(const AbilityRequest &abilityRequest)
9168 {
9169     if (abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_UID, IPCSkeleton::GetCallingUid()) == BROKER_UID &&
9170         abilityRequest.want.GetElement().GetBundleName() == SHELL_ASSISTANT_BUNDLENAME) {
9171         auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
9172         if (collaborator != nullptr) {
9173             TAG_LOGI(AAFwkTag::ABILITYMGR, "Collaborator CheckCallAbilityPermission.");
9174             return collaborator->CheckCallAbilityPermission(abilityRequest.want);
9175         }
9176     }
9177     if (abilityRequest.abilityInfo.isStageBasedModel) {
9178         auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9179         TAG_LOGD(AAFwkTag::ABILITYMGR, "extensionType is %{public}d.", static_cast<int>(extensionType));
9180         if (extensionType == AppExecFwk::ExtensionAbilityType::SERVICE ||
9181             extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE) {
9182             return CheckCallServiceExtensionPermission(abilityRequest);
9183         } else {
9184             return CheckCallOtherExtensionPermission(abilityRequest);
9185         }
9186     } else {
9187         return CheckCallServiceAbilityPermission(abilityRequest);
9188     }
9189 }
9190 
CheckCallDataAbilityPermission(AbilityRequest & abilityRequest,bool isShell,bool isSACall)9191 int AbilityManagerService::CheckCallDataAbilityPermission(AbilityRequest &abilityRequest, bool isShell, bool isSACall)
9192 {
9193     abilityRequest.appInfo = abilityRequest.abilityInfo.applicationInfo;
9194     abilityRequest.uid = abilityRequest.appInfo.uid;
9195     if (abilityRequest.appInfo.name.empty() || abilityRequest.appInfo.bundleName.empty()) {
9196         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid app info for data ability acquiring.");
9197         return ERR_INVALID_VALUE;
9198     }
9199     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::DATA) {
9200         TAG_LOGE(AAFwkTag::ABILITYMGR, "BMS query result is not a data ability.");
9201         return ERR_WRONG_INTERFACE_CALL;
9202     }
9203 
9204     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest,
9205         true, isShell, isSACall);
9206     if (isShell) {
9207         verificationInfo.isBackgroundCall = true;
9208     }
9209     if (!isShell && IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall, true) != ERR_OK) {
9210         return ERR_INVALID_VALUE;
9211     }
9212     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallDataAbilityPermission(verificationInfo,
9213         isShell);
9214     if (result != ERR_OK) {
9215         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start DataAbility");
9216         return result;
9217     }
9218 
9219     return ERR_OK;
9220 }
9221 
CreateVerificationInfo(const AbilityRequest & abilityRequest,bool isData,bool isShell,bool isSA)9222 AAFwk::PermissionVerification::VerificationInfo AbilityManagerService::CreateVerificationInfo(
9223     const AbilityRequest &abilityRequest, bool isData, bool isShell, bool isSA)
9224 {
9225     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9226     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9227     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9228     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9229     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call ServiceAbility or DataAbility, target bundleName: %{public}s.",
9230         abilityRequest.appInfo.bundleName.c_str());
9231     if (whiteListassociatedWakeUpFlag_ &&
9232         abilityRequest.appInfo.bundleName == BUNDLE_NAME_SETTINGSDATA) {
9233         TAG_LOGD(AAFwkTag::ABILITYMGR,
9234             "Call ServiceAbility or DataAbility, target bundle in white-list, allow associatedWakeUp.");
9235         verificationInfo.associatedWakeUp = true;
9236     } else {
9237         verificationInfo.associatedWakeUp = abilityRequest.appInfo.associatedWakeUp;
9238     }
9239     if (!isData) {
9240         isSA = AAFwk::PermissionVerification::GetInstance()->IsSACall();
9241         isShell = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
9242     }
9243     if (isSA || isShell) {
9244         return verificationInfo;
9245     }
9246     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9247     if (callerAbility) {
9248         verificationInfo.apiTargetVersion = callerAbility->GetApplicationInfo().apiTargetVersion;
9249     }
9250 
9251     return verificationInfo;
9252 }
9253 
CheckCallServiceExtensionPermission(const AbilityRequest & abilityRequest)9254 int AbilityManagerService::CheckCallServiceExtensionPermission(const AbilityRequest &abilityRequest)
9255 {
9256     TAG_LOGD(AAFwkTag::ABILITYMGR, "begin");
9257 
9258     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9259     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9260     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9261     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9262     verificationInfo.isBackgroundCall = false;
9263     if (isParamStartAbilityEnable_) {
9264         bool stopContinuousTaskFlag = ShouldPreventStartAbility(abilityRequest);
9265         if (stopContinuousTaskFlag) {
9266             TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension");
9267             return CHECK_PERMISSION_FAILED;
9268         }
9269     }
9270 
9271     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceExtensionPermission(verificationInfo);
9272     if (result != ERR_OK) {
9273         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension or DataShareExtension");
9274     }
9275     return result;
9276 }
CheckCallAutoFillExtensionPermission(const AbilityRequest & abilityRequest)9277 int AbilityManagerService::CheckCallAutoFillExtensionPermission(const AbilityRequest &abilityRequest)
9278 {
9279     if (!abilityRequest.appInfo.isSystemApp) {
9280         TAG_LOGE(AAFwkTag::ABILITYMGR, "application requesting call isn't system application");
9281         return CHECK_PERMISSION_FAILED;
9282     }
9283     std::string jsonDataStr = abilityRequest.want.GetStringParam(WANT_PARAMS_VIEW_DATA_KEY);
9284     AbilityBase::ViewData viewData;
9285     viewData.FromJsonString(jsonDataStr.c_str());
9286     std::string callerName;
9287     int32_t uid = 0;
9288     auto callerPid = IPCSkeleton::GetCallingPid();
9289     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
9290     if (viewData.bundleName != callerName) {
9291         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not %{public}s called, no allowed", viewData.bundleName.c_str());
9292         return ERR_WRONG_INTERFACE_CALL;
9293     }
9294     return ERR_OK;
9295 }
9296 
CheckCallOtherExtensionPermission(const AbilityRequest & abilityRequest)9297 int AbilityManagerService::CheckCallOtherExtensionPermission(const AbilityRequest &abilityRequest)
9298 {
9299     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9300     if (IPCSkeleton::GetCallingUid() != BROKER_UID && AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9301         return ERR_OK;
9302     }
9303 
9304     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9305     TAG_LOGD(AAFwkTag::ABILITYMGR, "OtherExtension type: %{public}d.", static_cast<int32_t>(extensionType));
9306     if (system::GetBoolParameter(DEVELOPER_MODE_STATE, false) &&
9307         PermissionVerification::GetInstance()->VerifyShellStartExtensionType(static_cast<int32_t>(extensionType))) {
9308         return ERR_OK;
9309     }
9310     if (extensionType == AppExecFwk::ExtensionAbilityType::WINDOW) {
9311         CHECK_CALLER_IS_SYSTEM_APP;
9312         return ERR_OK;
9313     }
9314     if (extensionType == AppExecFwk::ExtensionAbilityType::ADS_SERVICE) {
9315         return ERR_OK;
9316     }
9317     if (extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_PASSWORD ||
9318         extensionType == AppExecFwk::ExtensionAbilityType::AUTO_FILL_SMART) {
9319         return CheckCallAutoFillExtensionPermission(abilityRequest);
9320     }
9321     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionType)) {
9322         return CheckUIExtensionPermission(abilityRequest);
9323     }
9324     if (extensionType == AppExecFwk::ExtensionAbilityType::VPN) {
9325         return ERR_OK;
9326     }
9327     const std::string fileAccessPermission = "ohos.permission.FILE_ACCESS_MANAGER";
9328     if (extensionType == AppExecFwk::ExtensionAbilityType::FILEACCESS_EXTENSION &&
9329         AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(fileAccessPermission)) {
9330         TAG_LOGD(AAFwkTag::ABILITYMGR, "Temporary, FILEACCESS_EXTENSION use serviceExtension start-up rule.");
9331         return CheckCallServiceExtensionPermission(abilityRequest);
9332     }
9333 
9334     TAG_LOGE(AAFwkTag::ABILITYMGR, "Not SA, can not start other Extension");
9335     return CHECK_PERMISSION_FAILED;
9336 }
9337 
CheckUIExtensionPermission(const AbilityRequest & abilityRequest)9338 int AbilityManagerService::CheckUIExtensionPermission(const AbilityRequest &abilityRequest)
9339 {
9340     if (abilityRequest.want.HasParameter(AAFwk::SCREEN_MODE_KEY)) {
9341         // If started by embedded atomic service, allow it.
9342         return ERR_OK;
9343     }
9344 
9345     auto extensionType = abilityRequest.abilityInfo.extensionAbilityType;
9346     if (AAFwk::UIExtensionUtils::IsSystemUIExtension(extensionType)) {
9347         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9348         if (callerRecord == nullptr) {
9349             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid caller.");
9350             return NO_FOUND_ABILITY_BY_CALLER;
9351         }
9352 
9353         if (!abilityRequest.appInfo.isSystemApp) {
9354             TAG_LOGE(AAFwkTag::ABILITYMGR, "Bundle %{public}s wanna to start or caller bundle %{public}s "
9355                 "isn't system app, type %{public}d not allowed.", abilityRequest.appInfo.bundleName.c_str(),
9356                 callerRecord->GetApplicationInfo().bundleName.c_str(), extensionType);
9357             return CHECK_PERMISSION_FAILED;
9358         }
9359     }
9360 
9361     if (AAFwk::UIExtensionUtils::IsSystemCallerNeeded(extensionType)) {
9362         auto callerRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9363         if (callerRecord == nullptr) {
9364             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid caller.");
9365             return NO_FOUND_ABILITY_BY_CALLER;
9366         }
9367 
9368         if (!callerRecord->GetApplicationInfo().isSystemApp
9369             && !AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
9370             TAG_LOGE(AAFwkTag::ABILITYMGR,
9371                      "Bundle %{public}s wanna to start but caller bundle %{public}s "
9372                      "isn't system app, type %{public}d not allowed.",
9373                      abilityRequest.appInfo.bundleName.c_str(), callerRecord->GetApplicationInfo().bundleName.c_str(),
9374                      extensionType);
9375             return CHECK_PERMISSION_FAILED;
9376         }
9377     }
9378 
9379     if (!CheckUIExtensionCallerIsForeground(abilityRequest)) {
9380         return CHECK_PERMISSION_FAILED;
9381     }
9382 
9383     if (!CheckUIExtensionCallerPidByHostWindowId(abilityRequest)) {
9384         return ERR_INVALID_CALLER;
9385     }
9386 
9387     return ERR_OK;
9388 }
9389 
CheckUIExtensionCallerIsForeground(const AbilityRequest & abilityRequest)9390 bool AbilityManagerService::CheckUIExtensionCallerIsForeground(const AbilityRequest &abilityRequest)
9391 {
9392     if (!CheckUIExtensionCallerIsUIAbility(abilityRequest)) {
9393         // Check only if the caller is uiability, if caller is not a uiability, don't check.
9394         return true;
9395     }
9396 
9397     bool isBackgroundCall = true;
9398     auto ret = IsCallFromBackground(abilityRequest, isBackgroundCall);
9399     if (ret != ERR_OK) {
9400         TAG_LOGE(AAFwkTag::UI_EXT, "start uea when background");
9401         return false;
9402     }
9403 
9404     if (!isBackgroundCall) {
9405         return true;
9406     }
9407 
9408     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9409     if (callerAbility != nullptr) {
9410         if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9411             auto tokenId = callerAbility->GetApplicationInfo().accessTokenId;
9412             bool isFocused = false;
9413             if (CheckUIExtensionIsFocused(tokenId, isFocused) == ERR_OK && isFocused) {
9414                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Root caller is foreground");
9415                 return true;
9416             }
9417         }
9418 
9419         if (callerAbility->IsSceneBoard()) {
9420             return true;
9421         }
9422     }
9423 
9424     if (PermissionVerification::GetInstance()->VerifyCallingPermission(
9425         PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
9426         return true;
9427     }
9428 
9429     TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller app is not foreground, can't start %{public}s",
9430         abilityRequest.want.GetElement().GetURI().c_str());
9431     return false;
9432 }
9433 
CheckUIExtensionCallerIsUIAbility(const AbilityRequest & abilityRequest)9434 bool AbilityManagerService::CheckUIExtensionCallerIsUIAbility(const AbilityRequest &abilityRequest)
9435 {
9436     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9437     if (callerAbility == nullptr) {
9438         TAG_LOGE(AAFwkTag::UI_EXT, "caller ability invalid");
9439         return false;
9440     }
9441 
9442     if (callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9443         return true;
9444     }
9445 
9446     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9447         callerAbility = GetUIExtensionRootCaller(abilityRequest.callerToken, abilityRequest.userId);
9448         if (callerAbility != nullptr && callerAbility->GetAbilityInfo().type == AppExecFwk::AbilityType::PAGE) {
9449             return true;
9450         }
9451     }
9452 
9453     return false;
9454 }
9455 
CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest & abilityRequest)9456 bool AbilityManagerService::CheckUIExtensionCallerPidByHostWindowId(const AbilityRequest &abilityRequest)
9457 {
9458 #ifdef SUPPORT_SCREEN
9459     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9460         return true;
9461     }
9462 
9463     auto callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9464     CHECK_POINTER_AND_RETURN(callerAbility, false);
9465     if (callerAbility->IsSceneBoard()) {
9466         return true;
9467     }
9468 
9469     auto sessionInfo = abilityRequest.sessionInfo;
9470     CHECK_POINTER_AND_RETURN(sessionInfo, false);
9471     auto hostWindowId = sessionInfo->hostWindowId;
9472     auto sceneSessionManager = Rosen::SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
9473     CHECK_POINTER_AND_RETURN(sceneSessionManager, false);
9474     pid_t hostPid = 0;
9475     // If host window id is scb, it will return with error.
9476     auto ret = sceneSessionManager->CheckWindowId(hostWindowId, hostPid);
9477     TAG_LOGD(AAFwkTag::UI_EXT, "get pid %{public}d by windowId %{public}d", hostPid, hostWindowId);
9478     if (hostPid != 0 && callerAbility->GetPid() == hostPid) {
9479         return true;
9480     }
9481 
9482     if (UIExtensionUtils::IsUIExtension(callerAbility->GetAbilityInfo().extensionAbilityType)) {
9483         TAG_LOGD(AAFwkTag::UI_EXT, "caller is nested uiextability");
9484         auto connectManager = GetCurrentConnectManager();
9485         CHECK_POINTER_AND_RETURN(connectManager, false);
9486         bool matched = false;
9487         std::list<sptr<IRemoteObject>> callerList;
9488         connectManager->GetUIExtensionCallerTokenList(callerAbility, callerList);
9489         for (auto &item : callerList) {
9490             auto ability = AAFwk::Token::GetAbilityRecordByToken(item);
9491             if (ability == nullptr) {
9492                 TAG_LOGW(AAFwkTag::UI_EXT, "wrong ability");
9493                 continue;
9494             }
9495 
9496             if ((hostPid != 0 && ability->GetPid() == hostPid) || ability->IsSceneBoard()) {
9497                 matched = true;
9498                 return true;
9499             }
9500         }
9501         if (!matched) {
9502             TAG_LOGE(AAFwkTag::UI_EXT, "Check nested uiextability failed");
9503         }
9504     }
9505 
9506     TAG_LOGE(AAFwkTag::UI_EXT, "Check pid by windowId %{public}d failed, got %{public}d but actual is %{public}d",
9507         hostWindowId, hostPid, callerAbility->GetPid());
9508     return false;
9509 #else
9510     return true;
9511 #endif // SUPPORT_SCREEN
9512 }
9513 
CheckCallServiceAbilityPermission(const AbilityRequest & abilityRequest)9514 int AbilityManagerService::CheckCallServiceAbilityPermission(const AbilityRequest &abilityRequest)
9515 {
9516     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9517     AAFwk::PermissionVerification::VerificationInfo verificationInfo = CreateVerificationInfo(abilityRequest);
9518     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9519         return ERR_INVALID_VALUE;
9520     }
9521 
9522     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallServiceAbilityPermission(verificationInfo);
9523     if (result != ERR_OK) {
9524         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceAbility");
9525     }
9526     return result;
9527 }
9528 
CheckCallAbilityPermission(const AbilityRequest & abilityRequest,uint32_t specifyTokenId,bool isCallByShortcut)9529 int AbilityManagerService::CheckCallAbilityPermission(const AbilityRequest &abilityRequest, uint32_t specifyTokenId,
9530     bool isCallByShortcut)
9531 {
9532     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9533     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call");
9534 
9535     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9536     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9537     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9538     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9539     verificationInfo.specifyTokenId = specifyTokenId;
9540     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9541         return ERR_INVALID_VALUE;
9542     }
9543 
9544     int result = AAFwk::PermissionVerification::GetInstance()->CheckCallAbilityPermission(
9545         verificationInfo, isCallByShortcut);
9546     if (result != ERR_OK) {
9547         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start PageAbility(FA) or Ability(Stage)");
9548     }
9549     return result;
9550 }
9551 
CheckStartByCallPermission(const AbilityRequest & abilityRequest)9552 int AbilityManagerService::CheckStartByCallPermission(const AbilityRequest &abilityRequest)
9553 {
9554     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call");
9555     // check whether the target ability is page type and not specified mode.
9556     if (abilityRequest.abilityInfo.type != AppExecFwk::AbilityType::PAGE ||
9557         abilityRequest.abilityInfo.launchMode == AppExecFwk::LaunchMode::SPECIFIED) {
9558         TAG_LOGE(AAFwkTag::ABILITYMGR, "Called ability is not common ability.");
9559         return RESOLVE_CALL_ABILITY_TYPE_ERR;
9560     }
9561 
9562     AAFwk::PermissionVerification::VerificationInfo verificationInfo;
9563     verificationInfo.accessTokenId = abilityRequest.appInfo.accessTokenId;
9564     verificationInfo.visible = abilityRequest.abilityInfo.visible;
9565     verificationInfo.withContinuousTask = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
9566     if (IsCallFromBackground(abilityRequest, verificationInfo.isBackgroundCall) != ERR_OK) {
9567         return ERR_INVALID_VALUE;
9568     }
9569 
9570     if (AAFwk::PermissionVerification::GetInstance()->CheckStartByCallPermission(verificationInfo) != ERR_OK) {
9571         TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to StartAbilityByCall.");
9572         return RESOLVE_CALL_NO_PERMISSIONS;
9573     }
9574     TAG_LOGD(AAFwkTag::ABILITYMGR, "The caller has permission to resolve the call proxy of common ability.");
9575     return ERR_OK;
9576 }
9577 
IsCallFromBackground(const AbilityRequest & abilityRequest,bool & isBackgroundCall,bool isData)9578 int AbilityManagerService::IsCallFromBackground(const AbilityRequest &abilityRequest, bool &isBackgroundCall,
9579     bool isData)
9580 {
9581     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9582     if (!isData && AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
9583         isBackgroundCall = true;
9584         return ERR_OK;
9585     }
9586 
9587     if (!isData && (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
9588         AbilityUtil::IsStartFreeInstall(abilityRequest.want))) {
9589         isBackgroundCall = false;
9590         return ERR_OK;
9591     }
9592 
9593     AppExecFwk::RunningProcessInfo processInfo;
9594     std::shared_ptr<AbilityRecord> callerAbility = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
9595     if (callerAbility && callerAbility->GetAbilityInfo().bundleName == BUNDLE_NAME_DIALOG) {
9596         callerAbility = callerAbility->GetCallerRecord();
9597     }
9598     if (callerAbility) {
9599         if (callerAbility->IsForeground() || callerAbility->GetAbilityForegroundingFlag()) {
9600             isBackgroundCall = false;
9601             return ERR_OK;
9602         }
9603         // CallerAbility is not foreground, so check process state
9604         DelayedSingleton<AppScheduler>::GetInstance()->
9605             GetRunningProcessInfoByToken(callerAbility->GetToken(), processInfo);
9606         if (IsDelegatorCall(processInfo, abilityRequest)) {
9607             TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
9608             isBackgroundCall = false;
9609             return ERR_OK;
9610         }
9611         auto abilityState = callerAbility->GetAbilityState();
9612         if (abilityState == AbilityState::BACKGROUND || abilityState == AbilityState::BACKGROUNDING ||
9613             // If uiability or uiextensionability ability state is foreground when terminate,
9614             // it will move to background firstly. So if startAbility in onBackground() lifecycle,
9615             // the actual ability state may be had changed to terminating from background or backgrounding.
9616             abilityState == AbilityState::TERMINATING) {
9617             return ERR_OK;
9618         }
9619     } else {
9620         auto callerPid = IPCSkeleton::GetCallingPid();
9621         DelayedSingleton<AppScheduler>::GetInstance()->GetRunningProcessInfoByPid(callerPid, processInfo);
9622         if (processInfo.processName_.empty()) {
9623             TAG_LOGD(AAFwkTag::ABILITYMGR, "Can not find caller application by callerPid: %{private}d.", callerPid);
9624             if (AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
9625                 PermissionConstants::PERMISSION_START_ABILITIES_FROM_BACKGROUND)) {
9626                 TAG_LOGD(AAFwkTag::ABILITYMGR, "Caller has PERMISSION_START_ABILITIES_FROM_BACKGROUND, PASS.");
9627                 isBackgroundCall = false;
9628                 return ERR_OK;
9629             }
9630             TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller does not have PERMISSION_START_ABILITIES_FROM_BACKGROUND, REJECT.");
9631             return ERR_INVALID_VALUE;
9632         }
9633     }
9634     return SetBackgroundCall(processInfo, abilityRequest, isBackgroundCall);
9635 }
9636 
SetBackgroundCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest,bool & isBackgroundCall) const9637 int32_t AbilityManagerService::SetBackgroundCall(const AppExecFwk::RunningProcessInfo &processInfo,
9638     const AbilityRequest &abilityRequest, bool &isBackgroundCall) const
9639 {
9640     if (IsDelegatorCall(processInfo, abilityRequest)) {
9641         TAG_LOGD(AAFwkTag::ABILITYMGR, "The call is from AbilityDelegator, allow background-call.");
9642         isBackgroundCall = false;
9643         return ERR_OK;
9644     }
9645 
9646     if (backgroundJudgeFlag_) {
9647         isBackgroundCall = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND &&
9648             !processInfo.isFocused && !processInfo.isAbilityForegrounding;
9649     } else {
9650         isBackgroundCall = !processInfo.isFocused;
9651         if (!processInfo.isFocused && processInfo.state_ == AppExecFwk::AppProcessState::APP_STATE_FOREGROUND) {
9652             // Allow background startup within 1 second after application startup if state is FOREGROUND
9653             int64_t aliveTime = AbilityUtil::SystemTimeMillis() - processInfo.startTimeMillis_;
9654             isBackgroundCall = aliveTime > APP_ALIVE_TIME_MS;
9655             TAG_LOGD(AAFwkTag::ABILITYMGR, "Process %{public}s is alive %{public}s ms.",
9656                 processInfo.processName_.c_str(), std::to_string(aliveTime).c_str());
9657         }
9658     }
9659     TAG_LOGD(AAFwkTag::ABILITYMGR,
9660         "backgroundJudgeFlag: %{public}d, isBackgroundCall: %{public}d, callerAppState: %{public}d.",
9661         static_cast<int32_t>(backgroundJudgeFlag_),
9662         static_cast<int32_t>(isBackgroundCall),
9663         static_cast<int32_t>(processInfo.state_));
9664 
9665     return ERR_OK;
9666 }
9667 
IsTargetPermission(const Want & want) const9668 bool AbilityManagerService::IsTargetPermission(const Want &want) const
9669 {
9670     if (want.GetElement().GetBundleName() == PERMISSIONMGR_BUNDLE_NAME &&
9671         want.GetElement().GetAbilityName() == PERMISSIONMGR_ABILITY_NAME) {
9672         return true;
9673     }
9674 
9675     return false;
9676 }
9677 
IsDelegatorCall(const AppExecFwk::RunningProcessInfo & processInfo,const AbilityRequest & abilityRequest) const9678 inline bool AbilityManagerService::IsDelegatorCall(
9679     const AppExecFwk::RunningProcessInfo &processInfo, const AbilityRequest &abilityRequest) const
9680 {
9681     /*  To make sure the AbilityDelegator is not counterfeited
9682      *   1. The caller-process must be test-process
9683      *   2. The callerToken must be nullptr
9684      */
9685     if (processInfo.isTestProcess &&
9686         !abilityRequest.callerToken && abilityRequest.want.GetBoolParam(IS_DELEGATOR_CALL, false)) {
9687         return true;
9688     }
9689     return false;
9690 }
9691 
CheckNewRuleSwitchState(const std::string & param)9692 bool AbilityManagerService::CheckNewRuleSwitchState(const std::string &param)
9693 {
9694     char value[NEW_RULE_VALUE_SIZE] = "false";
9695     int retSysParam = GetParameter(param.c_str(), "false", value, NEW_RULE_VALUE_SIZE);
9696     TAG_LOGI(AAFwkTag::ABILITYMGR, "CheckNewRuleSwitchState, %{public}s value is %{public}s.", param.c_str(), value);
9697     if (retSysParam > 0 && !std::strcmp(value, "true")) {
9698         return true;
9699     }
9700     return false;
9701 }
9702 
GetStartUpNewRuleFlag() const9703 bool AbilityManagerService::GetStartUpNewRuleFlag() const
9704 {
9705     return startUpNewRule_;
9706 }
9707 
CallRequestDone(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callStub)9708 void AbilityManagerService::CallRequestDone(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callStub)
9709 {
9710     {
9711         std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
9712         callStubTokenMap_[callStub] = token;
9713     }
9714     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9715     CHECK_POINTER(abilityRecord);
9716     if (!JudgeSelfCalled(abilityRecord)) {
9717         return;
9718     }
9719 
9720     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9721         auto uiAbilityManager = GetCurrentUIAbilityManager();
9722         CHECK_POINTER(uiAbilityManager);
9723         uiAbilityManager->CallRequestDone(abilityRecord, callStub);
9724         return;
9725     }
9726 
9727     auto missionListManager = GetCurrentMissionListManager();
9728     CHECK_POINTER(missionListManager);
9729     missionListManager->CallRequestDone(abilityRecord, callStub);
9730 }
9731 
GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> & callStub,sptr<IRemoteObject> & token)9732 void AbilityManagerService::GetAbilityTokenByCalleeObj(const sptr<IRemoteObject> &callStub, sptr<IRemoteObject> &token)
9733 {
9734     std::lock_guard<ffrt::mutex> autoLock(abilityTokenLock_);
9735     auto it = callStubTokenMap_.find(callStub);
9736     if (it == callStubTokenMap_.end()) {
9737         token = nullptr;
9738         return;
9739     }
9740     token = callStubTokenMap_[callStub];
9741 }
9742 
AddStartControlParam(Want & want,const sptr<IRemoteObject> & callerToken)9743 int AbilityManagerService::AddStartControlParam(Want &want, const sptr<IRemoteObject> &callerToken)
9744 {
9745     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9746     if (AAFwk::PermissionVerification::GetInstance()->IsSACall() ||
9747         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
9748         return ERR_OK;
9749     }
9750     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
9751     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
9752     int32_t apiVersion = abilityRecord->GetApplicationInfo().apiTargetVersion;
9753     want.SetParam(DMS_API_VERSION, apiVersion);
9754     bool isCallerBackground = true;
9755     AppExecFwk::RunningProcessInfo processInfo;
9756     DelayedSingleton<AppScheduler>::GetInstance()->
9757         GetRunningProcessInfoByToken(abilityRecord->GetToken(), processInfo);
9758     if (backgroundJudgeFlag_) {
9759         isCallerBackground = processInfo.state_ != AppExecFwk::AppProcessState::APP_STATE_FOREGROUND;
9760     } else {
9761         isCallerBackground = !processInfo.isFocused;
9762     }
9763     want.SetParam(DMS_IS_CALLER_BACKGROUND, isCallerBackground);
9764     return ERR_OK;
9765 }
9766 
9767 #ifdef WITH_DLP
CheckDlpForExtension(const Want & want,const sptr<IRemoteObject> & callerToken,int32_t userId,EventInfo & eventInfo,const EventName & eventName)9768 int AbilityManagerService::CheckDlpForExtension(
9769     const Want &want, const sptr<IRemoteObject> &callerToken,
9770     int32_t userId, EventInfo &eventInfo, const EventName &eventName)
9771 {
9772     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9773     // check if form frs
9774     auto callingUid = IPCSkeleton::GetCallingUid();
9775     std::string bundleName = want.GetBundle();
9776     if (callingUid == FOUNDATION_UID && FRS_BUNDLE_NAME == bundleName) {
9777         return ERR_OK;
9778     }
9779 
9780     if (!DlpUtils::OtherAppsAccessDlpCheck(callerToken, want) ||
9781         VerifyAccountPermission(userId) == CHECK_PERMISSION_FAILED ||
9782         !DlpUtils::DlpAccessOtherAppsCheck(callerToken, want)) {
9783         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verify failed");
9784         eventInfo.errCode = CHECK_PERMISSION_FAILED;
9785         EventReport::SendExtensionEvent(eventName, HiSysEventType::FAULT, eventInfo);
9786         return CHECK_PERMISSION_FAILED;
9787     }
9788     return ERR_OK;
9789 }
9790 #endif // WITH_DLP
9791 
JudgeSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)9792 bool AbilityManagerService::JudgeSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
9793 {
9794     if (IPCSkeleton::GetCallingPid() == getprocpid()) {
9795         return true;
9796     }
9797 
9798     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9799     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9800     if (callingTokenId != tokenID) {
9801         TAG_LOGE(AAFwkTag::ABILITYMGR, "Is not self, not enabled");
9802         return false;
9803     }
9804 
9805     return true;
9806 }
9807 
IsAppSelfCalled(const std::shared_ptr<AbilityRecord> & abilityRecord)9808 bool AbilityManagerService::IsAppSelfCalled(const std::shared_ptr<AbilityRecord> &abilityRecord)
9809 {
9810     CHECK_POINTER_RETURN_BOOL(abilityRecord);
9811     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
9812     auto tokenID = abilityRecord->GetApplicationInfo().accessTokenId;
9813     if (callingTokenId != tokenID) {
9814         TAG_LOGE(AAFwkTag::ABILITYMGR, "not app self called");
9815         return false;
9816     }
9817     return true;
9818 }
9819 
GetFocusAbility()9820 std::shared_ptr<AbilityRecord> AbilityManagerService::GetFocusAbility()
9821 {
9822 #ifdef SUPPORT_GRAPHICS
9823     sptr<IRemoteObject> token;
9824     if (!wmsHandler_) {
9825         TAG_LOGE(AAFwkTag::ABILITYMGR, "wmsHandler_ is nullptr.");
9826         return nullptr;
9827     }
9828 
9829     wmsHandler_->GetFocusWindow(token);
9830     if (!token) {
9831         TAG_LOGE(AAFwkTag::ABILITYMGR, "token is nullptr");
9832         return nullptr;
9833     }
9834 
9835     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9836     if (!abilityRecord) {
9837         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is nullptr.");
9838     }
9839     return abilityRecord;
9840 #endif
9841 
9842     return nullptr;
9843 }
9844 
CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId,bool & isFocused)9845 int AbilityManagerService::CheckUIExtensionIsFocused(uint32_t uiExtensionTokenId, bool& isFocused)
9846 {
9847     sptr<IRemoteObject> token;
9848     auto ret = GetTopAbility(token);
9849     if (ret != ERR_OK) {
9850         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetTopAbility failed");
9851         return ret;
9852     }
9853 
9854     auto topAbility = Token::GetAbilityRecordByToken(token);
9855     if (topAbility != nullptr) {
9856         TAG_LOGD(AAFwkTag::ABILITYMGR, "top ability: %{public}s, pid: %{public}d, tokenId: %{public}d",
9857             topAbility->GetWant().GetElement().GetURI().c_str(), topAbility->GetPid(),
9858             topAbility->GetApplicationInfo().accessTokenId);
9859     }
9860 
9861     bool focused = false;
9862     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
9863     auto connectManager = GetConnectManagerByUserId(userId);
9864     if (connectManager) {
9865         focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
9866             || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
9867     } else {
9868         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", userId);
9869     }
9870     if (!focused && userId != U0_USER_ID) {
9871         TAG_LOGD(AAFwkTag::ABILITYMGR, "Check connectManager in user0");
9872         connectManager = GetConnectManagerByUserId(U0_USER_ID);
9873         if (connectManager) {
9874             focused = connectManager->IsUIExtensionFocused(uiExtensionTokenId, token)
9875                 || connectManager->IsWindowExtensionFocused(uiExtensionTokenId, token);
9876         } else {
9877             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: 0");
9878         }
9879     }
9880     isFocused = focused;
9881     TAG_LOGD(AAFwkTag::ABILITYMGR, "isFocused: %{public}d", isFocused);
9882     return ERR_OK;
9883 }
9884 
AddFreeInstallObserver(const sptr<IRemoteObject> & callerToken,const sptr<AbilityRuntime::IFreeInstallObserver> & observer)9885 int AbilityManagerService::AddFreeInstallObserver(const sptr<IRemoteObject> &callerToken,
9886     const sptr<AbilityRuntime::IFreeInstallObserver> &observer)
9887 {
9888     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
9889     if (freeInstallManager_ == nullptr) {
9890         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
9891         return ERR_INVALID_VALUE;
9892     }
9893     return freeInstallManager_->AddFreeInstallObserver(callerToken, observer);
9894 }
9895 
IsValidMissionIds(const std::vector<int32_t> & missionIds,std::vector<MissionValidResult> & results)9896 int32_t AbilityManagerService::IsValidMissionIds(
9897     const std::vector<int32_t> &missionIds, std::vector<MissionValidResult> &results)
9898 {
9899     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
9900     auto missionlistMgr = GetMissionListManagerByUserId(userId);
9901     if (missionlistMgr == nullptr) {
9902         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionlistMgr is nullptr.");
9903         return ERR_INVALID_VALUE;
9904     }
9905 
9906     return missionlistMgr->IsValidMissionIds(missionIds, results);
9907 }
9908 
VerifyPermission(const std::string & permission,int pid,int uid)9909 int AbilityManagerService::VerifyPermission(const std::string &permission, int pid, int uid)
9910 {
9911     TAG_LOGI(AAFwkTag::ABILITYMGR, "permission=%{public}s, pid=%{public}d, uid=%{public}d",
9912         permission.c_str(),
9913         pid,
9914         uid);
9915     if (permission.empty()) {
9916         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission permission invalid");
9917         return CHECK_PERMISSION_FAILED;
9918     }
9919 
9920     auto bms = GetBundleManager();
9921     CHECK_POINTER_AND_RETURN(bms, ERR_INVALID_VALUE);
9922 
9923     std::string bundleName;
9924     if (IN_PROCESS_CALL(bms->GetNameForUid(uid, bundleName)) != ERR_OK) {
9925         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get bundle name by uid");
9926         return CHECK_PERMISSION_FAILED;
9927     }
9928 
9929     int account = -1;
9930     DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->GetOsAccountLocalIdFromUid(uid, account);
9931     AppExecFwk::ApplicationInfo appInfo;
9932     if (!IN_PROCESS_CALL(bms->GetApplicationInfo(bundleName, AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT,
9933         account, appInfo))) {
9934         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission failed to get application info");
9935         return CHECK_PERMISSION_FAILED;
9936     }
9937 
9938     int32_t ret = Security::AccessToken::AccessTokenKit::VerifyAccessToken(appInfo.accessTokenId, permission, false);
9939     if (ret != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
9940         TAG_LOGE(AAFwkTag::ABILITYMGR, "VerifyPermission %{public}d: PERMISSION_DENIED", appInfo.accessTokenId);
9941         return CHECK_PERMISSION_FAILED;
9942     }
9943 
9944     return ERR_OK;
9945 }
9946 
AcquireShareData(const int32_t & missionId,const sptr<IAcquireShareDataCallback> & shareData)9947 int32_t AbilityManagerService::AcquireShareData(
9948     const int32_t &missionId, const sptr<IAcquireShareDataCallback> &shareData)
9949 {
9950     TAG_LOGD(AAFwkTag::ABILITYMGR, "missionId is %{public}d.", missionId);
9951     CHECK_CALLER_IS_SYSTEM_APP;
9952     std::shared_ptr<AbilityRecord> abilityRecord = nullptr;
9953     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
9954         auto uiAbilityManager = GetCurrentUIAbilityManager();
9955         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
9956         abilityRecord = uiAbilityManager->GetAbilityRecordsById(missionId);
9957     } else {
9958         auto missionListManager = GetCurrentMissionListManager();
9959         CHECK_POINTER_AND_RETURN(missionListManager, ERR_INVALID_VALUE);
9960         abilityRecord = missionListManager->GetAbilityRecordByMissionId(missionId);
9961     }
9962     if (!abilityRecord) {
9963         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityRecord is null.");
9964         return ERR_INVALID_VALUE;
9965     }
9966     std::lock_guard<ffrt::mutex> guard(iAcquireShareDataMapLock_);
9967     uniqueId_ = (uniqueId_ == INT_MAX) ? 0 : (uniqueId_ + 1);
9968     std::pair<int64_t, const sptr<IAcquireShareDataCallback>> shareDataPair =
9969         std::make_pair(abilityRecord->GetAbilityRecordId(), shareData);
9970     iAcquireShareDataMap_.emplace(uniqueId_, shareDataPair);
9971     abilityRecord->ShareData(uniqueId_);
9972     return ERR_OK;
9973 }
9974 
ShareDataDone(const sptr<IRemoteObject> & token,const int32_t & resultCode,const int32_t & uniqueId,WantParams & wantParam)9975 int32_t AbilityManagerService::ShareDataDone(
9976     const sptr<IRemoteObject> &token, const int32_t &resultCode, const int32_t &uniqueId, WantParams &wantParam)
9977 {
9978     TAG_LOGI(AAFwkTag::ABILITYMGR, "resultCode:%{public}d, uniqueId:%{public}d.", resultCode, uniqueId);
9979     if (!VerificationAllToken(token)) {
9980         return ERR_INVALID_VALUE;
9981     }
9982     auto abilityRecord = Token::GetAbilityRecordByToken(token);
9983     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "ability record is nullptr.");
9984     if (!JudgeSelfCalled(abilityRecord)) {
9985         return CHECK_PERMISSION_FAILED;
9986     }
9987     CHECK_POINTER_AND_RETURN_LOG(eventHandler_, ERR_INVALID_VALUE, "fail to get abilityEventHandler.");
9988     eventHandler_->RemoveEvent(SHAREDATA_TIMEOUT_MSG, uniqueId);
9989     return GetShareDataPairAndReturnData(abilityRecord, resultCode, uniqueId, wantParam);
9990 }
9991 
NotifySaveAsResult(const Want & want,int resultCode,int requestCode)9992 int32_t AbilityManagerService::NotifySaveAsResult(const Want &want, int resultCode, int requestCode)
9993 {
9994     TAG_LOGD(AAFwkTag::ABILITYMGR, "requestCode is %{public}d.", requestCode);
9995     CHECK_CALLER_IS_SYSTEM_APP;
9996 #ifdef WITH_DLP
9997     //caller check
9998     if (!DlpUtils::CheckCallerIsDlpManager(GetBundleManager())) {
9999         TAG_LOGW(AAFwkTag::ABILITYMGR, "caller check failed");
10000         return CHECK_PERMISSION_FAILED;
10001     }
10002 #endif // WITH_DLP
10003 
10004     for (const auto &item : startAbilityChain_) {
10005         if (item.second->GetHandlerName() == StartAbilitySandboxSavefile::handlerName_) {
10006             auto savefileHandler = (StartAbilitySandboxSavefile*)(item.second.get());
10007             savefileHandler->HandleResult(want, resultCode, requestCode);
10008             break;
10009         }
10010     }
10011     return ERR_OK;
10012 }
10013 
SetRootSceneSession(const sptr<IRemoteObject> & rootSceneSession)10014 void AbilityManagerService::SetRootSceneSession(const sptr<IRemoteObject> &rootSceneSession)
10015 {
10016     if (!IsCallerSceneBoard()) {
10017         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10018         return;
10019     }
10020     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10021     CHECK_POINTER(uiAbilityManager);
10022     uiAbilityManager->SetRootSceneSession(rootSceneSession);
10023 }
10024 
CallUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isColdStart)10025 void AbilityManagerService::CallUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isColdStart)
10026 {
10027     if (!IsCallerSceneBoard()) {
10028         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10029         return;
10030     }
10031     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10032     CHECK_POINTER(uiAbilityManager);
10033     uiAbilityManager->CallUIAbilityBySCB(sessionInfo, isColdStart);
10034 }
10035 
SetSessionManagerService(const sptr<IRemoteObject> & sessionManagerService)10036 int32_t AbilityManagerService::SetSessionManagerService(const sptr<IRemoteObject> &sessionManagerService)
10037 {
10038     if (!IsCallerSceneBoard()) {
10039         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10040         return ERR_WRONG_INTERFACE_CALL;
10041     }
10042 
10043     TAG_LOGI(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10044     auto ret = Rosen::MockSessionManagerService::GetInstance().SetSessionManagerService(sessionManagerService);
10045     if (ret) {
10046         TAG_LOGD(AAFwkTag::ABILITYMGR, "Call SetSessionManagerService of WMS.");
10047         return ERR_OK;
10048     }
10049     TAG_LOGE(AAFwkTag::ABILITYMGR, "SMS SetSessionManagerService return false.");
10050     return ERR_OK;
10051 }
10052 
CheckPrepareTerminateEnable()10053 bool AbilityManagerService::CheckPrepareTerminateEnable()
10054 {
10055     if (!isPrepareTerminateEnable_) {
10056         TAG_LOGD(AAFwkTag::ABILITYMGR, "Only support PC.");
10057         return false;
10058     }
10059     if (!AAFwk::PermissionVerification::GetInstance()->VerifyPrepareTerminatePermission()) {
10060         TAG_LOGD(AAFwkTag::ABILITYMGR, "failed, please apply permission ohos.permission.PREPARE_APP_TERMINATE");
10061         return false;
10062     }
10063     return true;
10064 }
10065 
StartSpecifiedAbilityBySCB(const Want & want)10066 void AbilityManagerService::StartSpecifiedAbilityBySCB(const Want &want)
10067 {
10068     if (!IsCallerSceneBoard()) {
10069         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10070         return;
10071     }
10072     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10073     CHECK_POINTER(uiAbilityManager);
10074     uiAbilityManager->StartSpecifiedAbilityBySCB(want);
10075 }
10076 
RegisterIAbilityManagerCollaborator(int32_t type,const sptr<IAbilityManagerCollaborator> & impl)10077 int32_t AbilityManagerService::RegisterIAbilityManagerCollaborator(
10078     int32_t type, const sptr<IAbilityManagerCollaborator> &impl)
10079 {
10080     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10081     auto callingUid = IPCSkeleton::GetCallingUid();
10082     if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
10083         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
10084         return CHECK_PERMISSION_FAILED;
10085     }
10086     if (!CheckCollaboratorType(type)) {
10087         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator register failed, invalid type.");
10088         return ERR_INVALID_VALUE;
10089     }
10090     {
10091         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10092         collaboratorMap_[type] = impl;
10093     }
10094     return ERR_OK;
10095 }
10096 
UnregisterIAbilityManagerCollaborator(int32_t type)10097 int32_t AbilityManagerService::UnregisterIAbilityManagerCollaborator(int32_t type)
10098 {
10099     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
10100     auto callingUid = IPCSkeleton::GetCallingUid();
10101     if (!isSaCall || (callingUid != BROKER_UID && callingUid != BROKER_RESERVE_UID)) {
10102         TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
10103         return CHECK_PERMISSION_FAILED;
10104     }
10105     if (!CheckCollaboratorType(type)) {
10106         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator unregister failed, invalid type.");
10107         return ERR_INVALID_VALUE;
10108     }
10109     {
10110         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10111         collaboratorMap_.erase(type);
10112     }
10113     return ERR_OK;
10114 }
10115 
GetCollaborator(int32_t type)10116 sptr<IAbilityManagerCollaborator> AbilityManagerService::GetCollaborator(int32_t type)
10117 {
10118     if (!CheckCollaboratorType(type)) {
10119         return nullptr;
10120     }
10121     {
10122         std::lock_guard<ffrt::mutex> autoLock(collaboratorMapLock_);
10123         auto it = collaboratorMap_.find(type);
10124         if (it != collaboratorMap_.end()) {
10125             return it->second;
10126         }
10127     }
10128     return nullptr;
10129 }
10130 
CheckCollaboratorType(int32_t type)10131 bool AbilityManagerService::CheckCollaboratorType(int32_t type)
10132 {
10133     if (type != CollaboratorType::RESERVE_TYPE && type != CollaboratorType::OTHERS_TYPE) {
10134         return false;
10135     }
10136     return true;
10137 }
10138 
GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> & sessionInfo,std::shared_ptr<AbilityConnectManager> & connectManager,std::shared_ptr<AbilityRecord> & targetAbility)10139 void AbilityManagerService::GetConnectManagerAndUIExtensionBySessionInfo(const sptr<SessionInfo> &sessionInfo,
10140     std::shared_ptr<AbilityConnectManager> &connectManager, std::shared_ptr<AbilityRecord> &targetAbility)
10141 {
10142     targetAbility = nullptr;
10143     int32_t userId = GetValidUserId(DEFAULT_INVAL_VALUE);
10144     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId=%{public}d", userId);
10145     connectManager = GetConnectManagerByUserId(userId);
10146     if (connectManager) {
10147         targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
10148     } else {
10149         TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: %{public}d", userId);
10150     }
10151     if (targetAbility == nullptr && userId != U0_USER_ID) {
10152         TAG_LOGD(AAFwkTag::ABILITYMGR, "try to find UIExtension in user0");
10153         connectManager = GetConnectManagerByUserId(U0_USER_ID);
10154         if (connectManager) {
10155             targetAbility = connectManager->GetUIExtensioBySessionInfo(sessionInfo);
10156         } else {
10157             TAG_LOGW(AAFwkTag::ABILITYMGR, "connectManager is nullptr, userId: 0");
10158         }
10159     }
10160 }
10161 
RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)10162 int32_t AbilityManagerService::RegisterStatusBarDelegate(sptr<AbilityRuntime::IStatusBarDelegate> delegate)
10163 {
10164     if (!IsCallerSceneBoard()) {
10165         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10166         return ERR_WRONG_INTERFACE_CALL;
10167     }
10168     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10169     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10170     return uiAbilityManager->RegisterStatusBarDelegate(delegate);
10171 }
10172 
KillProcessWithPrepareTerminate(const std::vector<int32_t> & pids)10173 int32_t AbilityManagerService::KillProcessWithPrepareTerminate(const std::vector<int32_t>& pids)
10174 {
10175     if (!IsCallerSceneBoard()) {
10176         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10177         return ERR_WRONG_INTERFACE_CALL;
10178     }
10179     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10180     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10181     return uiAbilityManager->TryPrepareTerminateByPids(pids);
10182 }
10183 
RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10184 int32_t AbilityManagerService::RegisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10185 {
10186     if (abilityAutoStartupService_ == nullptr) {
10187         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10188         return ERR_NO_INIT;
10189     }
10190     return abilityAutoStartupService_->RegisterAutoStartupSystemCallback(callback);
10191 }
10192 
UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> & callback)10193 int32_t AbilityManagerService::UnregisterAutoStartupSystemCallback(const sptr<IRemoteObject> &callback)
10194 {
10195     if (abilityAutoStartupService_ == nullptr) {
10196         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10197         return ERR_NO_INIT;
10198     }
10199     return abilityAutoStartupService_->UnregisterAutoStartupSystemCallback(callback);
10200 }
10201 
SetApplicationAutoStartup(const AutoStartupInfo & info)10202 int32_t AbilityManagerService::SetApplicationAutoStartup(const AutoStartupInfo &info)
10203 {
10204     if (abilityAutoStartupService_ == nullptr) {
10205         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10206         return ERR_NO_INIT;
10207     }
10208     return abilityAutoStartupService_->SetApplicationAutoStartup(info);
10209 }
10210 
CancelApplicationAutoStartup(const AutoStartupInfo & info)10211 int32_t AbilityManagerService::CancelApplicationAutoStartup(const AutoStartupInfo &info)
10212 {
10213     if (abilityAutoStartupService_ == nullptr) {
10214         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10215         return ERR_NO_INIT;
10216     }
10217     return abilityAutoStartupService_->CancelApplicationAutoStartup(info);
10218 }
10219 
QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> & infoList)10220 int32_t AbilityManagerService::QueryAllAutoStartupApplications(std::vector<AutoStartupInfo> &infoList)
10221 {
10222     if (abilityAutoStartupService_ == nullptr) {
10223         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10224         return ERR_NO_INIT;
10225     }
10226     return abilityAutoStartupService_->QueryAllAutoStartupApplications(infoList, GetUserId());
10227 }
10228 
PrepareTerminateAbilityBySCB(const sptr<SessionInfo> & sessionInfo,bool & isTerminate)10229 int AbilityManagerService::PrepareTerminateAbilityBySCB(const sptr<SessionInfo> &sessionInfo, bool &isTerminate)
10230 {
10231     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10232     TAG_LOGD(AAFwkTag::ABILITYMGR, "Call.");
10233     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
10234         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr");
10235         return ERR_INVALID_VALUE;
10236     }
10237 
10238     if (!IsCallerSceneBoard()) {
10239         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10240         return ERR_WRONG_INTERFACE_CALL;
10241     }
10242 
10243     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10244     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10245     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
10246     isTerminate = uiAbilityManager->PrepareTerminateAbility(abilityRecord);
10247 
10248     return ERR_OK;
10249 }
10250 
RegisterSessionHandler(const sptr<IRemoteObject> & object)10251 int AbilityManagerService::RegisterSessionHandler(const sptr<IRemoteObject> &object)
10252 {
10253     TAG_LOGI(AAFwkTag::ABILITYMGR, "call");
10254     if (!IsCallerSceneBoard()) {
10255         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10256         return ERR_WRONG_INTERFACE_CALL;
10257     }
10258     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10259     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10260     sptr<ISessionHandler> handler = iface_cast<ISessionHandler>(object);
10261     uiAbilityManager->SetSessionHandler(handler);
10262     return ERR_OK;
10263 }
10264 
CheckUserIdActive(int32_t userId)10265 bool AbilityManagerService::CheckUserIdActive(int32_t userId)
10266 {
10267     std::vector<int32_t> osActiveAccountIds;
10268     auto ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
10269         QueryActiveOsAccountIds(osActiveAccountIds);
10270     if (ret != ERR_OK) {
10271         TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryActiveOsAccountIds failed");
10272         return false;
10273     }
10274     if (osActiveAccountIds.empty()) {
10275         TAG_LOGE(AAFwkTag::ABILITYMGR, "QueryActiveOsAccountIds empty");
10276         return false;
10277     }
10278     auto iter = std::find(osActiveAccountIds.begin(), osActiveAccountIds.end(), userId);
10279     if (iter == osActiveAccountIds.end()) {
10280         return false;
10281     }
10282     return true;
10283 }
10284 
CheckProcessOptions(const Want & want,const StartOptions & startOptions,int32_t userId)10285 int32_t AbilityManagerService::CheckProcessOptions(const Want &want, const StartOptions &startOptions, int32_t userId)
10286 {
10287     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10288     if (startOptions.processOptions == nullptr ||
10289         !ProcessOptions::IsValidProcessMode(startOptions.processOptions->processMode)) {
10290         return ERR_OK;
10291     }
10292 
10293     TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability with process options.");
10294     bool isEnable = AppUtils::GetInstance().IsStartOptionsWithProcessOptions();
10295     if (!Rosen::SceneBoardJudgement::IsSceneBoardEnabled() || !isEnable) {
10296         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not support process options.");
10297         return ERR_CAPABILITY_NOT_SUPPORT;
10298     }
10299 
10300     auto element = want.GetElement();
10301     if (element.GetAbilityName().empty() || want.GetAction().compare(ACTION_CHOOSE) == 0) {
10302         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not allow implicit start.");
10303         return ERR_NOT_ALLOW_IMPLICIT_START;
10304     }
10305 
10306     int32_t appIndex = 0;
10307     appIndex = !AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex) ? 0 : appIndex;
10308     if (!CheckCallingTokenId(element.GetBundleName(), userId, appIndex)) {
10309         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not self application.");
10310         return ERR_NOT_SELF_APPLICATION;
10311     }
10312 
10313     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10314     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10315 
10316     if (ProcessOptions::IsAttachToStatusBarMode(startOptions.processOptions->processMode) &&
10317         !uiAbilityManager->IsCallerInStatusBar()) {
10318         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller is not in status bar in attch to status bar mode.");
10319         return ERR_START_OPTIONS_CHECK_FAILED;
10320     }
10321 
10322     auto abilityRecords = uiAbilityManager->GetAbilityRecordsByName(element);
10323     if (!abilityRecords.empty() && abilityRecords[0] &&
10324         abilityRecords[0]->GetAbilityInfo().launchMode != AppExecFwk::LaunchMode::STANDARD) {
10325         TAG_LOGE(AAFwkTag::ABILITYMGR, "If it is not in STANDARD mode, repeated starts are not allowed");
10326         return ERR_ABILITY_ALREADY_RUNNING;
10327     }
10328 
10329     return ERR_OK;
10330 }
10331 
RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10332 int32_t AbilityManagerService::RegisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10333 {
10334     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10335     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10336         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10337         return CHECK_PERMISSION_FAILED;
10338     }
10339     return DelayedSingleton<AppScheduler>::GetInstance()->RegisterAppDebugListener(listener);
10340 }
10341 
UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)10342 int32_t AbilityManagerService::UnregisterAppDebugListener(sptr<AppExecFwk::IAppDebugListener> listener)
10343 {
10344     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10345     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10346         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10347         return CHECK_PERMISSION_FAILED;
10348     }
10349     return DelayedSingleton<AppScheduler>::GetInstance()->UnregisterAppDebugListener(listener);
10350 }
10351 
ConnectInitAbilityDebugDeal()10352 std::shared_ptr<AbilityDebugDeal> AbilityManagerService::ConnectInitAbilityDebugDeal()
10353 {
10354     if (abilityDebugDeal_ != nullptr) {
10355         return abilityDebugDeal_;
10356     }
10357 
10358     std::unique_lock<ffrt::mutex> lock(abilityDebugDealLock_);
10359     if (abilityDebugDeal_ != nullptr) {
10360         return abilityDebugDeal_;
10361     }
10362 
10363     TAG_LOGD(AAFwkTag::ABILITYMGR, "Creat ability debug deal object.");
10364     abilityDebugDeal_ = std::make_shared<AbilityDebugDeal>();
10365     if (abilityDebugDeal_ == nullptr) {
10366         TAG_LOGE(AAFwkTag::ABILITYMGR, "Creat ability debug deal object failed.");
10367         return nullptr;
10368     }
10369 
10370     abilityDebugDeal_->RegisterAbilityDebugResponse();
10371     return abilityDebugDeal_;
10372 }
10373 
AttachAppDebug(const std::string & bundleName)10374 int32_t AbilityManagerService::AttachAppDebug(const std::string &bundleName)
10375 {
10376     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10377     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10378         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
10379         return ERR_NOT_DEVELOPER_MODE;
10380     }
10381 
10382     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10383         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10384         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10385         return CHECK_PERMISSION_FAILED;
10386     }
10387 
10388     ConnectInitAbilityDebugDeal();
10389     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->AttachAppDebug(bundleName));
10390 }
10391 
DetachAppDebug(const std::string & bundleName)10392 int32_t AbilityManagerService::DetachAppDebug(const std::string &bundleName)
10393 {
10394     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10395     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10396         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
10397         return ERR_NOT_DEVELOPER_MODE;
10398     }
10399 
10400     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
10401         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
10402         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10403         return CHECK_PERMISSION_FAILED;
10404     }
10405 
10406     return IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->DetachAppDebug(bundleName));
10407 }
10408 
ExecuteIntent(uint64_t key,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)10409 int32_t AbilityManagerService::ExecuteIntent(uint64_t key, const sptr<IRemoteObject> &callerToken,
10410     const InsightIntentExecuteParam &param)
10411 {
10412     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10413     auto paramPtr = std::make_shared<InsightIntentExecuteParam>(param);
10414     int32_t ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->CheckAndUpdateParam(key, callerToken,
10415         paramPtr);
10416     if (ret != ERR_OK) {
10417         return ret;
10418     }
10419 
10420     Want want;
10421     ret = InsightIntentExecuteManager::GenerateWant(paramPtr, want);
10422     if (ret != ERR_OK) {
10423         return ret;
10424     }
10425 
10426     switch (param.executeMode_) {
10427         case AppExecFwk::ExecuteMode::UI_ABILITY_FOREGROUND:
10428             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_FOREGROUND.");
10429             ret = StartAbilityWithInsightIntent(want);
10430             break;
10431         case AppExecFwk::ExecuteMode::UI_ABILITY_BACKGROUND: {
10432             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode UI_ABILITY_BACKGROUND.");
10433             ret = StartAbilityByCallWithInsightIntent(want, callerToken, param);
10434             break;
10435         }
10436         case AppExecFwk::ExecuteMode::UI_EXTENSION_ABILITY:
10437             TAG_LOGW(AAFwkTag::ABILITYMGR, "ExecuteMode UI_EXTENSION_ABILITY not supported.");
10438             ret = ERR_INVALID_OPERATION;
10439             break;
10440         case AppExecFwk::ExecuteMode::SERVICE_EXTENSION_ABILITY:
10441             TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteMode SERVICE_EXTENSION_ABILITY.");
10442             ret = StartExtensionAbilityWithInsightIntent(want, AppExecFwk::ExtensionAbilityType::SERVICE);
10443             break;
10444         default:
10445             TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid ExecuteMode.");
10446             ret = ERR_INVALID_OPERATION;
10447             break;
10448     }
10449     if (ret == START_ABILITY_WAITING) {
10450         TAG_LOGD(AAFwkTag::ABILITYMGR, "Top ability is foregrounding. The intent will be queued for execution");
10451         ret = ERR_OK;
10452     }
10453     if (ret != ERR_OK) {
10454         DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->RemoveExecuteIntent(paramPtr->insightIntentId_);
10455     }
10456 
10457     TAG_LOGD(AAFwkTag::ABILITYMGR, "ExecuteIntent done, ret: %{public}d.", ret);
10458     return ret;
10459 }
10460 
IsAbilityStarted(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord,const int32_t oriValidUserId)10461 bool AbilityManagerService::IsAbilityStarted(AbilityRequest &abilityRequest,
10462     std::shared_ptr<AbilityRecord> &targetRecord, const int32_t oriValidUserId)
10463 {
10464     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10465         TAG_LOGI(AAFwkTag::ABILITYMGR, "scene board is enable");
10466         auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
10467         CHECK_POINTER_AND_RETURN(uiAbilityManager, false);
10468         return uiAbilityManager->IsAbilityStarted(abilityRequest, targetRecord);
10469     }
10470 
10471     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10472     if (missionListMgr == nullptr) {
10473         return false;
10474     }
10475     return missionListMgr->IsAbilityStarted(abilityRequest, targetRecord);
10476 }
10477 
OnExecuteIntent(AbilityRequest & abilityRequest,std::shared_ptr<AbilityRecord> & targetRecord)10478 int32_t AbilityManagerService::OnExecuteIntent(AbilityRequest &abilityRequest,
10479     std::shared_ptr<AbilityRecord> &targetRecord)
10480 {
10481     TAG_LOGI(AAFwkTag::ABILITYMGR, "OnExecuteIntent");
10482     if (targetRecord == nullptr || targetRecord->GetScheduler() == nullptr) {
10483         return ERR_INVALID_VALUE;
10484     }
10485     targetRecord->GetScheduler()->OnExecuteIntent(abilityRequest.want);
10486 
10487     return ERR_OK;
10488 }
10489 
StartAbilityWithInsightIntent(const Want & want,int32_t userId,int requestCode)10490 int32_t AbilityManagerService::StartAbilityWithInsightIntent(const Want &want, int32_t userId, int requestCode)
10491 {
10492     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10493     bool startWithAccount = want.GetBoolParam(START_ABILITY_TYPE, false);
10494     if (startWithAccount || IsCrossUserCall(userId)) {
10495         (const_cast<Want &>(want)).RemoveParam(START_ABILITY_TYPE);
10496         CHECK_CALLER_IS_SYSTEM_APP;
10497     }
10498     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
10499     EventInfo eventInfo = BuildEventInfo(want, userId);
10500     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
10501     int32_t ret = StartAbilityWrap(want, nullptr, requestCode, false, userId);
10502     if (ret != ERR_OK) {
10503         eventInfo.errCode = ret;
10504         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
10505     }
10506     return ret;
10507 }
10508 
StartExtensionAbilityWithInsightIntent(const Want & want,AppExecFwk::ExtensionAbilityType extensionType)10509 int32_t AbilityManagerService::StartExtensionAbilityWithInsightIntent(const Want &want,
10510     AppExecFwk::ExtensionAbilityType extensionType)
10511 {
10512     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10513     return StartExtensionAbilityInner(want, nullptr, DEFAULT_INVAL_VALUE, extensionType, true);
10514 }
10515 
StartAbilityByCallWithInsightIntent(const Want & want,const sptr<IRemoteObject> & callerToken,const InsightIntentExecuteParam & param)10516 int32_t AbilityManagerService::StartAbilityByCallWithInsightIntent(const Want &want,
10517     const sptr<IRemoteObject> &callerToken, const InsightIntentExecuteParam &param)
10518 {
10519     TAG_LOGI(AAFwkTag::ABILITYMGR, "call StartAbilityByCallWithInsightIntent.");
10520     sptr<IAbilityConnection> connect = sptr<AbilityBackgroundConnection>::MakeSptr();
10521     if (connect == nullptr) {
10522         TAG_LOGE(AAFwkTag::ABILITYMGR, "Invalid connect.");
10523         return ERR_INVALID_VALUE;
10524     }
10525 
10526     AbilityUtil::RemoveWantKey(const_cast<Want &>(want));
10527     AbilityRequest abilityRequest;
10528     abilityRequest.callType = AbilityCallType::CALL_REQUEST_TYPE;
10529     abilityRequest.callerUid = IPCSkeleton::GetCallingUid();
10530     abilityRequest.callerToken = callerToken;
10531     abilityRequest.startSetting = nullptr;
10532     abilityRequest.want = want;
10533     abilityRequest.connect = connect;
10534     int32_t result = GenerateAbilityRequest(want, -1, abilityRequest, callerToken, GetUserId());
10535     if (result != ERR_OK) {
10536         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request error.");
10537         return result;
10538     }
10539     std::shared_ptr<AbilityRecord> targetRecord;
10540     int32_t oriValidUserId = GetValidUserId(DEFAULT_INVAL_VALUE);
10541     auto missionListMgr = GetMissionListManagerByUserId(oriValidUserId);
10542     if (IsAbilityStarted(abilityRequest, targetRecord, oriValidUserId)) {
10543         TAG_LOGI(AAFwkTag::ABILITYMGR, "ability has already started");
10544         UpdateCallerInfo(abilityRequest.want, callerToken);
10545         result = OnExecuteIntent(abilityRequest, targetRecord);
10546     }  else {
10547         result = StartAbilityByCall(want, connect, callerToken);
10548     }
10549 
10550     TAG_LOGI(AAFwkTag::ABILITYMGR, "StartAbilityByCallWithInsightIntent %{public}d", result);
10551     return result;
10552 }
10553 
IsAbilityControllerStart(const Want & want)10554 bool AbilityManagerService::IsAbilityControllerStart(const Want &want)
10555 {
10556     auto callingUid = IPCSkeleton::GetCallingUid();
10557     bool isBrokerCall = (callingUid == BROKER_UID || callingUid == BROKER_RESERVE_UID);
10558     if (isBrokerCall) {
10559         return IsAbilityControllerStart(want, want.GetBundle());
10560     }
10561     TAG_LOGE(AAFwkTag::ABILITYMGR, "The interface only support for broker");
10562     return true;
10563 }
10564 
ExecuteInsightIntentDone(const sptr<IRemoteObject> & token,uint64_t intentId,const InsightIntentExecuteResult & result)10565 int32_t AbilityManagerService::ExecuteInsightIntentDone(const sptr<IRemoteObject> &token, uint64_t intentId,
10566     const InsightIntentExecuteResult &result)
10567 {
10568     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10569     auto abilityRecord = Token::GetAbilityRecordByToken(token);
10570     CHECK_POINTER_AND_RETURN_LOG(abilityRecord, ERR_INVALID_VALUE, "Ability record is nullptr.");
10571     if (!JudgeSelfCalled(abilityRecord)) {
10572         return CHECK_PERMISSION_FAILED;
10573     }
10574 
10575     // check send by same bundleName.
10576     std::string bundleNameStored = "";
10577     auto ret = DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->GetBundleName(intentId, bundleNameStored);
10578     if (ret != ERR_OK) {
10579         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get matched bundleName failed, intentId: %{public}" PRIu64"", intentId);
10580         return ERR_INVALID_VALUE;
10581     }
10582 
10583     std::string bundleName = abilityRecord->GetAbilityInfo().bundleName;
10584     if (bundleNameStored != bundleName) {
10585         TAG_LOGE(AAFwkTag::ABILITYMGR,
10586             "BundleName %{public}s and %{public}s mismatch.", bundleName.c_str(), bundleNameStored.c_str());
10587         return ERR_INVALID_VALUE;
10588     }
10589 
10590     return DelayedSingleton<InsightIntentExecuteManager>::GetInstance()->ExecuteIntentDone(
10591         intentId, result.innerErr, result);
10592 }
10593 
SetApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)10594 int32_t AbilityManagerService::SetApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
10595 {
10596     if (abilityAutoStartupService_ == nullptr) {
10597         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10598         return ERR_NO_INIT;
10599     }
10600     return abilityAutoStartupService_->SetApplicationAutoStartupByEDM(info, flag);
10601 }
10602 
CancelApplicationAutoStartupByEDM(const AutoStartupInfo & info,bool flag)10603 int32_t AbilityManagerService::CancelApplicationAutoStartupByEDM(const AutoStartupInfo &info, bool flag)
10604 {
10605     if (abilityAutoStartupService_ == nullptr) {
10606         TAG_LOGE(AAFwkTag::ABILITYMGR, "abilityAutoStartupService_ is nullptr.");
10607         return ERR_NO_INIT;
10608     }
10609     return abilityAutoStartupService_->CancelApplicationAutoStartupByEDM(info, flag);
10610 }
10611 
GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> & list)10612 int32_t AbilityManagerService::GetForegroundUIAbilities(std::vector<AppExecFwk::AbilityStateData> &list)
10613 {
10614     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10615     CHECK_CALLER_IS_SYSTEM_APP;
10616     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
10617     if (!isPerm) {
10618         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10619         return CHECK_PERMISSION_FAILED;
10620     }
10621 
10622     std::vector<AbilityRunningInfo> abilityRunningInfos;
10623     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
10624         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10625         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10626         uiAbilityManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
10627     } else {
10628         auto missionListManager = GetCurrentMissionListManager();
10629         CHECK_POINTER_AND_RETURN(missionListManager, ERR_NULL_OBJECT);
10630         missionListManager->GetAbilityRunningInfos(abilityRunningInfos, isPerm);
10631     }
10632 
10633     for (auto &info : abilityRunningInfos) {
10634         if (info.abilityState != AbilityState::FOREGROUND) {
10635             continue;
10636         }
10637 
10638         AppExecFwk::AbilityStateData abilityData;
10639         abilityData.bundleName = info.ability.GetBundleName();
10640         abilityData.moduleName = info.ability.GetModuleName();
10641         abilityData.abilityName = info.ability.GetAbilityName();
10642         abilityData.abilityState = info.abilityState;
10643         abilityData.pid = info.pid;
10644         abilityData.uid = info.uid;
10645         abilityData.abilityType = static_cast<int32_t>(AppExecFwk::AbilityType::PAGE);
10646         abilityData.appCloneIndex = info.appCloneIndex;
10647         AppExecFwk::ApplicationInfo appInfo;
10648         if (!StartAbilityUtils::GetApplicationInfo(abilityData.bundleName, GetUserId(), appInfo)) {
10649             TAG_LOGE(AAFwkTag::ABILITYMGR, "can not get applicationInfo through bundleName");
10650         } else if (appInfo.bundleType == AppExecFwk::BundleType::ATOMIC_SERVICE) {
10651             abilityData.isAtomicService = true;
10652         }
10653         list.push_back(abilityData);
10654     }
10655     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get foreground ui abilities end, list.size = %{public}zu.", list.size());
10656     return ERR_OK;
10657 }
10658 
NotifyConfigurationChange(const AppExecFwk::Configuration & config,int32_t userId)10659 void AbilityManagerService::NotifyConfigurationChange(const AppExecFwk::Configuration &config, int32_t userId)
10660 {
10661     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
10662     if (collaborator == nullptr) {
10663         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator GetCollaborator is nullptr.");
10664         return;
10665     }
10666     collaborator->UpdateConfiguration(config, userId);
10667 }
10668 
NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> & bundleInfos)10669 void AbilityManagerService::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
10670 {
10671     if (userController_ == nullptr) {
10672         TAG_LOGE(AAFwkTag::ABILITYMGR, "userController_ null");
10673         return;
10674     }
10675     auto currentUser = userController_->GetCurrentUserId();
10676     std::vector<AppExecFwk::BundleInfo> bundleInfosForU0;
10677     std::vector<AppExecFwk::BundleInfo> bundleInfosForCurrentUser;
10678     for (const auto &item: bundleInfos) {
10679         auto user = item.uid / BASE_USER_RANGE;
10680         if (user == U0_USER_ID) {
10681             bundleInfosForU0.push_back(item);
10682         } else if (user == currentUser) {
10683             bundleInfosForCurrentUser.push_back(item);
10684         }
10685     }
10686 
10687     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
10688         bundleInfosForU0, U0_USER_ID);
10689     if (!bundleInfosForU0.empty()) {
10690         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForU0);
10691     }
10692 
10693     DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcessWithMainElement(
10694         bundleInfosForCurrentUser, currentUser);
10695     if (!bundleInfosForCurrentUser.empty()) {
10696         DelayedSingleton<ResidentProcessManager>::GetInstance()->StartResidentProcess(bundleInfosForCurrentUser);
10697     }
10698 }
10699 
NotifyAppPreCache(int32_t pid,int32_t userId)10700 void AbilityManagerService::NotifyAppPreCache(int32_t pid, int32_t userId)
10701 {
10702     ForceTerminateSerivceExtensionByPid(pid, userId);
10703 }
10704 
OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> & abilityTokens)10705 void AbilityManagerService::OnAppRemoteDied(const std::vector<sptr<IRemoteObject>> &abilityTokens)
10706 {
10707     std::shared_ptr<AbilityRecord> abilityRecord;
10708     for (auto &token : abilityTokens) {
10709         abilityRecord = Token::GetAbilityRecordByToken(token);
10710         if (abilityRecord == nullptr) {
10711             continue;
10712         }
10713         TAG_LOGI(AAFwkTag::ABILITYMGR, "App OnRemoteDied, ability is %{public}s, app is %{public}s",
10714             abilityRecord->GetAbilityInfo().name.c_str(), abilityRecord->GetAbilityInfo().bundleName.c_str());
10715         abilityRecord->OnProcessDied();
10716     }
10717 }
10718 
OpenFile(const Uri & uri,uint32_t flag)10719 int32_t AbilityManagerService::OpenFile(const Uri& uri, uint32_t flag)
10720 {
10721     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
10722     if (!IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().VerifyUriPermission(
10723         uri, flag, accessTokenId))) {
10724         TAG_LOGE(AAFwkTag::ABILITYMGR, "premission check failed");
10725         return -1;
10726     }
10727     auto collaborator = GetCollaborator(CollaboratorType::RESERVE_TYPE);
10728     if (collaborator == nullptr) {
10729         TAG_LOGE(AAFwkTag::ABILITYMGR, "collaborator GetCollaborator is nullptr.");
10730         return ERR_COLLABORATOR_NOT_REGISTER;
10731     }
10732     return collaborator->OpenFile(uri, flag);
10733 }
10734 
GetDialogSessionInfo(const std::string & dialogSessionId,sptr<DialogSessionInfo> & dialogSessionInfo)10735 int AbilityManagerService::GetDialogSessionInfo(const std::string &dialogSessionId,
10736     sptr<DialogSessionInfo> &dialogSessionInfo)
10737 {
10738     CHECK_CALLER_IS_SYSTEM_APP;
10739     dialogSessionInfo = DialogSessionManager::GetInstance().GetDialogSessionInfo(dialogSessionId);
10740     if (dialogSessionInfo) {
10741         TAG_LOGD(AAFwkTag::ABILITYMGR, "success");
10742         return ERR_OK;
10743     }
10744     TAG_LOGD(AAFwkTag::ABILITYMGR, "fail");
10745     return INNER_ERR;
10746 }
10747 
SendDialogResult(const Want & want,const std::string & dialogSessionId,bool isAllowed)10748 int AbilityManagerService::SendDialogResult(const Want &want, const std::string &dialogSessionId, bool isAllowed)
10749 {
10750     CHECK_CALLER_IS_SYSTEM_APP;
10751     return DialogSessionManager::GetInstance().SendDialogResult(want, dialogSessionId, isAllowed);
10752 }
10753 
CreateCloneSelectorDialog(AbilityRequest & request,int32_t userId,const std::string & replaceWantString)10754 int AbilityManagerService::CreateCloneSelectorDialog(AbilityRequest &request, int32_t userId,
10755     const std::string &replaceWantString)
10756 {
10757     CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
10758     return implicitStartProcessor_->ImplicitStartAbility(request, userId, 0, replaceWantString, true);
10759 }
10760 
RemoveSelectorIdentity(int32_t tokenId)10761 void AbilityManagerService::RemoveSelectorIdentity(int32_t tokenId)
10762 {
10763     CHECK_POINTER(implicitStartProcessor_);
10764     implicitStartProcessor_->RemoveIdentity(tokenId);
10765 }
10766 
SetTargetCloneIndexInSameBundle(const Want & want,sptr<IRemoteObject> callerToken)10767 void AbilityManagerService::SetTargetCloneIndexInSameBundle(const Want &want, sptr<IRemoteObject> callerToken)
10768 {
10769     auto callerRecord = Token::GetAbilityRecordByToken(callerToken);
10770     CHECK_POINTER(callerRecord);
10771     if (callerRecord->GetAbilityInfo().bundleName != want.GetElement().GetBundleName()) {
10772         TAG_LOGD(AAFwkTag::ABILITYMGR, "not the same bundle");
10773         return;
10774     }
10775     if (want.HasParameter(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY)) {
10776         TAG_LOGD(AAFwkTag::ABILITYMGR, "want with app clone index.");
10777         return;
10778     }
10779     int32_t appIndex = callerRecord->GetApplicationInfo().appIndex;
10780     if (appIndex >= 0 && appIndex < AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
10781         (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
10782     }
10783 }
10784 
RemoveLauncherDeathRecipient(int32_t userId)10785 void AbilityManagerService::RemoveLauncherDeathRecipient(int32_t userId)
10786 {
10787     auto connectManager = GetConnectManagerByUserId(userId);
10788     if (connectManager == nullptr) {
10789         TAG_LOGE(AAFwkTag::ABILITYMGR, "connectManager is nullptr. userId=%{public}d", userId);
10790         return;
10791     }
10792     connectManager->RemoveLauncherDeathRecipient();
10793 }
10794 
CheckDebugAssertPermission()10795 int32_t AbilityManagerService::CheckDebugAssertPermission()
10796 {
10797     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10798     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10799     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
10800         TAG_LOGE(AAFwkTag::ABILITYMGR, "Product of assert fault dialog is not enabled.");
10801         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
10802     }
10803     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
10804         TAG_LOGE(AAFwkTag::ABILITYMGR, "Developer Mode is false.");
10805         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
10806     }
10807 
10808     auto bundleMgr = GetBundleManager();
10809     if (bundleMgr == nullptr) {
10810         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle manager instance is nullptr.");
10811         return ERR_INVALID_VALUE;
10812     }
10813     int32_t flags = static_cast<int32_t>(AppExecFwk::GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION);
10814     AppExecFwk::BundleInfo bundleInfo;
10815     auto ret = bundleMgr->GetBundleInfoForSelf(flags, bundleInfo);
10816     if (ret != ERR_OK) {
10817         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get bundle Info failed.");
10818         return ret;
10819     }
10820     if (!bundleInfo.applicationInfo.debug) {
10821         TAG_LOGE(AAFwkTag::ABILITYMGR, "Non-debug version application.");
10822         return ERR_INVALID_VALUE;
10823     }
10824     return ERR_OK;
10825 }
10826 
SetResidentProcessEnabled(const std::string & bundleName,bool enable)10827 int32_t AbilityManagerService::SetResidentProcessEnabled(const std::string &bundleName, bool enable)
10828 {
10829     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
10830     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) {
10831         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed.");
10832         return ERR_NOT_SYSTEM_APP;
10833     }
10834 
10835     auto residentProcessManager = DelayedSingleton<ResidentProcessManager>::GetInstance();
10836     if (residentProcessManager == nullptr) {
10837         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get resident proces mgr is nullptr");
10838         return INNER_ERR;
10839     }
10840 
10841     std::string callerName;
10842     int32_t uid = 0;
10843     auto callerPid = IPCSkeleton::GetCallingPid();
10844     DelayedSingleton<AppScheduler>::GetInstance()->GetBundleNameByPid(callerPid, callerName, uid);
10845     if (callerName.empty()) {
10846         TAG_LOGE(AAFwkTag::ABILITYMGR, "Failed to obtain caller name.");
10847         return INNER_ERR;
10848     }
10849 
10850     return residentProcessManager->SetResidentProcessEnabled(bundleName, callerName, enable);
10851 }
10852 
CloseAssertDialog(const std::string & assertSessionId)10853 void AbilityManagerService::CloseAssertDialog(const std::string &assertSessionId)
10854 {
10855     TAG_LOGD(AAFwkTag::ABILITYMGR, "Close assert fault dialog begin.");
10856     auto validUserId = GetUserId();
10857     auto connectManager = GetConnectManagerByUserId(validUserId);
10858     if (connectManager == nullptr) {
10859         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
10860         return;
10861     }
10862 
10863     connectManager->CloseAssertDialog(assertSessionId);
10864 }
10865 
RequestAssertFaultDialog(const sptr<IRemoteObject> & callback,const AAFwk::WantParams & wantParams)10866 int32_t AbilityManagerService::RequestAssertFaultDialog(
10867     const sptr<IRemoteObject> &callback, const AAFwk::WantParams &wantParams)
10868 {
10869     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog begin.");
10870     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10871     auto checkRet = CheckDebugAssertPermission();
10872     if (checkRet != ERR_OK) {
10873         TAG_LOGE(AAFwkTag::ABILITYMGR, "Check debug assert permission error.");
10874         return checkRet;
10875     }
10876     sptr<IRemoteObject> remoteCallback = callback;
10877     if (remoteCallback == nullptr) {
10878         TAG_LOGE(AAFwkTag::ABILITYMGR, "Params remote callback is nullptr");
10879         return ERR_INVALID_VALUE;
10880     }
10881     auto debugDeal = ConnectInitAbilityDebugDeal();
10882     auto sysDialog = DelayedSingleton<SystemDialogScheduler>::GetInstance();
10883     if (sysDialog == nullptr || debugDeal == nullptr) {
10884         TAG_LOGE(AAFwkTag::ABILITYMGR, "sysDialog or debugDeal is nullptr.");
10885         return ERR_INVALID_VALUE;
10886     }
10887     Want want;
10888     if (!sysDialog->GetAssertFaultDialogWant(want)) {
10889         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get assert fault dialog want failed.");
10890         return ERR_INVALID_VALUE;
10891     }
10892     uint64_t assertFaultSessionId = reinterpret_cast<uint64_t>(remoteCallback.GetRefPtr());
10893     want.SetParam(Want::PARAM_ASSERT_FAULT_SESSION_ID, std::to_string(assertFaultSessionId));
10894     want.SetParam(ASSERT_FAULT_DETAIL, wantParams.GetStringParam(ASSERT_FAULT_DETAIL));
10895     auto &connection = AbilityRuntime::ModalSystemAssertUIExtension::GetInstance();
10896     want.SetParam(UIEXTENSION_MODAL_TYPE, 1);
10897     if (!IN_PROCESS_CALL(connection.CreateModalUIExtension(want))) {
10898         TAG_LOGE(AAFwkTag::ABILITYMGR, "Create modal ui extension failed.");
10899         return ERR_INVALID_VALUE;
10900     }
10901     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
10902     if (callbackDeathMgr == nullptr) {
10903         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callback death manager instance is nullptr.");
10904         return ERR_INVALID_VALUE;
10905     }
10906     auto callbackTask = [weak = weak_from_this()] (const std::string &assertSessionId) {
10907         auto abilityMgr = weak.lock();
10908         if (abilityMgr == nullptr) {
10909             TAG_LOGE(AAFwkTag::ABILITYMGR, "ability manager instance is nullptr.");
10910             return;
10911         }
10912         abilityMgr->CloseAssertDialog(assertSessionId);
10913     };
10914     callbackDeathMgr->AddAssertFaultCallback(remoteCallback, callbackTask);
10915     TAG_LOGD(AAFwkTag::ABILITYMGR, "Request to display assert fault dialog end.");
10916     return ERR_OK;
10917 }
10918 
NotifyDebugAssertResult(uint64_t assertFaultSessionId,AAFwk::UserStatus userStatus)10919 int32_t AbilityManagerService::NotifyDebugAssertResult(uint64_t assertFaultSessionId, AAFwk::UserStatus userStatus)
10920 {
10921     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10922     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
10923         TAG_LOGE(AAFwkTag::ABILITYMGR, "Product of assert fault dialog is not enabled.");
10924         return ERR_NOT_SUPPORTED_PRODUCT_TYPE;
10925     }
10926 
10927     CHECK_CALLER_IS_SYSTEM_APP;
10928     auto permissionSA = PermissionVerification::GetInstance();
10929     if (permissionSA == nullptr) {
10930         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification instance is nullptr.");
10931         return ERR_INVALID_VALUE;
10932     }
10933     if (!permissionSA->VerifyCallingPermission(PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT)) {
10934         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
10935             PermissionConstants::PERMISSION_NOTIFY_DEBUG_ASSERT_RESULT);
10936         return ERR_PERMISSION_DENIED;
10937     }
10938 
10939     auto callbackDeathMgr = DelayedSingleton<AbilityRuntime::AssertFaultCallbackDeathMgr>::GetInstance();
10940     if (callbackDeathMgr == nullptr) {
10941         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callback death manager instance is nullptr.");
10942         return ERR_INVALID_VALUE;
10943     }
10944     callbackDeathMgr->CallAssertFaultCallback(assertFaultSessionId, userStatus);
10945     return ERR_OK;
10946 }
10947 
UpdateSessionInfoBySCB(std::list<SessionInfo> & sessionInfos,int32_t userId,std::vector<int32_t> & sessionIds)10948 int32_t AbilityManagerService::UpdateSessionInfoBySCB(std::list<SessionInfo> &sessionInfos, int32_t userId,
10949     std::vector<int32_t> &sessionIds)
10950 {
10951     if (!IsCallerSceneBoard()) {
10952         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not sceneboard called, not allowed.");
10953         return ERR_WRONG_INTERFACE_CALL;
10954     }
10955     TAG_LOGI(AAFwkTag::ABILITYMGR, "The sceneboard is being restored.");
10956     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
10957     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
10958     return uiAbilityManager->UpdateSessionInfoBySCB(sessionInfos, sessionIds);
10959 }
10960 
CheckSenderWantInfo(int32_t callerUid,const WantSenderInfo & wantSenderInfo)10961 bool AbilityManagerService::CheckSenderWantInfo(int32_t callerUid, const WantSenderInfo &wantSenderInfo)
10962 {
10963     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
10964         auto bms = GetBundleManager();
10965         CHECK_POINTER_AND_RETURN(bms, false);
10966 
10967         std::string bundleName;
10968         if (IN_PROCESS_CALL(bms->GetNameForUid(callerUid, bundleName)) != ERR_OK) {
10969             TAG_LOGE(AAFwkTag::ABILITYMGR, "Get Bundle Name failed.");
10970             return false;
10971         }
10972         if (wantSenderInfo.bundleName != bundleName) {
10973             TAG_LOGE(AAFwkTag::ABILITYMGR, "wantSender bundleName check failed");
10974             return false;
10975         }
10976     }
10977     return true;
10978 }
10979 
CheckCallerIsDmsProcess()10980 bool AbilityManagerService::CheckCallerIsDmsProcess()
10981 {
10982     Security::AccessToken::NativeTokenInfo nativeTokenInfo;
10983     uint32_t accessToken = IPCSkeleton::GetCallingTokenID();
10984     auto tokenType = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessToken);
10985     int32_t result = Security::AccessToken::AccessTokenKit::GetNativeTokenInfo(accessToken, nativeTokenInfo);
10986     if (tokenType != Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE ||
10987         result != ERR_OK || nativeTokenInfo.processName != DMS_PROCESS_NAME) {
10988         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not dms");
10989         return false;
10990     }
10991     return true;
10992 }
10993 
GenerateEmbeddableUIAbilityRequest(const Want & want,AbilityRequest & request,const sptr<IRemoteObject> & callerToken,int32_t userId)10994 int32_t AbilityManagerService::GenerateEmbeddableUIAbilityRequest(
10995     const Want &want, AbilityRequest &request, const sptr<IRemoteObject> &callerToken, int32_t userId)
10996 {
10997     int32_t screenMode = want.GetIntParam(AAFwk::SCREEN_MODE_KEY, AAFwk::IDLE_SCREEN_MODE);
10998     int32_t result = ERR_OK;
10999     if (screenMode == AAFwk::EMBEDDED_FULL_SCREEN_MODE) {
11000         result = GenerateAbilityRequest(want, -1, request, callerToken, userId);
11001         request.abilityInfo.isModuleJson = true;
11002         request.abilityInfo.isStageBasedModel = true;
11003         request.abilityInfo.type = AppExecFwk::AbilityType::EXTENSION;
11004         request.abilityInfo.extensionAbilityType = AppExecFwk::ExtensionAbilityType::UI;
11005         struct timespec time = {0, 0};
11006         clock_gettime(CLOCK_MONOTONIC, &time);
11007         int64_t times = static_cast<int64_t>(time.tv_sec);
11008         request.abilityInfo.process = request.abilityInfo.bundleName + PROCESS_SUFFIX + std::to_string(times);
11009     } else {
11010         result = GenerateExtensionAbilityRequest(want, request, callerToken, userId);
11011     }
11012     return result;
11013 }
11014 
WaitBootAnimationStart()11015 void AbilityManagerService::WaitBootAnimationStart()
11016 {
11017     char value[BOOTEVENT_BOOT_ANIMATION_READY_SIZE] = "";
11018     int32_t ret = GetParameter(BOOTEVENT_BOOT_ANIMATION_READY, "", value,
11019         BOOTEVENT_BOOT_ANIMATION_READY_SIZE);
11020     if (ret > 0 && !std::strcmp(value, "false")) {
11021         // Get new param success and new param is not ready, wait the new param.
11022         WaitParameter(BOOTEVENT_BOOT_ANIMATION_READY, "true",
11023             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11024     } else if (ret <= 0 || !std::strcmp(value, "")) {
11025         // Get new param failed or new param is not set, wait the old param.
11026         WaitParameter(BOOTEVENT_BOOT_ANIMATION_STARTED, "true",
11027             AmsConfigurationParameter::GetInstance().GetBootAnimationTimeoutTime());
11028     }
11029     // other, the animation is ready, not wait.
11030 }
11031 
GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,UIExtensionSessionInfo & uiExtensionSessionInfo,int32_t userId)11032 int32_t AbilityManagerService::GetUIExtensionSessionInfo(const sptr<IRemoteObject> token,
11033     UIExtensionSessionInfo &uiExtensionSessionInfo, int32_t userId)
11034 {
11035     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11036     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11037     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11038 
11039     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11040         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
11041         return ERR_PERMISSION_DENIED;
11042     }
11043 
11044     auto validUserId = GetValidUserId(userId);
11045     auto connectManager = GetConnectManagerByUserId(validUserId);
11046     if (connectManager == nullptr) {
11047         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11048         return ERR_INVALID_VALUE;
11049     }
11050 
11051     auto ret = connectManager->GetUIExtensionSessionInfo(token, uiExtensionSessionInfo);
11052     if (ret != ERR_OK) {
11053         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get ui extension session info failed.");
11054         return ret;
11055     }
11056 
11057     return ERR_OK;
11058 }
11059 
RestartApp(const AAFwk::Want & want,bool isAppRecovery)11060 int32_t AbilityManagerService::RestartApp(const AAFwk::Want &want, bool isAppRecovery)
11061 {
11062     TAG_LOGI(AAFwkTag::ABILITYMGR, "RestartApp, isAppRecovery: %{public}d", isAppRecovery);
11063     auto appIndex = GetAppIndex(want);
11064     int result = CheckRestartAppWant(want, appIndex);
11065     if (result != ERR_OK) {
11066         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckRestartAppWant error.");
11067         return result;
11068     }
11069 
11070     int32_t callerUid = IPCSkeleton::GetCallingUid();
11071     int64_t now = time(nullptr);
11072     if (!isAppRecovery && RestartAppManager::GetInstance().IsRestartAppFrequent(callerUid, now)) {
11073         return AAFwk::ERR_RESTART_APP_FREQUENT;
11074     }
11075 
11076     bool isForegroundToRestartApp = RestartAppManager::GetInstance().IsForegroundToRestartApp();
11077     if (!isForegroundToRestartApp) {
11078         TAG_LOGE(AAFwkTag::ABILITYMGR, "RestartApp, IsForegroundToRestartApp failed.");
11079         return AAFwk::NOT_TOP_ABILITY;
11080     }
11081 
11082     int32_t userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11083     result = SignRestartAppFlag(userId, callerUid, isAppRecovery);
11084     if (result != ERR_OK) {
11085         TAG_LOGE(AAFwkTag::ABILITYMGR, "SignRestartAppFlag error.");
11086         return result;
11087     }
11088     result = DelayedSingleton<AppExecFwk::AppMgrClient>::GetInstance()->KillApplicationSelf("RestartApp");
11089     if (result != ERR_OK) {
11090         TAG_LOGE(AAFwkTag::ABILITYMGR, "KillApplicationSelf error.");
11091         return result;
11092     }
11093 
11094     TAG_LOGD(AAFwkTag::ABILITYMGR, "RestartApp, start ability without CheckCallAbilityPermission.");
11095     (const_cast<Want &>(want)).SetParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, appIndex);
11096     result = StartAbilityWrap(want, nullptr,
11097         DEFAULT_INVAL_VALUE, false, DEFAULT_INVAL_VALUE, false, 0, isForegroundToRestartApp);
11098     if (result != ERR_OK) {
11099         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartAbility error.");
11100         return result;
11101     }
11102     if (!isAppRecovery) {
11103         RestartAppManager::GetInstance().AddRestartAppHistory(callerUid, now);
11104     }
11105     return result;
11106 }
11107 
GetAppIndex(const Want & want)11108 int32_t AbilityManagerService::GetAppIndex(const Want& want)
11109 {
11110     int32_t appIndex = want.GetIntParam(AAFwk::Want::PARAM_APP_CLONE_INDEX_KEY, -1);
11111     if (appIndex == -1) {
11112         auto appMgr = AppMgrUtil::GetAppMgr();
11113         if (appMgr == nullptr) {
11114             TAG_LOGW(AAFwkTag::ABILITYMGR, "AppMgrUtil::GetAppMgr failed");
11115             return appIndex;
11116         }
11117         auto callingPid = IPCSkeleton::GetCallingPid();
11118         auto ret = IN_PROCESS_CALL(appMgr->GetAppIndexByPid(callingPid, appIndex));
11119         if (ret != ERR_OK) {
11120             TAG_LOGE(AAFwkTag::ABILITYMGR, "appMgr GetAppIndexByPid error");
11121         }
11122     }
11123     return appIndex;
11124 }
11125 
CheckRestartAppWant(const AAFwk::Want & want,int32_t appIndex)11126 int32_t AbilityManagerService::CheckRestartAppWant(const AAFwk::Want &want, int32_t appIndex)
11127 {
11128     std::string bundleName = want.GetElement().GetBundleName();
11129     auto userId = IPCSkeleton::GetCallingUid() / BASE_USER_RANGE;
11130     if (!CheckCallingTokenId(bundleName, userId, appIndex)) {
11131         TAG_LOGE(AAFwkTag::ABILITYMGR, "Not itself called, not allowed.");
11132         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11133     }
11134 
11135     auto bms = GetBundleManager();
11136     CHECK_POINTER_AND_RETURN(bms, GET_ABILITY_SERVICE_FAILED);
11137     auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
11138     AppExecFwk::AbilityInfo abilityInfo;
11139     auto queryResult = IN_PROCESS_CALL(
11140         bms->QueryCloneAbilityInfo(want.GetElement(), abilityInfoFlag, appIndex, abilityInfo, userId));
11141     if (queryResult != ERR_OK || abilityInfo.name.empty() || abilityInfo.bundleName.empty() ||
11142         abilityInfo.type != AbilityType::PAGE) {
11143         TAG_LOGE(AAFwkTag::ABILITYMGR, "Ability is invalid or not UIAbility.");
11144         return AAFwk::ERR_RESTART_APP_INCORRECT_ABILITY;
11145     }
11146     return ERR_OK;
11147 }
11148 
SignRestartAppFlag(int32_t userId,int32_t uid,bool isAppRecovery)11149 int32_t AbilityManagerService::SignRestartAppFlag(int32_t userId, int32_t uid, bool isAppRecovery)
11150 {
11151     auto appMgr = GetAppMgr();
11152     if (appMgr == nullptr) {
11153         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
11154         return ERR_INVALID_VALUE;
11155     }
11156     auto ret = IN_PROCESS_CALL(appMgr->SignRestartAppFlag(uid));
11157     if (ret != ERR_OK) {
11158         TAG_LOGE(AAFwkTag::ABILITYMGR, "AppMgr SignRestartAppFlag error");
11159         return ret;
11160     }
11161 
11162     auto connectManager = GetConnectManagerByUserId(userId);
11163     connectManager->SignRestartAppFlag(uid);
11164     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11165         auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
11166         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11167         uiAbilityManager->SignRestartAppFlag(uid, isAppRecovery);
11168         return ERR_OK;
11169     }
11170     auto missionListManager = GetMissionListManagerByUserId(userId);
11171     if (missionListManager == nullptr) {
11172         TAG_LOGE(AAFwkTag::ABILITYMGR, "missionListManager is nullptr. userId:%{public}d", userId);
11173         return ERR_INVALID_VALUE;
11174     }
11175     missionListManager->SignRestartAppFlag(uid);
11176     return ERR_OK;
11177 }
11178 
GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,UIExtensionHostInfo & hostInfo,int32_t userId)11179 int32_t AbilityManagerService::GetUIExtensionRootHostInfo(const sptr<IRemoteObject> token,
11180     UIExtensionHostInfo &hostInfo, int32_t userId)
11181 {
11182     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11183     TAG_LOGD(AAFwkTag::ABILITYMGR, "Get ui extension host info.");
11184     CHECK_POINTER_AND_RETURN(token, ERR_INVALID_VALUE);
11185 
11186     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() && !IsCallerSceneBoard()) {
11187         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission deny.");
11188         return ERR_PERMISSION_DENIED;
11189     }
11190 
11191     auto callerRecord = GetUIExtensionRootCaller(token, userId);
11192     if (callerRecord == nullptr) {
11193         TAG_LOGE(AAFwkTag::UI_EXT, "Get root host info failed.");
11194         return ERR_INVALID_VALUE;
11195     }
11196 
11197     hostInfo.elementName_ = callerRecord->GetElementName();
11198     TAG_LOGD(AAFwkTag::UI_EXT, "Root host uri: %{public}s.", hostInfo.elementName_.GetURI().c_str());
11199     return ERR_OK;
11200 }
11201 
GetUIExtensionRootCaller(const sptr<IRemoteObject> token,int32_t userId)11202 std::shared_ptr<AbilityRecord> AbilityManagerService::GetUIExtensionRootCaller(const sptr<IRemoteObject> token,
11203     int32_t userId)
11204 {
11205     auto validUserId = GetValidUserId(userId);
11206     auto connectManager = GetConnectManagerByUserId(validUserId);
11207     if (connectManager == nullptr) {
11208         TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", validUserId);
11209         return nullptr;
11210     }
11211 
11212     auto callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11213     if (callerRecord == nullptr && validUserId != U0_USER_ID) {
11214         connectManager = GetConnectManagerByUserId(U0_USER_ID);
11215         if (connectManager == nullptr) {
11216             TAG_LOGE(AAFwkTag::ABILITYMGR, "Connect manager is nullptr, userId: %{public}d.", U0_USER_ID);
11217             return nullptr;
11218         }
11219         callerRecord = connectManager->GetUIExtensionRootHostInfo(token);
11220     }
11221 
11222     return callerRecord;
11223 }
11224 
IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken,const std::string & appId)11225 bool AbilityManagerService::IsEmbeddedOpenAllowed(sptr<IRemoteObject> callerToken, const std::string &appId)
11226 {
11227     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11228     if (!AppUtils::GetInstance().IsLaunchEmbededUIAbility()) {
11229         TAG_LOGE(AAFwkTag::ABILITYMGR, "device type is not allowd.");
11230         return false;
11231     }
11232     auto accessTokenId = IPCSkeleton::GetCallingTokenID();
11233     auto type = Security::AccessToken::AccessTokenKit::GetTokenTypeFlag(accessTokenId);
11234     if (type != Security::AccessToken::TypeATokenTypeEnum::TOKEN_HAP) {
11235         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is not hap.");
11236         return false;
11237     }
11238     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11239     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11240     auto callerAbility = uiAbilityManager->GetAbilityRecordByToken(callerToken);
11241     if (callerAbility == nullptr) {
11242         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller is invalid.");
11243         return false;
11244     }
11245     if (callerAbility->GetApplicationInfo().accessTokenId != accessTokenId) {
11246         TAG_LOGE(AAFwkTag::ABILITYMGR, "The callerToken does not belong to the caller.");
11247         return false;
11248     }
11249     if (!callerAbility->IsForeground() && !callerAbility->GetAbilityForegroundingFlag()) {
11250         TAG_LOGE(AAFwkTag::ABILITYMGR, "The caller not foreground.");
11251         return false;
11252     }
11253     std::string bundleName = ATOMIC_SERVICE_PREFIX + appId;
11254     Want want;
11255     want.SetBundle(bundleName);
11256     want.SetParam("send_to_erms_embedded", 1);
11257     int32_t ret = freeInstallManager_->StartFreeInstall(want, GetUserId(), 0, callerToken, false);
11258     if (ret != ERR_OK) {
11259         TAG_LOGE(AAFwkTag::ABILITYMGR, "The target is not allowed to free install.");
11260         return false;
11261     }
11262     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerAbility->GetElementName().GetBundleName());
11263     auto erms = std::make_shared<EcologicalRuleInterceptor>();
11264     return erms->DoProcess(want, GetUserId());
11265 }
11266 
ShouldPreventStartAbility(const AbilityRequest & abilityRequest)11267 bool AbilityManagerService::ShouldPreventStartAbility(const AbilityRequest &abilityRequest)
11268 {
11269     std::shared_ptr<AbilityRecord> abilityRecord = Token::GetAbilityRecordByToken(abilityRequest.callerToken);
11270     if (abilityRecord == nullptr) {
11271         TAG_LOGD(AAFwkTag::ABILITYMGR, "No matched token pass");
11272         return false;
11273     }
11274     auto abilityInfo = abilityRequest.abilityInfo;
11275     auto callerAbilityInfo = abilityRecord->GetAbilityInfo();
11276     PrintStartAbilityInfo(callerAbilityInfo, abilityInfo);
11277     if (abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD < API12) {
11278         TAG_LOGD(AAFwkTag::ABILITYMGR, "API version %{public}d pass",
11279             abilityRecord->GetApplicationInfo().apiTargetVersion % API_VERSION_MOD);
11280         return false;
11281     }
11282     bool continuousFlag = IsBackgroundTaskUid(IPCSkeleton::GetCallingUid());
11283     if (abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::DATASHARE &&
11284         abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
11285         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process did not call service or datashare extension Pass");
11286         return false;
11287     }
11288     if (abilityInfo.applicationInfo.uid == IPCSkeleton::GetCallingUid()) {
11289         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in same bundle Pass");
11290         return false;
11291     }
11292     if (callerAbilityInfo.type != AppExecFwk::AbilityType::PAGE) {
11293         TAG_LOGD(AAFwkTag::ABILITYMGR, "Is not UI Ability Pass");
11294         return false;
11295     }
11296     if (abilityRecord->GetAbilityState() != AAFwk::AbilityState::BACKGROUND) {
11297         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is not on background Pass");
11298         return false;
11299     }
11300     if (continuousFlag) {
11301         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has continuous task Pass");
11302         return false;
11303     }
11304     if (IsInWhiteList(callerAbilityInfo.bundleName, abilityInfo.bundleName, abilityInfo.name)) {
11305         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process is in white list Pass");
11306         return false;
11307     }
11308     if(!IN_PROCESS_CALL(DelayedSingleton<AppScheduler>::GetInstance()->
11309         IsProcessContainsOnlyUIAbility(abilityRecord->GetPid()))) {
11310         TAG_LOGD(AAFwkTag::ABILITYMGR, "Process has other extension except UIAbility, pass");
11311         return false;
11312     }
11313     TAG_LOGE(AAFwkTag::ABILITYMGR, "Do not have permission to start ServiceExtension %{public}s.",
11314         abilityRecord->GetURI().c_str());
11315     ReportPreventStartAbilityResult(callerAbilityInfo, abilityInfo);
11316     return true;
11317 }
11318 
PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo,AppExecFwk::AbilityInfo calledInfo)11319 void AbilityManagerService::PrintStartAbilityInfo(AppExecFwk::AbilityInfo callerInfo, AppExecFwk::AbilityInfo calledInfo)
11320 {
11321     TAG_LOGD(AAFwkTag::ABILITYMGR, "calledAbilityInfo toString: "
11322         "calledUid is: %{public}d, "
11323         "name is: %{public}s, "
11324         "bundleName is: %{public}s, "
11325         "type is: %{public}d, "
11326         "extensionAbilityType is: %{public}d, "
11327         "moduleName is: %{public}s, "
11328         "applicationName is: %{public}s",
11329         calledInfo.applicationInfo.uid,
11330         calledInfo.name.c_str(),
11331         calledInfo.bundleName.c_str(),
11332         static_cast<int32_t>(calledInfo.type),
11333         static_cast<int32_t>(calledInfo.extensionAbilityType),
11334         calledInfo.moduleName.c_str(),
11335         calledInfo.applicationName.c_str());
11336 
11337 
11338     TAG_LOGD(AAFwkTag::ABILITYMGR, "callerAbilityInfo toString: "
11339         "callerUid is: %{public}d, "
11340         "callerPid is: %{public}d, "
11341         "name is: %{public}s, "
11342         "bundleName is: %{public}s, "
11343         "type is: %{public}d, "
11344         "extensionAbilityType is: %{public}d, "
11345         "moduleName is: %{public}s, "
11346         "applicationName is: %{public}s",
11347         IPCSkeleton::GetCallingUid(),
11348         IPCSkeleton::GetCallingPid(),
11349         callerInfo.name.c_str(),
11350         callerInfo.bundleName.c_str(),
11351         static_cast<int32_t>(callerInfo.type),
11352         static_cast<int32_t>(callerInfo.extensionAbilityType),
11353         callerInfo.moduleName.c_str(),
11354         callerInfo.applicationName.c_str());
11355 }
11356 
ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo & callerAbilityInfo,const AppExecFwk::AbilityInfo & abilityInfo)11357 void AbilityManagerService::ReportPreventStartAbilityResult(const AppExecFwk::AbilityInfo &callerAbilityInfo,
11358     const AppExecFwk::AbilityInfo &abilityInfo)
11359 {
11360     int32_t callerUid = IPCSkeleton::GetCallingUid();
11361     int32_t callerPid = IPCSkeleton::GetCallingPid();
11362     int32_t extensionAbilityType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
11363     TAG_LOGD(AAFwkTag::ABILITYMGR,
11364         "Prevent start ability debug log CALLER_BUNDLE_NAME %{public}s CALLEE_BUNDLE_NAME"
11365         "%{public}s ABILITY_NAME %{public}s",
11366         callerAbilityInfo.bundleName.c_str(), abilityInfo.name.c_str(), abilityInfo.name.c_str());
11367     HiSysEventWrite(HiSysEvent::Domain::AAFWK, "PREVENT_START_ABILITY", HiSysEvent::EventType::BEHAVIOR,
11368         "CALLER_UID", callerUid,
11369         "CALLER_PID", callerPid,
11370         "CALLER_PROCESS_NAME", callerAbilityInfo.process,
11371         "CALLER_BUNDLE_NAME", callerAbilityInfo.bundleName,
11372         "CALLEE_BUNDLE_NAME", abilityInfo.bundleName,
11373         "CALLEE_PROCESS_NAME", abilityInfo.process,
11374         "EXTENSION_ABILITY_TYPE", extensionAbilityType,
11375         "ABILITY_NAME", abilityInfo.name);
11376 }
11377 
IsInWhiteList(const std::string & callerBundleName,const std::string & calleeBundleName,const std::string & calleeAbilityName)11378 bool AbilityManagerService::IsInWhiteList(const std::string &callerBundleName, const std::string &calleeBundleName,
11379     const std::string &calleeAbilityName)
11380 {
11381     std::lock_guard<std::mutex> locker(whiteListMutex_);
11382     std::map<std::string, std::list<std::string>>::iterator iter = whiteListMap_.find(callerBundleName);
11383     std::string uri = calleeBundleName + "/" + calleeAbilityName;
11384     if (iter != whiteListMap_.end()) {
11385         if (std::find(std::begin(iter->second), std::end(iter->second), uri) != std::end(iter->second)) {
11386             return true;
11387         }
11388     }
11389     std::list<std::string>::iterator it = std::find(exportWhiteList_.begin(), exportWhiteList_.end(), uri);
11390     if (it != exportWhiteList_.end()) {
11391         return true;
11392     }
11393     return false;
11394 }
11395 
ParseJsonFromBoot(const std::string & relativePath)11396 bool AbilityManagerService::ParseJsonFromBoot(const std::string &relativePath)
11397 {
11398     nlohmann::json jsonObj;
11399     std::string absolutePath = GetConfigFileAbsolutePath(relativePath);
11400     if (ParseJsonValueFromFile(jsonObj, absolutePath) != ERR_OK) {
11401         return false;
11402     }
11403     std::lock_guard<std::mutex> locker(whiteListMutex_);
11404     nlohmann::json whiteListJsonList = jsonObj[WHITE_LIST];
11405     for (const auto& [key, value] : whiteListJsonList.items()) {
11406         if (!value.is_array()) {
11407             continue;
11408         }
11409         whiteListMap_.emplace(key, std::list<std::string>());
11410         for (const auto& it : value) {
11411             if (it.is_string()) {
11412                 whiteListMap_[key].push_back(it);
11413             }
11414         }
11415     }
11416     if (!jsonObj.contains("exposed_white_list")) {
11417         return false;
11418     }
11419     nlohmann::json exportWhiteJsonList = jsonObj["exposed_white_list"];
11420     for (const auto& it : exportWhiteJsonList) {
11421         if (it.is_string()) {
11422             exportWhiteList_.push_back(it);
11423         }
11424     }
11425     return true;
11426 }
11427 
GetConfigFileAbsolutePath(const std::string & relativePath)11428 std::string AbilityManagerService::GetConfigFileAbsolutePath(const std::string &relativePath)
11429 {
11430     if (relativePath.empty()) {
11431         TAG_LOGE(AAFwkTag::ABILITYMGR, "relativePath is empty");
11432         return "";
11433     }
11434     char buf[PATH_MAX];
11435     char *tmpPath = GetOneCfgFile(relativePath.c_str(), buf, PATH_MAX);
11436     char absolutePath[PATH_MAX] = {0};
11437     if (!tmpPath || strlen(tmpPath) > PATH_MAX || !realpath(tmpPath, absolutePath)) {
11438         TAG_LOGE(AAFwkTag::ABILITYMGR, "get file fail.");
11439         return "";
11440     }
11441     return std::string(absolutePath);
11442 }
11443 
ParseJsonValueFromFile(nlohmann::json & value,const std::string & filePath)11444 int32_t AbilityManagerService::ParseJsonValueFromFile(nlohmann::json &value, const std::string &filePath)
11445 {
11446     std::ifstream fin;
11447     std::string realPath;
11448     if (!ConvertFullPath(filePath, realPath)) {
11449         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get real path failed");
11450         return ERR_INVALID_VALUE;
11451     }
11452     fin.open(realPath, std::ios::in);
11453     if (!fin.is_open()) {
11454         TAG_LOGE(AAFwkTag::ABILITYMGR, "cannot open file %{private}s", realPath.c_str());
11455         return ERR_INVALID_VALUE;
11456     }
11457     char buffer[MAX_BUFFER];
11458     std::ostringstream os;
11459     while (fin.getline(buffer, MAX_BUFFER)) {
11460         os << buffer;
11461     }
11462     const std::string data = os.str();
11463     value = nlohmann::json::parse(data, nullptr, false);
11464     if (value.is_discarded()) {
11465         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed due to data is discarded");
11466         return ERR_INVALID_VALUE;
11467     }
11468     return ERR_OK;
11469 }
11470 
ConvertFullPath(const std::string & partialPath,std::string & fullPath)11471 bool AbilityManagerService::ConvertFullPath(const std::string& partialPath, std::string& fullPath)
11472 {
11473     if (partialPath.empty() || partialPath.length() >= PATH_MAX) {
11474         return false;
11475     }
11476     char tmpPath[PATH_MAX] = {0};
11477     if (realpath(partialPath.c_str(), tmpPath) == nullptr) {
11478         return false;
11479     }
11480     fullPath = tmpPath;
11481     return true;
11482 }
11483 
StartShortcut(const Want & want,const StartOptions & startOptions)11484 int32_t AbilityManagerService::StartShortcut(const Want &want, const StartOptions &startOptions)
11485 {
11486     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11487     if (!PermissionVerification::GetInstance()->IsSystemAppCall()) {
11488         TAG_LOGE(AAFwkTag::ABILITYMGR, "non-system app calling system api.");
11489         return ERR_NOT_SYSTEM_APP;
11490     }
11491     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
11492         PermissionConstants::PERMISSION_START_SHORTCUT)) {
11493         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission %{public}s verification failed.",
11494             PermissionConstants::PERMISSION_START_SHORTCUT);
11495         return ERR_PERMISSION_DENIED;
11496     }
11497     AbilityUtil::RemoveShowModeKey(const_cast<Want &>(want));
11498     return StartUIAbilityForOptionWrap(want, startOptions, nullptr, false, DEFAULT_INVAL_VALUE, DEFAULT_INVAL_VALUE,
11499         0, false, true);
11500 }
11501 
GetAbilityStateByPersistentId(int32_t persistentId,bool & state)11502 int32_t AbilityManagerService::GetAbilityStateByPersistentId(int32_t persistentId, bool &state)
11503 {
11504     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11505     if (!CheckCallerIsDmsProcess()) {
11506         TAG_LOGE(AAFwkTag::ABILITYMGR, "GetAbilityStateByPersistentId, caller is not dms.");
11507         return ERR_PERMISSION_DENIED;
11508     }
11509 
11510     if (Rosen::SceneBoardJudgement::IsSceneBoardEnabled()) {
11511         auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
11512         CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11513         return uiAbilityManager->GetAbilityStateByPersistentId(persistentId, state);
11514     }
11515     TAG_LOGE(AAFwkTag::ABILITYMGR, "GetAbilityStateByPersistentId, mission not have persistent id.");
11516     return INNER_ERR;
11517 }
11518 
TransferAbilityResultForExtension(const sptr<IRemoteObject> & callerToken,int32_t resultCode,const Want & want)11519 int32_t AbilityManagerService::TransferAbilityResultForExtension(const sptr<IRemoteObject> &callerToken,
11520     int32_t resultCode, const Want &want)
11521 {
11522     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11523     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
11524     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
11525     if (!JudgeSelfCalled(abilityRecord)) {
11526         TAG_LOGE(AAFwkTag::ABILITYMGR, "Caller mismatch.");
11527         return ERR_INVALID_VALUE;
11528     }
11529     auto type = abilityRecord->GetAbilityInfo().type;
11530     if (type != AppExecFwk::AbilityType::EXTENSION) {
11531         TAG_LOGE(AAFwkTag::ABILITYMGR, "type is not uiextension.");
11532         return ERR_INVALID_VALUE;
11533     }
11534     // save result to caller AbilityRecord.
11535     Want* newWant = const_cast<Want*>(&want);
11536     newWant->RemoveParam(Want::PARAM_RESV_CALLER_TOKEN);
11537     abilityRecord->SaveResultToCallers(resultCode, newWant);
11538     abilityRecord->SendResultToCallers();
11539     return ERR_OK;
11540 }
11541 
GetRunningMultiAppIndex(const std::string & bundleName,int32_t uid,int32_t & appIndex)11542 void AbilityManagerService::GetRunningMultiAppIndex(const std::string &bundleName, int32_t uid, int32_t &appIndex)
11543 {
11544     AppExecFwk::RunningMultiAppInfo runningMultiAppInfo;
11545     auto appMgr = GetAppMgr();
11546     if (appMgr == nullptr) {
11547         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetAppMgr failed");
11548         return;
11549     }
11550     auto ret = IN_PROCESS_CALL(appMgr->GetRunningMultiAppInfoByBundleName(bundleName, runningMultiAppInfo));
11551     if (ret != ERR_OK) {
11552         TAG_LOGW(AAFwkTag::ABILITYMGR, "GetRunningMultiAppInfo failed bundleName = %{public}s",
11553             bundleName.c_str());
11554     }
11555     for (auto &item : runningMultiAppInfo.runningAppClones) {
11556         if (item.uid == uid) {
11557             appIndex = item.appCloneIndex;
11558             break;
11559         }
11560     }
11561 }
11562 
NotifyFrozenProcessByRSS(const std::vector<int32_t> & pidList,int32_t uid)11563 void AbilityManagerService::NotifyFrozenProcessByRSS(const std::vector<int32_t> &pidList, int32_t uid)
11564 {
11565     if (!PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(RSS_PROCESS_NAME)) {
11566         TAG_LOGE(AAFwkTag::ABILITYMGR, "caller is not RSS.");
11567         return;
11568     }
11569     auto userId = uid / BASE_USER_RANGE;
11570     auto connectManager = GetConnectManagerByUserId(userId);
11571     CHECK_POINTER_LOG(connectManager, "can not find user connect manager");
11572     connectManager->HandleProcessFrozen(pidList, uid);
11573 }
11574 
HandleRestartResidentProcessDependedOnWeb()11575 void AbilityManagerService::HandleRestartResidentProcessDependedOnWeb()
11576 {
11577     TAG_LOGD(AAFwkTag::ABILITYMGR, "call");
11578     auto appMgr = GetAppMgr();
11579     CHECK_POINTER_LOG(appMgr, "get appMgr fail");
11580     appMgr->RestartResidentProcessDependedOnWeb();
11581 }
11582 
PreStartMission(const std::string & bundleName,const std::string & moduleName,const std::string & abilityName,const std::string & startTime)11583 int32_t AbilityManagerService::PreStartMission(const std::string& bundleName, const std::string& moduleName,
11584     const std::string& abilityName, const std::string& startTime)
11585 {
11586     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
11587     CHECK_CALLER_IS_SYSTEM_APP;
11588 
11589     if (!PermissionVerification::GetInstance()->VerifyPreStartAtomicServicePermission()) {
11590         TAG_LOGE(AAFwkTag::ABILITYMGR, "calling user is not ag.");
11591         return ERR_PERMISSION_DENIED;
11592     }
11593 
11594     if (!freeInstallManager_) {
11595         TAG_LOGE(AAFwkTag::ABILITYMGR, "freeInstallManager_ is nullptr.");
11596         return ERR_INVALID_VALUE;
11597     }
11598 
11599     FreeInstallInfo taskInfo;
11600     if (!freeInstallManager_->GetFreeInstallTaskInfo(bundleName, abilityName, startTime, taskInfo)) {
11601         TAG_LOGE(AAFwkTag::ABILITYMGR,
11602             "failed to find free install task info:bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
11603             bundleName.c_str(), abilityName.c_str(), startTime.c_str());
11604         return ERR_FREE_INSTALL_TASK_NOT_EXIST;
11605     }
11606 
11607     if (taskInfo.isFreeInstallFinished) {
11608         TAG_LOGI(AAFwkTag::ABILITYMGR, "free install is finished.");
11609         if (!taskInfo.isInstalled) {
11610             TAG_LOGE(AAFwkTag::ABILITYMGR, "free install task failed,resultCode=%{public}d",
11611                 taskInfo.resultCode);
11612         } else {
11613             TAG_LOGI(AAFwkTag::ABILITYMGR, "free install has succeeded.");
11614         }
11615         // if free install is already finished then either the window is opened (on success)
11616         // or the user is informed of the error (on failure).
11617         return taskInfo.resultCode;
11618     }
11619 
11620     return PreStartInner(taskInfo);
11621 }
11622 
PreStartInner(const FreeInstallInfo & taskInfo)11623 int32_t AbilityManagerService::PreStartInner(const FreeInstallInfo& taskInfo)
11624 {
11625     TAG_LOGD(AAFwkTag::ABILITYMGR, "called");
11626 
11627     const Want& want = taskInfo.want;
11628     sptr<IRemoteObject> callerToken = taskInfo.callerToken;
11629 
11630     EventInfo eventInfo = BuildEventInfo(want, taskInfo.userId);
11631     SendAbilityEvent(EventName::START_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
11632 
11633     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
11634         eventInfo.errCode = ERR_INVALID_VALUE;
11635         SendAbilityEvent(EventName::START_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
11636         return ERR_INVALID_CALLER;
11637     }
11638 
11639     int32_t oriValidUserId = GetValidUserId(taskInfo.userId);
11640 
11641     int32_t appIndex = 0;
11642     StartAbilityInfoWrap threadLocalInfo(want, oriValidUserId,
11643         StartAbilityUtils::GetAppIndex(want, callerToken, appIndex), callerToken);
11644 
11645     AbilityRequest abilityRequest = {
11646         .want = want,
11647         .requestCode = taskInfo.requestCode,
11648         .callerToken = callerToken,
11649         .startSetting = nullptr
11650     };
11651 
11652     TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
11653     UpdateCallerInfo(abilityRequest.want, callerToken);
11654 
11655     // sceneboard
11656     abilityRequest.userId = oriValidUserId;
11657     abilityRequest.want.SetParam(IS_CALL_BY_SCB, false);
11658     std::string sessionId = std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(
11659         std::chrono::system_clock::now().time_since_epoch()).count());
11660     abilityRequest.want.SetParam(KEY_SESSION_ID, sessionId);
11661     auto uiAbilityManager = GetUIAbilityManagerByUserId(oriValidUserId);
11662     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11663     sptr<SessionInfo> sessionInfo = nullptr;
11664     auto errCode = uiAbilityManager->NotifySCBToPreStartUIAbility(abilityRequest, sessionInfo);
11665     if (errCode != ERR_OK) {
11666         TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to notify sceneboard to pre-start uiability.");
11667         return errCode;
11668     }
11669     freeInstallManager_->SetFreeInstallTaskSessionId(taskInfo.want.GetElement().GetBundleName(),
11670         taskInfo.want.GetElement().GetAbilityName(),
11671         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME), sessionId);
11672 
11673     freeInstallManager_->SetPreStartMissionCallStatus(taskInfo.want.GetElement().GetBundleName(),
11674         taskInfo.want.GetElement().GetAbilityName(),
11675         taskInfo.want.GetStringParam(Want::PARAM_RESV_START_TIME),
11676         true);
11677     return ERR_OK;
11678 }
11679 
StartUIAbilityByPreInstall(const FreeInstallInfo & taskInfo)11680 int32_t AbilityManagerService::StartUIAbilityByPreInstall(const FreeInstallInfo &taskInfo)
11681 {
11682     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11683     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
11684     if (!taskInfo.isFreeInstallFinished || !taskInfo.isInstalled) {
11685         TAG_LOGE(AAFwkTag::ABILITYMGR, "free install is not finished or has failed.");
11686         return ERR_INVALID_VALUE;
11687     }
11688     if (!taskInfo.isStartUIAbilityBySCBCalled) {
11689         TAG_LOGI(AAFwkTag::ABILITYMGR, "Free install is finished, StartUIAbilityBySCB has not been called");
11690         return ERR_OK;
11691     }
11692 
11693     const auto& want = taskInfo.want;
11694     auto sessionId = want.GetStringParam(KEY_SESSION_ID);
11695     if (sessionId.empty()) {
11696         TAG_LOGE(AAFwkTag::ABILITYMGR, "session id is empty.");
11697         return ERR_INVALID_VALUE;
11698     }
11699     auto bundleName = want.GetElement().GetBundleName();
11700     auto abilityName = want.GetElement().GetAbilityName();
11701     auto startTime = want.GetStringParam(Want::PARAM_RESV_START_TIME);
11702     TAG_LOGI(AAFwkTag::ABILITYMGR, "called"
11703         "sessionId=%{public}s,bundleName=%{public}s,abilityName=%{public}s,startTime=%{public}s",
11704         sessionId.c_str(), bundleName.c_str(), abilityName.c_str(), startTime.c_str());
11705     sptr<SessionInfo> sessionInfo = nullptr;
11706     {
11707         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
11708         auto it = preStartSessionMap_.find(sessionId);
11709         if (it == preStartSessionMap_.end()) {
11710             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s",
11711                 sessionId.c_str());
11712             return ERR_INVALID_VALUE;
11713         }
11714         sessionInfo = it->second;
11715         (sessionInfo->want).SetElement(want.GetElement());
11716     }
11717 
11718     if (sessionInfo == nullptr || sessionInfo->isMinimizedDuringFreeInstall) {
11719         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr or ability is already minimized");
11720         RemovePreStartSession(sessionId);
11721         return ERR_INVALID_VALUE;
11722     }
11723 
11724     int errCode = ERR_OK;
11725     bool isColdStart = true;
11726     if ((errCode = StartUIAbilityByPreInstallInner(sessionInfo, taskInfo.specifyTokenId, 0, isColdStart)) != ERR_OK) {
11727         TAG_LOGE(AAFwkTag::ABILITYMGR, "StartUIAbilityByPreInstallInner failed,errCode=%{public}d.", errCode);
11728     }
11729     RemovePreStartSession(sessionId);
11730     return errCode;
11731 }
11732 
11733 // StartUIAbilityByPreInstallInner is called when free install task is already finished
StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo,uint32_t specifyTokenId,uint32_t sceneFlag,bool & isColdStart)11734 int AbilityManagerService::StartUIAbilityByPreInstallInner(sptr<SessionInfo> sessionInfo, uint32_t specifyTokenId,
11735     uint32_t sceneFlag, bool &isColdStart)
11736 {
11737     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
11738     auto callerToken = sessionInfo->callerToken;
11739     const auto& want = sessionInfo->want;
11740     const auto userId = sessionInfo->userId;
11741     const auto requestCode = sessionInfo->requestCode;
11742     bool isStartAsCaller = false;
11743 
11744     if (callerToken != nullptr && !VerificationAllToken(callerToken)) {
11745         auto isSpecificSA = AAFwk::PermissionVerification::GetInstance()->
11746             CheckSpecificSystemAbilityAccessPermission(DMS_PROCESS_NAME);
11747         if (!isSpecificSA) {
11748             TAG_LOGE(AAFwkTag::ABILITYMGR, "%{public}s VerificationAllToken failed.", __func__);
11749             return ERR_INVALID_CALLER;
11750         }
11751         TAG_LOGI(AAFwkTag::ABILITYMGR, "%{public}s: Caller is specific system ability.", __func__);
11752     }
11753 
11754     int32_t oriValidUserId = GetValidUserId(userId);
11755     int32_t validUserId = oriValidUserId;
11756 
11757     int32_t appIndex = 0;
11758     if (!StartAbilityUtils::GetAppIndex(want, callerToken, appIndex)) {
11759         return ERR_APP_CLONE_INDEX_INVALID;
11760     }
11761     StartAbilityInfoWrap threadLocalInfo(want, validUserId, appIndex, callerToken);
11762     AbilityInterceptorParam interceptorParam = AbilityInterceptorParam(want, requestCode, GetUserId(),
11763         true, nullptr);
11764     auto result = interceptorExecuter_ == nullptr ? ERR_INVALID_VALUE :
11765         interceptorExecuter_->DoProcess(interceptorParam);
11766     if (result != ERR_OK) {
11767         TAG_LOGE(AAFwkTag::ABILITYMGR, "interceptorExecuter_ is nullptr or DoProcess return error.");
11768         return result;
11769     }
11770 
11771     AbilityRequest abilityRequest;
11772     result = GenerateAbilityRequest(want, requestCode, abilityRequest, callerToken, validUserId);
11773     auto abilityRecord = Token::GetAbilityRecordByToken(callerToken);
11774     std::string callerBundleName = abilityRecord ? abilityRecord->GetAbilityInfo().bundleName : "";
11775 
11776     if (result != ERR_OK) {
11777         TAG_LOGE(AAFwkTag::ABILITYMGR, "Generate ability request local error.");
11778         return result;
11779     }
11780 
11781     if (specifyTokenId > 0 && callerToken != nullptr) { // for sa specify tokenId and caller token
11782         UpdateCallerInfoFromToken(abilityRequest.want, callerToken);
11783     } else if (!isStartAsCaller) {
11784         TAG_LOGD(AAFwkTag::ABILITYMGR, "do not start as caller, UpdateCallerInfo");
11785         UpdateCallerInfo(abilityRequest.want, callerToken);
11786     } else if (callerBundleName == BUNDLE_NAME_DIALOG) {
11787 #ifdef SUPPORT_SCREEN
11788         CHECK_POINTER_AND_RETURN(implicitStartProcessor_, ERR_IMPLICIT_START_ABILITY_FAIL);
11789         implicitStartProcessor_->ResetCallingIdentityAsCaller(
11790             abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), true);
11791 #endif // SUPPORT_SCREEN
11792     }
11793 
11794     auto abilityInfo = abilityRequest.abilityInfo;
11795     validUserId = abilityInfo.applicationInfo.singleton ? U0_USER_ID : validUserId;
11796     TAG_LOGD(AAFwkTag::ABILITYMGR, "userId is : %{public}d, singleton is : %{public}d",
11797         validUserId, static_cast<int>(abilityInfo.applicationInfo.singleton));
11798 
11799     result = CheckStaticCfgPermission(abilityRequest, isStartAsCaller,
11800         abilityRequest.want.GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, 0), false, false, false);
11801     if (result != AppExecFwk::Constants::PERMISSION_GRANTED) {
11802         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckStaticCfgPermission error, result is %{public}d.", result);
11803         return ERR_STATIC_CFG_PERMISSION;
11804     }
11805 
11806     result = CheckCallPermission(want, abilityInfo, abilityRequest, false,
11807         false, specifyTokenId, callerBundleName);
11808     if (result != ERR_OK) {
11809         TAG_LOGE(AAFwkTag::ABILITYMGR, "CheckCallPermission error, result is %{public}d.", result);
11810         return result;
11811     }
11812 
11813     Want newWant = abilityRequest.want;
11814     AbilityInterceptorParam afterCheckParam = AbilityInterceptorParam(newWant, requestCode, GetUserId(),
11815         true, callerToken, std::make_shared<AppExecFwk::AbilityInfo>(abilityInfo), isStartAsCaller, appIndex);
11816     result = afterCheckExecuter_ == nullptr ? ERR_INVALID_VALUE :
11817         afterCheckExecuter_->DoProcess(afterCheckParam);
11818     bool isReplaceWantExist = newWant.GetBoolParam("queryWantFromErms", false);
11819     newWant.RemoveParam("queryWantFromErms");
11820     if (result != ERR_OK && isReplaceWantExist == false) {
11821         TAG_LOGE(AAFwkTag::ABILITYMGR, "DoProcess failed or replaceWant not exist");
11822         return result;
11823     }
11824 #ifdef SUPPORT_SCREEN
11825     if (result != ERR_OK && isReplaceWantExist && callerBundleName != BUNDLE_NAME_DIALOG) {
11826         return DialogSessionManager::GetInstance().HandleErmsResult(abilityRequest, GetUserId(), newWant);
11827     }
11828     if (result == ERR_OK &&
11829         DialogSessionManager::GetInstance().IsCreateCloneSelectorDialog(abilityInfo.bundleName, GetUserId())) {
11830         TAG_LOGI(AAFwkTag::ABILITYMGR, "create clone selector dialog");
11831         return CreateCloneSelectorDialog(abilityRequest, GetUserId());
11832     }
11833 #endif // SUPPORT_SCREEN
11834 
11835     if (abilityInfo.type == AppExecFwk::AbilityType::SERVICE ||
11836         abilityInfo.type == AppExecFwk::AbilityType::EXTENSION) {
11837         return StartAbilityByConnectManager(want, abilityRequest, abilityInfo, validUserId, callerToken);
11838     }
11839 
11840     if (!IsAbilityControllerStart(want, abilityInfo.bundleName)) {
11841         TAG_LOGE(AAFwkTag::ABILITYMGR, "IsAbilityControllerStart failed: %{public}s.", abilityInfo.bundleName.c_str());
11842         return ERR_WOULD_BLOCK;
11843     }
11844 
11845     abilityRequest.want.RemoveParam(SPECIFY_TOKEN_ID);
11846     if (specifyTokenId > 0) {
11847         TAG_LOGD(AAFwkTag::ABILITYMGR, "Set specifyTokenId, the specifyTokenId is %{public}d.", specifyTokenId);
11848         abilityRequest.want.SetParam(SPECIFY_TOKEN_ID, static_cast<int32_t>(specifyTokenId));
11849         abilityRequest.specifyTokenId = specifyTokenId;
11850     }
11851     abilityRequest.want.RemoveParam(PARAM_SPECIFIED_PROCESS_FLAG);
11852 
11853     auto uiAbilityManager = GetCurrentUIAbilityManager();
11854     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
11855 
11856     return uiAbilityManager->StartUIAbility(abilityRequest, sessionInfo, sceneFlag, isColdStart);
11857 }
11858 
NotifySCBToHandleAtomicServiceException(const std::string & sessionId,int32_t errCode,const std::string & reason)11859 void AbilityManagerService::NotifySCBToHandleAtomicServiceException(const std::string& sessionId, int32_t errCode,
11860     const std::string& reason)
11861 {
11862     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
11863     sptr<SessionInfo> sessionInfo = nullptr;
11864     {
11865         std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
11866         auto it = preStartSessionMap_.find(sessionId);
11867         if (it == preStartSessionMap_.end()) {
11868             TAG_LOGE(AAFwkTag::ABILITYMGR, "failed to find session info with sessionId=%{public}s",
11869                 sessionId.c_str());
11870             return;
11871         }
11872         sessionInfo = it->second;
11873         preStartSessionMap_.erase(it);
11874     }
11875     if (sessionInfo == nullptr) {
11876         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is nullptr.");
11877         return;
11878     }
11879     auto uiAbilityManager = GetCurrentUIAbilityManager();
11880     CHECK_POINTER(uiAbilityManager);
11881     return uiAbilityManager->NotifySCBToHandleAtomicServiceException(sessionInfo, errCode, reason);
11882 }
11883 
RemovePreStartSession(const std::string & sessionId)11884 void AbilityManagerService::RemovePreStartSession(const std::string& sessionId)
11885 {
11886     std::lock_guard<ffrt::mutex> guard(preStartSessionMapLock_);
11887     preStartSessionMap_.erase(sessionId);
11888 }
11889 
OpenLink(const Want & want,sptr<IRemoteObject> callerToken,int32_t userId,int requestCode)11890 ErrCode AbilityManagerService::OpenLink(const Want& want, sptr<IRemoteObject> callerToken,
11891     int32_t userId, int requestCode)
11892 {
11893     TAG_LOGI(AAFwkTag::ABILITYMGR, "called");
11894     std::string url = want.GetUriString();
11895     bool isAtomicServiceShortUrl = false;
11896 #ifdef APP_DOMAIN_VERIFY_ENABLED
11897     isAtomicServiceShortUrl = AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->IsAtomicServiceUrl(url);
11898 #endif
11899     int32_t retCode = ERR_OK;
11900     if (!isAtomicServiceShortUrl) {
11901         TAG_LOGI(AAFwkTag::ABILITYMGR, "not atomic service short url, start ability by default.");
11902         retCode = StartAbility(want, callerToken, userId, requestCode);
11903         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
11904         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
11905     }
11906 
11907     Want convertedWant = want;
11908     retCode = ConvertToExplicitWant(convertedWant);
11909     if (retCode != ERR_OK) {
11910         TAG_LOGI(AAFwkTag::ABILITYMGR, "failed to convert to explicit want, start ability by default.");
11911         retCode = StartAbility(want, callerToken, userId, requestCode);
11912         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
11913         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
11914     }
11915 
11916     if (!freeInstallManager_) {
11917         TAG_LOGW(AAFwkTag::ABILITYMGR, "free install manager is nullptr, start ability by default.");
11918         retCode = StartAbility(want, callerToken, userId, requestCode);
11919         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
11920         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
11921     }
11922 
11923     convertedWant.AddFlags(Want::FLAG_INSTALL_ON_DEMAND);
11924     TAG_LOGD(AAFwkTag::ABILITYMGR, "convertedWant=%{public}s", convertedWant.ToString().c_str());
11925     retCode = freeInstallManager_->StartFreeInstall(convertedWant, GetValidUserId(userId),
11926         requestCode, callerToken, true, 0, true, std::make_shared<Want>(want));
11927     if (retCode != ERR_OK) {
11928         TAG_LOGW(AAFwkTag::ABILITYMGR, "StartFreeInstall returns errCode=%{public}d.", retCode);
11929         if (retCode == NOT_TOP_ABILITY) {
11930             TAG_LOGE(AAFwkTag::ABILITYMGR, "start from background is not allowed.");
11931             return retCode;
11932         }
11933         TAG_LOGI(AAFwkTag::ABILITYMGR, "start ability by default.");
11934         retCode = StartAbility(want, callerToken, userId, requestCode);
11935         CHECK_RET_RETURN_RET(retCode, "StartAbility failed");
11936         return ERR_OPEN_LINK_START_ABILITY_DEFAULT_OK;
11937     }
11938     return ERR_OK;
11939 }
11940 
ConvertToExplicitWant(Want & want)11941 ErrCode AbilityManagerService::ConvertToExplicitWant(Want& want)
11942 {
11943     ErrCode retCode = ERR_OK;
11944 #ifdef APP_DOMAIN_VERIFY_ENABLED
11945     auto bundleMgrHelper = GetBundleManager();
11946     if (bundleMgrHelper == nullptr) {
11947         TAG_LOGE(AAFwkTag::ABILITYMGR, "bundleMgrHelper is invalid.");
11948         return ERR_INVALID_VALUE;
11949     }
11950     int32_t callerUid = IPCSkeleton::GetCallingUid();
11951     std::string callerBundleName;
11952     retCode = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callerUid, callerBundleName));
11953     if (retCode != ERR_OK) {
11954         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get callerBundleName failed,retCode=%{public}d.", retCode);
11955         return retCode;
11956     }
11957     TAG_LOGI(AAFwkTag::ABILITYMGR, "callerBundleName=%{public}s.", callerBundleName.c_str());
11958     want.SetParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME, callerBundleName);
11959 
11960     bool isUsed = false;
11961     ffrt::condition_variable callbackDoneCv;
11962     ffrt::mutex callbackDoneMutex;
11963     ConvertCallbackTask task = [&retCode, &isUsed, &callbackDoneCv, &callbackDoneMutex,
11964         &convertedWant = want, this](int resultCode, AAFwk::Want& want) {
11965         TAG_LOGI(AAFwkTag::ABILITYMGR, "in convert callback task, resultCode=%{public}d,want=%{public}s",
11966             resultCode, want.ToString().c_str());
11967         retCode = resultCode;
11968         convertedWant = want;
11969         {
11970             std::lock_guard<ffrt::mutex> lock(callbackDoneMutex);
11971             isUsed = true;
11972         }
11973         TAG_LOGI(AAFwkTag::ABILITYMGR, "start to notify.");
11974         callbackDoneCv.notify_all();
11975         TAG_LOGI(AAFwkTag::ABILITYMGR, "convert callback task finished");
11976     };
11977     sptr<ConvertCallbackImpl> callbackTask = new ConvertCallbackImpl(std::move(task));
11978     sptr<OHOS::AppDomainVerify::IConvertCallback> callback = callbackTask;
11979     AppDomainVerify::AppDomainVerifyMgrClient::GetInstance()->ConvertToExplicitWant(want, callback);
11980     auto condition = [&isUsed] { return isUsed; };
11981     std::unique_lock<ffrt::mutex> lock(callbackDoneMutex);
11982     TAG_LOGI(AAFwkTag::ABILITYMGR, "start to wait for condition.");
11983     if (!callbackDoneCv.wait_for(lock, seconds(CONVERT_CALLBACK_TIMEOUT_SECONDS), condition)) {
11984         TAG_LOGE(AAFwkTag::ABILITYMGR, "convert callback timeout.");
11985         callbackTask->Cancel();
11986         retCode = ERR_TIMED_OUT;
11987     }
11988     TAG_LOGI(AAFwkTag::ABILITYMGR, "finish wait for condition.");
11989 #endif
11990     return retCode;
11991 }
11992 
CleanUIAbilityBySCB(const sptr<SessionInfo> & sessionInfo)11993 int32_t AbilityManagerService::CleanUIAbilityBySCB(const sptr<SessionInfo> &sessionInfo)
11994 {
11995     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
11996     if (sessionInfo == nullptr || sessionInfo->sessionToken == nullptr) {
11997         TAG_LOGE(AAFwkTag::ABILITYMGR, "sessionInfo is invalid.");
11998         return ERR_INVALID_VALUE;
11999     }
12000 
12001     if (!IsCallerSceneBoard()) {
12002         TAG_LOGE(AAFwkTag::ABILITYMGR, "only support sceneboard call.");
12003         return ERR_WRONG_INTERFACE_CALL;
12004     }
12005 
12006     SetMinimizedDuringFreeInstall(sessionInfo);
12007 
12008     auto uiAbilityManager = GetUIAbilityManagerByUid(IPCSkeleton::GetCallingUid());
12009     CHECK_POINTER_AND_RETURN(uiAbilityManager, ERR_INVALID_VALUE);
12010     TAG_LOGI(AAFwkTag::ABILITYMGR, "user request ot clean session: %{public}d.", sessionInfo->persistentId);
12011     auto abilityRecord = uiAbilityManager->GetUIAbilityRecordBySessionInfo(sessionInfo);
12012     CHECK_POINTER_AND_RETURN(abilityRecord, ERR_INVALID_VALUE);
12013     int32_t errCode = uiAbilityManager->CleanUIAbility(abilityRecord);
12014     ReportCleanSession(sessionInfo, abilityRecord, errCode);
12015     return errCode;
12016 }
12017 
ForceTerminateSerivceExtensionByPid(int32_t pid,int32_t userId)12018 void AbilityManagerService::ForceTerminateSerivceExtensionByPid(int32_t pid, int32_t userId)
12019 {
12020     std::vector<sptr<IRemoteObject>> tokens;
12021     IN_PROCESS_CALL_WITHOUT_RET(DelayedSingleton<AppScheduler>::GetInstance()->GetAbilityRecordsByProcessID(
12022         pid, tokens));
12023     auto connectManager = GetConnectManagerByUserId(userId);
12024     if (connectManager) {
12025         for (const auto& token : tokens) {
12026             auto abilityRecord = Token::GetAbilityRecordByToken(token);
12027             if (abilityRecord &&
12028                 abilityRecord->GetAbilityInfo().extensionAbilityType ==
12029                 AppExecFwk::ExtensionAbilityType::SERVICE) {
12030                 TAG_LOGI(AAFwkTag::ABILITYMGR, "app ForceTerminateSerivceExtensionByPid, pid is %{public}d", pid);
12031                 connectManager->TerminateAbility(token);
12032             }
12033         }
12034     }
12035 }
12036 
ReportCleanSession(const sptr<SessionInfo> & sessionInfo,const std::shared_ptr<AbilityRecord> & abilityRecord,int32_t errCode)12037 void AbilityManagerService::ReportCleanSession(const sptr<SessionInfo> &sessionInfo,
12038     const std::shared_ptr<AbilityRecord> &abilityRecord, int32_t errCode)
12039 {
12040     if (!sessionInfo || !abilityRecord) {
12041         return;
12042     }
12043 
12044     const auto &abilityInfo = abilityRecord->GetAbilityInfo();
12045     std::string abilityName = abilityInfo.name;
12046     if (abilityInfo.launchMode == AppExecFwk::LaunchMode::STANDARD) {
12047         abilityName += std::to_string(sessionInfo->persistentId);
12048     }
12049     (void)DelayedSingleton<AbilityRuntime::AppExitReasonDataManager>::GetInstance()->
12050         DeleteAbilityRecoverInfo(abilityInfo.applicationInfo.accessTokenId, abilityInfo.moduleName, abilityName);
12051 
12052     EventInfo eventInfo;
12053     eventInfo.errCode = errCode;
12054     eventInfo.bundleName = abilityRecord->GetAbilityInfo().bundleName;
12055     eventInfo.abilityName = abilityRecord->GetAbilityInfo().name;
12056     SendAbilityEvent(EventName::CLOSE_ABILITY, HiSysEventType::BEHAVIOR, eventInfo);
12057     if (eventInfo.errCode != ERR_OK) {
12058         SendAbilityEvent(EventName::TERMINATE_ABILITY_ERROR, HiSysEventType::FAULT, eventInfo);
12059     }
12060 }
12061 
SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo & abilityInfo,const Want & want,uint32_t specifyTokenId)12062 void AbilityManagerService::SendStartAbilityOtherExtensionEvent(const AppExecFwk::AbilityInfo& abilityInfo,
12063     const Want& want, uint32_t specifyTokenId)
12064 {
12065     if (abilityInfo.type == AppExecFwk::AbilityType::EXTENSION &&
12066         abilityInfo.extensionAbilityType != AppExecFwk::ExtensionAbilityType::SERVICE) {
12067         EventInfo eventInfo;
12068         eventInfo.bundleName = abilityInfo.bundleName;
12069         eventInfo.moduleName = abilityInfo.moduleName;
12070         eventInfo.abilityName = abilityInfo.name;
12071         eventInfo.extensionType = static_cast<int32_t>(abilityInfo.extensionAbilityType);
12072         if (specifyTokenId > 0) {
12073             // come from want agent or form
12074             Security::AccessToken::HapTokenInfo hapInfo;
12075             if (Security::AccessToken::AccessTokenKit::GetHapTokenInfo(specifyTokenId, hapInfo) == ERR_OK) {
12076                 eventInfo.callerBundleName = hapInfo.bundleName;
12077             }
12078         } else {
12079             eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
12080             if (eventInfo.callerBundleName.empty()) {
12081                 eventInfo.callerBundleName = want.GetStringParam(Want::PARAM_RESV_CALLER_NATIVE_NAME);
12082             }
12083         }
12084         TAG_LOGI(AAFwkTag::ABILITYMGR,
12085             "SendStartAbilityOtherExtensionEvent, bundleName:%{public}s, extensionAbilityType:%{public}d",
12086             eventInfo.bundleName.c_str(), eventInfo.extensionType);
12087         EventReport::SendStartAbilityOtherExtensionEvent(EventName::START_ABILITY_OTHER_EXTENSION, eventInfo);
12088     }
12089 }
12090 
TerminateMission(int32_t missionId)12091 int32_t AbilityManagerService::TerminateMission(int32_t missionId)
12092 {
12093     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
12094     TAG_LOGI(AAFwkTag::ABILITYMGR, "TerminateMission call");
12095     auto missionListManager = GetCurrentMissionListManager();
12096     CHECK_POINTER_AND_RETURN(missionListManager, ERR_NO_INIT);
12097     CHECK_CALLER_IS_SYSTEM_APP;
12098 
12099     if (!PermissionVerification::GetInstance()->VerifyCallingPermission(
12100         PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
12101         TAG_LOGE(AAFwkTag::ABILITYMGR, "Permission verification failed");
12102         return CHECK_PERMISSION_FAILED;
12103     }
12104 
12105     return missionListManager->ClearMission(missionId);
12106 }
12107 
EnableListForSCBRecovery(int32_t userId) const12108 void AbilityManagerService::EnableListForSCBRecovery(int32_t userId) const
12109 {
12110     auto uiAbilityManager = GetUIAbilityManagerByUserId(userId);
12111     CHECK_POINTER_LOG(uiAbilityManager, "UIAbilityMgr not exist.");
12112     uiAbilityManager->EnableListForSCBRecovery();
12113 }
12114 
UpdateKeepAliveEnableState(const std::string & bundleName,const std::string & moduleName,const std::string & mainElement,bool updateEnable,int32_t userId)12115 int32_t AbilityManagerService::UpdateKeepAliveEnableState(const std::string &bundleName,
12116     const std::string &moduleName, const std::string &mainElement, bool updateEnable, int32_t userId)
12117 {
12118     auto connectManager = GetConnectManagerByUserId(userId);
12119     CHECK_POINTER_AND_RETURN(connectManager, ERR_NULL_OBJECT);
12120     int32_t ret = connectManager->UpdateKeepAliveEnableState(bundleName, moduleName, mainElement, updateEnable);
12121     if (ret != ERR_OK) {
12122         TAG_LOGE(AAFwkTag::ABILITYMGR, "UpdateKeepAliveEnableState failed, err:%{public}d", ret);
12123     }
12124     return ret;
12125 }
12126 
UpdateAssociateConfigList(const std::map<std::string,std::list<std::string>> & configs,const std::list<std::string> & exportConfigs,int32_t flag)12127 int32_t AbilityManagerService::UpdateAssociateConfigList(const std::map<std::string, std::list<std::string>>& configs,
12128     const std::list<std::string>& exportConfigs, int32_t flag)
12129 {
12130     if (IPCSkeleton::GetCallingUid() != RESOURCE_SCHEDULE_UID) {
12131         TAG_LOGE(AAFwkTag::ABILITYMGR, "Update associate config, current process not rss process");
12132         return CHECK_PERMISSION_FAILED;
12133     }
12134     std::lock_guard<std::mutex> locker(whiteListMutex_);
12135     if (flag == UPDATE_CONFIG_FLAG_COVER) {
12136         whiteListMap_ = configs;
12137         exportWhiteList_ = exportConfigs;
12138     } else if (flag == UPDATE_CONFIG_FLAG_APPEND) {
12139         for (const auto& config : configs) {
12140             for (const auto& item : config.second) {
12141                 whiteListMap_[config.first].push_back(item);
12142             }
12143         }
12144         for (const auto& config : exportConfigs) {
12145             exportWhiteList_.push_back(config);
12146         }
12147     }
12148     return ERR_OK;
12149 }
12150 }  // namespace AAFwk
12151 }  // namespace OHOS
12152