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