• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "app_mgr_service_inner.h"
17 
18 #include <cctype>
19 #include <cinttypes>
20 #include <csignal>
21 #include <cstdint>
22 #include <cerrno>
23 #include <mutex>
24 #include <queue>
25 #include <securec.h>
26 #include <sstream>
27 #include <sys/stat.h>
28 #include <unistd.h>
29 
30 #include "ability_manager_errors.h"
31 #include "ability_window_configuration.h"
32 #include "accesstoken_kit.h"
33 #include "app_config_data_manager.h"
34 #include "app_mem_info.h"
35 #include "app_mgr_service.h"
36 #include "app_mgr_event.h"
37 #include "app_process_data.h"
38 #include "app_state_observer_manager.h"
39 #include "app_utils.h"
40 #include "appfreeze_manager.h"
41 #include "application_state_observer_stub.h"
42 #include "appspawn_util.h"
43 #include "bundle_constants.h"
44 #include "bundle_mgr_helper.h"
45 #include "common_event.h"
46 #include "common_event_manager.h"
47 #include "common_event_support.h"
48 #include "datetime_ex.h"
49 #include "distributed_data_mgr.h"
50 #include "extension_ability_info.h"
51 #include "ffrt.h"
52 #include "freeze_util.h"
53 #include "global_constant.h"
54 #include "hap_token_info.h"
55 #include "hilog_tag_wrapper.h"
56 #include "hitrace_meter.h"
57 #include "in_process_call_wrapper.h"
58 #include "ipc_skeleton.h"
59 #include "iremote_object.h"
60 #include "iservice_registry.h"
61 #include "itest_observer.h"
62 #include "killing_process_manager.h"
63 #include "last_exit_detail_info.h"
64 #include "os_account_manager.h"
65 #include "app_native_spawn_manager.h"
66 #ifdef SUPPORT_SCREEN
67 #include "locale_config.h"
68 #endif
69 #include "mem_mgr_client.h"
70 #include "mem_mgr_process_state_info.h"
71 #include "os_account_manager_wrapper.h"
72 #ifdef OHOS_ACCOUNT_ENABLED
73 #include "ohos_account_kits.h"
74 #endif // OHOS_ACCOUNT_ENABLED
75 #include "parameter.h"
76 #include "parameters.h"
77 #include "perf_profile.h"
78 #include "permission_constants.h"
79 #include "permission_verification.h"
80 #include "record_cost_time_util.h"
81 #include "render_state_observer_manager.h"
82 #include "res_sched_util.h"
83 #include "startup_util.h"
84 #include "string_ex.h"
85 #ifdef ABILITY_RUNTIME_FEATURE_SANDBOXMANAGER
86 #include "sandbox_manager_kit.h"
87 #endif
88 #include "system_ability_definition.h"
89 #include "time_util.h"
90 #include "ui_extension_utils.h"
91 #ifdef SUPPORT_UPMS
92 #include "uri_permission_manager_client.h"
93 #endif // SUPPORT_UPMS
94 #include "user_record_manager.h"
95 #ifdef APP_MGR_SERVICE_APPMS
96 #include "net_conn_client.h"
97 #endif
98 #include "application_info.h"
99 #include "meminfo.h"
100 #include "app_mgr_service_const.h"
101 #include "app_mgr_service_dump_error_code.h"
102 #include "param.h"
103 #include "window_focus_changed_listener.h"
104 #include "window_visibility_changed_listener.h"
105 #include "window_pid_visibility_changed_listener.h"
106 #include "cache_process_manager.h"
107 #include "res_sched_util.h"
108 #include "session_manager_lite.h"
109 #ifdef APP_NO_RESPONSE_DIALOG
110 #include "fault_data.h"
111 #include "modal_system_app_freeze_uiextension.h"
112 #endif
113 #ifdef APP_MGR_SERVICE_HICOLLIE_ENABLE
114 #include "xcollie/xcollie.h"
115 #include "xcollie/xcollie_define.h"
116 #endif
117 
118 namespace OHOS {
119 namespace AppExecFwk {
120 #ifdef SUPPORT_SCREEN
121 using namespace OHOS::Rosen;
122 #endif //SUPPORT_SCREEN
123 using namespace OHOS::Security;
124 using namespace OHOS::Rosen;
125 
126 namespace {
127 #define CHECK_CALLER_IS_SYSTEM_APP                                                             \
128     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
129         TAG_LOGE(AAFwkTag::APPMGR, "can't use SA");    \
130         return AAFwk::ERR_NOT_SYSTEM_APP;                                                      \
131     }
132 
133 #define CHECK_IS_SA_CALL(listener)                                                                              \
134     auto instance = AAFwk::PermissionVerification::GetInstance();                                               \
135     if ((listener) == nullptr || instance == nullptr || appRunningStatusModule_ == nullptr) {                     \
136         TAG_LOGE(AAFwkTag::APPMGR, "null listener, getInstance or appRunningStatusModule_"); \
137         return ERR_INVALID_VALUE;                                                                               \
138     }                                                                                                           \
139     if (!instance->IsSACall()) {                                                                                \
140         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not SA");                                                      \
141         return ERR_PERMISSION_DENIED;                                                                           \
142     }
143 
144 #define CHECK_POINTER_AND_RETURN_LOG(object, log)      \
145     if (!object) {                                     \
146         TAG_LOGE(AAFwkTag::APPMGR, "%{public}s", log); \
147         return;                                        \
148     }
149 
150 #define CHECK_POINTER_AND_RETURN_VALUE(object, value) \
151     if (!object) {                              \
152         TAG_LOGE(AAFwkTag::APPMGR, "nullptr");  \
153         return value;                           \
154     }
155 
156 // NANOSECONDS mean 10^9 nano second
157 constexpr int64_t NANOSECONDS = 1000000000;
158 // MICROSECONDS mean 10^6 milli second
159 constexpr int64_t MICROSECONDS = 1000000;
160 // Kill process timeout setting
161 constexpr int KILL_PROCESS_TIMEOUT_MICRO_SECONDS = 1000;
162 // Kill process delay time setting
163 constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200;
164 // kill process for logout user time out setting
165 constexpr int LOGOUT_USER_TIMEOUT_MILLISION_SECONDS = 5000;
166 // delay register focus listener to wms
167 constexpr int REGISTER_FOCUS_DELAY = 5000;
168 constexpr int REGISTER_VISIBILITY_DELAY = 5000;
169 constexpr int REGISTER_PID_VISIBILITY_DELAY = 5000;
170 // Max render process number limitation for phone device.
171 constexpr int PHONE_MAX_RENDER_PROCESS_NUM = 40;
172 constexpr int PROCESS_RESTART_MARGIN_MICRO_SECONDS = 2000;
173 constexpr int32_t DFX_TASKWORKER_NUM = 2;
174 constexpr int32_t RSS_TASKWORKER_NUM = 3;
175 constexpr const int32_t API10 = 10;
176 constexpr const int32_t API15 = 15;
177 constexpr const int32_t API_VERSION_MOD = 100;
178 constexpr const int32_t U0_USER_ID = 0;
179 constexpr const int32_t U1_USER_ID = 1;
180 constexpr const char* CLASS_NAME = "ohos.app.MainThread";
181 constexpr const char* FUNC_NAME = "main";
182 constexpr const char* RENDER_PARAM = "invalidparam";
183 constexpr const char* COLD_START = "coldStart";
184 constexpr const char* PERF_CMD = "perfCmd";
185 constexpr const char* ERROR_INFO_ENHANCE = "errorInfoEnhance";
186 constexpr const char* MULTI_THREAD = "multiThread";
187 constexpr const char* DEBUG_CMD = "debugCmd";
188 constexpr const char* ENTER_SANDBOX = "sandboxApp";
189 constexpr const char* PERMISSION_INTERNET = "ohos.permission.INTERNET";
190 constexpr const char* PERMISSION_MANAGE_VPN = "ohos.permission.MANAGE_VPN";
191 constexpr const char* PERMISSION_ACCESS_BUNDLE_DIR = "ohos.permission.ACCESS_BUNDLE_DIR";
192 constexpr const char* PERMISSION_PROTECT_SCREEN_LOCK_DATA = "ohos.permission.PROTECT_SCREEN_LOCK_DATA";
193 constexpr const char* PERMISSION_TEMP_JIT_ALLOW = "TEMPJITALLOW";
194 constexpr const char* TARGET_UID_KEY = "ohos.aafwk.param.targetUid";
195 constexpr const char* REUSING_WINDOW = "ohos.ability_runtime.reusing_window";
196 constexpr const char* SPECIFED_PROCESS_CALLER_PROCESS = "ohoSpecifiedProcessCallerProcess";
197 constexpr const int32_t KILL_PROCESS_BY_USER_INTERVAL = 20;
198 constexpr const int32_t KILL_PROCESS_BY_USER_DELAY_BASE = 500;
199 constexpr const int64_t PRELOAD_FREEZE_TIMEOUT = 60000;
200 constexpr size_t MAX_PROCESS_NAME_LENGTH = 64;
201 
202 #ifdef WITH_DLP
203 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
204 #endif // WITH_DLP
205 
206 constexpr const char* SUPPORT_ISOLATION_MODE = "persist.bms.supportIsolationMode";
207 constexpr const char* SUPPORT_SERVICE_EXT_MULTI_PROCESS = "component.startup.extension.multiprocess.enable";
208 constexpr const char* SERVICE_EXT_MULTI_PROCESS_WHITE_LIST = "component.startup.extension.multiprocess.whitelist";
209 constexpr const char* SCENE_BOARD_BUNDLE_NAME = "com.ohos.sceneboard";
210 constexpr const char* DEBUG_APP = "debugApp";
211 constexpr const char* NATIVE_DEBUG = "nativeDebug";
212 constexpr const char* DEBUG_FROM = "ohos.param.debugFrom";
213 constexpr const char* SERVICE_EXTENSION = ":ServiceExtension";
214 constexpr const char* KEEP_ALIVE = ":KeepAlive";
215 constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohoSpecifiedProcessFlag";
216 constexpr const char* TSAN_FLAG_NAME = "tsanEnabled";
217 constexpr const char* HWASAN_FLAG_NAME = "hwasanEnabled";
218 constexpr const char* UBSAN_FLAG_NAME = "ubsanEnabled";
219 constexpr const char* UIEXTENSION_ABILITY_ID = "ability.want.params.uiExtensionAbilityId";
220 constexpr const char* UIEXTENSION_ROOT_HOST_PID = "ability.want.params.uiExtensionRootHostPid";
221 constexpr const char* UIEXTENSION_HOST_PID = "ability.want.params.uiExtensionHostPid";
222 constexpr const char* UIEXTENSION_HOST_UID = "ability.want.params.uiExtensionHostUid";
223 constexpr const char* UIEXTENSION_HOST_BUNDLENAME = "ability.want.params.uiExtensionHostBundleName";
224 constexpr const char* UIEXTENSION_BIND_ABILITY_ID = "ability.want.params.uiExtensionBindAbilityId";
225 constexpr const char* UIEXTENSION_NOTIFY_BIND = "ohos.uiextension.params.notifyProcessBind";
226 constexpr const char* MEMMGR_PROC_NAME = "memmgrservice";
227 constexpr const char* ISOLATED_SANDBOX = "isolatedSandbox";
228 constexpr const char* RENDER_PROCESS_NAME = ":render";
229 constexpr const char* RENDER_PROCESS_TYPE = "render";
230 constexpr const char* GPU_PROCESS_NAME = ":gpu";
231 constexpr const char* GPU_PROCESS_TYPE = "gpu";
232 constexpr const char* KILL_REASON_USER_REQUEST = "User Request";
233 const std::string TOKEN_ID = "TOKEN_ID";
234 const int32_t SIGNAL_KILL = 9;
235 constexpr int32_t USER_SCALE = 200000;
236 #define ENUM_TO_STRING(s) #s
237 #define APP_ACCESS_BUNDLE_DIR 0x20
238 #define APP_OVERLAY_FLAG 0x100
239 
240 constexpr int32_t MAX_RESTART_COUNT = 3;
241 constexpr int32_t RESTART_INTERVAL_TIME = 120000;
242 
243 constexpr ErrCode APPMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, 0x01);
244  // Error code for already exist render.
245 constexpr ErrCode ERR_ALREADY_EXIST_RENDER = APPMGR_ERR_OFFSET + 100;
246  // Error code for reaching render process number limitation.
247 constexpr ErrCode ERR_REACHING_MAXIMUM_RENDER_PROCESS_LIMITATION = APPMGR_ERR_OFFSET + 101;
248 constexpr const char* EVENT_KEY_UID = "UID";
249 constexpr const char* EVENT_KEY_PID = "PID";
250 constexpr const char* EVENT_KEY_PACKAGE_NAME = "PACKAGE_NAME";
251 constexpr const char* EVENT_KEY_PROCESS_NAME = "PROCESS_NAME";
252 constexpr const char* EVENT_KEY_MESSAGE = "MSG";
253 constexpr const char* EVENT_KEY_FOREGROUND = "FOREGROUND";
254 
255 // Developer mode param
256 constexpr const char* DEVELOPER_MODE_STATE = "const.security.developermode.state";
257 constexpr const char* PRODUCT_ASSERT_FAULT_DIALOG_ENABLED = "persisit.sys.abilityms.support_assert_fault_dialog";
258 
259 // Msg length is less than 48 characters
260 constexpr const char* EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT = "Terminate Ability TimeOut!";
261 constexpr const char* EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT = "Terminate Application TimeOut!";
262 constexpr const char* EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT = "Add Ability Stage TimeOut!";
263 constexpr const char* EVENT_MESSAGE_START_SPECIFIED_PROCESS_TIMEOUT = "Start Specified Process Timeout!";
264 constexpr const char* EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT = "Start Specified Ability TimeOut!";
265 constexpr const char* EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT =
266     "Start Process Specified Ability TimeOut!";
267 constexpr const char* EVENT_MESSAGE_DEFAULT = "AppMgrServiceInner HandleTimeOut!";
268 constexpr const char* SUPPORT_CALL_NOTIFY_MEMORY_CHANGED =
269     "persist.sys.abilityms.support_call_notify_memory_changed";
270 
271 constexpr const char* SYSTEM_BASIC = "system_basic";
272 constexpr const char* SYSTEM_CORE = "system_core";
273 constexpr const char* ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
274 constexpr const char* PROCESS_EXIT_EVENT_TASK = "Send Process Exit Event Task";
275 constexpr const char* KILL_PROCESS_REASON_PREFIX = "Kill Reason:";
276 constexpr const char* PRELOAD_APPLIATION_TASK = "PreloadApplicactionTask";
277 constexpr const char* KEY_WATERMARK_BUSINESS_NAME = "com.ohos.param.watermarkBusinessName";
278 constexpr const char* KEY_IS_WATERMARK_ENABLED = "com.ohos.param.isWatermarkEnabled";
279 constexpr const char* KILL_SUB_PROCESS_REASON_PREFIX = "Kill SubProcess Reason:";
280 
281 constexpr const char* PROC_SELF_TASK_PATH = "/proc/self/task/";
282 
283 constexpr int32_t ROOT_UID = 0;
284 constexpr int32_t FOUNDATION_UID = 5523;
285 constexpr int32_t QUICKFIX_UID = 5524;
286 constexpr int32_t DEFAULT_USER_ID = 0;
287 constexpr int32_t CURRENT_USER_ID = -1;
288 constexpr int32_t RESOURCE_MANAGER_UID = 1096;
289 
290 constexpr int32_t BLUETOOTH_GROUPID = 1002;
291 
292 #ifdef APP_MGR_SERVICE_APPMS
293 constexpr int32_t NETSYS_SOCKET_GROUPID = 1097;
294 #endif
295 
296 constexpr int32_t SHADER_CACHE_GROUPID = 3099;
297 constexpr int32_t DEFAULT_INVAL_VALUE = -1;
298 constexpr int32_t NO_ABILITY_RECORD_ID = -1;
299 constexpr int32_t EXIT_REASON_UNKNOWN = 0;
300 constexpr int32_t PROCESS_START_FAILED_SUB_REASON_UNKNOWN = 0;
301 
302 constexpr int32_t MAX_SPECIFIED_PROCESS_NAME_LENGTH = 255;
303 
304 constexpr int32_t NWEB_PRELOAD_DELAY = 3000000;
305 
306 constexpr const char* APP_INSTANCE_KEY_0 = "app_instance_0";
307 
308 //listen fd use
309 constexpr int32_t PIPE_MSG_READ_BUFFER = 1024;
310 constexpr const char* NATIVESPAWN_STARTED = "startup.service.ctl.nativespawn.pid";
311 
312 // Max child process number limitation for pc device.
313 constexpr int32_t PC_MAX_CHILD_PROCESS_NUM = 50;
314 constexpr int32_t USER100 = 100;
315 constexpr const char* LIFE_CYCLE_STATE_START_FOREGROUND = "start foreground";
316 constexpr const char* LIFE_CYCLE_STATE_START_BACKGROUND = "start background";
317 const std::string LARGE_SCREEN = "large_screen";
318 
319 // runtime language arkts version
320 const std::string CODE_LANGUAGE_ARKTS_1_2 = "static";
321 const std::string CODE_LANGUAGE_ARKTS_HYBRID = "hybrid";
322 
GetUserIdByUid(int32_t uid)323 int32_t GetUserIdByUid(int32_t uid)
324 {
325     return uid / BASE_USER_RANGE;
326 }
327 
IsCjAbility(const std::string & info)328 bool IsCjAbility(const std::string& info)
329 {
330     // in cj application, the srcEntry format should be packageName.AbilityClassName.
331     std::string pattern = "^([a-zA-Z0-9_]+\\.)+[a-zA-Z0-9_]+$";
332     return std::regex_match(info, std::regex(pattern));
333 }
334 
IsCjApplication(const BundleInfo & bundleInfo)335 bool IsCjApplication(const BundleInfo &bundleInfo)
336 {
337     bool findEntryHapModuleInfo = false;
338     AppExecFwk::HapModuleInfo entryHapModuleInfo;
339     if (!bundleInfo.hapModuleInfos.empty()) {
340         for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
341             if (hapModuleInfo.moduleType == AppExecFwk::ModuleType::ENTRY) {
342                 findEntryHapModuleInfo = true;
343                 entryHapModuleInfo = hapModuleInfo;
344                 break;
345             }
346         }
347         if (!findEntryHapModuleInfo) {
348             TAG_LOGW(AAFwkTag::APPMGR, "not find hap module");
349             entryHapModuleInfo = bundleInfo.hapModuleInfos.back();
350         }
351         if (entryHapModuleInfo.srcEntrance.length() > 0) {
352             return IsCjAbility(entryHapModuleInfo.srcEntrance);
353         }
354     }
355     return false;
356 }
357 
GetEventName(int32_t eventId)358 std::string GetEventName(int32_t eventId)
359 {
360     switch (eventId) {
361         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
362         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
363         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
364         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
365         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
366         case AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG:
367             return AppExecFwk::AppFreezeType::LIFECYCLE_TIMEOUT;
368         default:
369             return AppExecFwk::AppFreezeType::LIFECYCLE_HALF_TIMEOUT;
370     }
371 }
372 
GetEventTypeAndMsg(int32_t eventId)373 std::pair<int, std::string> GetEventTypeAndMsg(int32_t eventId)
374 {
375     std::pair<int, std::string> result{AppExecFwk::AppfreezeManager::TypeAttribute::NORMAL_TIMEOUT, ""};
376     switch (eventId) {
377         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
378         case AMSEventHandler::TERMINATE_ABILITY_HALF_TIMEOUT_MSG:
379             result.second = EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT;
380             break;
381         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
382         case AMSEventHandler::TERMINATE_APPLICATION_HALF_TIMEOUT_MSG:
383             result.second = EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT;
384             break;
385         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
386         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_HALF_TIMEOUT_MSG:
387             result.second = EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT;
388             result.first = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
389             break;
390         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
391         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG:
392             result.second = EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT;
393             result.first = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
394             break;
395         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
396         case AMSEventHandler::START_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG:
397             result.second = EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT;
398             result.first = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
399             break;
400         case AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG:
401         case AMSEventHandler::START_SPECIFIED_PROCESS_HALF_TIMEOUT_MSG:
402             result.second = EVENT_MESSAGE_START_SPECIFIED_PROCESS_TIMEOUT;
403             result.first = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
404             break;
405         default:
406             result.second = EVENT_MESSAGE_DEFAULT;
407             break;
408     }
409     return result;
410 }
411 }  // namespace
412 
413 using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED;
414 using OHOS::AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
415 
AppMgrServiceInner()416 AppMgrServiceInner::AppMgrServiceInner()
417     : remoteClientManager_(std::make_shared<RemoteClientManager>()),
418       appRunningManager_(std::make_shared<AppRunningManager>()),
419       appDebugManager_(std::make_shared<AppDebugManager>()),
420       appRunningStatusModule_(std::make_shared<AbilityRuntime::AppRunningStatusModule>()),
421       securityModeManager_(std::make_shared<AdvancedSecurityModeManager>()),
422       appPreloader_(std::make_shared<AppPreloader>(remoteClientManager_)),
423       multiUserConfigurationMgr_(std::make_shared<MultiUserConfigurationMgr>())
424 {}
425 
Init()426 void AppMgrServiceInner::Init()
427 {
428     InitGlobalConfiguration();
429     AddWatchParameter();
430     supportIsolationMode_ = OHOS::system::GetParameter(SUPPORT_ISOLATION_MODE, "false");
431     supportServiceExtMultiProcess_ = OHOS::system::GetParameter(SUPPORT_SERVICE_EXT_MULTI_PROCESS, "false");
432     ParseServiceExtMultiProcessWhiteList();
433     DelayedSingleton<AppStateObserverManager>::GetInstance()->Init();
434     DelayedSingleton<RenderStateObserverManager>::GetInstance()->Init();
435     dfxTaskHandler_ = AAFwk::TaskHandlerWrap::CreateConcurrentQueueHandler(
436         "dfx_freeze_task_queue", DFX_TASKWORKER_NUM, AAFwk::TaskQoS::USER_INITIATED);
437     dfxTaskHandler_->SetPrintTaskLog(true);
438     rssTaskHandler_ = AAFwk::TaskHandlerWrap::CreateConcurrentQueueHandler(
439         "rss_report_task_queue", RSS_TASKWORKER_NUM, AAFwk::TaskQoS::USER_INITIATED);
440     rssTaskHandler_->SetPrintTaskLog(true);
441     willKillPidsNum_ = 0;
442     if (securityModeManager_) {
443         securityModeManager_->Init();
444     }
445     ffrt::submit([pThis = shared_from_this()]() {
446         pThis->nwebPreloadSet_ = AAFwk::ResSchedUtil::GetInstance().GetNWebPreloadSet();
447         }, ffrt::task_attr().delay(NWEB_PRELOAD_DELAY)
448         .timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
449     AppNativeSpawnManager::GetInstance().InitNativeSpawnMsgPipe(appRunningManager_);
450 }
451 
~AppMgrServiceInner()452 AppMgrServiceInner::~AppMgrServiceInner()
453 {}
454 
StartSpecifiedProcess(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo,int32_t requestId,const std::string & customProcess)455 void AppMgrServiceInner::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
456     int32_t requestId, const std::string &customProcess)
457 {
458     TAG_LOGI(AAFwkTag::APPMGR, "StartSpecifiedProcess, requestId = %{public}d, customProcess = %{public}s", requestId,
459         customProcess.c_str());
460     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
461     TAG_LOGD(AAFwkTag::APPMGR, "call.");
462     BundleInfo bundleInfo;
463     HapModuleInfo hapModuleInfo;
464     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
465 
466     int32_t appIndex = 0;
467     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
468     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
469         return;
470     }
471     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
472         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
473         return;
474     }
475 
476     std::string processName;
477     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
478     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, "", processName, false);
479     TAG_LOGD(AAFwkTag::APPMGR, "processName = %{public}s", processName.c_str());
480     auto instanceKey = want.GetStringParam(Want::APP_INSTANCE_KEY);
481     auto masterAppRecord = appRunningManager_->FindMasterProcessAppRunningRecord(appInfo->name, abilityInfo,
482         appInfo->uid);
483     std::string customProcessFlag = "";
484     if (masterAppRecord == nullptr) {
485         if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo.extensionAbilityType)) {
486             customProcessFlag = customProcess;
487         } else {
488             customProcessFlag = abilityInfo.process;
489         }
490         masterAppRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid,
491             bundleInfo, "", nullptr, instanceKey, customProcessFlag);
492         if(masterAppRecord != nullptr){
493             masterAppRecord->SetMasterProcess(true);
494         }
495     }
496     if (masterAppRecord != nullptr) {
497         TAG_LOGI(AAFwkTag::APPMGR, "master process exists: %{public}s.", masterAppRecord->GetProcessName().c_str());
498         masterAppRecord->SetScheduleNewProcessRequestState(requestId, want, hapModuleInfo.moduleName);
499         auto moduleRecord = masterAppRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
500         if (!moduleRecord) {
501             TAG_LOGI(AAFwkTag::APPMGR, "module record is nullptr, add modules");
502             std::vector<HapModuleInfo> hapModules = { hapModuleInfo };
503             masterAppRecord->AddModules(appInfo, hapModules);
504             if (masterAppRecord->GetApplicationClient() != nullptr) {
505                 masterAppRecord->AddAbilityStageBySpecifiedProcess(appInfo->bundleName);
506             }
507             return;
508         }
509         TAG_LOGD(AAFwkTag::APPMGR, "schedule new process request.");
510         masterAppRecord->ScheduleNewProcessRequest(want, hapModuleInfo.moduleName);
511         return;
512     }
513     TAG_LOGI(AAFwkTag::APPMGR, "main process do not exists.");
514     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
515     if (abilityInfo.type == AppExecFwk::AbilityType::PAGE) {
516         appRecord = !AAFwk::AppUtils::GetInstance().InOnNewProcessEnableList(bundleInfo.name) ? nullptr :
517             appRunningManager_->CheckAppRunningRecordForSpecifiedProcess(appInfo->uid, instanceKey, customProcessFlag);
518     }
519     if (appRecord != nullptr) {
520         TAG_LOGI(AAFwkTag::APPMGR, "starting process [%{public}s]", processName.c_str());
521         AbilityRuntime::LoadParam loadParam;
522         loadParam.instanceKey = instanceKey;
523         auto newAppRecord = CreateAppRunningRecord(std::make_shared<AbilityRuntime::LoadParam>(loadParam),
524             appInfo, std::make_shared<AbilityInfo>(abilityInfo), processName, bundleInfo, hapModuleInfo,
525             std::make_shared<AAFwk::Want>(want), false);
526         if (newAppRecord == nullptr) {
527             TAG_LOGE(AAFwkTag::APPMGR, "create new appRecord failed");
528             return;
529         }
530         newAppRecord->SetMasterProcess(true);
531         newAppRecord->SetScheduleNewProcessRequestState(requestId, want, hapModuleInfo.moduleName);
532         bool appExistFlag = appRunningManager_->IsAppExist(bundleInfo.applicationInfo.accessTokenId);
533         auto ret = StartProcess(abilityInfo.applicationName, processName, 0, newAppRecord,
534             appInfo->uid, bundleInfo, appInfo->bundleName, 0, appExistFlag);
535         TAG_LOGI(AAFwkTag::APPMGR, "start process ret %{public}d, schedule new process request", ret);
536         return;
537     }
538     if (startSpecifiedAbilityResponse_) {
539         startSpecifiedAbilityResponse_->OnNewProcessRequestResponse("", requestId);
540     }
541 }
542 
PreloadApplicationByPhase(const std::string & bundleName,int32_t userId,int32_t appIndex,AppExecFwk::PreloadPhase preloadPhase)543 int32_t AppMgrServiceInner::PreloadApplicationByPhase(const std::string &bundleName, int32_t userId, int32_t appIndex,
544     AppExecFwk::PreloadPhase preloadPhase)
545 {
546     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
547     TAG_LOGI(AAFwkTag::APPMGR, "PreloadApplicationByPhase bundleName:%{public}s, userId:%{public}d, \
548     appIndex:%{public}d, preloadPhase:%{public}d", bundleName.c_str(), userId, appIndex,
549         static_cast<int32_t>(preloadPhase));
550     if (!AAFwk::AppUtils::GetInstance().IsPreloadApplicationEnabled()) {
551         TAG_LOGE(AAFwkTag::ABILITYMGR, "preload application not supported");
552         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
553     }
554     return PreloadApplication(bundleName, userId, appIndex, AppExecFwk::PreloadMode::PRELOAD_BY_PHASE, preloadPhase);
555 }
556 
PreloadApplication(const std::string & bundleName,int32_t userId,AppExecFwk::PreloadMode preloadMode,int32_t appIndex)557 int32_t AppMgrServiceInner::PreloadApplication(const std::string &bundleName, int32_t userId,
558     AppExecFwk::PreloadMode preloadMode, int32_t appIndex)
559 {
560     CHECK_CALLER_IS_SYSTEM_APP;
561     if (!AAFwk::PermissionVerification::GetInstance()->VerifyPreloadApplicationPermission()) {
562         TAG_LOGE(AAFwkTag::APPMGR, "permission verify fail");
563         return ERR_PERMISSION_DENIED;
564     }
565     return PreloadApplication(bundleName, userId, appIndex, preloadMode, AppExecFwk::PreloadPhase::UNSPECIFIED);
566 }
567 
PreloadApplication(const std::string & bundleName,int32_t userId,int32_t appIndex,AppExecFwk::PreloadMode preloadMode,AppExecFwk::PreloadPhase preloadPhase)568 int32_t AppMgrServiceInner::PreloadApplication(const std::string &bundleName, int32_t userId, int32_t appIndex,
569     AppExecFwk::PreloadMode preloadMode, AppExecFwk::PreloadPhase preloadPhase)
570 {
571     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
572     TAG_LOGI(AAFwkTag::APPMGR, "PreloadApplication, bundleName:%{public}s, userId:%{public}d, \
573     appIndex:%{public}d, preloadMode:%{public}d, preloadPhase:%{public}d", bundleName.c_str(), userId, appIndex,
574         static_cast<int32_t>(preloadMode), static_cast<int32_t>(preloadPhase));
575 
576     if (!appPreloader_) {
577         TAG_LOGE(AAFwkTag::APPMGR, "null appPreloader");
578         return ERR_INVALID_VALUE;
579     }
580     if (userId == CURRENT_USER_ID) {
581         userId = currentUserId_;
582     }
583     if (UserRecordManager::GetInstance().IsLogoutUser(userId)) {
584         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
585         return ERR_INVALID_OPERATION;
586     }
587     auto allowPreload = appPreloader_->PreCheck(bundleName, preloadMode);
588     if (!allowPreload) {
589         TAG_LOGI(AAFwkTag::APPMGR, "bundleName: %{public}s preload preCheck:unallow", bundleName.c_str());
590         return AAFwk::ERR_NOT_ALLOW_PRELOAD_BY_RSS;
591     }
592 
593     PreloadRequest request;
594     request.preloadMode = preloadMode;
595     request.preloadPhase = preloadPhase;
596     auto ret = appPreloader_->GeneratePreloadRequest(bundleName, userId, appIndex, request);
597     if (ret != ERR_OK) {
598         TAG_LOGE(AAFwkTag::APPMGR, "generatePreloadRequest fail, ret:%{public}d", ret);
599         return ret;
600     }
601     SetPreloadDebugApp(request.want, request.appInfo);
602     auto task = [innerServiceWeak = weak_from_this(), request] () {
603         auto innerService = innerServiceWeak.lock();
604         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
605         innerService->HandlePreloadApplication(request);
606     };
607     if (!taskHandler_) {
608         TAG_LOGE(AAFwkTag::APPMGR, "null taskHandler_");
609         return ERR_INVALID_VALUE;
610     }
611     TAG_LOGD(AAFwkTag::APPMGR, "submit task, bundleName:%{public}s, userId:%{public}d",
612         bundleName.c_str(), userId);
613     taskHandler_->SubmitTask(task, PRELOAD_APPLIATION_TASK);
614     return ERR_OK;
615 }
616 
PreloadModuleFinished(const int32_t pid)617 void AppMgrServiceInner::PreloadModuleFinished(const int32_t pid)
618 {
619     TAG_LOGD(AAFwkTag::APPMGR, "AppMgrServiceInner PreloadModuleFinished call.");
620     auto appRecord = GetAppRunningRecordByPid(pid);
621     if (appRecord == nullptr) {
622         TAG_LOGE(AAFwkTag::APPMGR, "appRecord not found by pid %{public}d", pid);
623         return;
624     }
625     auto reportLoadTask = [appRecord]() {
626         auto priorityObj = appRecord->GetPriorityObject();
627         if (priorityObj) {
628             AAFwk::ResSchedUtil::GetInstance().ReportLoadingEventToRss(AAFwk::LoadingStage::PRELOAD_END,
629                 priorityObj->GetPid(), appRecord->GetUid(), 0, 0);
630         }
631     };
632     if (rssTaskHandler_) {
633         rssTaskHandler_->SubmitTask(reportLoadTask, "reportPreloadTask");
634     }
635 }
636 
SetPreloadDebugApp(std::shared_ptr<AAFwk::Want> want,std::shared_ptr<ApplicationInfo> appInfo)637 void AppMgrServiceInner::SetPreloadDebugApp(std::shared_ptr<AAFwk::Want> want, std::shared_ptr<ApplicationInfo> appInfo)
638 {
639     CHECK_POINTER_AND_RETURN_LOG(want, "SetPreloadDebugApp want null");
640     CHECK_POINTER_AND_RETURN_LOG(appInfo, "SetPreloadDebugApp appInfo null");
641     if (!appInfo->debug ||
642         appInfo->appProvisionType != AppExecFwk::Constants::APP_PROVISION_TYPE_DEBUG ||
643         !system::GetBoolParameter(DEVELOPER_MODE_STATE, false) ||
644         !IsWaitingDebugAppInner(appInfo->bundleName)) {
645         TAG_LOGD(AAFwkTag::ABILITYMGR, "Not meeting the set debugging conditions.");
646         return;
647     }
648     want->SetParam(DEBUG_APP, true);
649 }
650 
HandlePreloadApplication(const PreloadRequest & request)651 void AppMgrServiceInner::HandlePreloadApplication(const PreloadRequest &request)
652 {
653     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
654     auto abilityInfo = request.abilityInfo;
655     if (!abilityInfo) {
656         TAG_LOGE(AAFwkTag::APPMGR, "null request");
657         return;
658     }
659     auto bundleInfo = request.bundleInfo;
660     TAG_LOGI(AAFwkTag::APPMGR, "bundleName:%{public}s, abilityName:%{public}s, \
661     appIndex:%{public}d", bundleInfo.name.c_str(), abilityInfo->name.c_str(), request.appIndex);
662 
663     CHECK_POINTER_AND_RETURN_LOG(appRunningManager_, "handlePreloadApplication fail, appRunningManager null");
664     std::string processName;
665     std::string specifiedProcessFlag;
666     if (CheckAppRecordExistByPreloadRequest(request, processName, specifiedProcessFlag)) {
667         TAG_LOGE(AAFwkTag::APPMGR, "appRecord already exists when preload application");
668         return;
669     }
670 
671     auto appInfo = request.appInfo;
672     auto hapModuleInfo = request.hapModuleInfo;
673     auto want = request.want;
674 
675     bool isExtensionSandBox = IsIsolateExtensionSandBox(abilityInfo, hapModuleInfo);
676     TAG_LOGD(AAFwkTag::APPMGR, "HandlePreloadApplication processName = %{public}s", processName.c_str());
677     CHECK_POINTER_AND_RETURN_LOG(appInfo, "appInfo null");
678     AAFwk::ResSchedUtil::GetInstance().ReportPreloadApplicationToRSS(abilityInfo,
679         static_cast<int32_t>(request.preloadMode));
680     bool appExistFlag = appRunningManager_->IsAppExist(appInfo->accessTokenId);
681     bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid);
682     if (!appMultiUserExistFlag) {
683         NotifyAppRunningStatusEvent(
684             bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
685     }
686     auto loadParam = std::make_shared<AbilityRuntime::LoadParam>();
687     auto appRecord = CreateAppRunningRecord(loadParam, appInfo, abilityInfo, processName, bundleInfo, hapModuleInfo, want);
688     if (appRecord != nullptr) {
689         appRecord->SetPreloadState(PreloadState::PRELOADING);
690         appRecord->SetPreloadMode(request.preloadMode);
691         appRecord->SetPreloadPhase(request.preloadPhase);
692         appRecord->SetNeedPreloadModule(request.preloadMode == AppExecFwk::PreloadMode::PRELOAD_MODULE ||
693             request.preloadPhase == AppExecFwk::PreloadPhase::ABILITY_STAGE_CREATED);
694         appRecord->SetNeedLimitPrio(request.preloadMode != PreloadMode::PRESS_DOWN);
695         appRecord->SetExtensionSandBoxFlag(isExtensionSandBox);
696         LoadAbilityNoAppRecord(appRecord, false, appInfo, abilityInfo, processName, specifiedProcessFlag, bundleInfo,
697             hapModuleInfo, want, appExistFlag, true, request.preloadMode);
698         appRecord->SetNeedLimitPrio(false);
699         if (request.preloadMode == AppExecFwk::PreloadMode::PRELOAD_MODULE) {
700             reportpreLoadTask(appRecord);
701         }
702     }
703 }
704 
CheckPreloadAppRecordExist(const std::string & bundleName,int32_t userId,int32_t appIndex)705 bool AppMgrServiceInner::CheckPreloadAppRecordExist(const std::string &bundleName, int32_t userId, int32_t appIndex)
706 {
707     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
708     TAG_LOGI(AAFwkTag::APPMGR, "CheckPreload, bundleName:%{public}s, userId:%{public}d, appIndex:%{public}d",
709         bundleName.c_str(), userId, appIndex);
710     if (!appPreloader_) {
711         TAG_LOGE(AAFwkTag::APPMGR, "null appPreloader");
712         return false;
713     }
714     PreloadRequest request;
715     auto ret = appPreloader_->GeneratePreloadRequest(bundleName, userId, appIndex, request);
716     if (ret != ERR_OK) {
717         TAG_LOGE(AAFwkTag::APPMGR, "generatePreloadRequest fail, ret:%{public}d", ret);
718         return false;
719     }
720     std::string processName;
721     std::string specifiedProcessFlag;
722     return CheckAppRecordExistByPreloadRequest(request, processName, specifiedProcessFlag);
723 }
724 
CheckAppRecordExistByPreloadRequest(const PreloadRequest & request,std::string & processName,std::string & specifiedProcessFlag)725 bool AppMgrServiceInner::CheckAppRecordExistByPreloadRequest(const PreloadRequest &request, std::string &processName,
726     std::string &specifiedProcessFlag)
727 {
728     auto &abilityInfo = request.abilityInfo;
729     auto &appInfo = request.appInfo;
730     CHECK_POINTER_AND_RETURN_VALUE(appInfo, false);
731 
732     specifiedProcessFlag = GetSpecifiedProcessFlag(abilityInfo, request.want);
733     MakeProcessName(abilityInfo, appInfo, request.hapModuleInfo, request.appIndex, specifiedProcessFlag, processName, false);
734 
735     if (!appRunningManager_) {
736         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
737         return false;
738     }
739     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, request.bundleInfo,
740         specifiedProcessFlag, nullptr, "", "", true);
741     return appRecord != nullptr;
742 }
743 
reportpreLoadTask(const std::shared_ptr<AppRunningRecord> appRecord)744 void AppMgrServiceInner::reportpreLoadTask(const std::shared_ptr<AppRunningRecord> appRecord)
745 {
746     auto reportLoadTask = [appRecord]() {
747         auto priorityObj = appRecord->GetPriorityObject();
748         if (priorityObj) {
749             AAFwk::ResSchedUtil::GetInstance().ReportLoadingEventToRss(AAFwk::LoadingStage::PRELOAD_BEGIN,
750                 priorityObj->GetPid(), appRecord->GetUid(), PRELOAD_FREEZE_TIMEOUT, 0);
751         }
752     };
753     if (rssTaskHandler_) {
754         rssTaskHandler_->SubmitTask(reportLoadTask, "reportpreLoadTask");
755     }
756 }
757 
NotifyPreloadAbilityStateChanged(sptr<IRemoteObject> token,bool isPreForeground)758 int32_t AppMgrServiceInner::NotifyPreloadAbilityStateChanged(sptr<IRemoteObject> token, bool isPreForeground)
759 {
760     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
761     TAG_LOGD(AAFwkTag::APPMGR, "NotifyPreloadAbilityStateChanged");
762     if (!token) {
763         TAG_LOGE(AAFwkTag::APPMGR, "token null");
764         return AAFwk::INVALID_CALLER_TOKEN;
765     }
766     auto appRecord = GetAppRunningRecordByAbilityToken(token);
767     if (!appRecord) {
768         TAG_LOGE(AAFwkTag::APPMGR, "appRecord not exist");
769         return ERR_NULL_OBJECT;
770     }
771     if (appRecord->IsPreForeground() == isPreForeground) {
772         TAG_LOGI(AAFwkTag::APPMGR,"NotifyPreloadAbilityStateChanged, pid:%{public}d, isPreForeground Same:%{public}d",
773             appRecord->GetPid(), isPreForeground);
774         return AAFwk::ERR_NOTIFY_PRELOAD_ABILITY_NO_CHANGE;
775     }
776     if (isPreForeground && appRecord->GetAbilities().size() > 1) {
777         TAG_LOGI(AAFwkTag::APPMGR,"NotifyPreloadAbilityStateChanged, has other ability, pid:%{public}d",
778             appRecord->GetPid());
779         return AAFwk::ERR_NOTIFY_PRELOAD_ABILITY_HAS_OTHER;
780     }
781     TAG_LOGI(AAFwkTag::APPMGR,
782         "NotifyPreloadAbilityStateChanged bundle:%{public}s, pid:%{public}d, isPreForeground:%{public}d",
783         appRecord->GetBundleName().c_str(), appRecord->GetPid(), isPreForeground);
784     appRecord->SetPreForeground(isPreForeground);
785     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessPreForegroundChanged(appRecord);
786     return ERR_OK;
787 }
788 
MakeKiaProcess(std::shared_ptr<AAFwk::Want> want,bool & isKia,std::string & watermarkBusinessName,bool & isWatermarkEnabled,bool & isFileUri,std::string & processName)789 int32_t AppMgrServiceInner::MakeKiaProcess(std::shared_ptr<AAFwk::Want> want, bool &isKia,
790     std::string &watermarkBusinessName, bool &isWatermarkEnabled,
791     bool &isFileUri, std::string &processName)
792 {
793     if (!AAFwk::AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
794         return ERR_OK;
795     }
796     if (want == nullptr) {
797         TAG_LOGE(AAFwkTag::APPMGR, "want is nullptr");
798         return ERR_INVALID_VALUE;
799     }
800 #ifdef INCLUDE_ZURI
801     isFileUri = !want->GetUriString().empty() && want->GetUri().GetScheme() == "file";
802 #endif
803     if (isFileUri && kiaInterceptor_ != nullptr) {
804         auto resultCode = kiaInterceptor_->OnIntercept(*want);
805         watermarkBusinessName = want->GetStringParam(KEY_WATERMARK_BUSINESS_NAME);
806         isWatermarkEnabled = want->GetBoolParam(KEY_IS_WATERMARK_ENABLED, false);
807         TAG_LOGI(AAFwkTag::APPMGR, "After calling kiaInterceptor_->OnIntercept,"
808             "resultCode=%{public}d,watermarkBusinessName=%{private}s,isWatermarkEnabled=%{private}d",
809             resultCode, watermarkBusinessName.c_str(),
810             static_cast<int>(isWatermarkEnabled));
811         isKia = (resultCode == ERR_OK && !watermarkBusinessName.empty() && isWatermarkEnabled);
812         if (isKia) {
813             processName += "_KIA";
814         }
815     }
816     return ERR_OK;
817 }
818 
ProcessKia(bool isKia,std::shared_ptr<AppRunningRecord> appRecord,const std::string & watermarkBusinessName,bool isWatermarkEnabled)819 int32_t AppMgrServiceInner::ProcessKia(bool isKia, std::shared_ptr<AppRunningRecord> appRecord,
820     const std::string& watermarkBusinessName, bool isWatermarkEnabled)
821 {
822     if (!AAFwk::AppUtils::GetInstance().IsStartOptionsWithAnimation() || !isKia) {
823         return ERR_OK;
824     }
825     if (appRecord == nullptr) {
826         TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr");
827         return ERR_INVALID_VALUE;
828     }
829 #ifdef SUPPORT_SCREEN
830     TAG_LOGI(AAFwkTag::APPMGR, "Openning KIA file, start setting watermark");
831     int32_t resultCode = static_cast<int32_t>(WindowManager::GetInstance().SetProcessWatermark(
832         appRecord->GetPid(), watermarkBusinessName, isWatermarkEnabled));
833     if (resultCode != ERR_OK) {
834         TAG_LOGE(AAFwkTag::APPMGR, "setting watermark fails with result code:%{public}d", resultCode);
835         return resultCode;
836     }
837     TAG_LOGI(AAFwkTag::APPMGR, "setting watermark succeeds, start setting snapshot skip");
838     resultCode = static_cast<int32_t>(WindowManager::GetInstance().SkipSnapshotForAppProcess(
839         appRecord->GetPid(), isWatermarkEnabled));
840     if (resultCode != ERR_OK) {
841         TAG_LOGE(AAFwkTag::APPMGR, "setting snapshot skip fails with result code:%{public}d", resultCode);
842         return resultCode;
843     }
844     TAG_LOGI(AAFwkTag::APPMGR, "setting snapshot skip succeeds");
845 #endif // SUPPORT_SCREEN
846     return ERR_OK;
847 }
848 
ReportEventToRSS(const AppExecFwk::AbilityInfo & abilityInfo,const std::shared_ptr<AppRunningRecord> & appRecord)849 void AppMgrServiceInner::ReportEventToRSS(const AppExecFwk::AbilityInfo &abilityInfo,
850     const std::shared_ptr<AppRunningRecord> &appRecord)
851 {
852     if (taskHandler_ == nullptr || appRecord == nullptr || appRecord->GetPid() <= 0) {
853         return;
854     }
855 
856     std::string reason = AAFwk::ResSchedUtil::GetInstance().GetThawReasonByAbilityType(abilityInfo);
857     const int32_t uid = abilityInfo.applicationInfo.uid;
858     const std::string bundleName = abilityInfo.applicationInfo.bundleName;
859     const int32_t pid = appRecord->GetPid();
860     const int32_t callerPid = appRecord->GetCallerPid();
861     TAG_LOGD(AAFwkTag::APPMGR, "%{public}d_%{public}s_%{public}d reason=%{public}s callerPid=%{public}d", uid,
862         bundleName.c_str(), pid, reason.c_str(), callerPid);
863     taskHandler_->SubmitTask([uid, bundleName, reason, pid, callerPid]() {
864         AAFwk::ResSchedUtil::GetInstance().ReportEventToRSS(uid, bundleName, reason, pid, callerPid);
865     });
866 }
867 
LoadAbility(std::shared_ptr<AbilityInfo> abilityInfo,std::shared_ptr<ApplicationInfo> appInfo,std::shared_ptr<AAFwk::Want> want,std::shared_ptr<AbilityRuntime::LoadParam> loadParam)868 void AppMgrServiceInner::LoadAbility(std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<ApplicationInfo> appInfo,
869     std::shared_ptr<AAFwk::Want> want, std::shared_ptr<AbilityRuntime::LoadParam> loadParam)
870 {
871     if (AAFwk::AppUtils::GetInstance().IsForbidStart()) {
872         TAG_LOGW(AAFwkTag::APPMGR, "forbid start: %{public}s", abilityInfo ? abilityInfo->bundleName.c_str() : "");
873         return;
874     }
875     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
876     if (loadParam == nullptr) {
877         TAG_LOGE(AAFwkTag::APPMGR, "null loadParam");
878         return;
879     }
880     if (!CheckLoadAbilityConditions(loadParam->token, abilityInfo, appInfo)) {
881         TAG_LOGE(AAFwkTag::APPMGR, "checkLoadAbilityConditions fail");
882         return;
883     }
884     if (abilityInfo->type == AbilityType::PAGE || abilityInfo->type == AbilityType::EXTENSION) {
885         std::string entry = "AppMgrServiceInner::LoadAbility";
886         AbilityRuntime::FreezeUtil::GetInstance().AddLifecycleEvent(loadParam->token, entry);
887     }
888 
889     if (!appRunningManager_) {
890         TAG_LOGE(AAFwkTag::APPMGR, "null appRunningManager_");
891         return;
892     }
893 
894     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
895         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
896         return;
897     }
898 
899     BundleInfo bundleInfo;
900     HapModuleInfo hapModuleInfo;
901     int32_t appIndex = 0;
902     std::string callerKey;
903     std::string processName;
904     std::string specifiedProcessFlag = GetSpecifiedProcessFlag(abilityInfo, want); // for isolation process
905     bool isKia = false;
906     std::string watermarkBusinessName;
907     bool isWatermarkEnabled = false;
908     bool isFileUri = false;
909     std::string customProcessFlag = loadParam->customProcessFlag;
910     bool isProcCache = false;
911     bool isExtensionSandBox = false;
912     if (want != nullptr) {
913         (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, appIndex);
914         callerKey = want->GetStringParam(Want::PARAMS_REAL_CALLER_KEY);
915         want->RemoveParam(Want::PARAMS_REAL_CALLER_KEY);
916     }
917     std::shared_ptr<AppRunningRecord> appRecord;
918     if (want && (want->GetBoolParam(AAFwk::Want::DESTINATION_PLUGIN_ABILITY, false))) {
919         TAG_LOGI(AAFwkTag::APPMGR, "load plugin ability");
920         appRecord = GetAppRunningRecordByAbilityToken(loadParam->preToken);
921         while (appRecord && appRecord->GetProcessType() != ProcessType::NORMAL) {
922             auto callerPid = appRecord->GetCallerPid();
923             TAG_LOGI(AAFwkTag::APPMGR, "pre host: %{public}d", callerPid);
924             appRecord = GetAppRunningRecordByPid(callerPid);
925         }
926         if (!appRecord) {
927             TAG_LOGE(AAFwkTag::APPMGR, "plugin appRecord null");
928             return;
929         }
930         auto element = want->GetElement();
931         auto pluginRet = DelayedSingleton<BundleMgrHelper>::GetInstance()->GetPluginHapModuleInfo(
932             appRecord->GetBundleName(), element.GetBundleName(), element.GetModuleName(),
933             appRecord->GetUserId(), hapModuleInfo);
934         if (pluginRet != ERR_OK) {
935             TAG_LOGE(AAFwkTag::APPMGR, "GetPluginHapModuleInfo failed: %{public}d", pluginRet);
936             return;
937         }
938         isProcCache = DelayedSingleton<CacheProcessManager>::GetInstance()->ReuseCachedProcess(appRecord);
939     } else {
940         if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
941             TAG_LOGE(AAFwkTag::APPMGR, "getBundleAndHapInfo fail");
942             return;
943         }
944         MakeProcessName(abilityInfo, appInfo, hapModuleInfo, appIndex, specifiedProcessFlag,
945             processName, loadParam->isCallerSetProcess);
946         isExtensionSandBox = IsIsolateExtensionSandBox(abilityInfo, hapModuleInfo);
947         TAG_LOGI(AAFwkTag::APPMGR, "name:%{public}s-%{public}s processName = %{public}s",
948             abilityInfo->bundleName.c_str(), abilityInfo->name.c_str(), processName.c_str());
949         if (MakeKiaProcess(want, isKia, watermarkBusinessName, isWatermarkEnabled, isFileUri, processName) != ERR_OK) {
950             TAG_LOGE(AAFwkTag::APPMGR, "MakeKiaProcess failed");
951             return;
952         }
953         appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name,
954             processName, appInfo->uid, bundleInfo, specifiedProcessFlag, &isProcCache, loadParam->instanceKey,
955             customProcessFlag);
956     }
957 
958     if (appRecord && appRecord->IsCaching()) {
959         auto priorityObj = appRecord->GetPriorityObject();
960         if (priorityObj) {
961             int32_t pid = priorityObj->GetPid();
962             TAG_LOGI(AAFwkTag::APPMGR, "process %{public}s is caching start ability set to blocked pid %{public}d",
963                 processName.c_str(), pid);
964         }
965         appRecord->SetProcessCacheBlocked(true);
966         appRecord = nullptr;
967     }
968     if (appRecord && abilityInfo->type == AppExecFwk::AbilityType::PAGE) {
969         NotifyMemMgrPriorityChanged(appRecord);
970     }
971 
972     if (!appRecord) {
973         TAG_LOGD(AAFwkTag::APPMGR, "appRecord null");
974         if (KillingProcessManager::GetInstance().IsCallerKilling(callerKey)) {
975             TAG_LOGE(AAFwkTag::APPMGR, "caller is killing");
976             NotifyLoadAbilityFailed(loadParam->token);
977             return;
978         }
979         bool appExistFlag = appRunningManager_->IsAppExist(appInfo->accessTokenId);
980         bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid);
981         if (!appMultiUserExistFlag) {
982             NotifyAppRunningStatusEvent(
983                 bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
984         }
985         appRecord = CreateAppRunningRecord(loadParam, appInfo, abilityInfo,
986             processName, bundleInfo, hapModuleInfo, want, isKia);
987 
988         if (abilityInfo->isolationProcess) {
989             bool isMasterProcessExist = appRunningManager_->CheckMasterProcessAppRunningRecordIsExist(
990                                     appInfo->name, *abilityInfo, appInfo->uid);
991             if (!isMasterProcessExist) {
992                 appRecord->SetMasterProcess(true);
993             }
994         }
995 
996         if (appRecord != nullptr) {
997             appRecord->SetExtensionSandBoxFlag(isExtensionSandBox);
998         }
999         LoadAbilityNoAppRecord(appRecord, loadParam->isShellCall, appInfo, abilityInfo, processName,
1000             specifiedProcessFlag, bundleInfo, hapModuleInfo, want, appExistFlag, false,
1001             AppExecFwk::PreloadMode::PRESS_DOWN, loadParam->token, customProcessFlag, loadParam->isStartupHide);
1002         if (ProcessKia(isKia, appRecord, watermarkBusinessName, isWatermarkEnabled) != ERR_OK) {
1003             TAG_LOGE(AAFwkTag::APPMGR, "ProcessKia failed");
1004             return;
1005         }
1006     } else {
1007         TAG_LOGI(AAFwkTag::APPMGR, "have apprecord");
1008         if (!appRecord->IsKeepAliveDkv()) {
1009             TAG_LOGD(AAFwkTag::APPMGR, "appRecord setKeepAlive");
1010             appRecord->SetKeepAliveDkv(loadParam->isKeepAlive);
1011         }
1012         if (!appRecord->IsMainElementRunning()) {
1013             TAG_LOGD(AAFwkTag::APPMGR, "appRecord SetMainElementRunning");
1014             appRecord->SetMainElementRunning(loadParam->isMainElementRunning);
1015         }
1016         ReportEventToRSS(*abilityInfo, appRecord);
1017         appRunningManager_->UpdateConfigurationDelayed(appRecord);
1018         if (!isProcCache) {
1019             SendPreloadAppStartupTypeEvent(appRecord, abilityInfo);
1020         } else {
1021             SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::WARM, AppStartReason::SUGGEST_CACHE);
1022         }
1023         if (appRecord->IsPreloaded()) {
1024             appRecord->SetPreloadState(PreloadState::NONE);
1025             appRecord->SetPreloadMode(PreloadMode::PRELOAD_NONE);
1026         }
1027         int32_t requestProcCode = (want == nullptr) ? 0 : want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0);
1028         if (requestProcCode != 0 && appRecord->GetRequestProcCode() == 0) {
1029             appRecord->SetRequestProcCode(requestProcCode);
1030             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessReused(appRecord);
1031         }
1032         StartAbility(loadParam->token, loadParam->preToken, abilityInfo, appRecord, hapModuleInfo, want,
1033             loadParam->abilityRecordId);
1034         if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
1035             AddUIExtensionBindItem(want, appRecord, loadParam->token);
1036             AddUIExtensionLauncherItem(want, appRecord, loadParam->token);
1037         }
1038     }
1039 
1040     if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType) &&
1041         appRecord != nullptr && want != nullptr) {
1042         auto abilityRunningRecord = appRecord->GetAbilityRunningRecordByToken(loadParam->token);
1043         auto uiExtensionAbilityId = want->GetIntParam(UIEXTENSION_ABILITY_ID, -1);
1044         auto uiExtensionBindAbilityId = want->GetIntParam(UIEXTENSION_BIND_ABILITY_ID, -1);
1045         if (abilityRunningRecord != nullptr) {
1046             abilityRunningRecord->SetUIExtensionAbilityId(uiExtensionAbilityId);
1047             abilityRunningRecord->SetUIExtensionBindAbilityId(uiExtensionBindAbilityId);
1048         }
1049         want->RemoveParam(UIEXTENSION_BIND_ABILITY_ID);
1050     }
1051     AfterLoadAbility(appRecord, abilityInfo, loadParam);
1052 }
1053 
AfterLoadAbility(std::shared_ptr<AppRunningRecord> appRecord,std::shared_ptr<AbilityInfo> abilityInfo,std::shared_ptr<AbilityRuntime::LoadParam> loadParam)1054 void AppMgrServiceInner::AfterLoadAbility(std::shared_ptr<AppRunningRecord> appRecord,
1055     std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<AbilityRuntime::LoadParam> loadParam)
1056 {
1057     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1058     if (!appRecord || !abilityInfo || !loadParam) {
1059         return;
1060     }
1061     if (abilityInfo->type == AppExecFwk::AbilityType::PAGE) {
1062         appRecord->SetUIAbilityLaunched(true);
1063     }
1064     PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount());
1065     PerfProfile::GetInstance().Dump();
1066     PerfProfile::GetInstance().Reset();
1067 
1068     auto reportLoadTask = [appRecord, abilityRecordId = loadParam->abilityRecordId]() {
1069         auto priorityObj = appRecord->GetPriorityObject();
1070         if (priorityObj) {
1071             auto timeOut = AbilityRuntime::GlobalConstant::GetLoadTimeOutBase() *
1072                 AAFwk::AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
1073             if (appRecord->GetExtensionType() == ExtensionAbilityType::SERVICE) {
1074                 timeOut = AbilityRuntime::GlobalConstant::GetLoadAndInactiveTimeout() *
1075                     AAFwk::AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
1076             }
1077 
1078             AAFwk::ResSchedUtil::GetInstance().ReportLoadingEventToRss(AAFwk::LoadingStage::LOAD_BEGIN,
1079                 priorityObj->GetPid(), appRecord->GetUid(), timeOut, static_cast<int64_t>(abilityRecordId));
1080         }
1081     };
1082     if (rssTaskHandler_) {
1083         rssTaskHandler_->SubmitTask(reportLoadTask, "reportLoadTask");
1084     }
1085     //UIExtension notifies Extension & Ability state changes
1086     if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
1087         UpdateExtensionState(loadParam->token, ExtensionState::EXTENSION_STATE_CREATE);
1088     }
1089     appRecord->UpdateAbilityState(loadParam->token, AbilityState::ABILITY_STATE_CREATE);
1090 }
1091 
AddUIExtensionLauncherItem(std::shared_ptr<AAFwk::Want> want,std::shared_ptr<AppRunningRecord> appRecord,sptr<IRemoteObject> token)1092 void AppMgrServiceInner::AddUIExtensionLauncherItem(std::shared_ptr<AAFwk::Want> want,
1093     std::shared_ptr<AppRunningRecord> appRecord, sptr<IRemoteObject> token)
1094 {
1095     if (want == nullptr || appRecord == nullptr || token == nullptr || appRunningManager_ == nullptr) {
1096         TAG_LOGE(AAFwkTag::APPMGR, "invalid input params");
1097         return;
1098     }
1099 
1100     auto uiExtensionAbilityId = want->GetIntParam(UIEXTENSION_ABILITY_ID, -1);
1101     auto hostPid = want->GetIntParam(UIEXTENSION_ROOT_HOST_PID, -1);
1102     pid_t providerPid = -1;
1103     if (appRecord->GetPriorityObject() != nullptr) {
1104         providerPid = appRecord->GetPid();
1105     }
1106     if (uiExtensionAbilityId == -1 || hostPid == -1 || providerPid == -1) {
1107         TAG_LOGE(AAFwkTag::APPMGR, "invalid want params");
1108         return;
1109     }
1110 
1111     TAG_LOGI(AAFwkTag::APPMGR, "uiExtensionAbilityId: %{public}d, hostPid: %{public}d, "
1112         "providerPid: %{public}d", uiExtensionAbilityId, hostPid, providerPid);
1113     appRunningManager_->AddUIExtensionLauncherItem(uiExtensionAbilityId, hostPid, providerPid);
1114 
1115     want->RemoveParam(UIEXTENSION_ABILITY_ID);
1116     want->RemoveParam(UIEXTENSION_ROOT_HOST_PID);
1117 }
1118 
RemoveUIExtensionLauncherItem(std::shared_ptr<AppRunningRecord> appRecord,sptr<IRemoteObject> token)1119 void AppMgrServiceInner::RemoveUIExtensionLauncherItem(std::shared_ptr<AppRunningRecord> appRecord,
1120     sptr<IRemoteObject> token)
1121 {
1122     if (appRecord == nullptr || token == nullptr || appRunningManager_ == nullptr) {
1123         TAG_LOGE(AAFwkTag::APPMGR, "invalid input params");
1124         return;
1125     }
1126 
1127     auto abilityRunningRecord = appRecord->GetAbilityRunningRecordByToken(token);
1128     if (abilityRunningRecord == nullptr) {
1129         TAG_LOGW(AAFwkTag::APPMGR, "invalid ability");
1130         return;
1131     }
1132 
1133     auto abilityInfo = abilityRunningRecord->GetAbilityInfo();
1134     if (abilityInfo == nullptr) {
1135         TAG_LOGW(AAFwkTag::APPMGR, "invalid ability");
1136         return;
1137     }
1138 
1139     if (!AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
1140         return;
1141     }
1142 
1143     auto uiExtensionAbilityId = abilityRunningRecord->GetUIExtensionAbilityId();
1144     appRunningManager_->RemoveUIExtensionLauncherItemById(uiExtensionAbilityId);
1145 }
1146 
CheckLoadAbilityConditions(const sptr<IRemoteObject> & token,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo)1147 bool AppMgrServiceInner::CheckLoadAbilityConditions(const sptr<IRemoteObject> &token,
1148     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo)
1149 {
1150     if (!token || !abilityInfo || !appInfo) {
1151         TAG_LOGE(AAFwkTag::APPMGR, "param error");
1152         return false;
1153     }
1154     if (abilityInfo->name.empty() || appInfo->name.empty()) {
1155         TAG_LOGE(AAFwkTag::APPMGR, "error abilityInfo or appInfo");
1156         return false;
1157     }
1158     if (abilityInfo->applicationName != appInfo->name) {
1159         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo and appInfo have diff appName");
1160         return false;
1161     }
1162 
1163     return true;
1164 }
1165 
MakeServiceExtProcessName(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,std::string & processName) const1166 void AppMgrServiceInner::MakeServiceExtProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
1167     const std::shared_ptr<ApplicationInfo> &appInfo, std::string &processName) const
1168 {
1169     if (abilityInfo == nullptr || appInfo == nullptr) {
1170         TAG_LOGE(AAFwkTag::APPMGR, "null ability or app info");
1171         return;
1172     }
1173 
1174     if (supportServiceExtMultiProcess_.compare("true") != 0) {
1175         return;
1176     }
1177 
1178     if (processName == appInfo->bundleName &&
1179         abilityInfo->extensionAbilityType == ExtensionAbilityType::SERVICE) {
1180         auto iter = std::find(
1181             serviceExtensionWhiteList_.begin(), serviceExtensionWhiteList_.end(), processName);
1182         if (iter != serviceExtensionWhiteList_.end()) {
1183             TAG_LOGD(AAFwkTag::APPMGR, "Application is in whiteList, skipping!");
1184             return;
1185         }
1186 
1187         processName += SERVICE_EXTENSION;
1188         if (appInfo->keepAlive) {
1189             processName += KEEP_ALIVE;
1190         }
1191     }
1192 }
1193 
MakeProcessName(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,int32_t appIndex,const std::string & specifiedProcessFlag,std::string & processName,bool isCallerSetProcess) const1194 void AppMgrServiceInner::MakeProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
1195     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, int32_t appIndex,
1196     const std::string &specifiedProcessFlag, std::string &processName, bool isCallerSetProcess) const
1197 {
1198     if (!abilityInfo || !appInfo) {
1199         TAG_LOGE(AAFwkTag::APPMGR, "param error");
1200         return;
1201     }
1202     if (!abilityInfo->process.empty() && (isCallerSetProcess || specifiedProcessFlag.empty())) {
1203         TAG_LOGD(AAFwkTag::APPMGR, "Process not null");
1204         if (abilityInfo->type == AppExecFwk::AbilityType::PAGE && abilityInfo->isStageBasedModel) {
1205             processName = appInfo->bundleName + abilityInfo->process;
1206         } else {
1207             processName = abilityInfo->process;
1208         }
1209         if (appIndex != 0) {
1210             processName += ":" + std::to_string(appIndex);
1211         }
1212         return;
1213     }
1214     MakeProcessName(appInfo, hapModuleInfo, processName);
1215     MakeServiceExtProcessName(abilityInfo, appInfo, processName);
1216     if (appIndex != 0) {
1217         processName += std::to_string(appIndex);
1218     }
1219 
1220     if (!specifiedProcessFlag.empty()) {
1221         processName = (processName + ":" + specifiedProcessFlag).substr(0, MAX_SPECIFIED_PROCESS_NAME_LENGTH);
1222         TAG_LOGI(AAFwkTag::APPMGR, "specifiedProcessFlag: %{public}s, processName: %{public}s",
1223             specifiedProcessFlag.c_str(), processName.c_str());
1224     }
1225 }
1226 
MakeProcessName(const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,std::string & processName) const1227 void AppMgrServiceInner::MakeProcessName(
1228     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, std::string &processName) const
1229 {
1230     if (!appInfo) {
1231         TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
1232         return;
1233     }
1234     // check after abilityInfo, because abilityInfo contains extension process.
1235     if (hapModuleInfo.isStageBasedModel && !hapModuleInfo.process.empty()
1236         && hapModuleInfo.process != appInfo->bundleName) {
1237         processName = hapModuleInfo.process;
1238         TAG_LOGI(AAFwkTag::APPMGR, "processName:%{public}s", processName.c_str());
1239         return;
1240     }
1241     bool isRunInIsolationMode = CheckIsolationMode(hapModuleInfo);
1242     if (hapModuleInfo.isStageBasedModel && isRunInIsolationMode) {
1243         processName = appInfo->bundleName;
1244         processName.append(":");
1245         processName.append(hapModuleInfo.name);
1246         return;
1247     }
1248     if (!appInfo->process.empty()) {
1249         processName = appInfo->process;
1250         return;
1251     }
1252     processName = appInfo->bundleName;
1253 }
1254 
LoadAbilityNoAppRecord(const std::shared_ptr<AppRunningRecord> appRecord,bool isShellCall,std::shared_ptr<ApplicationInfo> appInfo,std::shared_ptr<AbilityInfo> abilityInfo,const std::string & processName,const std::string & specifiedProcessFlag,const BundleInfo & bundleInfo,const HapModuleInfo & hapModuleInfo,std::shared_ptr<AAFwk::Want> want,bool appExistFlag,bool isPreload,AppExecFwk::PreloadMode preloadMode,sptr<IRemoteObject> token,const std::string & customProcessFlag,bool isStartupHide)1255 void AppMgrServiceInner::LoadAbilityNoAppRecord(const std::shared_ptr<AppRunningRecord> appRecord,
1256     bool isShellCall, std::shared_ptr<ApplicationInfo> appInfo,
1257     std::shared_ptr<AbilityInfo> abilityInfo, const std::string &processName,
1258     const std::string &specifiedProcessFlag, const BundleInfo &bundleInfo, const HapModuleInfo &hapModuleInfo,
1259     std::shared_ptr<AAFwk::Want> want, bool appExistFlag, bool isPreload, AppExecFwk::PreloadMode preloadMode,
1260     sptr<IRemoteObject> token, const std::string &customProcessFlag, bool isStartupHide)
1261 {
1262     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1263     TAG_LOGI(AAFwkTag::APPMGR, "processName:%{public}s, isPreload:%{public}d",
1264         processName.c_str(), isPreload);
1265     if (!appRecord || !abilityInfo) {
1266         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord or abilityInfo");
1267         return;
1268     }
1269     if (!specifiedProcessFlag.empty()) {
1270         appRecord->SetSpecifiedProcessFlag(specifiedProcessFlag);
1271     }
1272     if (!customProcessFlag.empty()) {
1273         appRecord->SetCustomProcessFlag(customProcessFlag);
1274     }
1275     if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, processName)) {
1276         appRecord->SetEmptyKeepAliveAppState(false);
1277         appRecord->SetMainProcess(false);
1278         TAG_LOGI(AAFwkTag::APPMGR, "%{public}s will not alive", hapModuleInfo.process.c_str());
1279     }
1280     uint32_t startFlags = (want == nullptr) ? 0 : AppspawnUtil::BuildStartFlags(*want, *abilityInfo);
1281     int32_t bundleIndex = 0;
1282     if (want != nullptr) {
1283         (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, bundleIndex);
1284     }
1285     if (StartProcess(abilityInfo->applicationName, processName, startFlags, appRecord,
1286         appInfo->uid, bundleInfo, appInfo->bundleName, bundleIndex, appExistFlag, isPreload, preloadMode,
1287         abilityInfo->moduleName, abilityInfo->name, token, want, abilityInfo->extensionAbilityType) != ERR_OK) {
1288         NotifyStartProcessFailed(token);
1289     }
1290 
1291     ffrt::submit([appRecord, abilityInfo, innerServiceWeak = weak_from_this(), isStartupHide]() {
1292         auto innerService = innerServiceWeak.lock();
1293         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
1294         innerService->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_SET_COLD_START, false, false);
1295         if (appRecord && appRecord->IsAlreadyHaveAbility()) {
1296             AppStartReason startReason = isStartupHide ? AppStartReason::STARTUP_HIDE : AppStartReason::NONE;
1297             innerService->SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::COLD, startReason);
1298         }
1299         }, ffrt::task_attr().name("AppStateChangedNotify")
1300         .timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
1301 
1302     if (isShellCall) {
1303         std::string perfCmd = (want == nullptr) ? "" : want->GetStringParam(PERF_CMD);
1304         bool isSandboxApp = (want == nullptr) ? false : want->GetBoolParam(ENTER_SANDBOX, false);
1305         (void)StartPerfProcess(appRecord, perfCmd, "", isSandboxApp);
1306     }
1307 }
1308 
GetSpecifiedProcessFlag(std::shared_ptr<AbilityInfo> abilityInfo,std::shared_ptr<AAFwk::Want> want)1309 std::string AppMgrServiceInner::GetSpecifiedProcessFlag(std::shared_ptr<AbilityInfo> abilityInfo,
1310     std::shared_ptr<AAFwk::Want> want)
1311 {
1312     if (!abilityInfo) {
1313         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo null");
1314         return "";
1315     }
1316     if (!want) {
1317         TAG_LOGE(AAFwkTag::APPMGR, "want null");
1318         return "";
1319     }
1320     return GetSpecifiedProcessFlag(*abilityInfo, *want);
1321 }
1322 
GetSpecifiedProcessFlag(const AbilityInfo & abilityInfo,const AAFwk::Want & want)1323 std::string AppMgrServiceInner::GetSpecifiedProcessFlag(const AbilityInfo &abilityInfo, const AAFwk::Want &want)
1324 {
1325     std::string specifiedProcessFlag;
1326     bool isUIAbility = (abilityInfo.type == AppExecFwk::AbilityType::PAGE && abilityInfo.isStageBasedModel);
1327     bool isSpecifiedProcess = abilityInfo.isolationProcess &&
1328         AAFwk::AppUtils::GetInstance().IsStartSpecifiedProcess() && isUIAbility;
1329     if (isSpecifiedProcess) {
1330         specifiedProcessFlag = want.GetStringParam(PARAM_SPECIFIED_PROCESS_FLAG);
1331         TAG_LOGI(AAFwkTag::APPMGR, "specifiedProcessFlag: %{public}s", specifiedProcessFlag.c_str());
1332     }
1333     if (abilityInfo.isolationProcess &&
1334         AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo.extensionAbilityType)) {
1335         specifiedProcessFlag = want.GetStringParam(PARAM_SPECIFIED_PROCESS_FLAG);
1336         TAG_LOGI(AAFwkTag::APPMGR, "UIExtension process, specifiedProcessFlag: %{public}s",
1337             specifiedProcessFlag.c_str());
1338     }
1339     return specifiedProcessFlag;
1340 }
1341 
IsMainProcess(const std::shared_ptr<ApplicationInfo> & appInfo,const std::string & processName) const1342 bool AppMgrServiceInner::IsMainProcess(const std::shared_ptr<ApplicationInfo> &appInfo,
1343     const std::string &processName) const
1344 {
1345     if (!appInfo) {
1346         return true;
1347     }
1348     if (!appInfo->process.empty()) {
1349         if (processName == appInfo->process) {
1350             return true;
1351         }
1352     } else {
1353         if (processName == appInfo->bundleName) {
1354             return true;
1355         }
1356     }
1357     return false;
1358 }
1359 
CheckIsolationMode(const HapModuleInfo & hapModuleInfo) const1360 bool AppMgrServiceInner::CheckIsolationMode(const HapModuleInfo &hapModuleInfo) const
1361 {
1362     IsolationMode isolationMode = hapModuleInfo.isolationMode;
1363     if (supportIsolationMode_.compare("true") == 0) {
1364         switch (isolationMode) {
1365             case IsolationMode::ISOLATION_FIRST:
1366                 return true;
1367             case IsolationMode::ISOLATION_ONLY:
1368                 return true;
1369             default:
1370                 return false;
1371         }
1372     }
1373     return false;
1374 }
1375 
GetBundleAndHapInfo(const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo,int32_t appIndex) const1376 bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo,
1377     const std::shared_ptr<ApplicationInfo> &appInfo, BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo,
1378     int32_t appIndex) const
1379 {
1380     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1381     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1382     if (bundleMgrHelper == nullptr) {
1383         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
1384         return false;
1385     }
1386 
1387     auto userId = GetUserIdByUid(appInfo->uid);
1388     TAG_LOGD(AAFwkTag::APPMGR, "userId: %{public}d, bundleName: %{public}s, appIndex: %{public}d", userId,
1389         appInfo->bundleName.c_str(), appIndex);
1390     int32_t bundleMgrResult;
1391     if (appIndex == 0) {
1392         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfoV9(appInfo->bundleName,
1393             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) |
1394             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) |
1395             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) |
1396             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION), bundleInfo, userId));
1397     } else if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
1398         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetCloneBundleInfo(appInfo->bundleName,
1399             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) |
1400             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION),
1401             appIndex, bundleInfo, userId));
1402     } else {
1403         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetSandboxBundleInfo(appInfo->bundleName,
1404             appIndex, userId, bundleInfo));
1405     }
1406 
1407     if (bundleMgrResult != ERR_OK) {
1408         TAG_LOGE(AAFwkTag::APPMGR, "getBundleInfo fail");
1409         return false;
1410     }
1411     bool hapQueryResult = false;
1412     if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
1413         hapQueryResult = bundleMgrHelper->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo);
1414     } else {
1415         hapQueryResult = (bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo) == 0);
1416     }
1417     if (!hapQueryResult) {
1418         TAG_LOGE(AAFwkTag::APPMGR, "getHapModuleInfo fail");
1419         return false;
1420     }
1421     return true;
1422 }
1423 
AttachApplication(const pid_t pid,const sptr<IAppScheduler> & appScheduler)1424 void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr<IAppScheduler> &appScheduler)
1425 {
1426     TAG_LOGD(AAFwkTag::APPMGR, "%{public}s called", __func__);
1427     if (pid <= 0) {
1428         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}d", pid);
1429         return;
1430     }
1431     AbilityRuntime::FreezeUtil::GetInstance().AddAppLifecycleEvent(pid, "ServiceInner::AttachApplication");
1432     auto appRecord = GetAppRunningRecordByPid(pid);
1433     CHECK_POINTER_AND_RETURN_LOG(appRecord, "no such appRecord");
1434     auto applicationInfo = appRecord->GetApplicationInfo();
1435     AAFwk::EventInfo eventInfo;
1436     if (!applicationInfo) {
1437         TAG_LOGE(AAFwkTag::APPMGR, "null appInfo");
1438     } else {
1439         eventInfo.bundleName = applicationInfo->name;
1440         eventInfo.versionName = applicationInfo->versionName;
1441         eventInfo.versionCode = applicationInfo->versionCode;
1442     }
1443     std::string connector = "##";
1444     std::string traceName = __PRETTY_FUNCTION__ + connector + eventInfo.bundleName;
1445     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
1446     if (appScheduler == nullptr) {
1447         TAG_LOGE(AAFwkTag::APPMGR, "attach null, pid: %{public}d, bundleName: %{public}s", pid,
1448             eventInfo.bundleName.c_str());
1449         NotifyAppAttachFailed(appRecord);
1450         return;
1451     }
1452     TAG_LOGI(AAFwkTag::APPMGR, "attach pid:%{public}d, bundle:%{public}s", pid, eventInfo.bundleName.c_str());
1453     sptr<AppDeathRecipient> appDeathRecipient = sptr<AppDeathRecipient>::MakeSptr();
1454     CHECK_POINTER_AND_RETURN_LOG(appDeathRecipient, "Failed to create death recipient.");
1455     appDeathRecipient->SetTaskHandler(taskHandler_);
1456     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
1457     auto object = appScheduler->AsObject();
1458     if (!object || !object->AddDeathRecipient(appDeathRecipient)) {
1459         TAG_LOGE(AAFwkTag::APPMGR, "add DeathRecipient for %{public}s fail", appRecord->GetProcessName().c_str());
1460         return;
1461     }
1462 
1463     appRecord->SetAppDeathRecipient(appDeathRecipient);
1464     appRecord->SetApplicationClient(appScheduler);
1465     if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
1466         LaunchApplicationExt(appRecord);
1467     }
1468 
1469     // submit cached load ability task after scene board attach
1470     if (appRecord->GetBundleName() == SCENE_BOARD_BUNDLE_NAME) {
1471         sceneBoardAttachFlag_ = true;
1472         SubmitCacheLoadAbilityTask();
1473     }
1474     eventInfo.pid = appRecord->GetPid();
1475     eventInfo.processName = appRecord->GetProcessName();
1476     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_ATTACH, HiSysEventType::BEHAVIOR, eventInfo);
1477 }
1478 
LaunchApplicationExt(const std::shared_ptr<AppRunningRecord> & appRecord)1479 void AppMgrServiceInner::LaunchApplicationExt(const std::shared_ptr<AppRunningRecord> &appRecord)
1480 {
1481     auto isPreload = IsAllowedNWebPreload(appRecord->GetProcessName());
1482     appRecord->SetNWebPreload(isPreload);
1483     LaunchApplication(appRecord);
1484 }
1485 
IsAllowedNWebPreload(const std::string & processName)1486 bool AppMgrServiceInner::IsAllowedNWebPreload(const std::string &processName)
1487 {
1488     // nwebPreloadSet_ only be initialized in Init(), no lock required.
1489     return nwebPreloadSet_.count(processName);
1490 }
1491 
NotifyAppAttachFailed(std::shared_ptr<AppRunningRecord> appRecord)1492 void AppMgrServiceInner::NotifyAppAttachFailed(std::shared_ptr<AppRunningRecord> appRecord)
1493 {
1494     CHECK_POINTER_AND_RETURN_LOG(appRecord, "AppRecord null.");
1495     std::vector<sptr<IRemoteObject>> abilityTokens;
1496     for (const auto &token : appRecord->GetAbilities()) {
1497         abilityTokens.emplace_back(token.first);
1498     }
1499     TAG_LOGI(AAFwkTag::APPMGR, "attach fail name: %{public}s %{public}zu", appRecord->GetProcessName().c_str(),
1500         abilityTokens.size());
1501     std::lock_guard lock(appStateCallbacksLock_);
1502     for (const auto &item : appStateCallbacks_) {
1503         if (item.callback != nullptr) {
1504             item.callback->OnAppRemoteDied(abilityTokens);
1505         }
1506     }
1507 }
1508 
NotifyLoadAbilityFailed(sptr<IRemoteObject> token)1509 void AppMgrServiceInner::NotifyLoadAbilityFailed(sptr<IRemoteObject> token)
1510 {
1511     CHECK_POINTER_AND_RETURN_LOG(token, "token null.");
1512     std::vector<sptr<IRemoteObject>> abilityTokens;
1513     abilityTokens.emplace_back(token);
1514     std::lock_guard lock(appStateCallbacksLock_);
1515     for (const auto &item : appStateCallbacks_) {
1516         if (item.callback != nullptr) {
1517             item.callback->OnAppRemoteDied(abilityTokens);
1518         }
1519     }
1520 }
1521 
NotifyStartProcessFailed(std::shared_ptr<AppRunningRecord> appRecord)1522 void AppMgrServiceInner::NotifyStartProcessFailed(std::shared_ptr<AppRunningRecord> appRecord)
1523 {
1524     CHECK_POINTER_AND_RETURN_LOG(appRecord, "AppRecord null.");
1525     std::vector<sptr<IRemoteObject>> abilityTokens;
1526     for (const auto &token : appRecord->GetAbilities()) {
1527         abilityTokens.emplace_back(token.first);
1528     }
1529     TAG_LOGI(AAFwkTag::APPMGR, "start process fail name: %{public}s %{public}zu", appRecord->GetProcessName().c_str(),
1530         abilityTokens.size());
1531     if (abilityTokens.empty()) {
1532         return;
1533     }
1534     std::lock_guard lock(appStateCallbacksLock_);
1535     for (const auto &item : appStateCallbacks_) {
1536         if (item.callback != nullptr) {
1537             item.callback->OnStartProcessFailed(abilityTokens);
1538         }
1539     }
1540 }
1541 
NotifyStartProcessFailed(sptr<IRemoteObject> token)1542 void AppMgrServiceInner::NotifyStartProcessFailed(sptr<IRemoteObject> token)
1543 {
1544     CHECK_POINTER_AND_RETURN_LOG(token, "token null.");
1545     std::vector<sptr<IRemoteObject>> abilityTokens;
1546     abilityTokens.emplace_back(token);
1547     std::lock_guard lock(appStateCallbacksLock_);
1548     for (const auto &item : appStateCallbacks_) {
1549         if (item.callback != nullptr) {
1550             item.callback->OnStartProcessFailed(abilityTokens);
1551         }
1552     }
1553 }
1554 
LaunchApplication(const std::shared_ptr<AppRunningRecord> & appRecord)1555 void AppMgrServiceInner::LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
1556 {
1557     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord null");
1558     appRecord->AddAppLifecycleEvent("ServiceInner::LaunchApplication");
1559     auto applicationInfo = appRecord->GetApplicationInfo();
1560     std::string bundleName = "";
1561     if (!applicationInfo) {
1562         TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
1563     } else {
1564         bundleName = applicationInfo->name;
1565     }
1566     std::string connector = "##";
1567     std::string traceName = __PRETTY_FUNCTION__ + connector + bundleName;
1568     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
1569 
1570     if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) {
1571         TAG_LOGE(AAFwkTag::APPMGR, "wrong app state:%{public}d", appRecord->GetState());
1572         return;
1573     }
1574     if (multiUserConfigurationMgr_ == nullptr) {
1575         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
1576         return;
1577     }
1578     int32_t userId = appRecord->GetUid() / BASE_USER_RANGE;
1579     auto config = multiUserConfigurationMgr_->GetConfigurationByUserId(userId);
1580     if (config == nullptr) {
1581         TAG_LOGE(AAFwkTag::APPMGR, "config null");
1582         return;
1583     }
1584 
1585     TAG_LOGD(AAFwkTag::APPMGR, "LaunchApplication configuration:%{public}s", config->GetName().c_str());
1586     appRecord->LaunchApplication(*config);
1587     appRecord->SetState(ApplicationState::APP_STATE_READY);
1588     int restartResidentProcCount = MAX_RESTART_COUNT;
1589     appRecord->SetRestartResidentProcCount(restartResidentProcCount);
1590 
1591     // There is no ability when the empty resident process starts
1592     // The status of all resident processes is ready
1593     // There is no process of switching the foreground, waiting for his first ability to start
1594     if (appRecord->IsEmptyKeepAliveApp()) {
1595         appRecord->AddAbilityStage();
1596         return;
1597     }
1598     appRecord->LaunchPendingAbilities();
1599     AddAbilityStageForSpecified(appRecord);
1600 
1601     if (appRecord->IsPreloading()) {
1602         appRecord->SetPreloadState(PreloadState::PRELOADED);
1603     }
1604     SendAppLaunchEvent(appRecord);
1605 }
1606 
AddAbilityStageForSpecified(std::shared_ptr<AppRunningRecord> appRecord)1607 void AppMgrServiceInner::AddAbilityStageForSpecified(std::shared_ptr<AppRunningRecord> appRecord)
1608 {
1609     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord null");
1610     if (appRecord->IsStartSpecifiedAbility()) {
1611         TAG_LOGI(AAFwkTag::APPMGR, "start specified ability");
1612         auto moduleRecordList = appRecord->GetAllModuleRecord();
1613         for (const auto &iter : moduleRecordList) {
1614             iter->SetModuleRecordState(ModuleRecordState::INITIALIZED_STATE);
1615         }
1616         appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName());
1617     }
1618 
1619     if (appRecord->IsNewProcessRequest()) {
1620         appRecord->AddAbilityStageBySpecifiedProcess(appRecord->GetBundleName());
1621     }
1622 }
1623 
AddAbilityStageDone(const int32_t recordId)1624 void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId)
1625 {
1626     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1627     if (!appRecord) {
1628         TAG_LOGE(AAFwkTag::APPMGR, "get appRecord fail");
1629         return;
1630     }
1631     appRecord->AddAbilityStageDone();
1632 }
1633 
UpdateAllProviderConfig(const std::shared_ptr<AppRunningRecord> & appRecord)1634 void AppMgrServiceInner::UpdateAllProviderConfig(const std::shared_ptr<AppRunningRecord> &appRecord)
1635 {
1636     if (appRunningManager_ == nullptr || appRecord == nullptr) {
1637         TAG_LOGE(AAFwkTag::APPMGR, "null ptr");
1638         return;
1639     }
1640 
1641     auto obj = appRecord->GetPriorityObject();
1642     if (obj == nullptr) {
1643         TAG_LOGE(AAFwkTag::APPMGR, "null ptr");
1644         return;
1645     }
1646 
1647     TAG_LOGD(AAFwkTag::APPMGR, "hostPid: %{public}d", obj->GetPid());
1648     std::vector<pid_t> providerPids;
1649     appRunningManager_->GetAllUIExtensionProviderPid(obj->GetPid(), providerPids);
1650 
1651     for (pid_t providerPid : providerPids) {
1652         auto providerRecord = appRunningManager_->GetAppRunningRecordByPid(providerPid);
1653         appRunningManager_->UpdateConfigurationDelayed(providerRecord);
1654     }
1655 }
1656 
ApplicationForegrounded(const int32_t recordId)1657 void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId)
1658 {
1659     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1660     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1661     if (!appRecord) {
1662         TAG_LOGE(AAFwkTag::APPMGR, "get appRecord fail");
1663         return;
1664     }
1665     appRecord->AddAppLifecycleEvent("ServiceInner::AppForegrounded");
1666     // Prevent forged requests from changing the app's state.
1667     if (appRecord->GetApplicationScheduleState() != ApplicationScheduleState::SCHEDULE_FOREGROUNDING) {
1668         TAG_LOGE(AAFwkTag::APPMGR, "app is not scheduling to foreground");
1669         return;
1670     }
1671     appRecord->SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_READY);
1672     ApplicationState appState = appRecord->GetState();
1673     if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) {
1674         if (appState == ApplicationState::APP_STATE_BACKGROUND) {
1675             appRunningManager_->UpdateConfigurationDelayed(appRecord);
1676             UpdateAllProviderConfig(appRecord);
1677         }
1678         appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND);
1679         bool needNotifyApp = appRunningManager_->IsApplicationFirstForeground(*appRecord);
1680         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp, false);
1681         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
1682     } else {
1683         TAG_LOGW(AAFwkTag::APPMGR, "app name(%{public}s), app state(%{public}d)",
1684             appRecord->GetName().c_str(), static_cast<ApplicationState>(appState));
1685     }
1686     appRecord->PopForegroundingAbilityTokens();
1687 
1688     TAG_LOGI(AAFwkTag::APPMGR, "ApplicationForegrounded, bundle: %{public}s, pendingState: %{public}d",
1689         appRecord->GetBundleName().c_str(), appRecord->GetApplicationPendingState());
1690     if (appRecord->GetApplicationPendingState() == ApplicationPendingState::BACKGROUNDING) {
1691         appRecord->ScheduleBackgroundRunning();
1692     } else if (appRecord->GetApplicationPendingState() == ApplicationPendingState::FOREGROUNDING) {
1693         appRecord->SetApplicationPendingState(ApplicationPendingState::READY);
1694     }
1695     auto eventInfo = BuildEventInfo(appRecord);
1696     int32_t callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
1697     auto callerRecord = GetAppRunningRecordByPid(callerPid);
1698     if (callerRecord != nullptr) {
1699         eventInfo.callerBundleName = callerRecord->GetBundleName();
1700     } else {
1701         TAG_LOGD(AAFwkTag::APPMGR, "callerRecord null");
1702     }
1703     AAFwk::EventReport::SendAppForegroundEvent(AAFwk::EventName::APP_FOREGROUND, eventInfo);
1704 }
1705 
ApplicationBackgrounded(const int32_t recordId)1706 void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId)
1707 {
1708     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1709     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1710     if (!appRecord) {
1711         TAG_LOGE(AAFwkTag::APPMGR, "get appRecord fail");
1712         return;
1713     }
1714     // Prevent forged requests from changing the app's state.
1715     appRecord->AddAppLifecycleEvent("ServiceInner::AppBackgrounded");
1716     if (appRecord->GetApplicationScheduleState() != ApplicationScheduleState::SCHEDULE_BACKGROUNDING) {
1717         TAG_LOGE(AAFwkTag::APPMGR, "app is not scheduling to background");
1718         return;
1719     }
1720     appRecord->SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_READY);
1721     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
1722         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
1723         bool needNotifyApp = !AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
1724             && !AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
1725             && appRunningManager_->IsApplicationBackground(*appRecord);
1726         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND, needNotifyApp, false);
1727         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
1728     } else {
1729         TAG_LOGW(AAFwkTag::APPMGR, "app name(%{public}s), app state(%{public}d)",
1730             appRecord->GetName().c_str(), static_cast<ApplicationState>(appRecord->GetState()));
1731     }
1732     auto pendingState = appRecord->GetApplicationPendingState();
1733     TAG_LOGI(AAFwkTag::APPMGR, "app backgrounded: %{public}s, pState: %{public}d", appRecord->GetBundleName().c_str(),
1734         pendingState);
1735     if (pendingState == ApplicationPendingState::FOREGROUNDING) {
1736         appRecord->ScheduleForegroundRunning();
1737     } else if (pendingState == ApplicationPendingState::BACKGROUNDING) {
1738         appRecord->SetApplicationPendingState(ApplicationPendingState::READY);
1739     }
1740     auto eventInfo = BuildEventInfo(appRecord);
1741     AAFwk::EventReport::SendAppBackgroundEvent(AAFwk::EventName::APP_BACKGROUND, eventInfo);
1742 }
1743 
BuildEventInfo(std::shared_ptr<AppRunningRecord> appRecord) const1744 AAFwk::EventInfo AppMgrServiceInner::BuildEventInfo(std::shared_ptr<AppRunningRecord> appRecord) const
1745 {
1746     AAFwk::EventInfo eventInfo;
1747     if (appRecord == nullptr) {
1748         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
1749         return eventInfo;
1750     }
1751     auto applicationInfo = appRecord->GetApplicationInfo();
1752     if (!applicationInfo) {
1753         TAG_LOGW(AAFwkTag::APPMGR, "appInfo null");
1754     } else {
1755         eventInfo.bundleName = applicationInfo->name;
1756         eventInfo.versionName = applicationInfo->versionName;
1757         eventInfo.versionCode = applicationInfo->versionCode;
1758         eventInfo.bundleType = static_cast<int32_t>(applicationInfo->bundleType);
1759     }
1760     if (appRecord->GetPriorityObject() != nullptr) {
1761         eventInfo.pid = appRecord->GetPid();
1762     }
1763     eventInfo.processName = appRecord->GetProcessName();
1764     eventInfo.processType = static_cast<int32_t>(appRecord->GetProcessType());
1765     return eventInfo;
1766 }
1767 
ApplicationTerminated(const int32_t recordId)1768 void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId)
1769 {
1770     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1771     if (!appRunningManager_) {
1772         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
1773         return;
1774     }
1775     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1776     if (!appRecord) {
1777         TAG_LOGE(AAFwkTag::APPMGR, "get appRecord fail");
1778         return;
1779     }
1780     appRecord->ApplicationTerminated();
1781     if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
1782         TAG_LOGD(AAFwkTag::APPMGR, "current state is not background");
1783         return;
1784     }
1785 
1786     KillRenderProcess(appRecord);
1787 #ifdef SUPPORT_CHILD_PROCESS
1788     KillChildProcess(appRecord);
1789     KillAttachedChildProcess(appRecord);
1790 #endif // SUPPORT_CHILD_PROCESS
1791     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
1792     appRecord->RemoveAppDeathRecipient();
1793     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED);
1794     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false, false);
1795     appRunningManager_->RemoveAppRunningRecordById(recordId);
1796     AAFwk::EventInfo eventInfo;
1797     auto applicationInfo = appRecord->GetApplicationInfo();
1798     if (!applicationInfo) {
1799         TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
1800     } else {
1801         eventInfo.bundleName = applicationInfo->name;
1802         eventInfo.versionName = applicationInfo->versionName;
1803         eventInfo.versionCode = applicationInfo->versionCode;
1804     }
1805     ClearAppRunningDataForKeepAlive(appRecord);
1806     eventInfo.pid = appRecord->GetPid();
1807     eventInfo.processName = appRecord->GetProcessName();
1808     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
1809 
1810     ApplicationTerminatedSendProcessEvent(appRecord);
1811     taskHandler_->CancelTask("DELAY_KILL_PROCESS_" + std::to_string(recordId));
1812     auto uid = appRecord->GetUid();
1813     bool foreground = appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND ||
1814         appRecord->GetState() == ApplicationState::APP_STATE_FOCUS;
1815     std::string killReason = appRecord->GetKillReason().empty() ? "Kill Reason:app exit" : appRecord->GetKillReason();
1816     auto result = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL",
1817         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT,
1818         EVENT_KEY_PID, std::to_string(eventInfo.pid), EVENT_KEY_PROCESS_NAME, eventInfo.processName,
1819         EVENT_KEY_MESSAGE, killReason, EVENT_KEY_FOREGROUND, foreground);
1820     TAG_LOGW(AAFwkTag::APPMGR, "hisysevent write result=%{public}d, send [FRAMEWORK,PROCESS_KILL], pid=%{public}d,"
1821         " processName=%{public}s, msg=%{public}s, FOREGROUND = %{public}d",
1822         result, eventInfo.pid, eventInfo.processName.c_str(), killReason.c_str(), foreground);
1823     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
1824 }
1825 
UpdateApplicationInfoInstalled(const std::string & bundleName,const int uid,const std::string & moduleName,bool isPlugin)1826 int32_t AppMgrServiceInner::UpdateApplicationInfoInstalled(
1827     const std::string &bundleName, const int uid, const std::string &moduleName, bool isPlugin)
1828 {
1829     if (!appRunningManager_) {
1830         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
1831         return ERR_NO_INIT;
1832     }
1833 
1834     int32_t result = VerifyRequestPermission();
1835     if (result != ERR_OK) {
1836         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
1837         return result;
1838     }
1839 
1840     if (remoteClientManager_ == nullptr) {
1841         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ fail");
1842         return ERR_NO_INIT;
1843     }
1844 
1845     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1846     if (bundleMgrHelper == nullptr) {
1847         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
1848         return ERR_NO_INIT;
1849     }
1850     auto userId = GetUserIdByUid(uid);
1851     TAG_LOGD(AAFwkTag::APPMGR, "userId: %{public}d, bundleName: %{public}s", userId, bundleName.c_str());
1852     ApplicationInfo appInfo;
1853     HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetApplicationInfo");
1854     if (isPlugin) {
1855         appInfo.bundleName = bundleName;
1856         appInfo.uid = uid;
1857         appInfo.name = bundleName;
1858         appInfo.bundleType = BundleType::APP_PLUGIN;
1859     } else {
1860         bool bundleMgrResult = bundleMgrHelper->GetApplicationInfo(bundleName,
1861             ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo);
1862         if (!bundleMgrResult) {
1863             TAG_LOGE(AAFwkTag::APPMGR, "get applicationInfo fail");
1864             return ERR_INVALID_OPERATION;
1865         }
1866     }
1867 
1868     TAG_LOGD(AAFwkTag::APPMGR, "uid value is %{public}d", uid);
1869     result = appRunningManager_->ProcessUpdateApplicationInfoInstalled(appInfo, moduleName);
1870     if (result != ERR_OK) {
1871         TAG_LOGI(AAFwkTag::APPMGR, "process corresponding package name unstart");
1872     }
1873 
1874     return result;
1875 }
1876 
KillApplication(const std::string & bundleName,bool clearPageStack,int32_t appIndex)1877 int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName, bool clearPageStack, int32_t appIndex)
1878 {
1879     TAG_LOGI(AAFwkTag::APPMGR, "call");
1880     if (!appRunningManager_) {
1881         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
1882         return ERR_NO_INIT;
1883     }
1884 
1885     auto result = VerifyKillProcessPermission(bundleName);
1886     if (result != ERR_OK) {
1887         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
1888         return result;
1889     }
1890 
1891     return KillApplicationByBundleName(bundleName, appIndex, clearPageStack, "KillApplication");
1892 }
1893 
ForceKillApplication(const std::string & bundleName,const int userId,const int appIndex)1894 int32_t AppMgrServiceInner::ForceKillApplication(const std::string &bundleName,
1895     const int userId, const int appIndex)
1896 {
1897     TAG_LOGI(AAFwkTag::APPMGR, "call");
1898     if (!IsSceneBoardCall()) {
1899         TAG_LOGE(AAFwkTag::APPMGR, "not called by sceneBoard");
1900         return AAFwk::CHECK_PERMISSION_FAILED;
1901     }
1902 
1903     return ForceKillApplicationInner(bundleName, userId, appIndex);
1904 }
1905 
ForceKillApplicationInner(const std::string & bundleName,const int userId,const int appIndex)1906 int32_t AppMgrServiceInner::ForceKillApplicationInner(const std::string &bundleName,
1907     const int userId, const int appIndex)
1908 {
1909     TAG_LOGD(AAFwkTag::APPMGR, "Called.");
1910     if (!appRunningManager_) {
1911         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
1912         return ERR_NO_INIT;
1913     }
1914 
1915     std::list<pid_t> pids;
1916     int32_t newUserId = userId;
1917     if (userId == DEFAULT_INVAL_VALUE) {
1918         newUserId = GetUserIdByUid(IPCSkeleton::GetCallingUid());
1919     }
1920     int32_t result = ERR_OK;
1921     if (!appRunningManager_->GetPidsByBundleNameUserIdAndAppIndex(bundleName, newUserId, appIndex, pids)) {
1922         TAG_LOGI(AAFwkTag::APPMGR, "unstart");
1923         return result;
1924     }
1925     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1926         result = KillProcessByPid(*iter, "ForceKillApplicationByBundleName");
1927         if (result < 0) {
1928             TAG_LOGE(AAFwkTag::APPMGR,
1929                 "forceKillApplicationByBundleName fail for bundleName:%{public}s pid:%{public}d",
1930                 bundleName.c_str(), *iter);
1931             return result;
1932         }
1933     }
1934     return result;
1935 }
1936 
WaitProcessesExitAndKill(std::list<pid_t> & pids,const int64_t startTime,const std::string & reason)1937 int32_t AppMgrServiceInner::WaitProcessesExitAndKill(std::list<pid_t> &pids, const int64_t startTime,
1938     const std::string& reason)
1939 {
1940     int32_t result = ERR_OK;
1941     if (WaitForRemoteProcessExit(pids, startTime)) {
1942         TAG_LOGI(AAFwkTag::APPMGR, "remote process exited successs");
1943         return result;
1944     }
1945     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1946         auto singleRet = KillProcessByPid(*iter, reason);
1947         if (singleRet != 0 && singleRet != AAFwk::ERR_KILL_PROCESS_NOT_EXIST) {
1948             TAG_LOGE(AAFwkTag::APPMGR, "killApplication fail for pid:%{public}d", *iter);
1949             result = singleRet;
1950         }
1951     }
1952     return result;
1953 }
1954 
DoAllProcessExitCallback(std::list<SimpleProcessInfo> & processInfos,int32_t userId,sptr<AAFwk::IUserCallback> callback,int64_t startTime)1955 bool AppMgrServiceInner::DoAllProcessExitCallback(std::list<SimpleProcessInfo> &processInfos,
1956     int32_t userId, sptr<AAFwk::IUserCallback> callback, int64_t startTime)
1957 {
1958     if (callback == nullptr) {
1959         TAG_LOGE(AAFwkTag::APPMGR, "callback nullptr");
1960         return false;
1961     }
1962     auto checkProcessExistCallback = [processInfos, userId, callback, startTime,
1963         appMgrInner = shared_from_this()] () mutable {
1964         TAG_LOGI(AAFwkTag::APPMGR, "checkProcessExistCallback call");
1965         if (callback == nullptr) {
1966             TAG_LOGE(AAFwkTag::APPMGR, "callback nullptr");
1967             return;
1968         }
1969         if (appMgrInner == nullptr) {
1970             TAG_LOGE(AAFwkTag::APPMGR, "appMgrInner nullptr");
1971             callback->OnLogoutUserDone(userId, AAFwk::ERR_LOGOUT_USER_APP_MANAGER_NULL);
1972             return;
1973         }
1974         if (ProcessUtil::IsAllProcessKilled(processInfos)) {
1975             TAG_LOGI(AAFwkTag::APPMGR, "all process exit");
1976             callback->OnLogoutUserDone(userId, ERR_OK);
1977             return;
1978         }
1979         int64_t currentTime = appMgrInner->SystemTimeMillisecond();
1980         if (currentTime - startTime > LOGOUT_USER_TIMEOUT_MILLISION_SECONDS) {
1981             TAG_LOGE(AAFwkTag::APPMGR, "kill process timeout");
1982             callback->OnLogoutUserDone(userId, AAFwk::ERR_LOGOUT_USER_KILL_PROCESS_TIMEOUT);
1983             return;
1984         }
1985         appMgrInner->DoAllProcessExitCallback(processInfos, userId, callback, startTime);
1986     };
1987     if (taskHandler_ == nullptr) {
1988         TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ nullptr");
1989         callback->OnLogoutUserDone(userId, AAFwk::ERR_LOGOUT_USER_TASK_HANDLE_NULL);
1990         return false;
1991     }
1992     taskHandler_->SubmitTaskJust(checkProcessExistCallback, "DelayCheckProcessExit",
1993         AMSEventHandler::DELAY_CHECK_ALL_PROCESSES_EXITED);
1994     return true;
1995 }
1996 
WaitProcessesExitAndKill(std::list<SimpleProcessInfo> & processInfos,const int64_t startTime,const std::string & reason,int32_t userId,sptr<AAFwk::IUserCallback> callback)1997 int32_t AppMgrServiceInner::WaitProcessesExitAndKill(std::list<SimpleProcessInfo> &processInfos,
1998     const int64_t startTime, const std::string& reason, int32_t userId, sptr<AAFwk::IUserCallback> callback)
1999 {
2000     int32_t result = ERR_OK;
2001     ProcessUtil::UpdateProcessNameByProcFile(processInfos);
2002     if (WaitForRemoteProcessExit(processInfos, startTime)) {
2003         TAG_LOGI(AAFwkTag::APPMGR, "remote process exited successs");
2004         if (callback) {
2005             callback->OnLogoutUserDone(userId, ERR_OK);
2006         }
2007         return result;
2008     }
2009     for (auto iter = processInfos.begin(); iter != processInfos.end(); ++iter) {
2010         auto singleRet = KillProcessByPid((*iter).pid, reason);
2011         if (singleRet != 0 && singleRet != AAFwk::ERR_KILL_PROCESS_NOT_EXIST) {
2012             TAG_LOGE(AAFwkTag::APPMGR, "killApplication fail for pid:%{public}d", (*iter).pid);
2013             result = singleRet;
2014         }
2015     }
2016     DoAllProcessExitCallback(processInfos, userId, callback, startTime);
2017     return result;
2018 }
2019 
KillProcessesByAccessTokenId(const uint32_t accessTokenId)2020 int32_t AppMgrServiceInner::KillProcessesByAccessTokenId(const uint32_t accessTokenId)
2021 {
2022     TAG_LOGI(AAFwkTag::APPMGR, "call");
2023     CHECK_CALLER_IS_SYSTEM_APP;
2024     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2025         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
2026     if (!isCallingPerm) {
2027         TAG_LOGE(AAFwkTag::APPMGR, "no permission to kill processes");
2028         return ERR_PERMISSION_DENIED;
2029     }
2030 
2031     int32_t result = ERR_OK;
2032     std::vector<pid_t> pids;
2033     result = GetPidsByAccessTokenId(accessTokenId, pids);
2034     if (result != ERR_OK) {
2035         return result;
2036     }
2037     if (pids.empty()) {
2038         TAG_LOGI(AAFwkTag::APPMGR, "no accessTokenId");
2039         return ERR_OK;
2040     }
2041 
2042     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
2043         result = KillProcessByPid(*iter, "KillProcessesByAccessTokenId");
2044         if (result < 0) {
2045             TAG_LOGE(AAFwkTag::APPMGR,
2046                 "killProcessesByAccessTokenId fail for accessTokenId:%{public}d,pid:%{public}d",
2047                 accessTokenId, *iter);
2048             return result;
2049         }
2050     }
2051     return result;
2052 }
2053 
KillApplicationByUid(const std::string & bundleName,const int uid,const std::string & reason)2054 int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid,
2055     const std::string& reason)
2056 {
2057     if (!appRunningManager_) {
2058         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
2059         return ERR_NO_INIT;
2060     }
2061 
2062     int32_t result = ERR_OK;
2063     result = VerifyKillProcessPermission(bundleName);
2064     if (result != ERR_OK) {
2065         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
2066         return result;
2067     }
2068 
2069     int64_t startTime = SystemTimeMillisecond();
2070     std::list<pid_t> pids;
2071     TAG_LOGI(AAFwkTag::APPMGR, "uid value: %{public}d", uid);
2072     KillProcessConfig config{false, false, reason};
2073     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids, config)) {
2074         TAG_LOGI(AAFwkTag::APPMGR, "unstart");
2075         return result;
2076     }
2077     return WaitProcessesExitAndKill(pids, startTime, reason);
2078 }
2079 
InsertUninstallOrUpgradeUidSet(int32_t uid)2080 void AppMgrServiceInner::InsertUninstallOrUpgradeUidSet(int32_t uid)
2081 {
2082     std::lock_guard lock(uninstallOrUpgradeUidSetLock_);
2083     auto ret = uninstallOrUpgradeUidSet_.insert(uid);
2084     if (!ret.second) {
2085         TAG_LOGD(AAFwkTag::APPMGR, "already inserted");
2086     }
2087 }
2088 
RemoveUninstallOrUpgradeUidSet(int32_t uid)2089 void AppMgrServiceInner::RemoveUninstallOrUpgradeUidSet(int32_t uid)
2090 {
2091     std::lock_guard lock(uninstallOrUpgradeUidSetLock_);
2092     auto ret = uninstallOrUpgradeUidSet_.erase(uid);
2093     if (ret == 0) {
2094         TAG_LOGD(AAFwkTag::APPMGR, "not exist");
2095     }
2096 }
2097 
IsUninstallingOrUpgrading(int32_t uid)2098 bool AppMgrServiceInner::IsUninstallingOrUpgrading(int32_t uid)
2099 {
2100     std::lock_guard lock(uninstallOrUpgradeUidSetLock_);
2101     if (uninstallOrUpgradeUidSet_.find(uid) != uninstallOrUpgradeUidSet_.end()) {
2102         return true;
2103     }
2104     return false;
2105 }
2106 
NotifyUninstallOrUpgradeApp(const std::string & bundleName,int32_t uid,bool isUpgrade)2107 int32_t AppMgrServiceInner::NotifyUninstallOrUpgradeApp(const std::string &bundleName, int32_t uid, bool isUpgrade)
2108 {
2109     std::unique_lock lock(startProcessLock_);
2110     std::string killReason = isUpgrade ? "UpgradeApp" : "UninstallApp";
2111     InsertUninstallOrUpgradeUidSet(uid);
2112     return KillApplicationByUid(bundleName, uid, killReason);
2113 }
2114 
NotifyUninstallOrUpgradeAppEnd(int32_t uid)2115 void AppMgrServiceInner::NotifyUninstallOrUpgradeAppEnd(int32_t uid)
2116 {
2117     RemoveUninstallOrUpgradeUidSet(uid);
2118 }
2119 
UpdateProcessMemoryState(const std::vector<ProcessMemoryState> & procMemState)2120 int32_t AppMgrServiceInner::UpdateProcessMemoryState(const std::vector<ProcessMemoryState> &procMemState)
2121 {
2122     for (const auto &state : procMemState) {
2123         auto appRecord = GetAppRunningRecordByPid(state.pid);
2124         if (!appRecord) {
2125             TAG_LOGW(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", state.pid);
2126             continue;
2127         }
2128         appRecord->SetRssValue(state.rssValue);
2129         appRecord->SetPssValue(state.pssValue);
2130     }
2131     return ERR_OK;
2132 }
2133 
SendProcessExitEventTask(pid_t pid,const std::string & processName,int32_t extensionType,int32_t exitReason,time_t exitTime,int32_t count)2134 void AppMgrServiceInner::SendProcessExitEventTask(pid_t pid, const std::string &processName, int32_t extensionType,
2135     int32_t exitReason, time_t exitTime, int32_t count)
2136 {
2137     auto exitResult = !ProcessUtil::ProcessExist(pid);
2138     constexpr int32_t EXIT_SUCESS = 0;
2139     constexpr int32_t EXIT_FAILED = -1;
2140     AAFwk::EventInfo eventInfo;
2141     eventInfo.time = exitTime;
2142     eventInfo.pid = pid;
2143     eventInfo.processName = processName;
2144     eventInfo.extensionType = extensionType;
2145     eventInfo.exitReason = exitReason;
2146 
2147     if (exitResult) {
2148         eventInfo.exitResult = EXIT_SUCESS;
2149         AAFwk::EventReport::SendProcessExitEvent(AAFwk::EventName::PROCESS_EXIT, eventInfo);
2150         return;
2151     }
2152 
2153     if (--count <= 0) {
2154         eventInfo.exitResult = EXIT_FAILED;
2155         AAFwk::EventReport::SendProcessExitEvent(AAFwk::EventName::PROCESS_EXIT, eventInfo);
2156         return;
2157     }
2158 
2159     auto sendEventTask = [innerServiceWeak = weak_from_this(), pid, processName, extensionType, exitReason, exitTime,
2160         count] () {
2161         auto innerService = innerServiceWeak.lock();
2162         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
2163         innerService->SendProcessExitEventTask(pid, processName, extensionType, exitReason, exitTime, count);
2164     };
2165     CHECK_POINTER_AND_RETURN_LOG(taskHandler_, "Task handler is nullptr.");
2166     taskHandler_->SubmitTaskJust(sendEventTask, PROCESS_EXIT_EVENT_TASK, KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
2167 }
2168 
SendProcessExitEvent(std::shared_ptr<AppRunningRecord> appRecord)2169 void AppMgrServiceInner::SendProcessExitEvent(std::shared_ptr<AppRunningRecord> appRecord)
2170 {
2171     TAG_LOGD(AAFwkTag::APPMGR, "called");
2172     if (appRecord == nullptr) {
2173         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
2174         return;
2175     }
2176     if (appRecord->GetPriorityObject() == nullptr) {
2177         TAG_LOGE(AAFwkTag::APPMGR, "priority object null");
2178         return;
2179     }
2180     time_t currentTime;
2181     time(&currentTime);
2182     constexpr int32_t RETRY_COUNT = 5;
2183 
2184     auto pid = appRecord->GetPid();
2185     auto processName = appRecord->GetProcessName();
2186     auto extensionType = static_cast<int32_t>(appRecord->GetExtensionType());
2187     auto exitReason = appRecord->GetExitReason();
2188     SendProcessExitEventTask(pid, processName, extensionType, exitReason, currentTime, RETRY_COUNT);
2189     return;
2190 }
2191 
KillApplicationSelf(const bool clearPageStack,const std::string & reason)2192 int32_t AppMgrServiceInner::KillApplicationSelf(const bool clearPageStack, const std::string& reason)
2193 {
2194     TAG_LOGI(AAFwkTag::APPMGR, "start");
2195     if (!appRunningManager_) {
2196         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
2197         return ERR_NO_INIT;
2198     }
2199 
2200     auto callerPid = IPCSkeleton::GetCallingPid();
2201     auto appRecord = GetAppRunningRecordByPid(callerPid);
2202     if (!appRecord) {
2203         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, callerPid:%{public}d", callerPid);
2204         return ERR_INVALID_VALUE;
2205     }
2206     int64_t startTime = SystemTimeMillisecond();
2207     auto bundleName = appRecord->GetBundleName();
2208     auto callingUid = IPCSkeleton::GetCallingUid();
2209     TAG_LOGI(AAFwkTag::APPMGR, "uid value: %{public}d", callingUid);
2210     std::list<pid_t> pids;
2211     KillProcessConfig config{clearPageStack, false, reason};
2212     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, callingUid, pids, config)) {
2213         TAG_LOGI(AAFwkTag::APPMGR, "unstart");
2214         return ERR_OK;
2215     }
2216     return WaitProcessesExitAndKill(pids, startTime, reason);
2217 }
2218 
KillAppSelfWithInstanceKey(const std::string & instanceKey,bool clearPageStack,const std::string & reason)2219 int32_t AppMgrServiceInner::KillAppSelfWithInstanceKey(const std::string &instanceKey, bool clearPageStack,
2220     const std::string& reason)
2221 {
2222     if (!appRunningManager_) {
2223         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
2224         return ERR_NO_INIT;
2225     }
2226 
2227     int64_t startTime = SystemTimeMillisecond();
2228     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
2229     TAG_LOGI(AAFwkTag::APPMGR, "callingTokenId value: %{public}d", callingTokenId);
2230     std::list<pid_t> pids;
2231     if (!appRunningManager_->ProcessExitByTokenIdAndInstance(callingTokenId, instanceKey, pids, clearPageStack)) {
2232         TAG_LOGI(AAFwkTag::APPMGR, "not exist");
2233         return ERR_OK;
2234     }
2235     return WaitProcessesExitAndKill(pids, startTime, reason);
2236 }
2237 
KillApplicationByBundleName(const std::string & bundleName,int32_t appIndex,bool clearPageStack,const std::string & reason)2238 int32_t AppMgrServiceInner::KillApplicationByBundleName(
2239     const std::string &bundleName, int32_t appIndex, bool clearPageStack, const std::string& reason)
2240 {
2241     int result = ERR_OK;
2242     int64_t startTime = SystemTimeMillisecond();
2243     std::list<pid_t> pids;
2244 
2245     if (!appRunningManager_->ProcessExitByBundleNameAndAppIndex(bundleName, appIndex, pids, clearPageStack)) {
2246         TAG_LOGE(AAFwkTag::APPMGR, "process corresponding to the package name did not start");
2247         return result;
2248     }
2249     result = WaitProcessesExitAndKill(pids, startTime, reason);
2250     NotifyAppStatus(bundleName, appIndex, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
2251     return result;
2252 }
2253 
KillApplicationByUserId(const std::string & bundleName,int32_t appCloneIndex,const int userId,const bool clearPageStack,const std::string & reason)2254 int32_t AppMgrServiceInner::KillApplicationByUserId(
2255     const std::string &bundleName, int32_t appCloneIndex, const int userId,
2256     const bool clearPageStack, const std::string& reason)
2257 {
2258     CHECK_CALLER_IS_SYSTEM_APP;
2259     if (VerifyAccountPermission(
2260         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES, userId) == ERR_PERMISSION_DENIED &&
2261         VerifyAccountPermission(
2262             AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES, userId) == ERR_PERMISSION_DENIED) {
2263         TAG_LOGE(AAFwkTag::APPMGR, "permission verify fail");
2264         return ERR_PERMISSION_DENIED;
2265     }
2266 
2267     KillProcessConfig config{clearPageStack, true, reason};
2268     return KillApplicationByUserIdLocked(bundleName, appCloneIndex, userId, config);
2269 }
2270 
KillApplicationByUserIdLocked(const std::string & bundleName,int32_t appCloneIndex,const int userId,const KillProcessConfig & config)2271 int32_t AppMgrServiceInner::KillApplicationByUserIdLocked(
2272     const std::string &bundleName, int32_t appCloneIndex, const int userId, const KillProcessConfig &config)
2273 {
2274     if (!appRunningManager_) {
2275         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
2276         return ERR_NO_INIT;
2277     }
2278 
2279     int64_t startTime = SystemTimeMillisecond();
2280     std::list<pid_t> pids;
2281     if (remoteClientManager_ == nullptr) {
2282         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
2283         return ERR_NO_INIT;
2284     }
2285     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2286     if (bundleMgrHelper == nullptr) {
2287         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
2288         return ERR_NO_INIT;
2289     }
2290 
2291     TAG_LOGD(AAFwkTag::APPMGR, "userId: %{public}d, bundleName: %{public}s, appCloneIndex: %{public}d",
2292         userId, bundleName.c_str(), appCloneIndex);
2293     int uid = IN_PROCESS_CALL(bundleMgrHelper->GetUidByBundleName(bundleName, userId, appCloneIndex));
2294     TAG_LOGI(AAFwkTag::APPMGR, "uID value: %{public}d", uid);
2295     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids, config)) {
2296         TAG_LOGI(AAFwkTag::APPMGR, "process corresponding package name unstart");
2297         return ERR_OK;
2298     }
2299     return WaitProcessesExitAndKill(pids, startTime, "KillApplicationByUserId");
2300 }
2301 
ClearUpApplicationData(const std::string & bundleName,int32_t callerUid,pid_t callerPid,int32_t appCloneIndex,int32_t userId)2302 int32_t AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName,
2303     int32_t callerUid, pid_t callerPid, int32_t appCloneIndex, int32_t userId)
2304 {
2305     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2306     int32_t newUserId = userId;
2307     if (userId == DEFAULT_INVAL_VALUE) {
2308         newUserId = GetUserIdByUid(callerUid);
2309         if (newUserId == U0_USER_ID || newUserId == U1_USER_ID) {
2310             newUserId = currentUserId_;
2311         }
2312     }
2313     TAG_LOGI(AAFwkTag::APPMGR, "bundleName: %{public}s, uId: %{public}d, appIndex: %{public}d", bundleName.c_str(),
2314         newUserId, appCloneIndex);
2315     return ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, appCloneIndex, newUserId,
2316         false, "ClearUpApplicationData");
2317 }
2318 
ClearUpApplicationDataBySelf(int32_t callerUid,pid_t callerPid,int32_t userId)2319 int32_t AppMgrServiceInner::ClearUpApplicationDataBySelf(int32_t callerUid, pid_t callerPid, int32_t userId)
2320 {
2321     auto appRecord = GetAppRunningRecordByPid(callerPid);
2322     if (!appRecord) {
2323         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, callerPid:%{public}d", callerPid);
2324         return ERR_INVALID_VALUE;
2325     }
2326     auto callerBundleName = appRecord->GetBundleName();
2327     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2328     int32_t newUserId = userId;
2329     if (userId == DEFAULT_INVAL_VALUE) {
2330         newUserId = GetUserIdByUid(callerUid);
2331         if (newUserId == U0_USER_ID) {
2332             newUserId = currentUserId_;
2333         }
2334     }
2335     auto appCloneIndex = appRecord->GetAppIndex();
2336     return ClearUpApplicationDataByUserId(callerBundleName, callerUid, callerPid, appCloneIndex, newUserId, true,
2337         "ClearUpApplicationDataBySelf");
2338 }
2339 
ClearUpApplicationDataByUserId(const std::string & bundleName,int32_t callerUid,pid_t callerPid,int32_t appCloneIndex,int32_t userId,bool isBySelf,const std::string & reason)2340 int32_t AppMgrServiceInner::ClearUpApplicationDataByUserId(const std::string &bundleName, int32_t callerUid,
2341     pid_t callerPid, int32_t appCloneIndex, int32_t userId, bool isBySelf, const std::string& reason)
2342 {
2343     if (callerPid <= 0) {
2344         TAG_LOGE(AAFwkTag::APPMGR, "invalid callerPid:%{public}d", callerPid);
2345         return ERR_INVALID_OPERATION;
2346     }
2347     if (callerUid < 0) {
2348         TAG_LOGE(AAFwkTag::APPMGR, "invalid callerUid:%{public}d", callerUid);
2349         return ERR_INVALID_OPERATION;
2350     }
2351     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2352     if (bundleMgrHelper == nullptr) {
2353         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
2354         return ERR_INVALID_OPERATION;
2355     }
2356 
2357     // request to clear user information permission.
2358     TAG_LOGD(AAFwkTag::APPMGR, "userId: %{public}d, bundleName: %{public}s, appCloneIndex: %{public}d",
2359         userId, bundleName.c_str(), appCloneIndex);
2360     auto tokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, appCloneIndex);
2361     int32_t result = AccessToken::AccessTokenKit::ClearUserGrantedPermissionState(tokenId);
2362     if (result != ERR_OK) {
2363         TAG_LOGE(AAFwkTag::APPMGR, "clearUserGrantedPermissionState fail, ret:%{public}d", result);
2364         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
2365     }
2366     // 2.delete bundle side user data
2367     if (!IN_PROCESS_CALL(bundleMgrHelper->CleanBundleDataFiles(bundleName, userId, appCloneIndex, callerUid))) {
2368         TAG_LOGE(AAFwkTag::APPMGR, "delete user data fail");
2369         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
2370     }
2371     // 3.kill application
2372     // 4.revoke user rights
2373     result =
2374         isBySelf ? KillApplicationSelf(false, reason)
2375             : KillApplicationByUserId(bundleName, appCloneIndex, userId, false, reason);
2376     if (result < 0) {
2377         TAG_LOGE(AAFwkTag::APPMGR, "kill app fail");
2378         return ERR_INVALID_OPERATION;
2379     }
2380     // 5.revoke uri permission rights
2381 #ifdef SUPPORT_UPMS
2382     auto ret = IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().RevokeAllUriPermissions(tokenId));
2383     if (ret != ERR_OK) {
2384         TAG_LOGE(AAFwkTag::APPMGR, "revoke all uri permissions fail");
2385     }
2386 #endif // SUPPORT_UPMS
2387     auto dataMgr = OHOS::DistributedKv::DistributedDataMgr();
2388     auto dataRet = dataMgr.ClearAppStorage(bundleName, userId, appCloneIndex, tokenId);
2389     if (dataRet != 0) {
2390         TAG_LOGW(
2391             AAFwkTag::APPMGR, "fail, bundleName:%{public}s", bundleName.c_str());
2392     }
2393     int targetUid = IN_PROCESS_CALL(bundleMgrHelper->GetUidByBundleName(bundleName, userId, appCloneIndex));
2394     NotifyAppStatusByCallerUid(bundleName, tokenId, userId, callerUid, targetUid,
2395         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
2396     TAG_LOGI(AAFwkTag::APPMGR, "clear");
2397     return ERR_OK;
2398 }
2399 
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)2400 int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
2401 {
2402     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2403     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2404     // check permission
2405     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2406         const auto &appRecord = item.second;
2407         if (!appRecord || !appRecord->GetSpawned()) {
2408             continue;
2409         }
2410         if (isPerm) {
2411             GetRunningProcesses(appRecord, info);
2412         } else {
2413             auto applicationInfo = appRecord->GetApplicationInfo();
2414             if (!applicationInfo) {
2415                 continue;
2416             }
2417             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
2418             auto tokenId = applicationInfo->accessTokenId;
2419             if (callingTokenId == tokenId) {
2420                 GetRunningProcesses(appRecord, info);
2421             }
2422         }
2423     }
2424     return ERR_OK;
2425 }
2426 
GetRunningProcessesByBundleType(BundleType bundleType,std::vector<RunningProcessInfo> & info)2427 int32_t AppMgrServiceInner::GetRunningProcessesByBundleType(BundleType bundleType,
2428     std::vector<RunningProcessInfo> &info)
2429 {
2430     TAG_LOGD(AAFwkTag::APPMGR, "called");
2431     CHECK_CALLER_IS_SYSTEM_APP;
2432     if (!AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm()) {
2433         TAG_LOGE(AAFwkTag::APPMGR, "permission deny");
2434         return ERR_PERMISSION_DENIED;
2435     }
2436     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2437         const auto &appRecord = item.second;
2438         if (!appRecord || !appRecord->GetSpawned()) {
2439             continue;
2440         }
2441         if (GetUserIdByUid(appRecord->GetUid()) != currentUserId_) {
2442             continue;
2443         }
2444         auto appInfo = appRecord->GetApplicationInfo();
2445         if (appInfo && appInfo->bundleType == bundleType) {
2446             GetRunningProcesses(appRecord, info);
2447         }
2448     }
2449     return ERR_OK;
2450 }
2451 
GetRunningMultiAppInfoByBundleName(const std::string & bundleName,RunningMultiAppInfo & info)2452 int32_t AppMgrServiceInner::GetRunningMultiAppInfoByBundleName(const std::string &bundleName,
2453     RunningMultiAppInfo &info)
2454 {
2455     if (bundleName.empty()) {
2456         TAG_LOGE(AAFwkTag::APPMGR, "bundlename null");
2457         return AAFwk::INVALID_PARAMETERS_ERR;
2458     }
2459     if (remoteClientManager_ == nullptr) {
2460         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
2461         return ERR_INVALID_VALUE;
2462     }
2463     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2464     if (bundleMgrHelper == nullptr) {
2465         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
2466         return ERR_INVALID_VALUE;
2467     }
2468     ApplicationInfo appInfo;
2469     TAG_LOGD(AAFwkTag::APPMGR, "userId: %{public}d, bundleName: %{public}s", currentUserId_, bundleName.c_str());
2470     auto queryRet = IN_PROCESS_CALL(bundleMgrHelper->GetApplicationInfo(bundleName,
2471         ApplicationFlag::GET_BASIC_APPLICATION_INFO, currentUserId_, appInfo));
2472     if (!queryRet) {
2473         TAG_LOGE(AAFwkTag::APPMGR, "bundle unexist");
2474         return AAFwk::ERR_BUNDLE_NOT_EXIST;
2475     }
2476     if (appInfo.multiAppMode.multiAppModeType == MultiAppModeType::UNSPECIFIED) {
2477         TAG_LOGE(AAFwkTag::APPMGR, "bundle unsupport multi-app");
2478         return AAFwk::ERR_MULTI_APP_NOT_SUPPORTED;
2479     }
2480     info.bundleName = bundleName;
2481     info.mode = static_cast<int32_t>(appInfo.multiAppMode.multiAppModeType);
2482     if (!appRunningManager_) {
2483         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
2484         return ERR_INVALID_VALUE;
2485     }
2486     auto multiAppInfoMap = appRunningManager_->GetAppRunningRecordMap();
2487     for (const auto &item : multiAppInfoMap) {
2488         const std::shared_ptr<AppRunningRecord> &appRecord = item.second;
2489         if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) {
2490             continue;
2491         }
2492         if (GetUserIdByUid(appRecord->GetUid()) != currentUserId_) {
2493             continue;
2494         }
2495 #ifdef SUPPORT_CHILD_PROCESS
2496         GetRunningCloneAppInfo(appRecord, info);
2497 #endif // SUPPORT_CHILD_PROCESS
2498     }
2499     return ERR_OK;
2500 }
2501 
GetAllRunningInstanceKeysBySelf(std::vector<std::string> & instanceKeys)2502 int32_t AppMgrServiceInner::GetAllRunningInstanceKeysBySelf(std::vector<std::string> &instanceKeys)
2503 {
2504     if (remoteClientManager_ == nullptr) {
2505         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
2506         return ERR_NO_INIT;
2507     }
2508     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2509     if (bundleMgrHelper == nullptr) {
2510         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
2511         return ERR_INVALID_VALUE;
2512     }
2513     std::string bundleName;
2514     int32_t callingUid = IPCSkeleton::GetCallingUid();
2515     auto ret = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, bundleName));
2516     if (ret != ERR_OK) {
2517         TAG_LOGE(AAFwkTag::APPMGR, "GetNameForUid failed, ret=%{public}d", ret);
2518         return AAFwk::ERR_BUNDLE_NOT_EXIST;
2519     }
2520     return GetAllRunningInstanceKeysByBundleNameInner(bundleName, instanceKeys, currentUserId_);
2521 }
2522 
GetAllRunningInstanceKeysByBundleName(const std::string & bundleName,std::vector<std::string> & instanceKeys,int32_t userId)2523 int32_t AppMgrServiceInner::GetAllRunningInstanceKeysByBundleName(const std::string &bundleName,
2524     std::vector<std::string> &instanceKeys, int32_t userId)
2525 {
2526     if (userId == -1) {
2527         userId = currentUserId_;
2528     }
2529     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
2530         ERR_PERMISSION_DENIED) {
2531         TAG_LOGE(AAFwkTag::APPMGR, "%{public}s: Permission verification fail", __func__);
2532         return ERR_PERMISSION_DENIED;
2533     }
2534     return GetAllRunningInstanceKeysByBundleNameInner(bundleName, instanceKeys, userId);
2535 }
2536 
GetAllRunningInstanceKeysByBundleNameInner(const std::string & bundleName,std::vector<std::string> & instanceKeys,int32_t userId)2537 int32_t AppMgrServiceInner::GetAllRunningInstanceKeysByBundleNameInner(const std::string &bundleName,
2538     std::vector<std::string> &instanceKeys, int32_t userId)
2539 {
2540     if (bundleName.empty()) {
2541         TAG_LOGE(AAFwkTag::APPMGR, "bundlename null");
2542         return AAFwk::INVALID_PARAMETERS_ERR;
2543     }
2544     if (remoteClientManager_ == nullptr) {
2545         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
2546         return ERR_INVALID_VALUE;
2547     }
2548     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
2549     if (bundleMgrHelper == nullptr) {
2550         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
2551         return ERR_INVALID_VALUE;
2552     }
2553     ApplicationInfo appInfo;
2554     TAG_LOGD(AAFwkTag::APPMGR, "userId: %{public}d, bundleName: %{public}s", userId, bundleName.c_str());
2555     auto queryRet = IN_PROCESS_CALL(bundleMgrHelper->GetApplicationInfo(bundleName,
2556         ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo));
2557     if (!queryRet) {
2558         TAG_LOGE(AAFwkTag::APPMGR, "bundle unexist");
2559         return AAFwk::ERR_BUNDLE_NOT_EXIST;
2560     }
2561     if (appInfo.multiAppMode.multiAppModeType != MultiAppModeType::MULTI_INSTANCE) {
2562         TAG_LOGE(AAFwkTag::APPMGR, "bundle unsupport multi-instance");
2563         return AAFwk::ERR_MULTI_INSTANCE_NOT_SUPPORTED;
2564     }
2565     if (!appRunningManager_) {
2566         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
2567         return ERR_INVALID_VALUE;
2568     }
2569     auto multiAppInfoMap = appRunningManager_->GetAppRunningRecordMap();
2570     for (const auto &item : multiAppInfoMap) {
2571         const std::shared_ptr<AppRunningRecord> &appRecord = item.second;
2572         if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) {
2573             continue;
2574         }
2575         if (GetUserIdByUid(appRecord->GetUid()) != userId) {
2576             continue;
2577         }
2578         GetRunningMultiInstanceKeys(appRecord, instanceKeys);
2579     }
2580     return ERR_OK;
2581 }
2582 
2583 #ifdef SUPPORT_CHILD_PROCESS
GetRunningCloneAppInfo(const std::shared_ptr<AppRunningRecord> & appRecord,RunningMultiAppInfo & info)2584 void AppMgrServiceInner::GetRunningCloneAppInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
2585     RunningMultiAppInfo &info)
2586 {
2587     if (info.mode == static_cast<int32_t>(MultiAppModeType::APP_CLONE)) {
2588         GetAppCloneInfo(appRecord, info);
2589         return;
2590     }
2591     if (info.mode == static_cast<int32_t>(MultiAppModeType::MULTI_INSTANCE)) {
2592         GetMultiInstanceInfo(appRecord, info);
2593     }
2594 }
2595 #endif // SUPPORT_CHILD_PROCESS
2596 
CheckAppRecordAndPriorityObject(const std::shared_ptr<AppRunningRecord> & appRecord)2597 bool AppMgrServiceInner::CheckAppRecordAndPriorityObject(const std::shared_ptr<AppRunningRecord> &appRecord)
2598 {
2599     if (!appRecord) {
2600         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
2601         return false;
2602     }
2603     if (appRecord->GetPriorityObject() == nullptr) {
2604         TAG_LOGE(AAFwkTag::APPMGR, "priorityObject null");
2605         return false;
2606     }
2607     return true;
2608 }
2609 
2610 #ifdef SUPPORT_CHILD_PROCESS
GetAppCloneInfo(const std::shared_ptr<AppRunningRecord> & appRecord,RunningMultiAppInfo & info)2611 void AppMgrServiceInner::GetAppCloneInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
2612     RunningMultiAppInfo &info)
2613 {
2614     if (!CheckAppRecordAndPriorityObject(appRecord)) {
2615         return;
2616     }
2617     auto PriorityObject = appRecord->GetPriorityObject();
2618     size_t index = 0;
2619     for (; index < info.runningAppClones.size(); index++) {
2620         if (info.runningAppClones[index].appCloneIndex == appRecord->GetAppIndex()) {
2621             break;
2622         }
2623     }
2624     auto childProcessRecordMap = appRecord->GetChildProcessRecordMap();
2625     if (index < info.runningAppClones.size()) {
2626         info.runningAppClones[index].pids.emplace_back(PriorityObject->GetPid());
2627         for (auto it : childProcessRecordMap) {
2628             info.runningAppClones[index].pids.emplace_back(it.first);
2629         }
2630         return;
2631     }
2632     RunningAppClone cloneInfo;
2633     cloneInfo.appCloneIndex = appRecord->GetAppIndex();
2634     cloneInfo.uid = appRecord->GetUid();
2635     cloneInfo.pids.emplace_back(PriorityObject->GetPid());
2636     for (auto it : childProcessRecordMap) {
2637         cloneInfo.pids.emplace_back(it.first);
2638     }
2639     info.runningAppClones.emplace_back(cloneInfo);
2640 }
2641 
GetMultiInstanceInfo(const std::shared_ptr<AppRunningRecord> & appRecord,RunningMultiAppInfo & info)2642 void AppMgrServiceInner::GetMultiInstanceInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
2643     RunningMultiAppInfo &info)
2644 {
2645     if (!CheckAppRecordAndPriorityObject(appRecord)) {
2646         return;
2647     }
2648     auto PriorityObject = appRecord->GetPriorityObject();
2649     size_t index = 0;
2650     for (; index < info.runningMultiIntanceInfos.size(); index++) {
2651         if (info.runningMultiIntanceInfos[index].instanceKey == appRecord->GetInstanceKey()) {
2652             break;
2653         }
2654     }
2655     auto childProcessRecordMap = appRecord->GetChildProcessRecordMap();
2656     if (index < info.runningMultiIntanceInfos.size()) {
2657         info.runningMultiIntanceInfos[index].pids.emplace_back(PriorityObject->GetPid());
2658         for (auto it : childProcessRecordMap) {
2659             info.runningMultiIntanceInfos[index].pids.emplace_back(it.first);
2660         }
2661         return;
2662     }
2663     RunningMultiInstanceInfo instanceInfo;
2664     instanceInfo.instanceKey = appRecord->GetInstanceKey();
2665     instanceInfo.uid = appRecord->GetUid();
2666     instanceInfo.pids.emplace_back(PriorityObject->GetPid());
2667     for (auto it : childProcessRecordMap) {
2668         instanceInfo.pids.emplace_back(it.first);
2669     }
2670     info.runningMultiIntanceInfos.emplace_back(instanceInfo);
2671 }
2672 #endif // SUPPORT_CHILD_PROCESS
2673 
GetRunningMultiInstanceKeys(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<std::string> & instanceKeys)2674 void AppMgrServiceInner::GetRunningMultiInstanceKeys(const std::shared_ptr<AppRunningRecord> &appRecord,
2675     std::vector<std::string> &instanceKeys)
2676 {
2677     if (!appRecord) {
2678         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
2679         return;
2680     }
2681     auto PriorityObject = appRecord->GetPriorityObject();
2682     if (!PriorityObject) {
2683         TAG_LOGE(AAFwkTag::APPMGR, "priorityObject null");
2684         return;
2685     }
2686     size_t index = 0;
2687     for (; index < instanceKeys.size(); ++index) {
2688         if (instanceKeys[index] == appRecord->GetInstanceKey()) {
2689             return;
2690         }
2691     }
2692     instanceKeys.emplace_back(appRecord->GetInstanceKey());
2693 }
2694 
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)2695 int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
2696 {
2697     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
2698         ERR_PERMISSION_DENIED) {
2699         TAG_LOGE(AAFwkTag::APPMGR, "%{public}s: Permission verification fail", __func__);
2700         return ERR_PERMISSION_DENIED;
2701     }
2702 
2703     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2704         const auto &appRecord = item.second;
2705         if (!appRecord || !appRecord->GetSpawned()) {
2706             continue;
2707         }
2708         int32_t userIdTemp = static_cast<int32_t>(appRecord->GetUid() / USER_SCALE);
2709         if (userIdTemp == userId) {
2710             GetRunningProcesses(appRecord, info);
2711         }
2712     }
2713     return ERR_OK;
2714 }
2715 
GetProcessRunningInformation(RunningProcessInfo & info)2716 int32_t AppMgrServiceInner::GetProcessRunningInformation(RunningProcessInfo &info)
2717 {
2718     if (!appRunningManager_) {
2719         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
2720         return ERR_NO_INIT;
2721     }
2722     auto callerPid = IPCSkeleton::GetCallingPid();
2723     auto appRecord = GetAppRunningRecordByPid(callerPid);
2724     if (!appRecord) {
2725         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, callerPid:%{public}d", callerPid);
2726         return ERR_INVALID_VALUE;
2727     }
2728     GetRunningProcess(appRecord, info);
2729     return ERR_OK;
2730 }
2731 
GetAllRenderProcesses(std::vector<RenderProcessInfo> & info)2732 int32_t AppMgrServiceInner::GetAllRenderProcesses(std::vector<RenderProcessInfo> &info)
2733 {
2734     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2735     // check permission
2736     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2737         const auto &appRecord = item.second;
2738         if (isPerm) {
2739             GetRenderProcesses(appRecord, info);
2740         } else {
2741             if (appRecord == nullptr) {
2742                 continue;
2743             }
2744             auto applicationInfo = appRecord->GetApplicationInfo();
2745             if (!applicationInfo) {
2746                 continue;
2747             }
2748             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
2749             auto tokenId = applicationInfo->accessTokenId;
2750             if (callingTokenId == tokenId) {
2751                 GetRenderProcesses(appRecord, info);
2752             }
2753         }
2754     }
2755     return ERR_OK;
2756 }
2757 
2758 #ifdef SUPPORT_CHILD_PROCESS
GetAllChildrenProcesses(std::vector<ChildProcessInfo> & info)2759 int AppMgrServiceInner::GetAllChildrenProcesses(std::vector<ChildProcessInfo> &info)
2760 {
2761     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2762     // check permission
2763     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2764         const auto &appRecord = item.second;
2765         if (isPerm) {
2766             GetChildrenProcesses(appRecord, info);
2767         } else {
2768             auto applicationInfo = appRecord->GetApplicationInfo();
2769             if (!applicationInfo) {
2770                 continue;
2771             }
2772             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
2773             auto tokenId = applicationInfo->accessTokenId;
2774             if (callingTokenId == tokenId) {
2775                 GetChildrenProcesses(appRecord, info);
2776             }
2777         }
2778     }
2779     return ERR_OK;
2780 }
2781 #endif // SUPPORT_CHILD_PROCESS
2782 
NotifyMemoryLevel(int32_t level)2783 int32_t AppMgrServiceInner::NotifyMemoryLevel(int32_t level)
2784 {
2785     TAG_LOGI(AAFwkTag::APPMGR, "start");
2786 
2787     bool isMemmgrCall = AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(
2788         MEMMGR_PROC_NAME);
2789     if (!isMemmgrCall) {
2790         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not %{public}s", MEMMGR_PROC_NAME);
2791         return ERR_INVALID_VALUE;
2792     }
2793     if (!(level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_MODERATE ||
2794         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_CRITICAL ||
2795         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_LOW)) {
2796         TAG_LOGE(AAFwkTag::APPMGR, "level value error");
2797         return ERR_INVALID_VALUE;
2798     }
2799     if (!appRunningManager_) {
2800         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
2801         return ERR_INVALID_VALUE;
2802     }
2803 
2804     return appRunningManager_->NotifyMemoryLevel(level);
2805 }
2806 
NotifyProcMemoryLevel(const std::map<pid_t,MemoryLevel> & procLevelMap)2807 int32_t AppMgrServiceInner::NotifyProcMemoryLevel(const std::map<pid_t, MemoryLevel> &procLevelMap)
2808 {
2809     TAG_LOGI(AAFwkTag::APPMGR, "start");
2810 
2811     bool isMemmgrCall = AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(
2812         MEMMGR_PROC_NAME);
2813     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
2814     bool isDevelopMode = system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
2815     if (!(isMemmgrCall || (isShellCall && isDevelopMode))) {
2816         TAG_LOGE(AAFwkTag::APPMGR, "Permission check failed: callerToken is not %{public}s, isMemmgrCall=%{public}d, "
2817         "isShellCall=%{public}d, isDevelopMode=%{public}d", MEMMGR_PROC_NAME, isMemmgrCall, isShellCall, isDevelopMode);
2818         return ERR_INVALID_VALUE;
2819     }
2820     if (!appRunningManager_) {
2821         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
2822         return ERR_INVALID_VALUE;
2823     }
2824 
2825     return appRunningManager_->NotifyProcMemoryLevel(procLevelMap);
2826 }
2827 
DumpHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)2828 int32_t AppMgrServiceInner::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
2829 {
2830     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2831     if (!isSaCall) {
2832         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not SA");
2833         return ERR_INVALID_VALUE;
2834     }
2835     if (pid < 0) {
2836         TAG_LOGE(AAFwkTag::APPMGR, "pid illegal");
2837         return ERR_INVALID_VALUE;
2838     }
2839     if (!appRunningManager_) {
2840         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
2841         return ERR_INVALID_VALUE;
2842     }
2843     return appRunningManager_->DumpHeapMemory(pid, mallocInfo);
2844 }
2845 
DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)2846 int32_t AppMgrServiceInner::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
2847 {
2848     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2849     if (!isSaCall) {
2850         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not SA");
2851         return ERR_INVALID_VALUE;
2852     }
2853     if (info.pid == 0) {
2854         TAG_LOGE(AAFwkTag::APPMGR, "pid illegal");
2855         return ERR_INVALID_VALUE;
2856     }
2857     if (!appRunningManager_) {
2858         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
2859         return ERR_INVALID_VALUE;
2860     }
2861     return appRunningManager_->DumpJsHeapMemory(info);
2862 }
2863 
DumpCjHeapMemory(OHOS::AppExecFwk::CjHeapDumpInfo & info)2864 int32_t AppMgrServiceInner::DumpCjHeapMemory(OHOS::AppExecFwk::CjHeapDumpInfo &info)
2865 {
2866     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2867     if (!isSaCall) {
2868         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not SA");
2869         return ERR_INVALID_VALUE;
2870     }
2871     if (info.pid <= 0) {
2872         TAG_LOGE(AAFwkTag::APPMGR, "pid illegal");
2873         return ERR_INVALID_VALUE;
2874     }
2875     static std::mutex mutex_;
2876     std::lock_guard<std::mutex> lock(mutex_);
2877     if (!appRunningManager_) {
2878         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
2879         return ERR_INVALID_VALUE;
2880     }
2881     return appRunningManager_->DumpCjHeapMemory(info);
2882 }
2883 
GetRunningProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RunningProcessInfo> & info)2884 void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
2885     std::vector<RunningProcessInfo> &info)
2886 {
2887     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2888     RunningProcessInfo runningProcessInfo;
2889     GetRunningProcess(appRecord, runningProcessInfo);
2890     info.emplace_back(runningProcessInfo);
2891 }
2892 
GetRunningProcess(const std::shared_ptr<AppRunningRecord> & appRecord,RunningProcessInfo & info)2893 void AppMgrServiceInner::GetRunningProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
2894     RunningProcessInfo &info)
2895 {
2896     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord unexist");
2897     info.processName_ = appRecord->GetProcessName();
2898     info.pid_ = appRecord->GetPid();
2899     info.uid_ = appRecord->GetUid();
2900     info.state_ = static_cast<AppProcessState>(appRecord->GetState());
2901     info.isContinuousTask = appRecord->IsContinuousTask();
2902     info.isKeepAlive = appRecord->IsKeepAliveApp();
2903     info.isKeepAliveAppService = appRecord->IsKeepAliveAppService();
2904     info.isFocused = appRecord->GetFocusFlag();
2905     info.startTimeMillis_ = appRecord->GetAppStartTime();
2906     appRecord->GetBundleNames(info.bundleNames);
2907     info.processType_ = appRecord->GetProcessType();
2908     info.extensionType_ = appRecord->GetExtensionType();
2909     info.preloadMode_ = appRecord->GetPreloadMode();
2910     info.isDebugApp  = appRecord->IsDebug();
2911     info.isExiting = appRecord->IsTerminating() || appRecord->IsKilling()
2912         || appRecord->GetRestartAppFlag() || appRecord->IsUserRequestCleaning();
2913     info.isPreForeground  = appRecord->IsPreForeground();
2914     info.isCached = DelayedSingleton<CacheProcessManager>::GetInstance()->IsCachedProcess(appRecord);
2915     if (appRecord->GetUserTestInfo() != nullptr && system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
2916         info.isTestMode = true;
2917     }
2918     auto appInfo = appRecord->GetApplicationInfo();
2919     if (appInfo) {
2920         info.bundleType = static_cast<int32_t>(appInfo->bundleType);
2921         if (appInfo->multiAppMode.multiAppModeType == MultiAppModeType::APP_CLONE) {
2922             info.appCloneIndex = appRecord->GetAppIndex();
2923         }
2924     }
2925 }
2926 
GetRenderProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RenderProcessInfo> & info)2927 void AppMgrServiceInner::GetRenderProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
2928     std::vector<RenderProcessInfo> &info)
2929 {
2930     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord unexist");
2931     auto renderRecordMap = appRecord->GetRenderRecordMap();
2932     if (renderRecordMap.empty()) {
2933         return;
2934     }
2935     for (auto iter : renderRecordMap) {
2936         auto renderRecord = iter.second;
2937         if (renderRecord != nullptr) {
2938             RenderProcessInfo renderProcessInfo;
2939             renderProcessInfo.bundleName_ = renderRecord->GetHostBundleName();
2940             renderProcessInfo.processName_ = renderRecord->GetProcessName();
2941             renderProcessInfo.pid_ = renderRecord->GetPid();
2942             renderProcessInfo.uid_ = renderRecord->GetUid();
2943             renderProcessInfo.hostUid_ = renderRecord->GetHostUid();
2944             renderProcessInfo.hostPid_ = renderRecord->GetHostPid();
2945             renderProcessInfo.state_ = renderRecord->GetState();
2946             info.emplace_back(renderProcessInfo);
2947         }
2948     }
2949 }
2950 
2951 #ifdef SUPPORT_CHILD_PROCESS
GetChildrenProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<ChildProcessInfo> & info)2952 void AppMgrServiceInner::GetChildrenProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
2953     std::vector<ChildProcessInfo> &info)
2954 {
2955     auto childProcessRecordMap = appRecord->GetChildProcessRecordMap();
2956     if (childProcessRecordMap.empty()) {
2957         return;
2958     }
2959     int32_t retCode = ERR_OK;
2960     for (auto iter : childProcessRecordMap) {
2961         auto childProcessRecord = iter.second;
2962         if (childProcessRecord != nullptr) {
2963             ChildProcessInfo childProcessInfo;
2964             retCode = GetChildProcessInfo(childProcessRecord, appRecord, childProcessInfo, true);
2965             if (retCode != ERR_OK) {
2966                 TAG_LOGW(
2967                     AAFwkTag::APPMGR, "GetChildProcessInfo failed. host pid=%{public}d, child pid=%{public}d",
2968                     appRecord->GetPid(), childProcessRecord->GetPid());
2969                 continue;
2970             }
2971             info.emplace_back(childProcessInfo);
2972         }
2973     }
2974 }
2975 #endif // SUPPORT_CHILD_PROCESS
2976 
KillProcessByPid(const pid_t pid,const std::string & reason,bool isKillPrecedeStart)2977 int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid, const std::string& reason, bool isKillPrecedeStart)
2978 {
2979     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2980     if (!ProcessUtil::ProcessExist(pid)) {
2981         TAG_LOGI(AAFwkTag::APPMGR, "null killProcessByPid, pid: %{public}d", pid);
2982         return AAFwk::ERR_KILL_PROCESS_NOT_EXIST;
2983     }
2984     std::string killReason = KILL_PROCESS_REASON_PREFIX + reason + ",callingPid=" +
2985         std::to_string(IPCSkeleton::GetCallingPid());
2986     auto appRecord = GetAppRunningRecordByPid(pid);
2987     if (appRecord && appRecord->GetExitReason() == EXIT_REASON_UNKNOWN) {
2988         appRecord->SetExitMsg(killReason);
2989     }
2990     TAG_LOGI(AAFwkTag::APPMGR, "kill reason=%{public}s, pid=%{public}d", reason.c_str(), pid);
2991     return KillProcessByPidInner(pid, reason, killReason, appRecord, isKillPrecedeStart);
2992 }
2993 
KillProcessByPidInner(const pid_t pid,const std::string & reason,const std::string & killReason,std::shared_ptr<AppRunningRecord> appRecord,bool isKillPrecedeStart)2994 int32_t AppMgrServiceInner::KillProcessByPidInner(const pid_t pid, const std::string& reason,
2995     const std::string& killReason, std::shared_ptr<AppRunningRecord> appRecord, bool isKillPrecedeStart)
2996 {
2997     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2998     AAFwk::RecordCostTimeUtil timeRecord("KillProcessByPidInner");
2999     int32_t ret = -1;
3000     if (pid > 0) {
3001         if (CheckIsThreadInFoundation(pid)) {
3002             TAG_LOGI(AAFwkTag::APPMGR, "don't kill pid %{public}d", pid);
3003             return AAFwk::ERR_KILL_FOUNDATION_UID;
3004         }
3005         ret = kill(pid, SIGNAL_KILL);
3006         if (ret == -1 && errno == ESRCH) {
3007             TAG_LOGW(AAFwkTag::APPMGR, "kill process not exist, pid=%{public}d", pid);
3008             return AAFwk::ERR_KILL_PROCESS_NOT_EXIST;
3009         }
3010         if (reason == "OnRemoteDied") {
3011             TAG_LOGW(AAFwkTag::APPMGR, "application is dead, double check, pid=%{public}d", pid);
3012         } else {
3013             TAG_LOGW(AAFwkTag::APPMGR, "kill pid %{public}d, ret:%{public}d, %{public}s",
3014                 pid, ret, killReason.c_str());
3015         }
3016     }
3017     CHECK_POINTER_AND_RETURN_VALUE(appRecord, ret);
3018     AAFwk::EventInfo eventInfo;
3019     SetKilledEventInfo(appRecord, eventInfo);
3020     appRecord->SetKillReason(reason);
3021     appRecord->SetIsKillPrecedeStart(isKillPrecedeStart);
3022     if (ret >= 0) {
3023         AddToKillProcessMap(appRecord->GetProcessName());
3024     }
3025     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
3026     std::string newReason = appRecord->GetKillReason().empty() ? killReason : appRecord->GetKillReason();
3027     bool foreground = appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND ||
3028         appRecord->GetState() == ApplicationState::APP_STATE_FOCUS;
3029     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
3030     int result = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL",
3031         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_KEY_PID, std::to_string(eventInfo.pid),
3032         EVENT_KEY_PROCESS_NAME, eventInfo.processName, EVENT_KEY_MESSAGE, newReason,
3033         EVENT_KEY_FOREGROUND, foreground);
3034     TAG_LOGW(AAFwkTag::APPMGR, "hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL], pid="
3035         "%{public}d, processName=%{public}s, msg=%{public}s, FOREGROUND=%{public}d, ret=%{public}d",
3036         result, pid, eventInfo.processName.c_str(), newReason.c_str(), foreground, ret);
3037     return ret;
3038 }
3039 
SetKilledEventInfo(std::shared_ptr<AppRunningRecord> appRecord,AAFwk::EventInfo & eventInfo)3040 void AppMgrServiceInner::SetKilledEventInfo(std::shared_ptr<AppRunningRecord> appRecord, AAFwk::EventInfo &eventInfo)
3041 {
3042     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord is null");
3043     auto applicationInfo = appRecord->GetApplicationInfo();
3044     if (!applicationInfo) {
3045         TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
3046     } else {
3047         eventInfo.bundleName = applicationInfo->name;
3048         eventInfo.versionName = applicationInfo->versionName;
3049         eventInfo.versionCode = applicationInfo->versionCode;
3050     }
3051     eventInfo.pid = appRecord->GetPid();
3052     eventInfo.processName = appRecord->GetProcessName();
3053 }
3054 
AddToKillProcessMap(const std::string & processName)3055 void AppMgrServiceInner::AddToKillProcessMap(const std::string &processName)
3056 {
3057     std::lock_guard lock(killedProcessMapLock_);
3058     int64_t killTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::
3059         system_clock::now().time_since_epoch()).count();
3060     killedProcessMap_.emplace(killTime, processName);
3061 }
3062 
CheckIsThreadInFoundation(pid_t pid)3063 bool AppMgrServiceInner::CheckIsThreadInFoundation(pid_t pid)
3064 {
3065     std::ostringstream pathBuilder;
3066     pathBuilder << PROC_SELF_TASK_PATH << pid;
3067     std::string path = pathBuilder.str();
3068     TAG_LOGD(AAFwkTag::APPMGR, "CheckIsThreadInFoundation path:%{public}s", path.c_str());
3069     return access(path.c_str(), F_OK) == 0;
3070 }
3071 
WaitForRemoteProcessExit(std::list<pid_t> & pids,const int64_t startTime)3072 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime)
3073 {
3074     int64_t delayTime = SystemTimeMillisecond() - startTime;
3075     if (ProcessUtil::CheckAllProcessExit(pids)) {
3076         return true;
3077     }
3078     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
3079         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
3080         if (ProcessUtil::CheckAllProcessExit(pids)) {
3081             return true;
3082         }
3083         delayTime = SystemTimeMillisecond() - startTime;
3084     }
3085     return false;
3086 }
3087 
WaitForRemoteProcessExit(std::list<SimpleProcessInfo> & processInfos,const int64_t startTime)3088 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<SimpleProcessInfo> &processInfos, const int64_t startTime)
3089 {
3090     int64_t delayTime = SystemTimeMillisecond() - startTime;
3091     if (ProcessUtil::CheckAllProcessExit(processInfos)) {
3092         return true;
3093     }
3094     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
3095         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
3096         if (ProcessUtil::CheckAllProcessExit(processInfos)) {
3097             return true;
3098         }
3099         delayTime = SystemTimeMillisecond() - startTime;
3100     }
3101     return false;
3102 }
3103 
SystemTimeMillisecond()3104 int64_t AppMgrServiceInner::SystemTimeMillisecond()
3105 {
3106     struct timespec t;
3107     t.tv_sec = 0;
3108     t.tv_nsec = 0;
3109     clock_gettime(CLOCK_MONOTONIC, &t);
3110     return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS;
3111 }
3112 
GetAppRunningRecordByPid(const pid_t pid) const3113 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
3114 {
3115     if (!appRunningManager_) {
3116         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
3117         return nullptr;
3118     }
3119     return appRunningManager_->GetAppRunningRecordByPid(pid);
3120 }
3121 
CreateAppRunningRecord(std::shared_ptr<AbilityRuntime::LoadParam> loadParam,std::shared_ptr<ApplicationInfo> appInfo,std::shared_ptr<AbilityInfo> abilityInfo,const std::string & processName,const BundleInfo & bundleInfo,const HapModuleInfo & hapModuleInfo,std::shared_ptr<AAFwk::Want> want,bool isKia)3122 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(
3123     std::shared_ptr<AbilityRuntime::LoadParam> loadParam, std::shared_ptr<ApplicationInfo> appInfo,
3124     std::shared_ptr<AbilityInfo> abilityInfo, const std::string &processName, const BundleInfo &bundleInfo,
3125     const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, bool isKia)
3126 {
3127     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3128     if (want != nullptr && (want->GetBoolParam(DEBUG_APP, false) || want->GetBoolParam(NATIVE_DEBUG, false) ||
3129         want->GetBoolParam(DEBUG_FROM, false))) {
3130         if (appInfo != nullptr && appInfo->appProvisionType != AppExecFwk::Constants::APP_PROVISION_TYPE_DEBUG) {
3131             TAG_LOGE(AAFwkTag::APPMGR, "release app not support debug");
3132             return nullptr;
3133         }
3134     }
3135     if (!appRunningManager_ || loadParam == nullptr) {
3136         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager or loadParam null");
3137         return nullptr;
3138     }
3139     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
3140     if (abilityInfo && AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
3141         appRecord = appRunningManager_->CreateAppRunningRecord(
3142             appInfo, processName, bundleInfo, loadParam->instanceKey, loadParam->customProcessFlag);
3143     } else {
3144         appRecord = appRunningManager_->CreateAppRunningRecord(
3145             appInfo, processName, bundleInfo, loadParam->instanceKey, abilityInfo ? abilityInfo->process : "");
3146     }
3147 
3148     CHECK_POINTER_AND_RETURN_VALUE(appRecord, nullptr);
3149     appRecord->SetProcessAndExtensionType(abilityInfo, loadParam->extensionProcessMode);
3150     appRecord->SetKeepAliveEnableState(bundleInfo.isKeepAlive);
3151     appRecord->SetKeepAliveDkv(loadParam->isKeepAlive);
3152     appRecord->SetMainElementRunning(loadParam->isMainElementRunning);
3153     appRecord->SetKeepAliveAppService(loadParam->isKeepAliveAppService);
3154     appRecord->SetEmptyKeepAliveAppState(false);
3155     appRecord->SetTaskHandler(taskHandler_);
3156     appRecord->SetEventHandler(eventHandler_);
3157     appRecord->AddModule(appInfo, abilityInfo, loadParam->token, hapModuleInfo, want, loadParam->abilityRecordId);
3158     appRecord->SetIsKia(isKia);
3159     SetAppRunningRecordStrictMode(appRecord, loadParam);
3160     if (want) {
3161         appRecord->SetStartupTaskData(*want);
3162         appRecord->SetDebugApp(want->GetBoolParam(DEBUG_APP, false));
3163         appRecord->SetNativeDebug(want->GetBoolParam("nativeDebug", false));
3164         appRecord->SetDebugFromLocal(want->GetBoolParam(DEBUG_FROM, false));
3165         if (want->GetBoolParam(COLD_START, false)) {
3166             appRecord->SetDebugApp(true);
3167         }
3168         appRecord->SetPerfCmd(want->GetStringParam(PERF_CMD));
3169         appRecord->SetErrorInfoEnhance(want->GetBoolParam(ERROR_INFO_ENHANCE, false));
3170         appRecord->SetMultiThread(want->GetBoolParam(MULTI_THREAD, false));
3171         int32_t appIndex = 0;
3172         (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, appIndex);
3173         appRecord->SetAppIndex(appIndex);
3174 #ifdef WITH_DLP
3175         appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false));
3176 #endif // WITH_DLP
3177         appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0));
3178         appRecord->SetCallerPid(want->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
3179         appRecord->SetCallerUid(want->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
3180         appRecord->SetCallerTokenId(want->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
3181         appRecord->SetAssignTokenId(want->GetIntParam("specifyTokenId", 0));
3182         appRecord->SetNativeStart(want->GetBoolParam("native", false));
3183         appRecord->SetDebugFromLocal(want->GetBoolParam(DEBUG_FROM, false));
3184     }
3185     return appRecord;
3186 }
3187 
SetAppRunningRecordStrictMode(std::shared_ptr<AppRunningRecord> appRecord,std::shared_ptr<AbilityRuntime::LoadParam> loadParam)3188 void AppMgrServiceInner::SetAppRunningRecordStrictMode(std::shared_ptr<AppRunningRecord> appRecord,
3189     std::shared_ptr<AbilityRuntime::LoadParam> loadParam)
3190 {
3191     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord is null");
3192     CHECK_POINTER_AND_RETURN_LOG(loadParam, "loadParam is null");
3193     appRecord->SetStrictMode(loadParam->extensionLoadParam.strictMode);
3194     appRecord->SetNetworkEnableFlags(loadParam->extensionLoadParam.networkEnableFlags);
3195     appRecord->SetSAEnableFlags(loadParam->extensionLoadParam.saEnableFlags);
3196 }
3197 
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag)3198 void AppMgrServiceInner::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag)
3199 {
3200     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3201     TAG_LOGD(AAFwkTag::APPMGR, "Terminate ability come.");
3202     if (!token) {
3203         TAG_LOGE(AAFwkTag::APPMGR, "terminateAbility token null");
3204         return;
3205     }
3206     auto appRecord = GetAppRunningRecordByAbilityToken(token);
3207     if (!appRecord) {
3208         TAG_LOGE(AAFwkTag::APPMGR, "terminateAbility app unexist");
3209         return;
3210     }
3211 
3212     RemoveUIExtensionBindItem(appRecord, token);
3213     RemoveUIExtensionLauncherItem(appRecord, token);
3214 
3215     if (appRunningManager_) {
3216         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner = shared_from_this();
3217         appRunningManager_->TerminateAbility(token, clearMissionFlag, appMgrServiceInner);
3218         if (appRecord->IsTerminating() && appRunningManager_->CheckAppRunningRecordIsLast(appRecord)) {
3219             TAG_LOGD(AAFwkTag::APPMGR, "clear uri permission");
3220             appRecord->UnSetPolicy();
3221         }
3222     }
3223 }
3224 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)3225 void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
3226 {
3227     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3228     TAG_LOGD(AAFwkTag::APPMGR, "state %{public}d.", static_cast<int32_t>(state));
3229     CHECK_POINTER_AND_RETURN_LOG(token, "token null");
3230     if (state == AbilityState::ABILITY_STATE_FOREGROUND) {
3231         AbilityRuntime::FreezeUtil::GetInstance().AppendLifecycleEvent(token, "ServiceInner::UpdateAbilityState");
3232     }
3233     auto appRecord = GetAppRunningRecordByAbilityToken(token);
3234     CHECK_POINTER_AND_RETURN_LOG(appRecord, "app unexist");
3235     if (appRecord->IsPreForeground() && state == AbilityState::ABILITY_STATE_FOREGROUND) {
3236         appRecord->SetPreForeground(false);
3237         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessPreForegroundChanged(appRecord);
3238     }
3239     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
3240     if (!abilityRecord) {
3241         TAG_LOGE(AAFwkTag::APPMGR, "can't find record");
3242         return;
3243     }
3244     if (state == abilityRecord->GetState()) {
3245         TAG_LOGE(AAFwkTag::APPMGR, "current state is already");
3246         OnAbilityStateChanged(abilityRecord, state);
3247         return;
3248     }
3249     if (abilityRecord->GetAbilityInfo() == nullptr) {
3250         TAG_LOGE(AAFwkTag::APPMGR, "info null");
3251         return;
3252     }
3253     auto type = abilityRecord->GetAbilityInfo()->type;
3254     if (type == AppExecFwk::AbilityType::PAGE) {
3255         SendAbilityEvent(abilityRecord, state);
3256     }
3257     if (type == AppExecFwk::AbilityType::SERVICE &&
3258         (state == AbilityState::ABILITY_STATE_CREATE ||
3259         state == AbilityState::ABILITY_STATE_TERMINATED ||
3260         state == AbilityState::ABILITY_STATE_CONNECTED ||
3261         state == AbilityState::ABILITY_STATE_DISCONNECTED)) {
3262         TAG_LOGI(
3263             AAFwkTag::APPMGR, "state:%{public}d", static_cast<int32_t>(state));
3264         appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), true, false);
3265         return;
3266     }
3267     if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) {
3268         TAG_LOGE(AAFwkTag::APPMGR, "state is not foreground or background");
3269         return;
3270     }
3271 
3272     appRecord->UpdateAbilityState(token, state);
3273     CheckCleanAbilityByUserRequest(appRecord, abilityRecord, state);
3274 }
3275 
UpdateExtensionState(const sptr<IRemoteObject> & token,const ExtensionState state)3276 void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
3277 {
3278     if (!token) {
3279         TAG_LOGE(AAFwkTag::APPMGR, "token null");
3280         return;
3281     }
3282     auto appRecord = GetAppRunningRecordByAbilityToken(token);
3283     if (!appRecord) {
3284         TAG_LOGE(AAFwkTag::APPMGR, "app unexist");
3285         return;
3286     }
3287     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
3288     if (!abilityRecord) {
3289         TAG_LOGE(AAFwkTag::APPMGR, "can't find record");
3290         return;
3291     }
3292     appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), false, false);
3293 }
3294 
OnStop()3295 void AppMgrServiceInner::OnStop()
3296 {
3297     if (!appRunningManager_) {
3298         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
3299         return;
3300     }
3301 
3302     appRunningManager_->ClearAppRunningRecordMap();
3303     CloseAppSpawnConnection();
3304 }
3305 
OpenAppSpawnConnection()3306 ErrCode AppMgrServiceInner::OpenAppSpawnConnection()
3307 {
3308     if (remoteClientManager_ == nullptr) {
3309         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
3310         return ERR_INVALID_VALUE;
3311     }
3312 
3313     if (remoteClientManager_->GetSpawnClient()) {
3314         return remoteClientManager_->GetSpawnClient()->OpenConnection();
3315     }
3316     return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
3317 }
3318 
CloseAppSpawnConnection() const3319 void AppMgrServiceInner::CloseAppSpawnConnection() const
3320 {
3321     if (remoteClientManager_ == nullptr) {
3322         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
3323         return;
3324     }
3325 
3326     if (remoteClientManager_->GetSpawnClient()) {
3327         remoteClientManager_->GetSpawnClient()->CloseConnection();
3328     }
3329 }
3330 
QueryAppSpawnConnectionState() const3331 SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const
3332 {
3333     if (remoteClientManager_ == nullptr) {
3334         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
3335         return SpawnConnectionState::STATE_NOT_CONNECT;
3336     }
3337 
3338     if (remoteClientManager_->GetSpawnClient()) {
3339         return remoteClientManager_->GetSpawnClient()->QueryConnectionState();
3340     }
3341     return SpawnConnectionState::STATE_NOT_CONNECT;
3342 }
3343 
SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)3344 void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)
3345 {
3346     if (remoteClientManager_ == nullptr) {
3347         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
3348         return;
3349     }
3350 
3351     remoteClientManager_->SetSpawnClient(std::move(spawnClient));
3352 }
3353 
SetBundleManagerHelper(const std::shared_ptr<BundleMgrHelper> & bundleMgrHelper)3354 void AppMgrServiceInner::SetBundleManagerHelper(const std::shared_ptr<BundleMgrHelper> &bundleMgrHelper)
3355 {
3356     if (remoteClientManager_ == nullptr) {
3357         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
3358         return;
3359     }
3360 
3361     remoteClientManager_->SetBundleManagerHelper(bundleMgrHelper);
3362 }
3363 
RegisterAppStateCallback(const sptr<IAppStateCallback> & callback)3364 void AppMgrServiceInner::RegisterAppStateCallback(const sptr<IAppStateCallback>& callback)
3365 {
3366     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3367     if (callback != nullptr) {
3368         std::lock_guard lock(appStateCallbacksLock_);
3369         TAG_LOGI(AAFwkTag::APPMGR, "RegisterAppStateCallback");
3370         appStateCallbacks_.push_back(
3371             AppStateCallbackWithUserId { callback, GetUserIdByUid(IPCSkeleton::GetCallingUid()) });
3372         auto remoteObjedct = callback->AsObject();
3373         if (remoteObjedct) {
3374             remoteObjedct->AddDeathRecipient(
3375                 sptr<AppStateCallbackDeathRecipient>(new AppStateCallbackDeathRecipient(weak_from_this())));
3376         }
3377     }
3378 }
3379 
RemoveDeadAppStateCallback(const wptr<IRemoteObject> & remote)3380 void AppMgrServiceInner::RemoveDeadAppStateCallback(const wptr<IRemoteObject> &remote)
3381 {
3382     auto remoteObject = remote.promote();
3383     if (remoteObject == nullptr) {
3384         TAG_LOGE(AAFwkTag::APPMGR, "remoteObject null");
3385         return;
3386     }
3387 
3388     std::lock_guard lock(appStateCallbacksLock_);
3389     for (auto it = appStateCallbacks_.begin(); it != appStateCallbacks_.end(); ++it) {
3390         auto callback = (*it).callback;
3391         if (callback && callback->AsObject() == remoteObject) {
3392             TAG_LOGI(AAFwkTag::APPMGR, "RemoveDeadAppStateCallback");
3393             appStateCallbacks_.erase(it);
3394             break;
3395         }
3396     }
3397 }
3398 
KillProcessByAbilityToken(const sptr<IRemoteObject> & token)3399 void AppMgrServiceInner::KillProcessByAbilityToken(const sptr<IRemoteObject> &token)
3400 {
3401     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3402     if (!token) {
3403         TAG_LOGE(AAFwkTag::APPMGR, "token null");
3404         return;
3405     }
3406     auto appRecord = GetAppRunningRecordByAbilityToken(token);
3407     if (!appRecord) {
3408         TAG_LOGE(AAFwkTag::APPMGR, "appRecord unexist");
3409         return;
3410     }
3411 
3412     // before exec ScheduleProcessSecurityExit return
3413     // The resident process won't let him die
3414     if (appRecord->IsKeepAliveApp() && IsMemorySizeSufficient()) {
3415         return;
3416     }
3417 
3418     pid_t pid = appRecord->GetPid();
3419     if (pid > 0) {
3420         std::list<pid_t> pids;
3421         pids.push_back(pid);
3422         appRecord->ScheduleProcessSecurityExit();
3423         if (!WaitForRemoteProcessExit(pids, SystemTimeMillisecond())) {
3424             int32_t result = KillProcessByPid(pid, "KillProcessByAbilityToken");
3425             if (result < 0) {
3426                 TAG_LOGE(AAFwkTag::APPMGR, "killProcessByAbilityToken kill process fail");
3427                 return;
3428             }
3429         }
3430     }
3431 }
3432 
KillProcessesByUserId(int32_t userId,bool isNeedSendAppSpawnMsg,sptr<AAFwk::IUserCallback> callback)3433 void AppMgrServiceInner::KillProcessesByUserId(int32_t userId, bool isNeedSendAppSpawnMsg,
3434     sptr<AAFwk::IUserCallback> callback)
3435 {
3436     if (!appRunningManager_) {
3437         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
3438         return;
3439     }
3440     int32_t result = ERR_OK;
3441     int64_t startTime = SystemTimeMillisecond();
3442     if (callback == nullptr) {
3443         std::list<pid_t> pids;
3444         if (!appRunningManager_->GetPidsByUserId(userId, pids)) {
3445             TAG_LOGI(AAFwkTag::APPMGR, "process corresponding uId unstart");
3446             if (isNeedSendAppSpawnMsg) {
3447                 TAG_LOGI(AAFwkTag::APPMGR, "developer mode, send uninstall debug hap messages");
3448                 SendAppSpawnUninstallDebugHapMsg(userId);
3449             }
3450             return;
3451         }
3452         result = WaitProcessesExitAndKill(pids, startTime, "KillProcessesByUserId");
3453     } else {
3454         // for logout user to callback
3455         std::list<SimpleProcessInfo> processInfos;
3456         if (!appRunningManager_->GetProcessInfosByUserId(userId, processInfos)) {
3457             TAG_LOGI(AAFwkTag::APPMGR, "process corresponding uId unstart");
3458             callback->OnLogoutUserDone(userId, ERR_OK);
3459             if (isNeedSendAppSpawnMsg) {
3460                 TAG_LOGI(AAFwkTag::APPMGR, "developer mode, send uninstall debug hap messages");
3461                 SendAppSpawnUninstallDebugHapMsg(userId);
3462             }
3463             return;
3464         }
3465         result = WaitProcessesExitAndKill(processInfos, startTime, "KillProcessesByUserId", userId, callback);
3466     }
3467     if (result == ERR_OK && isNeedSendAppSpawnMsg) {
3468         TAG_LOGI(AAFwkTag::APPMGR, "developer mode, send uninstall debug hap messages");
3469         SendAppSpawnUninstallDebugHapMsg(userId);
3470     }
3471 }
3472 
KillProcessesInBatch(const std::vector<int32_t> & pids)3473 int32_t AppMgrServiceInner::KillProcessesInBatch(const std::vector<int32_t> &pids)
3474 {
3475     CHECK_CALLER_IS_SYSTEM_APP;
3476     if (!AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
3477         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
3478         TAG_LOGE(AAFwkTag::APPMGR, "verify permission failed.");
3479         return ERR_PERMISSION_DENIED;
3480     }
3481     if (!AAFwk::AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
3482         TAG_LOGE(AAFwkTag::APPMGR, "not supported.");
3483         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
3484     }
3485     for (const auto& pid: pids) {
3486         auto appRecord = GetAppRunningRecordByPid(pid);
3487         if (appRecord == nullptr) {
3488             TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
3489             continue;
3490         }
3491         std::string callerKey = std::to_string(pid) + ":" + std::to_string(appRecord->GetUid());
3492         KillingProcessManager::GetInstance().AddKillingCallerKey(callerKey);
3493         (void)KillProcessByPid(pid, "KillProcessesInBatch");
3494     }
3495     return ERR_OK;
3496 }
3497 
KillSubProcessBypidInner(const pid_t pid,const std::string & reason,AAFwk::EventInfo & eventInfo)3498 int32_t AppMgrServiceInner::KillSubProcessBypidInner(const pid_t pid, const std::string &reason,
3499     AAFwk::EventInfo &eventInfo)
3500 {
3501     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3502     int32_t ret = -1;
3503     if (!ProcessUtil::ProcessExist(pid) || pid <= 0) {
3504         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid: %{public}d", pid);
3505         return AAFwk::ERR_KILL_PROCESS_NOT_EXIST;
3506     }
3507     if (CheckIsThreadInFoundation(pid)) {
3508         TAG_LOGI(AAFwkTag::APPMGR, "don't kill pid %{public}d", pid);
3509         return AAFwk::ERR_KILL_FOUNDATION_UID;
3510     }
3511     ret = kill(pid, SIGNAL_KILL);
3512     if (ret < 0) {
3513         TAG_LOGE(AAFwkTag::APPMGR, "Kill pid %{public}d err: %{public}d", pid, ret);
3514     }
3515 
3516     std::string killReason = KILL_SUB_PROCESS_REASON_PREFIX + reason;
3517     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
3518     int result = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL",
3519         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_KEY_PID, std::to_string(eventInfo.pid),
3520         EVENT_KEY_PROCESS_NAME, eventInfo.processName, EVENT_KEY_MESSAGE, killReason);
3521     TAG_LOGW(AAFwkTag::APPMGR, "hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL], pid="
3522         "%{public}d, processName=%{public}s, msg=%{public}s, ret=%{public}d",
3523         result, pid, eventInfo.processName.c_str(), killReason.c_str(), ret);
3524     return ret;
3525 }
3526 
KillSubProcessBypid(const pid_t pid,const std::string & reason)3527 int32_t AppMgrServiceInner::KillSubProcessBypid(const pid_t pid, const std::string &reason)
3528 {
3529     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3530     int32_t ret = ERR_OK;
3531     if (!appRunningManager_) {
3532         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
3533         return ERR_INVALID_VALUE;
3534     }
3535     // get render record
3536     auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid);
3537     if (appRecord) {
3538         auto renderRecord = appRecord->GetRenderRecordByPid(pid);
3539         if (renderRecord) {
3540             AAFwk::EventInfo renderEventInfo;
3541             renderEventInfo.pid = renderRecord->GetPid();
3542             renderEventInfo.processName = renderRecord->GetProcessName();
3543             return KillSubProcessBypidInner(pid, reason, renderEventInfo);
3544         }
3545     }
3546     // get child process
3547 #ifdef SUPPORT_CHILD_PROCESS
3548     appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(pid);
3549     if (appRecord) {
3550         auto childRecordMap = appRecord->GetChildProcessRecordMap();
3551         auto iter = childRecordMap.find(pid);
3552         if (iter != childRecordMap.end()) {
3553             auto childProcessRecord = iter->second;
3554             if (childProcessRecord) {
3555                 AAFwk::EventInfo childEventInfo;
3556                 childEventInfo.pid = childProcessRecord->GetPid();
3557                 childEventInfo.processName = childProcessRecord->GetProcessName();
3558                 return KillSubProcessBypidInner(pid, reason, childEventInfo);
3559             }
3560         }
3561     }
3562 #endif
3563     // get child record process
3564     appRecord = appRunningManager_->GetAppRunningRecordByChildRecordPid(pid);
3565     if (appRecord) {
3566         auto childAppRecordMap = appRecord->GetChildAppRecordMap();
3567         auto it = childAppRecordMap.find(pid);
3568         if (it != childAppRecordMap.end()) {
3569             auto weakChildAppRecord = it->second;
3570             auto childAppRecord = weakChildAppRecord.lock();
3571             if (childAppRecord) {
3572                 AAFwk::EventInfo childRecordEventInfo;
3573                 childRecordEventInfo.pid = childAppRecord->GetPid();
3574                 childRecordEventInfo.processName = childAppRecord->GetProcessName();
3575                 return KillSubProcessBypidInner(pid, reason, childRecordEventInfo);
3576             }
3577         }
3578     }
3579 
3580     return ERR_OK;
3581 }
3582 
KillProcessesByPids(const std::vector<int32_t> & pids,const std::string & reason,bool subProcess,bool isKillPrecedeStart)3583 int32_t AppMgrServiceInner::KillProcessesByPids(const std::vector<int32_t> &pids, const std::string &reason,
3584     bool subProcess, bool isKillPrecedeStart)
3585 {
3586     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3587     int32_t ret = ERR_OK;
3588     for (const auto& pid: pids) {
3589         auto appRecord = GetAppRunningRecordByPid(pid);
3590         if (appRecord != nullptr) {
3591             ret = KillProcessByPid(pid, reason, isKillPrecedeStart);
3592             if (ret != ERR_OK) {
3593                 TAG_LOGW(AAFwkTag::APPMGR, "fail, pid:%{public}d", pid);
3594                 return ret;
3595             }
3596             continue;
3597         }
3598         if (subProcess == false) {
3599             continue;
3600         }
3601         ret = KillSubProcessBypid(pid, reason);
3602         if (ret != ERR_OK) {
3603             TAG_LOGW(AAFwkTag::APPMGR, "KillSubProcessBypid fail, pid:%{public}d, ret:%{public}d", pid, ret);
3604             return ret;
3605         }
3606     }
3607     return ret;
3608 }
3609 
AttachPidToParent(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callerToken)3610 void AppMgrServiceInner::AttachPidToParent(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callerToken)
3611 {
3612     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3613     auto appRecord = GetAppRunningRecordByAbilityToken(token);
3614     if (appRecord == nullptr) {
3615         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord null");
3616         return;
3617     }
3618     auto pid = appRecord->GetPid();
3619     if (pid <= 0) {
3620         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid");
3621         return;
3622     }
3623     auto callRecord = GetAppRunningRecordByAbilityToken(callerToken);
3624     if (callRecord == nullptr) {
3625         TAG_LOGE(AAFwkTag::APPMGR, "callRecord null");
3626         auto result = KillProcessByPid(pid, "AttachPidToParent");
3627         if (result < 0) {
3628             TAG_LOGW(AAFwkTag::APPMGR, "fail, pid: %{public}d", pid);
3629         }
3630         return;
3631     }
3632     appRecord->SetParentAppRecord(callRecord);
3633     callRecord->AddChildAppRecord(pid, appRecord);
3634 }
3635 
StartAbility(sptr<IRemoteObject> token,sptr<IRemoteObject> preToken,std::shared_ptr<AbilityInfo> abilityInfo,std::shared_ptr<AppRunningRecord> appRecord,const HapModuleInfo & hapModuleInfo,std::shared_ptr<AAFwk::Want> want,int32_t abilityRecordId)3636 void AppMgrServiceInner::StartAbility(sptr<IRemoteObject> token, sptr<IRemoteObject> preToken,
3637     std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<AppRunningRecord> appRecord,
3638     const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, int32_t abilityRecordId)
3639 {
3640     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3641     CHECK_POINTER_AND_RETURN_LOG(abilityInfo, "abilityInfo null");
3642     TAG_LOGI(AAFwkTag::APPMGR, "start ability, %{public}s-%{public}s",
3643         abilityInfo->bundleName.c_str(), abilityInfo->name.c_str());
3644     if (!appRecord) {
3645         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
3646         return;
3647     }
3648 
3649     if (want) {
3650 #ifdef WITH_DLP
3651         want->SetParam(DLP_PARAMS_SECURITY_FLAG, appRecord->GetSecurityFlag());
3652 #endif // WITH_DLP
3653 
3654         auto isDebugApp = want->GetBoolParam(DEBUG_APP, false);
3655         if (isDebugApp && !appRecord->IsDebugApp()) {
3656             ProcessAppDebug(appRecord, isDebugApp);
3657         }
3658     }
3659 
3660     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
3661     if (abilityInfo->launchMode == LaunchMode::SINGLETON && ability != nullptr) {
3662         TAG_LOGW(AAFwkTag::APPMGR, "can't add same ability");
3663         return;
3664     }
3665 
3666     if (ability && preToken) {
3667         TAG_LOGE(AAFwkTag::APPMGR, "ability already start");
3668         return;
3669     }
3670 
3671     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo->applicationInfo);
3672     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want, abilityRecordId);
3673     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
3674     if (!moduleRecord) {
3675         TAG_LOGE(AAFwkTag::APPMGR, "add moduleRecord fail");
3676         return;
3677     }
3678 
3679     ability = moduleRecord->GetAbilityRunningRecordByToken(token);
3680     if (!ability) {
3681         TAG_LOGE(AAFwkTag::APPMGR, "add ability fail");
3682         return;
3683     }
3684 
3685     ApplicationState appState = appRecord->GetState();
3686     if (appState == ApplicationState::APP_STATE_CREATE) {
3687         TAG_LOGE(AAFwkTag::APPMGR, "don't launch ability, bundleName:%{public}s, ability:%{public}s",
3688             appInfo->bundleName.c_str(), abilityInfo->name.c_str());
3689         return;
3690     }
3691     appRecord->LaunchAbility(ability);
3692 }
3693 
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken) const3694 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAbilityToken(
3695     const sptr<IRemoteObject> &abilityToken) const
3696 {
3697     if (!appRunningManager_) {
3698         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
3699         return nullptr;
3700     }
3701 
3702     return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken);
3703 }
3704 
GetTerminatingAppRunningRecord(const sptr<IRemoteObject> & token) const3705 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetTerminatingAppRunningRecord(
3706     const sptr<IRemoteObject> &token) const
3707 {
3708     if (!appRunningManager_) {
3709         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
3710         return nullptr;
3711     }
3712     return appRunningManager_->GetTerminatingAppRunningRecord(token);
3713 }
3714 
AbilityTerminated(const sptr<IRemoteObject> & token)3715 void AppMgrServiceInner::AbilityTerminated(const sptr<IRemoteObject> &token)
3716 {
3717     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3718     TAG_LOGD(AAFwkTag::APPMGR, "Terminate ability come.");
3719     if (!token) {
3720         TAG_LOGE(AAFwkTag::APPMGR, "token null");
3721         return;
3722     }
3723 
3724     auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token);
3725     if (!appRecord) {
3726         TAG_LOGE(AAFwkTag::APPMGR, "appRecord unexist");
3727         return;
3728     }
3729 
3730     appRecord->AbilityTerminated(token);
3731 }
3732 
GetAppRunningRecordByAppRecordId(const int32_t recordId) const3733 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const
3734 {
3735     if (appRunningManager_ == nullptr) {
3736         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
3737         return nullptr;
3738     }
3739     const auto&& appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
3740     const auto& iter = appRunningRecordMap.find(recordId);
3741     return iter != appRunningRecordMap.end() ? iter->second : nullptr;
3742 }
3743 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp,bool isFromWindowFocusChanged)3744 void AppMgrServiceInner::OnAppStateChanged(
3745     const std::shared_ptr<AppRunningRecord> &appRecord,
3746     const ApplicationState state,
3747     bool needNotifyApp,
3748     bool isFromWindowFocusChanged)
3749 {
3750     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3751     if (!appRecord) {
3752         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
3753         return;
3754     }
3755 
3756     TAG_LOGD(AAFwkTag::APPMGR, "OnAppStateChanged begin, bundleName is %{public}s, state:%{public}d",
3757         appRecord->GetBundleName().c_str(), static_cast<int32_t>(state));
3758     {
3759         std::lock_guard lock(appStateCallbacksLock_);
3760         for (const auto &item : appStateCallbacks_) {
3761             if (item.callback != nullptr) {
3762                 item.callback->OnAppStateChanged(WrapAppProcessData(appRecord, state, isFromWindowFocusChanged));
3763             }
3764         }
3765     }
3766 
3767     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStateChanged(
3768         appRecord, state, needNotifyApp, isFromWindowFocusChanged);
3769 }
3770 
OnAppStarted(const std::shared_ptr<AppRunningRecord> & appRecord)3771 void AppMgrServiceInner::OnAppStarted(const std::shared_ptr<AppRunningRecord> &appRecord)
3772 {
3773     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3774     if (!appRecord) {
3775         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
3776         return;
3777     }
3778 
3779     if (appRecord->GetPriorityObject() == nullptr) {
3780         TAG_LOGE(AAFwkTag::APPMGR, "priorityobject null");
3781         return;
3782     }
3783 
3784     TAG_LOGD(AAFwkTag::APPMGR, "OnAppStarted begin, bundleName is %{public}s, pid:%{public}d",
3785         appRecord->GetBundleName().c_str(), appRecord->GetPid());
3786 
3787     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStarted(appRecord);
3788 }
3789 
3790 
OnAppStopped(const std::shared_ptr<AppRunningRecord> & appRecord)3791 void AppMgrServiceInner::OnAppStopped(const std::shared_ptr<AppRunningRecord> &appRecord)
3792 {
3793     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3794     if (!appRecord) {
3795         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
3796         return;
3797     }
3798 
3799     if (appRecord->GetPriorityObject() == nullptr) {
3800         TAG_LOGE(AAFwkTag::APPMGR, "priorityObject null");
3801         return;
3802     }
3803 
3804     TAG_LOGD(AAFwkTag::APPMGR, "OnAppStopped begin, bundleName is %{public}s, pid:%{public}d",
3805         appRecord->GetBundleName().c_str(), appRecord->GetPid());
3806 
3807     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStopped(appRecord);
3808 }
3809 
WrapAppProcessData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool isFromWindowFocusChanged)3810 AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
3811     const ApplicationState state, bool isFromWindowFocusChanged)
3812 {
3813     AppProcessData processData;
3814     CHECK_POINTER_AND_RETURN_VALUE(appRecord, processData);
3815     auto appInfoList = appRecord->GetAppInfoList();
3816     for (const auto &list : appInfoList) {
3817         AppData data;
3818         if (!list) {
3819             continue;
3820         }
3821         data.appName = list->name;
3822         data.uid = list->uid;
3823         processData.appDatas.push_back(data);
3824     }
3825     processData.processName = appRecord->GetProcessName();
3826     processData.pid = appRecord->GetPid();
3827     processData.appState = state;
3828     processData.isFocused = appRecord->GetFocusFlag();
3829     processData.appIndex = appRecord->GetAppIndex();
3830     processData.instanceKey = appRecord->GetInstanceKey();
3831     processData.bundleName = appRecord->GetBundleName();
3832     processData.isFromWindowFocusChanged = isFromWindowFocusChanged;
3833     auto renderRecordMap = appRecord->GetRenderRecordMap();
3834     if (!renderRecordMap.empty()) {
3835         for (auto iter : renderRecordMap) {
3836             auto renderRecord = iter.second;
3837             if (renderRecord != nullptr) {
3838                 processData.renderPids.emplace_back(renderRecord->GetPid());
3839             }
3840         }
3841     }
3842     return processData;
3843 }
3844 
OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> & ability,const AbilityState state)3845 void AppMgrServiceInner::OnAbilityStateChanged(
3846     const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
3847 {
3848     if (!ability) {
3849         TAG_LOGE(AAFwkTag::APPMGR, "ability null");
3850         return;
3851     }
3852     std::lock_guard lock(appStateCallbacksLock_);
3853     for (const auto &item : appStateCallbacks_) {
3854         if (item.callback != nullptr) {
3855             item.callback->OnAbilityRequestDone(ability->GetToken(), state);
3856         }
3857     }
3858 }
3859 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility,bool isFromWindowFocusChanged)3860 void AppMgrServiceInner::StateChangedNotifyObserver(
3861     const AbilityStateData abilityStateData, bool isAbility, bool isFromWindowFocusChanged)
3862 {
3863     DelayedSingleton<AppStateObserverManager>::GetInstance()->StateChangedNotifyObserver(
3864         abilityStateData, isAbility, isFromWindowFocusChanged);
3865 }
3866 
StartPerfProcessByStartMsg(AppSpawnStartMsg & startMsg,const std::string & perfCmd,const std::string & debugCmd,bool isSandboxApp)3867 int32_t AppMgrServiceInner::StartPerfProcessByStartMsg(AppSpawnStartMsg &startMsg,
3868     const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp)
3869 {
3870     if (!remoteClientManager_ || !remoteClientManager_->GetSpawnClient()) {
3871         TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient null");
3872         return ERR_NO_INIT;
3873     }
3874     if (perfCmd.empty() && debugCmd.empty()) {
3875         TAG_LOGD(AAFwkTag::APPMGR, "perfCmd is empty");
3876         return ERR_INVALID_OPERATION;
3877     }
3878 
3879     startMsg.code = static_cast<int32_t>(MSG_SPAWN_NATIVE_PROCESS);
3880     if (!isSandboxApp) {
3881         TAG_LOGD(AAFwkTag::APPMGR, "debuggablePipe sandbox: false.");
3882         startMsg.flags |= (START_FLAG_BASE << StartFlags::NO_SANDBOX);
3883     } else {
3884         TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe sandbox: true");
3885     }
3886     if (!perfCmd.empty()) {
3887         startMsg.renderParam = perfCmd;
3888         TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe perfCmd:%{public}s", perfCmd.c_str());
3889     } else {
3890         startMsg.renderParam = debugCmd;
3891         TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe debugCmd:%{public}s", debugCmd.c_str());
3892     }
3893     pid_t pid = 0;
3894     auto errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
3895     if (FAILED(errCode)) {
3896         TAG_LOGE(AAFwkTag::APPMGR, "new native process fail, errCode %{public}08x", errCode);
3897         return errCode;
3898     }
3899     return ERR_OK;
3900 }
3901 
StartPerfProcess(const std::shared_ptr<AppRunningRecord> & appRecord,const std::string & perfCmd,const std::string & debugCmd,bool isSandboxApp)3902 int32_t AppMgrServiceInner::StartPerfProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
3903     const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp)
3904 {
3905     if (!appRecord) {
3906         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
3907         return ERR_INVALID_OPERATION;
3908     }
3909 
3910     auto&& startMsg = appRecord->GetStartMsg();
3911     return StartPerfProcessByStartMsg(startMsg, perfCmd, debugCmd, isSandboxApp);
3912 }
3913 
SetOverlayInfo(const std::string & bundleName,const int32_t userId,AppSpawnStartMsg & startMsg)3914 void AppMgrServiceInner::SetOverlayInfo(const std::string &bundleName,
3915                                         const int32_t userId,
3916                                         AppSpawnStartMsg &startMsg)
3917 {
3918     if (remoteClientManager_ == nullptr) {
3919         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
3920         return;
3921     }
3922     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
3923     if (bundleMgrHelper == nullptr) {
3924         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
3925         return;
3926     }
3927     auto overlayMgrProxy = bundleMgrHelper->GetOverlayManagerProxy();
3928     if (overlayMgrProxy !=  nullptr) {
3929         std::vector<OverlayModuleInfo> overlayModuleInfo;
3930         TAG_LOGD(AAFwkTag::APPMGR, "Check overlay app begin.");
3931         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetOverlayModuleInfoForTarget");
3932         auto targetRet = IN_PROCESS_CALL(overlayMgrProxy->GetOverlayModuleInfoForTarget(
3933             bundleName, "", overlayModuleInfo, userId));
3934         if (targetRet == ERR_OK && overlayModuleInfo.size() != 0) {
3935             TAG_LOGD(AAFwkTag::APPMGR, "Start an overlay app process.");
3936             startMsg.flags = startMsg.flags | APP_OVERLAY_FLAG;
3937             std::string overlayInfoPaths;
3938             for (auto it : overlayModuleInfo) {
3939                 overlayInfoPaths += (it.hapPath + "|");
3940             }
3941             startMsg.overlayInfo = overlayInfoPaths;
3942         }
3943     }
3944 }
3945 
SetAppEnvInfo(const BundleInfo & bundleInfo,AppSpawnStartMsg & startMsg)3946 void AppMgrServiceInner::SetAppEnvInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg& startMsg)
3947 {
3948     if (bundleInfo.applicationInfo.tsanEnabled) {
3949         startMsg.appEnv.emplace(TSAN_FLAG_NAME, std::to_string(1));
3950     } else {
3951         startMsg.appEnv.emplace(TSAN_FLAG_NAME, std::to_string(0));
3952     }
3953 
3954     if (bundleInfo.applicationInfo.hwasanEnabled) {
3955         startMsg.appEnv.emplace(HWASAN_FLAG_NAME, std::to_string(1));
3956     } else {
3957         startMsg.appEnv.emplace(HWASAN_FLAG_NAME, std::to_string(0));
3958     }
3959 
3960     if (bundleInfo.applicationInfo.ubsanEnabled) {
3961         startMsg.appEnv.emplace(UBSAN_FLAG_NAME, std::to_string(1));
3962     } else {
3963         startMsg.appEnv.emplace(UBSAN_FLAG_NAME, std::to_string(0));
3964     }
3965 
3966     if (!bundleInfo.applicationInfo.appEnvironments.empty()) {
3967         for (const auto& appEnvironment : bundleInfo.applicationInfo.appEnvironments) {
3968             startMsg.appEnv.emplace(appEnvironment.name, appEnvironment.value);
3969         }
3970     }
3971 }
3972 
AddMountPermission(uint32_t accessTokenId,std::set<std::string> & permissions)3973 void AppMgrServiceInner::AddMountPermission(uint32_t accessTokenId, std::set<std::string> &permissions)
3974 {
3975     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3976     CHECK_POINTER_AND_RETURN_LOG(remoteClientManager_, "remoteClientManager_ null");
3977     auto spawnClient = remoteClientManager_->GetSpawnClient();
3978     if (!spawnClient) {
3979         TAG_LOGE(AAFwkTag::APPMGR, "spawnClient null");
3980         return;
3981     }
3982     auto handle = spawnClient->GetAppSpawnClientHandle();
3983     int32_t maxPermissionIndex = GetMaxPermissionIndex(handle);
3984     if (maxPermissionIndex <= 0) {
3985         TAG_LOGE(AAFwkTag::APPMGR, "maxPermissionIndex error: %{public}d", maxPermissionIndex);
3986         return;
3987     }
3988     std::vector<std::string> tmpPermissionList;
3989     tmpPermissionList.reserve(maxPermissionIndex);
3990     for (int i = 0; i < maxPermissionIndex; i++) {
3991         tmpPermissionList.emplace_back(std::string(GetPermissionByIndex(handle, i)));
3992     }
3993 
3994     std::vector<int32_t> permStateList;
3995     auto result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(accessTokenId, tmpPermissionList,
3996         permStateList, true);
3997     if (result != ERR_OK || permStateList.size() != tmpPermissionList.size()) {
3998         TAG_LOGE(AAFwkTag::APPMGR, "VerifyAccessToken error: %{public}d", result);
3999         return;
4000     }
4001     for (size_t i = 0; i < permStateList.size(); i++) {
4002         if (permStateList[i] == Security::AccessToken::PERMISSION_GRANTED) {
4003             permissions.insert(tmpPermissionList[i]);
4004         }
4005     }
4006 }
4007 
StartProcessVerifyPermission(const BundleInfo & bundleInfo,bool & hasAccessBundleDirReq,uint8_t & setAllowInternet,uint8_t & allowInternet,std::vector<int32_t> & gids)4008 void AppMgrServiceInner::StartProcessVerifyPermission(const BundleInfo &bundleInfo, bool &hasAccessBundleDirReq,
4009                                                       uint8_t &setAllowInternet, uint8_t &allowInternet,
4010                                                       std::vector<int32_t> &gids)
4011 {
4012     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
4013     hasAccessBundleDirReq = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
4014         [] (const auto &reqPermission) {
4015             if (PERMISSION_ACCESS_BUNDLE_DIR == reqPermission) {
4016                 return true;
4017             }
4018             return false;
4019         });
4020 
4021     auto token = bundleInfo.applicationInfo.accessTokenId;
4022     {
4023         HITRACE_METER_NAME(HITRACE_TAG_APP, "AccessTokenKit::VerifyAccessToken");
4024 #ifdef ABILITY_PLATFORM_CHECK_PERMISSION
4025         int result = CheckStablePermission(bundleInfo);
4026 #else
4027         int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_INTERNET, false);
4028 #endif //ABILITY_PLATFORM_CHECK_PERMISSION
4029         if (result != Security::AccessToken::PERMISSION_GRANTED) {
4030             setAllowInternet = 1;
4031             allowInternet = 0;
4032     #ifdef APP_MGR_SERVICE_APPMS
4033             auto ret = OHOS::NetManagerStandard::NetConnClient::GetInstance().SetInternetPermission(bundleInfo.uid, 0);
4034             TAG_LOGD(AAFwkTag::APPMGR, "SetInternetPermission, ret = %{public}d", ret);
4035         } else {
4036             auto ret = OHOS::NetManagerStandard::NetConnClient::GetInstance().SetInternetPermission(bundleInfo.uid, 1);
4037             TAG_LOGD(AAFwkTag::APPMGR, "SetInternetPermission, ret = %{public}d", ret);
4038             gids.push_back(NETSYS_SOCKET_GROUPID);
4039     #endif
4040         }
4041 
4042         result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_MANAGE_VPN, false);
4043         if (result == Security::AccessToken::PERMISSION_GRANTED) {
4044             gids.push_back(BLUETOOTH_GROUPID);
4045         }
4046 
4047         if (hasAccessBundleDirReq) {
4048             int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token,
4049                 PERMISSION_ACCESS_BUNDLE_DIR, false);
4050             if (result != Security::AccessToken::PERMISSION_GRANTED) {
4051                 TAG_LOGE(AAFwkTag::APPMGR, "startProcess not granted");
4052                 hasAccessBundleDirReq = false;
4053             }
4054         }
4055     }
4056 }
4057 
4058 #ifdef ABILITY_PLATFORM_CHECK_PERMISSION
CheckStablePermission(const BundleInfo & bundleInfo)4059 int AppMgrServiceInner::CheckStablePermission(const BundleInfo &bundleInfo)
4060 {
4061     HITRACE_METER_NAME(HITRACE_TAG_APP, "AccessTokenKit::CheckStablePermission");
4062     auto token = bundleInfo.applicationInfo.accessTokenId;
4063     std::vectorSecurity::AccessToken::PermissionStateFull reqPermList;
4064     auto deviceid = bundleInfo.applicationInfo.deviceId;
4065     Security::AccessToken::AccessTokenKit::GetReqPermissions(token, reqPermList, true);
4066     bool granted = std::any_of(
4067         reqPermList.begin(), reqPermList.end(),
4068         [deviceid](const Security::AccessToken::PermissionStateFull &status) {
4069             if (status.permissionName == PERMISSION_INTERNET &&
4070                 status.grantStatus.size() == status.resDeviceID.size()) {
4071                 if (CheckDeviceStatus(status, deviceId)) {
4072                     return true;
4073                 }
4074             }
4075         return false;
4076     });
4077     int result = granted ? Security::AccessToken::PERMISSION_GRANTED : Security::AccessToken::PERMISSION_DENIED;
4078     TAG_LOGI(AAFwkTag::APPMGR, "GetInternetPermission, ret %{public}d, uid %{public}d, token %{public}d", result,
4079         bundleInfo.uid, token);
4080     return result;
4081 }
4082 
CheckDeviceStatus(Security::AccessToken::PermissionStateFull & status,std::string deviceid)4083 bool AppMgrServiceInner::CheckDeviceStatus(Security::AccessToken::PermissionStateFull &status,
4084     std::string deviceid)
4085 {
4086     for (size_t i = 0; i < status.resDeviceID.size(); i++) {
4087         if (status.resDeviceID[i] == deviceid &&
4088             status.grantStatus[i] == Security::AccessToken::PERMISSION_GRANTED) {
4089             return true;
4090         }
4091     }
4092     return false;
4093 }
4094 #endif //ABILITY_PLATFORM_CHECK_PERMISSION
4095 
CreatNewStartMsg(const Want & want,const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,const std::string & processName,AppSpawnStartMsg & startMsg)4096 int32_t AppMgrServiceInner::CreatNewStartMsg(const Want &want, const AbilityInfo &abilityInfo,
4097     const std::shared_ptr<ApplicationInfo> &appInfo, const std::string &processName, AppSpawnStartMsg &startMsg)
4098 {
4099     TAG_LOGD(AAFwkTag::APPMGR, "called");
4100     if (!remoteClientManager_) {
4101         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager null");
4102         return ERR_NO_INIT;
4103     }
4104     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
4105     if (!bundleMgrHelper) {
4106         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
4107         return ERR_NO_INIT;
4108     }
4109 
4110     BundleInfo bundleInfo;
4111     HapModuleInfo hapModuleInfo;
4112     int32_t appIndex = want.GetIntParam(AppspawnUtil::DLP_PARAMS_INDEX, 0);
4113     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
4114         TAG_LOGE(AAFwkTag::APPMGR, "getBundleAndHapInfo fail");
4115         return ERR_NO_INIT;
4116     }
4117 
4118     uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, abilityInfo);
4119     CHECK_POINTER_AND_RETURN_VALUE(appInfo, ERR_NO_INIT);
4120     auto uid = appInfo->uid;
4121     auto bundleType = appInfo->bundleType;
4122     CreateStartMsgParam startMsgParam;
4123     startMsgParam.processName = processName;
4124     startMsgParam.startFlags = startFlags;
4125     startMsgParam.uid = uid;
4126     startMsgParam.bundleInfo = bundleInfo;
4127     startMsgParam.bundleIndex = appIndex;
4128     startMsgParam.bundleType = bundleType;
4129     auto ret = CreateStartMsg(startMsgParam, startMsg);
4130     if (ret != ERR_OK) {
4131         TAG_LOGE(AAFwkTag::APPMGR, "createStartMsg fail");
4132     }
4133     return ret;
4134 }
4135 
SetAtomicServiceInfo(BundleType bundleType,AppSpawnStartMsg & startMsg)4136 void AppMgrServiceInner::SetAtomicServiceInfo(BundleType bundleType, AppSpawnStartMsg &startMsg)
4137 {
4138 #ifdef OHOS_ACCOUNT_ENABLED
4139     TAG_LOGD(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED on");
4140     if (bundleType == BundleType::ATOMIC_SERVICE) {
4141         TAG_LOGI(AAFwkTag::APPMGR, "app is atomic service type");
4142         AccountSA::OhosAccountInfo accountInfo;
4143         auto errCode = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfo(accountInfo);
4144         if (errCode == ERR_OK) {
4145             TAG_LOGI(AAFwkTag::APPMGR, "getOhosAccountInfo succeed, uid %{public}s", accountInfo.uid_.c_str());
4146             startMsg.atomicServiceFlag = true;
4147             startMsg.atomicAccount = accountInfo.uid_;
4148         } else {
4149             TAG_LOGE(AAFwkTag::APPMGR, "get ohos account info:%{public}d fail", errCode);
4150         }
4151     }
4152 #else
4153     TAG_LOGD(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED off");
4154 #endif // OHOS_ACCOUNT_ENABLED
4155 }
4156 
SetAppInfo(const BundleInfo & bundleInfo,AppSpawnStartMsg & startMsg)4157 void AppMgrServiceInner::SetAppInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg)
4158 {
4159     bool hasAccessBundleDirReq;
4160     bool tempJitAllow = false;
4161     uint8_t setAllowInternet = 0;
4162     uint8_t allowInternet = 1;
4163     std::vector<int32_t> gids;
4164     StartProcessVerifyPermission(bundleInfo, hasAccessBundleDirReq, setAllowInternet, allowInternet, gids);
4165     startMsg.uid = bundleInfo.uid;
4166     startMsg.gid = bundleInfo.gid;
4167     startMsg.hapFlags = bundleInfo.isPreInstallApp ? 1 : 0;
4168     startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId;
4169     startMsg.accessTokenIdEx = bundleInfo.applicationInfo.accessTokenIdEx;
4170     startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel;
4171     startMsg.ownerId = bundleInfo.signatureInfo.appIdentifier;
4172     startMsg.provisionType = bundleInfo.applicationInfo.appProvisionType;
4173     startMsg.apiTargetVersion = bundleInfo.applicationInfo.apiTargetVersion % API_VERSION_MOD;
4174 #ifdef SUPPORT_CHILD_PROCESS
4175     if (bundleInfo.applicationInfo.apiTargetVersion % API_VERSION_MOD < API15) {
4176         startMsg.maxChildProcess = 0;
4177     } else {
4178         if (startMsg.maxChildProcess == 0) {
4179             startMsg.maxChildProcess = bundleInfo.applicationInfo.maxChildProcess;
4180         }
4181     }
4182 #endif // SUPPORT_CHILD_PROCESS
4183     startMsg.setAllowInternet = setAllowInternet;
4184     startMsg.allowInternet = allowInternet;
4185     startMsg.gids = gids;
4186     startMsg.flags |= hasAccessBundleDirReq ? APP_ACCESS_BUNDLE_DIR : 0;
4187     tempJitAllow = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
4188         [] (const auto &reqPermission) {
4189             if (PERMISSION_TEMP_JIT_ALLOW == reqPermission) {
4190                 return true;
4191             }
4192             return false;
4193         });
4194     startMsg.flags |= tempJitAllow ? START_FLAG_BASE << StartFlags::TEMP_JIT_ALLOW : 0;
4195     SetAppEnvInfo(bundleInfo, startMsg);
4196 }
4197 
CreateStartMsg(const CreateStartMsgParam & param,AppSpawnStartMsg & startMsg)4198 int32_t AppMgrServiceInner::CreateStartMsg(const CreateStartMsgParam &param, AppSpawnStartMsg &startMsg)
4199 {
4200     if (!remoteClientManager_) {
4201         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager null");
4202         return ERR_NO_INIT;
4203     }
4204     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
4205     if (!bundleMgrHelper) {
4206         TAG_LOGE(AAFwkTag::APPMGR, "get bundle manager helper fail");
4207         return ERR_NO_INIT;
4208     }
4209 
4210     auto &bundleInfo = param.bundleInfo;
4211     AAFwk::AutoSyncTaskHandle autoSync(AAFwk::TaskHandlerWrap::GetFfrtHandler()->SubmitTask([&]() {
4212         AddMountPermission(bundleInfo.applicationInfo.accessTokenId, startMsg.permissions);
4213         }, AAFwk::TaskAttribute{
4214             .taskName_ = "AddMountPermission",
4215             .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
4216         }));
4217 
4218     HspList hspList;
4219     auto ret = bundleMgrHelper->GetBaseSharedBundleInfos(bundleInfo.name, hspList,
4220         AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO);
4221     if (ret != ERR_OK) {
4222         TAG_LOGE(AAFwkTag::APPMGR, "getBaseSharedBundleInfos fail: %{public}d", ret);
4223         return ret;
4224     }
4225     startMsg.hspList = hspList;
4226 
4227     auto userId = GetUserIdByUid(param.uid);
4228     DataGroupInfoList dataGroupInfoList;
4229     bool result = bundleMgrHelper->QueryDataGroupInfos(bundleInfo.name, userId, dataGroupInfoList);
4230     if (!result || dataGroupInfoList.empty()) {
4231         TAG_LOGD(AAFwkTag::APPMGR, "the bundle has no groupInfos.");
4232     }
4233     QueryExtensionSandBox(param.moduleName, param.abilityName, bundleInfo, startMsg, dataGroupInfoList, param.want);
4234     SetStartMsgStrictMode(startMsg, param);
4235     startMsg.bundleName = bundleInfo.name;
4236     startMsg.renderParam = RENDER_PARAM;
4237     startMsg.flags = param.startFlags;
4238     startMsg.bundleIndex = param.bundleIndex;
4239     startMsg.procName = param.processName;
4240     SetAtomicServiceInfo(param.bundleType, startMsg);
4241     SetOverlayInfo(bundleInfo.name, userId, startMsg);
4242     SetAppInfo(bundleInfo, startMsg);
4243     SetStartMsgCustomSandboxFlag(startMsg, bundleInfo.applicationInfo.accessTokenId);
4244     GetKernelPermissions(bundleInfo.applicationInfo.accessTokenId, startMsg.jitPermissionsMap);
4245     TAG_LOGI(AAFwkTag::APPMGR, "apl: %{public}s, bundleName: %{public}s, startFlags: %{public}d, userId: %{public}d",
4246         startMsg.apl.c_str(), bundleInfo.name.c_str(), param.startFlags, userId);
4247 
4248     autoSync.Sync();
4249     return ERR_OK;
4250 }
4251 
SetStartMsgCustomSandboxFlag(AppSpawnStartMsg & startMsg,uint32_t accessTokenId)4252 void AppMgrServiceInner::SetStartMsgCustomSandboxFlag(AppSpawnStartMsg &startMsg, uint32_t accessTokenId)
4253 {
4254     if (!AAFwk::AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
4255         TAG_LOGD(AAFwkTag::APPMGR, "not supported device");
4256         return;
4257     }
4258 
4259     if (AAFwk::PermissionVerification::GetInstance()->VerifyCustomSandbox(accessTokenId)) {
4260         startMsg.isCustomSandboxFlag = true;
4261     }
4262 }
4263 
GetKernelPermissions(uint32_t accessTokenId,JITPermissionsMap & permissionsMap)4264 void AppMgrServiceInner::GetKernelPermissions(uint32_t accessTokenId, JITPermissionsMap &permissionsMap)
4265 {
4266     std::vector<Security::AccessToken::PermissionWithValue> permissionWithValueList;
4267     AccessToken::AccessTokenKit::GetKernelPermissions(accessTokenId, permissionWithValueList);
4268     for (const auto &item : permissionWithValueList) {
4269         permissionsMap.emplace(item.permissionName, item.value);
4270     }
4271     std::vector<std::string> permissionsList;
4272     AppspawnUtil::SetJITPermissions(accessTokenId, permissionsList);
4273     for (const auto &item : permissionsList) {
4274         auto it = permissionsMap.find(item);
4275         if (it == permissionsMap.end()) {
4276             permissionsMap.emplace(item, "");
4277         }
4278     }
4279 }
4280 
SetStartMsgStrictMode(AppSpawnStartMsg & startMsg,const CreateStartMsgParam & param)4281 void AppMgrServiceInner::SetStartMsgStrictMode(AppSpawnStartMsg &startMsg, const CreateStartMsgParam &param)
4282 {
4283     startMsg.strictMode = param.strictMode;
4284     if (param.extensionAbilityType == ExtensionAbilityType::INPUTMETHOD) {
4285         startMsg.isolatedSandboxFlagLegacy = true;
4286     } else {
4287         startMsg.isolatedNetworkFlag = !param.networkEnableFlags;
4288         startMsg.isolatedSELinuxFlag = !param.saEnableFlags;
4289         startMsg.extensionTypeName = ConvertToExtensionTypeName(param.extensionAbilityType);
4290     }
4291 }
4292 
4293 #ifdef SUPPORT_CHILD_PROCESS
PresetMaxChildProcess(std::shared_ptr<AppRunningRecord> appRecord,int32_t & maxChildProcess)4294 void AppMgrServiceInner::PresetMaxChildProcess(std::shared_ptr<AppRunningRecord> appRecord, int32_t &maxChildProcess)
4295 {
4296     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord null");
4297     ProcessType processType = appRecord->GetProcessType();
4298     ExtensionAbilityType extensionType = appRecord->GetExtensionType();
4299     if (processType == ProcessType::EXTENSION && extensionType != ExtensionAbilityType::DATASHARE &&
4300         extensionType != ExtensionAbilityType::SERVICE) {
4301         maxChildProcess = 1;
4302     }
4303 }
4304 #endif // SUPPORT_CHILD_PROCESS
4305 
QueryExtensionSandBox(const std::string & moduleName,const std::string & abilityName,const BundleInfo & bundleInfo,AppSpawnStartMsg & startMsg,DataGroupInfoList & dataGroupInfoList,std::shared_ptr<AAFwk::Want> want)4306 void AppMgrServiceInner::QueryExtensionSandBox(const std::string &moduleName, const std::string &abilityName,
4307     const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg, DataGroupInfoList &dataGroupInfoList,
4308     std::shared_ptr<AAFwk::Want> want)
4309 {
4310     std::vector<ExtensionAbilityInfo> extensionInfos;
4311     for (auto hapModuleInfo: bundleInfo.hapModuleInfos) {
4312         extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(),
4313             hapModuleInfo.extensionInfos.end());
4314     }
4315     auto isExist = (want == nullptr) ? false : want->HasParameter(ISOLATED_SANDBOX);
4316     bool isolatedSandbox = false;
4317     if (isExist) {
4318         isolatedSandbox = (want == nullptr) ? false : want->GetBoolParam(ISOLATED_SANDBOX, false);
4319     }
4320     auto infoExisted = [&moduleName, &abilityName, &isExist, &isolatedSandbox](
4321                            const ExtensionAbilityInfo &info) {
4322         auto ret = info.moduleName == moduleName && info.name == abilityName && info.needCreateSandbox;
4323         if (isExist) {
4324             return ret && isolatedSandbox;
4325         }
4326         return ret;
4327     };
4328     auto infoIter = std::find_if(extensionInfos.begin(), extensionInfos.end(), infoExisted);
4329     DataGroupInfoList extensionDataGroupInfoList;
4330     if (infoIter != extensionInfos.end()) {
4331         startMsg.isolatedExtension = true;
4332         startMsg.extensionSandboxPath = infoIter->moduleName + "-" + infoIter->name;
4333         for (auto dataGroupInfo : dataGroupInfoList) {
4334             auto groupIdExisted = [&dataGroupInfo](const std::string &dataGroupId) {
4335                 return dataGroupInfo.dataGroupId == dataGroupId;
4336             };
4337             if (std::find_if(infoIter->dataGroupIds.begin(), infoIter->dataGroupIds.end(), groupIdExisted) !=
4338                 infoIter->dataGroupIds.end()) {
4339                 extensionDataGroupInfoList.emplace_back(dataGroupInfo);
4340             }
4341         }
4342         startMsg.dataGroupInfoList = extensionDataGroupInfoList;
4343     } else {
4344         startMsg.dataGroupInfoList = dataGroupInfoList;
4345     }
4346     bool isScreenLockDataProtect = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
4347         [] (const auto &reqPermission) {
4348             if (PERMISSION_PROTECT_SCREEN_LOCK_DATA == reqPermission) {
4349                 TAG_LOGD(AAFwkTag::APPMGR, "has el5 permission: %{public}s", PERMISSION_PROTECT_SCREEN_LOCK_DATA);
4350                 return true;
4351             }
4352             return false;
4353         });
4354     startMsg.isScreenLockDataProtect = isScreenLockDataProtect;
4355 }
4356 
StartProcess(const std::string & appName,const std::string & processName,uint32_t startFlags,std::shared_ptr<AppRunningRecord> appRecord,const int uid,const BundleInfo & bundleInfo,const std::string & bundleName,const int32_t bundleIndex,bool appExistFlag,bool isPreload,AppExecFwk::PreloadMode preloadMode,const std::string & moduleName,const std::string & abilityName,sptr<IRemoteObject> token,std::shared_ptr<AAFwk::Want> want,ExtensionAbilityType extensionAbilityType)4357 int32_t AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName,
4358     uint32_t startFlags, std::shared_ptr<AppRunningRecord> appRecord, const int uid, const BundleInfo &bundleInfo,
4359     const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag, bool isPreload,
4360     AppExecFwk::PreloadMode preloadMode, const std::string &moduleName, const std::string &abilityName,
4361     sptr<IRemoteObject> token, std::shared_ptr<AAFwk::Want> want, ExtensionAbilityType extensionAbilityType)
4362 {
4363     if (AAFwk::AppUtils::GetInstance().IsForbidStart()) {
4364         TAG_LOGW(AAFwkTag::APPMGR, "forbid start: %{public}s", processName.c_str());
4365         return AAFwk::INNER_ERR;
4366     }
4367     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
4368     std::shared_lock lock(startProcessLock_);
4369     TAG_LOGD(AAFwkTag::APPMGR, "bundleName: %{public}s, isPreload: %{public}d", bundleName.c_str(), isPreload);
4370     if (!appRecord) {
4371         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4372         return ERR_INVALID_VALUE;
4373     }
4374     if (!appRunningManager_) {
4375         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
4376         return ERR_INVALID_VALUE;
4377     }
4378     auto ret = PreCheckStartProcess(bundleName, uid, want);
4379     if (ret != ERR_OK) {
4380         TAG_LOGE(AAFwkTag::APPMGR, "precheck failed");
4381         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
4382         return ret;
4383     }
4384     bool isCJApp = IsCjApplication(bundleInfo);
4385     if (!remoteClientManager_ || !remoteClientManager_->GetSpawnClient()) {
4386         TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient null");
4387         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
4388         if (!isCJApp) {
4389             SendProcessStartFailedEvent(appRecord, ProcessStartFailedReason::GET_SPAWN_CLIENT_FAILED,
4390                 AAFwk::ERR_GET_SPAWN_CLIENT_FAILED);
4391         }
4392         return AAFwk::ERR_GET_SPAWN_CLIENT_FAILED;
4393     }
4394 
4395     AppSpawnStartMsg startMsg;
4396     auto appInfo = appRecord->GetApplicationInfo();
4397     auto bundleType = appInfo ? appInfo->bundleType : BundleType::APP;
4398 #ifdef SUPPORT_CHILD_PROCESS
4399     PresetMaxChildProcess(appRecord, startMsg.maxChildProcess);
4400 #endif // SUPPORT_CHILD_PROCESS
4401     CreateStartMsgParam startMsgParam;
4402     startMsgParam.processName = processName;
4403     startMsgParam.startFlags = startFlags;
4404     startMsgParam.uid = uid;
4405     startMsgParam.bundleInfo = bundleInfo;
4406     startMsgParam.bundleIndex = bundleIndex;
4407     startMsgParam.bundleType = bundleType;
4408     startMsgParam.want = want;
4409     startMsgParam.moduleName = moduleName;
4410     startMsgParam.abilityName = abilityName;
4411     startMsgParam.strictMode = appRecord->IsStrictMode();
4412     startMsgParam.networkEnableFlags = appRecord->GetNetworkEnableFlags();
4413     startMsgParam.saEnableFlags = appRecord->GetSAEnableFlags();
4414     startMsgParam.extensionAbilityType = extensionAbilityType;
4415     ret = CreateStartMsg(startMsgParam, startMsg);
4416     if (ret != ERR_OK) {
4417         TAG_LOGE(AAFwkTag::APPMGR, "createStartMsg fail");
4418         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
4419         if (!isCJApp) {
4420             SendProcessStartFailedEvent(appRecord, ProcessStartFailedReason::CREATE_START_MSG_FAILED, ret);
4421         }
4422         return AAFwk::ERR_CREATE_START_MSG_FAILED;
4423     };
4424     SetProcessJITState(appRecord);
4425     PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
4426     pid_t pid = 0;
4427     ErrCode errCode = ERR_OK;
4428     if (isCJApp) {
4429         if (!remoteClientManager_->GetCJSpawnClient()) {
4430             TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient null");
4431             appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
4432             return AAFwk::ERR_GET_SPAWN_CLIENT_FAILED;
4433         }
4434         SendCreateAtomicServiceProcessEvent(appRecord, bundleType, moduleName, abilityName);
4435         errCode = remoteClientManager_->GetCJSpawnClient()->StartProcess(startMsg, pid);
4436     } else if (appInfo != nullptr &&
4437         (appInfo->arkTSMode == CODE_LANGUAGE_ARKTS_1_2 || appInfo->arkTSMode == CODE_LANGUAGE_ARKTS_HYBRID)) {
4438         SendCreateAtomicServiceProcessEvent(appRecord, bundleType, moduleName, abilityName);
4439         startMsg.gids.push_back(SHADER_CACHE_GROUPID);
4440         errCode = remoteClientManager_->GetHybridSpawnClient()->StartProcess(startMsg, pid);
4441     } else {
4442         SendCreateAtomicServiceProcessEvent(appRecord, bundleType, moduleName, abilityName);
4443         startMsg.gids.push_back(SHADER_CACHE_GROUPID);
4444         errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
4445     }
4446     if (FAILED(errCode)) {
4447         TAG_LOGE(AAFwkTag::APPMGR, "spawn new app fail, errCode %{public}08x", errCode);
4448         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
4449         if (!isCJApp) {
4450             SendProcessStartFailedEvent(appRecord, ProcessStartFailedReason::APPSPAWN_FAILED,
4451                 static_cast<int32_t>(errCode));
4452         }
4453         return AAFwk::ERR_SPAWN_PROCESS_FAILED;
4454     }
4455 
4456     #ifdef ABILITY_RUNTIME_FEATURE_SANDBOXMANAGER
4457     bool checkApiVersion = (appInfo && (appInfo->apiTargetVersion % API_VERSION_MOD == API10));
4458     TAG_LOGD(AAFwkTag::APPMGR, "version of api is %{public}d", appInfo->apiTargetVersion % API_VERSION_MOD);
4459     if (checkApiVersion && AAFwk::AppUtils::GetInstance().IsGrantPersistUriPermission()) {
4460         uint32_t tokenId = appInfo->accessTokenId;
4461         auto sandboxRet = AccessControl::SandboxManager::SandboxManagerKit::StartAccessingByTokenId(tokenId);
4462         TAG_LOGI(AAFwkTag::APPMGR, "tokenId: %{public}u, ret: %{public}d", tokenId, sandboxRet);
4463     }
4464     #endif
4465 
4466     TAG_LOGI(AAFwkTag::APPMGR, "start process success, pid: %{public}d, processName: %{public}s",
4467         pid, processName.c_str());
4468     SetRunningSharedBundleList(bundleName, startMsg.hspList);
4469     CHECK_POINTER_AND_RETURN_VALUE(appRecord->GetPriorityObject(), ERR_INVALID_VALUE);
4470     appRecord->GetPriorityObject()->SetPid(pid);
4471     appRecord->SetUid(startMsg.uid);
4472     appRecord->SetStartMsg(startMsg);
4473     appRecord->SetAppMgrServiceInner(weak_from_this());
4474     appRecord->SetSpawned();
4475     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionAbilityType)) {
4476         TAG_LOGD(AAFwkTag::APPMGR, "Add UIExtension LauncherItem.");
4477         AddUIExtensionLauncherItem(want, appRecord, token);
4478     }
4479     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, false, false);
4480     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessCreated(appRecord, isPreload);
4481     if (AAFwk::UIExtensionUtils::IsUIExtension(extensionAbilityType)) {
4482         AddUIExtensionBindItem(want, appRecord, token);
4483     }
4484     if (!appExistFlag) {
4485         OnAppStarted(appRecord);
4486     }
4487     PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
4488     SendProcessStartEvent(appRecord, isPreload, preloadMode);
4489     ProcessAppDebug(appRecord, appRecord->IsDebugApp());
4490     return ERR_OK;
4491 }
4492 
SetProcessJITState(const std::shared_ptr<AppRunningRecord> appRecord)4493 void AppMgrServiceInner::SetProcessJITState(const std::shared_ptr<AppRunningRecord> appRecord)
4494 {
4495     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
4496     TAG_LOGD(AAFwkTag::APPMGR, "called");
4497     if (!appRecord) {
4498         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4499         return;
4500     }
4501     if (!securityModeManager_) {
4502         TAG_LOGE(AAFwkTag::APPMGR, "securityModeManager_ null");
4503         appRecord->SetJITEnabled(true);
4504         return;
4505     }
4506     appRecord->SetJITEnabled(securityModeManager_->IsJITEnabled());
4507 }
4508 
MakeAppDebugInfo(const std::shared_ptr<AppRunningRecord> & appRecord,const bool & isDebugStart)4509 AppDebugInfo AppMgrServiceInner::MakeAppDebugInfo(
4510     const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart)
4511 {
4512     AppDebugInfo info;
4513     if (appRecord == nullptr) {
4514         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4515         return info;
4516     }
4517 
4518     info.bundleName = appRecord->GetBundleName();
4519     auto priorityObject = appRecord->GetPriorityObject();
4520     if (priorityObject) {
4521         info.pid = priorityObject->GetPid();
4522     }
4523     info.uid = appRecord->GetUid();
4524     info.isDebugStart = isDebugStart;
4525     return info;
4526 }
4527 
ProcessAppDebug(const std::shared_ptr<AppRunningRecord> & appRecord,const bool & isDebugStart)4528 void AppMgrServiceInner::ProcessAppDebug(const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart)
4529 {
4530     TAG_LOGD(AAFwkTag::APPMGR, "called");
4531     if (appRecord == nullptr || appDebugManager_ == nullptr) {
4532         TAG_LOGE(AAFwkTag::APPMGR, "appRecord or appDebugManager_ null");
4533         return;
4534     }
4535 
4536     auto startDebug = [this, appRecord](const bool &isDebugStart) {
4537         std::vector<AppDebugInfo> debugInfos;
4538         debugInfos.emplace_back(MakeAppDebugInfo(appRecord, isDebugStart));
4539         appDebugManager_->StartDebug(debugInfos);
4540     };
4541 
4542     if (isDebugStart && !appRecord->IsDebugApp()) {
4543         appRecord->SetDebugApp(true);
4544         startDebug(true);
4545         return;
4546     }
4547 
4548     if (appRecord->IsDebugApp()) {
4549         startDebug(true);
4550         return;
4551     }
4552 
4553     auto bundleName = appRecord->GetBundleName();
4554     auto isDebugFromLocal = appRecord->GetDebugFromLocal();
4555     if (appDebugManager_->IsAttachDebug(bundleName)) {
4556         appRecord->SetAttachDebug(true, isDebugFromLocal);
4557         startDebug(false);
4558     }
4559 }
4560 
SendCreateAtomicServiceProcessEvent(const std::shared_ptr<AppRunningRecord> & appRecord,const BundleType & bundleType,const std::string & moduleName,const std::string & abilityName)4561 bool AppMgrServiceInner::SendCreateAtomicServiceProcessEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
4562     const BundleType &bundleType, const std::string &moduleName, const std::string &abilityName)
4563 {
4564     if (bundleType != BundleType::ATOMIC_SERVICE) {
4565         return false;
4566     }
4567     if (!appRecord) {
4568         TAG_LOGI(AAFwkTag::APPMGR, "null appRecord");
4569         return false;
4570     }
4571     TAG_LOGI(AAFwkTag::APPMGR, "report createAtomicServiceProcessEvent");
4572     auto callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
4573     auto callerAppRecord = GetAppRunningRecordByPid(callerPid);
4574     return AppMgrEventUtil::SendCreateAtomicServiceProcessEvent(callerAppRecord, appRecord, moduleName, abilityName);
4575 }
4576 
SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> & appRecord,bool isPreload,AppExecFwk::PreloadMode preloadMode)4577 bool AppMgrServiceInner::SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> &appRecord, bool isPreload,
4578     AppExecFwk::PreloadMode preloadMode)
4579 {
4580     if (!appRecord) {
4581         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4582         return false;
4583     }
4584     AAFwk::EventInfo eventInfo;
4585     auto callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
4586     auto callerAppRecord = GetAppRunningRecordByPid(callerPid);
4587     eventInfo.isPreload = isPreload;
4588     eventInfo.preloadMode = static_cast<int32_t>(preloadMode);
4589     AppMgrEventUtil::SendProcessStartEvent(callerAppRecord, appRecord, eventInfo);
4590     SendReStartProcessEvent(eventInfo, appRecord->GetUid());
4591     return true;
4592 }
4593 
SendReStartProcessEvent(AAFwk::EventInfo & eventInfo,int32_t appUid)4594 void AppMgrServiceInner::SendReStartProcessEvent(AAFwk::EventInfo &eventInfo, int32_t appUid)
4595 {
4596     TAG_LOGD(AAFwkTag::APPMGR, "called");
4597     std::lock_guard lock(killedProcessMapLock_);
4598     int64_t restartTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::
4599         system_clock::now().time_since_epoch()).count();
4600     for (auto iter = killedProcessMap_.begin(); iter != killedProcessMap_.end();) {
4601         int64_t killTime = iter->first;
4602         if (restartTime - killTime > PROCESS_RESTART_MARGIN_MICRO_SECONDS) {
4603             iter = killedProcessMap_.erase(iter);
4604             continue;
4605         }
4606         if (eventInfo.bundleName == eventInfo.callerBundleName &&
4607             eventInfo.processName != eventInfo.callerProcessName) {
4608             AppMgrEventUtil::SendReStartProcessEvent(eventInfo, appUid, restartTime);
4609             iter = killedProcessMap_.erase(iter);
4610             continue;
4611         }
4612         ++iter;
4613     }
4614 }
4615 
SendProcessStartFailedEvent(std::shared_ptr<AppRunningRecord> appRecord,ProcessStartFailedReason reason,int32_t subReason)4616 bool AppMgrServiceInner::SendProcessStartFailedEvent(std::shared_ptr<AppRunningRecord> appRecord,
4617     ProcessStartFailedReason reason, int32_t subReason)
4618 {
4619     if (!appRecord) {
4620         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4621         return false;
4622     }
4623     TAG_LOGD(AAFwkTag::APPMGR, "processName:%{public}s, reason:%{public}d, subReason:%{public}d",
4624         appRecord->GetProcessName().c_str(), reason, subReason);
4625     AAFwk::EventInfo eventInfo;
4626     eventInfo.reason = static_cast<int32_t>(reason);
4627     eventInfo.subReason = subReason;
4628     auto callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
4629     auto callerAppRecord = GetAppRunningRecordByPid(callerPid);
4630     AppMgrEventUtil::SendProcessStartFailedEvent(callerAppRecord, appRecord, eventInfo);
4631     return true;
4632 }
4633 
SendPreloadAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> & appRecord,const std::shared_ptr<AbilityInfo> & abilityInfo)4634 void AppMgrServiceInner::SendPreloadAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
4635     const std::shared_ptr<AbilityInfo> &abilityInfo)
4636 {
4637     if (!appRecord) {
4638         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4639         return;
4640     }
4641 
4642     PreloadMode preloadMode = appRecord->GetPreloadMode();
4643     PreloadPhase preloadPhase = appRecord->GetPreloadPhase();
4644     if (!appRecord->IsPreloading() && !appRecord->IsPreloaded()) {
4645         TAG_LOGD(AAFwkTag::APPMGR, "not preload app start");
4646         if (appRecord->IsAlreadyHaveAbility()) {
4647             SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::WARM, AppStartReason::NONE);
4648         }
4649         return;
4650     }
4651     if (preloadMode == PreloadMode::PRE_MAKE) {
4652         SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::WARM, AppStartReason::PRE_MAKE);
4653     } else if (preloadMode == PreloadMode::PRELOAD_MODULE) {
4654         SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::WARM, AppStartReason::PRELOAD_MODULE);
4655     } else if (preloadMode == PreloadMode::PRESS_DOWN) {
4656         SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::WARM, AppStartReason::PRESS_DOWN);
4657     } else if (preloadMode == PreloadMode::PRELOAD_BY_PHASE) {
4658         if (preloadPhase == PreloadPhase::PROCESS_CREATED) {
4659             SendAppStartupTypeEvent(appRecord,
4660                 abilityInfo, AppStartType::WARM, AppStartReason::PRELOAD_BY_PHASE_PROCESS_CREATED);
4661         } else if (preloadPhase == PreloadPhase::ABILITY_STAGE_CREATED) {
4662             SendAppStartupTypeEvent(appRecord,
4663                 abilityInfo, AppStartType::WARM, AppStartReason::PRELOAD_BY_PHASE_ABILITY_STAGE_CREATED);
4664         }
4665     } else {
4666         TAG_LOGD(AAFwkTag::APPMGR, "app preload mode: %{public}d", static_cast<int32_t>(preloadMode));
4667     }
4668 }
4669 
SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> & appRecord,const std::shared_ptr<AbilityInfo> & abilityInfo,const AppStartType startType,const AppStartReason reason)4670 void AppMgrServiceInner::SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
4671     const std::shared_ptr<AbilityInfo> &abilityInfo, const AppStartType startType, const AppStartReason reason)
4672 {
4673     if (!appRecord) {
4674         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4675         return;
4676     }
4677 
4678     if (abilityInfo && abilityInfo->type != AppExecFwk::AbilityType::PAGE &&
4679         !AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
4680         return;
4681     }
4682 
4683     AAFwk::EventInfo eventInfo;
4684     auto applicationInfo = appRecord->GetApplicationInfo();
4685     if (!applicationInfo) {
4686         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo null");
4687     } else {
4688         eventInfo.bundleName = applicationInfo->name;
4689         eventInfo.versionName = applicationInfo->versionName;
4690         eventInfo.versionCode = applicationInfo->versionCode;
4691     }
4692     if (!abilityInfo) {
4693         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo null");
4694     } else {
4695         eventInfo.abilityName = abilityInfo->name;
4696     }
4697     if (appRecord->GetPriorityObject() == nullptr) {
4698         TAG_LOGE(AAFwkTag::APPMGR, "priorityObject null");
4699     } else {
4700         eventInfo.pid = appRecord->GetPid();
4701     }
4702     eventInfo.startType = static_cast<int32_t>(startType);
4703     eventInfo.startReason = static_cast<int32_t>(reason);
4704     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_STARTUP_TYPE, HiSysEventType::BEHAVIOR, eventInfo);
4705 }
4706 
GetAbilityNames(const std::map<const sptr<IRemoteObject>,std::shared_ptr<AbilityRunningRecord>> & abilityRecordList,std::vector<std::string> & abilityNames,std::vector<std::string> & uiExtensionNames,std::string & bundleName)4707 static bool GetAbilityNames(
4708     const std::map<const sptr<IRemoteObject>, std::shared_ptr<AbilityRunningRecord>> &abilityRecordList,
4709     std::vector<std::string> &abilityNames, std::vector<std::string> &uiExtensionNames,
4710     std::string &bundleName)
4711 {
4712     std::string abilityName = "";
4713     std::string moduleName = "";
4714     for (auto it = abilityRecordList.begin(); it != abilityRecordList.end(); ++it) {
4715         if (it->second == nullptr) {
4716             continue;
4717         }
4718         auto abilityInfo = it->second->GetAbilityInfo();
4719         if (abilityInfo == nullptr) {
4720             continue;
4721         }
4722         abilityName = it->second->GetName();
4723         moduleName = it->second->GetModuleName();
4724         bundleName = it->second->GetBundleName();
4725         if (abilityInfo->type == AppExecFwk::AbilityType::PAGE) {
4726             abilityNames.push_back(abilityName);
4727         } else if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
4728             uiExtensionNames.push_back(moduleName + ":" + abilityName);
4729         }
4730     }
4731     if (abilityNames.empty() && uiExtensionNames.empty()) {
4732         TAG_LOGI(AAFwkTag::APPMGR, "no ability or uiextension");
4733         return false;
4734     }
4735     return true;
4736 }
4737 
CacheExitInfo(const std::shared_ptr<AppRunningRecord> & appRecord)4738 void AppMgrServiceInner::CacheExitInfo(const std::shared_ptr<AppRunningRecord> &appRecord)
4739 {
4740     if (appRecord == nullptr) {
4741         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4742         return;
4743     }
4744     if (appRecord->GetReasonExist()) {
4745         TAG_LOGI(AAFwkTag::APPMGR, "exit info exist");
4746         return;
4747     }
4748     RunningProcessInfo exitInfo;
4749     if (appRunningManager_) {
4750         appRunningManager_->AssignRunningProcessInfoByAppRecord(appRecord, exitInfo);
4751     }
4752     std::vector<std::string> abilityNames;
4753     std::vector<std::string> uiExtensionNames;
4754     std::string bundleName = "";
4755     auto applicationInfo = appRecord->GetApplicationInfo();
4756     if (applicationInfo == nullptr) {
4757         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo null");
4758         return;
4759     }
4760     uint32_t accessTokenId = applicationInfo->accessTokenId;
4761     auto abilityRecordList = appRecord->GetAbilities();
4762     if (!GetAbilityNames(abilityRecordList, abilityNames, uiExtensionNames, bundleName)) {
4763         return;
4764     }
4765     {
4766         std::lock_guard lock(appStateCallbacksLock_);
4767         for (const auto &item : appStateCallbacks_) {
4768             if (item.callback != nullptr) {
4769                 item.callback->OnCacheExitInfo(accessTokenId, exitInfo, bundleName, abilityNames, uiExtensionNames);
4770             }
4771         }
4772     }
4773 }
4774 
OnRemoteDied(const wptr<IRemoteObject> & remote,bool isRenderProcess,bool isChildProcess)4775 void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess, bool isChildProcess)
4776 {
4777     TAG_LOGD(AAFwkTag::APPMGR, "On remote died.");
4778     if (isRenderProcess) {
4779         OnRenderRemoteDied(remote);
4780         return;
4781     }
4782 #ifdef SUPPORT_CHILD_PROCESS
4783     if (isChildProcess) {
4784         OnChildProcessRemoteDied(remote);
4785         return;
4786     }
4787 #endif // SUPPORT_CHILD_PROCESS
4788 
4789     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
4790     {
4791         std::lock_guard lock(exceptionLock_);
4792         appRecord = appRunningManager_->OnRemoteDied(remote, shared_from_this());
4793     }
4794     if (appRecord == nullptr) {
4795         TAG_LOGI(AAFwkTag::APPMGR, "null appRecord");
4796         return;
4797     }
4798     AppExecFwk::AppfreezeManager::GetInstance()->RemoveDeathProcess(appRecord->GetBundleName());
4799     std::vector<sptr<IRemoteObject>> abilityTokens;
4800     for (const auto &token : appRecord->GetAbilities()) {
4801         abilityTokens.emplace_back(token.first);
4802     }
4803     CacheExitInfo(appRecord);
4804     {
4805         std::lock_guard lock(appStateCallbacksLock_);
4806         for (const auto &item : appStateCallbacks_) {
4807             if (item.callback != nullptr) {
4808                 item.callback->OnAppRemoteDied(abilityTokens);
4809             }
4810         }
4811     }
4812     ClearData(appRecord);
4813 
4814     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
4815         startSpecifiedAbilityResponse_->OnStartSpecifiedFailed(appRecord->GetSpecifiedRequestId());
4816     }
4817     appRecord->ResetSpecifiedRequest();
4818     if (appRecord->IsNewProcessRequest() && startSpecifiedAbilityResponse_) {
4819         startSpecifiedAbilityResponse_->OnStartSpecifiedFailed(appRecord->GetNewProcessRequestId());
4820     }
4821     appRecord->ResetNewProcessRequest();
4822 }
4823 
ClearAppRunningData(const std::shared_ptr<AppRunningRecord> & appRecord)4824 void AppMgrServiceInner::ClearAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord)
4825 {
4826     if (!appRecord) {
4827         return;
4828     }
4829 
4830     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
4831     FinishUserTestLocked("App died", -1, appRecord);
4832     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_REMOTE_DIED);
4833 
4834     for (const auto &item : appRecord->GetAbilities()) {
4835         const auto &abilityRecord = item.second;
4836         //UIExtension notifies Extension & Ability state changes
4837         if (AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())) {
4838             appRecord->StateChangedNotifyObserver(abilityRecord,
4839                 static_cast<int32_t>(ExtensionState::EXTENSION_STATE_TERMINATED), false, false);
4840         }
4841         appRecord->StateChangedNotifyObserver(abilityRecord,
4842             static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true, false);
4843     }
4844     OnProcessDied(appRecord);
4845     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
4846 
4847     // kill render if exist.
4848     KillRenderProcess(appRecord);
4849 #ifdef SUPPORT_CHILD_PROCESS
4850     KillChildProcess(appRecord);
4851     KillAttachedChildProcess(appRecord);
4852 #endif // SUPPORT_CHILD_PROCESS
4853 
4854     SendProcessExitEvent(appRecord);
4855 
4856     auto appInfo = appRecord->GetApplicationInfo();
4857     if (appInfo != nullptr && !appRunningManager_->IsAppExist(appInfo->accessTokenId)) {
4858         appRecord->UnSetPolicy();
4859         TAG_LOGD(AAFwkTag::APPMGR, "before OnAppStopped");
4860         OnAppStopped(appRecord);
4861     }
4862 
4863     if (appDebugManager_ != nullptr) {
4864         auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
4865         appDebugManager_->RemoveAppDebugInfo(info);
4866     }
4867 
4868     ClearAppRunningDataForKeepAlive(appRecord);
4869 
4870     auto uid = appRecord->GetUid();
4871     TAG_LOGD(AAFwkTag::APPMGR, "before NotifyAppRunningStatusEvent");
4872     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
4873 }
4874 
HandleTimeOut(const AAFwk::EventWrap & event)4875 void AppMgrServiceInner::HandleTimeOut(const AAFwk::EventWrap &event)
4876 {
4877     TAG_LOGD(AAFwkTag::APPMGR, "called");
4878     if (!appRunningManager_) {
4879         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
4880         return;
4881     }
4882 
4883     // check libc.hook_mode
4884     const int bufferLen = 128;
4885     char paramOutBuf[bufferLen] = {0};
4886     const char *hook_mode = "startup:";
4887     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
4888     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
4889         TAG_LOGD(AAFwkTag::APPMGR, "HandleTimeOut, Hook_mode: no handle time out");
4890         return;
4891     }
4892     auto appRecord = AppEventUtil::GetInstance().RemoveEvent(event.GetEventId(), event.GetParam());
4893     switch (event.GetEventId()) {
4894         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
4895             appRunningManager_->HandleTerminateTimeOut(event.GetParam());
4896             break;
4897         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
4898             SendHiSysEvent(event.GetEventId(), appRecord);
4899             HandleTerminateApplicationTimeOut(appRecord);
4900             break;
4901         case AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG:
4902             SendHiSysEvent(event.GetEventId(), appRecord);
4903             HandleStartSpecifiedProcessTimeout(appRecord);
4904             break;
4905         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
4906         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
4907             SendHiSysEvent(event.GetEventId(), appRecord);
4908             HandleAddAbilityStageTimeOut(appRecord);
4909             break;
4910         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
4911             SendHiSysEvent(event.GetEventId(), appRecord);
4912             HandleStartSpecifiedAbilityTimeOut(appRecord);
4913             break;
4914         case AMSEventHandler::TERMINATE_APPLICATION_HALF_TIMEOUT_MSG:
4915         case AMSEventHandler::START_SPECIFIED_PROCESS_HALF_TIMEOUT_MSG:
4916         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG:
4917         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_HALF_TIMEOUT_MSG:
4918         case AMSEventHandler::START_SPECIFIED_ABILITY_HALF_TIMEOUT_MSG:
4919             SendHiSysEvent(event.GetEventId(), appRecord);
4920             break;
4921         default:
4922             break;
4923     }
4924 }
4925 
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token)4926 void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token)
4927 {
4928     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
4929     TAG_LOGD(AAFwkTag::APPMGR, "called");
4930     if (!appRunningManager_) {
4931         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
4932         return;
4933     }
4934     appRunningManager_->HandleAbilityAttachTimeOut(token, shared_from_this());
4935 }
4936 
PrepareTerminate(const sptr<IRemoteObject> & token,bool clearMissionFlag)4937 void AppMgrServiceInner::PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag)
4938 {
4939     TAG_LOGD(AAFwkTag::APPMGR, "called");
4940     if (!appRunningManager_) {
4941         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
4942         return;
4943     }
4944     appRunningManager_->PrepareTerminate(token, clearMissionFlag);
4945 }
4946 
HandleTerminateApplicationTimeOut(std::shared_ptr<AppRunningRecord> appRecord)4947 void AppMgrServiceInner::HandleTerminateApplicationTimeOut(std::shared_ptr<AppRunningRecord> appRecord)
4948 {
4949     TAG_LOGD(AAFwkTag::APPMGR, "called");
4950     TerminateApplication(appRecord);
4951 }
4952 
TerminateApplication(const std::shared_ptr<AppRunningRecord> & appRecord)4953 void AppMgrServiceInner::TerminateApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
4954 {
4955     if (!appRecord) {
4956         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
4957         return;
4958     }
4959     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
4960     appRecord->RemoveAppDeathRecipient();
4961     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED_TIMEOUT);
4962     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false, false);
4963     pid_t pid = appRecord->GetPid();
4964     int32_t uid = appRecord->GetUid();
4965     if (pid > 0) {
4966         auto timeoutTask = [appRecord, pid, uid, innerServiceWeak = weak_from_this()]() {
4967             auto innerService = innerServiceWeak.lock();
4968             CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
4969             TAG_LOGI(AAFwkTag::APPMGR, "killProcessByPid %{public}d, uid: %{public}d", pid, uid);
4970             int32_t result = innerService->KillProcessByPid(pid, "TerminateApplication");
4971             innerService->SendProcessExitEvent(appRecord);
4972             if (result < 0) {
4973                 TAG_LOGE(AAFwkTag::APPMGR, "killProcessByPid kill process fail");
4974                 return;
4975             }
4976         };
4977         if (!taskHandler_) {
4978             TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
4979             return;
4980         }
4981         taskHandler_->SubmitTaskJust(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
4982     }
4983     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
4984     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
4985         RemoveRunningSharedBundleList(appRecord->GetBundleName());
4986     }
4987     OnProcessDied(appRecord);
4988     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
4989     auto appInfo = appRecord->GetApplicationInfo();
4990     if (appInfo != nullptr && !appRunningManager_->IsAppExist(appInfo->accessTokenId)) {
4991         OnAppStopped(appRecord);
4992     }
4993 
4994     if (appDebugManager_) {
4995         auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
4996         appDebugManager_->RemoveAppDebugInfo(info);
4997     }
4998     ClearAppRunningDataForKeepAlive(appRecord);
4999 
5000     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
5001 }
5002 
HandleAddAbilityStageTimeOut(std::shared_ptr<AppRunningRecord> appRecord)5003 void AppMgrServiceInner::HandleAddAbilityStageTimeOut(std::shared_ptr<AppRunningRecord> appRecord)
5004 {
5005     TAG_LOGI(AAFwkTag::APPMGR, "call");
5006     if (!appRecord) {
5007         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
5008         return;
5009     }
5010 
5011     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
5012         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedRequestId());
5013     }
5014     appRecord->ResetSpecifiedRequest();
5015 
5016     if (appRecord->IsNewProcessRequest() && startSpecifiedAbilityResponse_) {
5017         startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestId());
5018     }
5019     appRecord->ResetNewProcessRequest();
5020 
5021     KillApplicationByRecord(appRecord);
5022 }
5023 
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)5024 void AppMgrServiceInner::GetRunningProcessInfoByToken(
5025     const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
5026 {
5027     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5028     TAG_LOGD(AAFwkTag::APPMGR, "called");
5029     if (!CheckGetRunningInfoPermission()) {
5030         return;
5031     }
5032 
5033     appRunningManager_->GetRunningProcessInfoByToken(token, info);
5034 }
5035 
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info) const5036 int32_t AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid,
5037     OHOS::AppExecFwk::RunningProcessInfo &info) const
5038 {
5039     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
5040     TAG_LOGD(AAFwkTag::APPMGR, "called");
5041     if (!CheckGetRunningInfoPermission()) {
5042         return ERR_PERMISSION_DENIED;
5043     }
5044 
5045     return appRunningManager_->GetRunningProcessInfoByPid(pid, info);
5046 }
5047 
GetRunningProcessInfoByChildProcessPid(const pid_t childPid,OHOS::AppExecFwk::RunningProcessInfo & info) const5048 int32_t AppMgrServiceInner::GetRunningProcessInfoByChildProcessPid(const pid_t childPid,
5049     OHOS::AppExecFwk::RunningProcessInfo &info) const
5050 {
5051     TAG_LOGD(AAFwkTag::APPMGR, "called");
5052     if (!CheckGetRunningInfoPermission()) {
5053         return ERR_PERMISSION_DENIED;
5054     }
5055 
5056     return appRunningManager_->GetRunningProcessInfoByChildProcessPid(childPid, info);
5057 }
5058 
SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const5059 void AppMgrServiceInner::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const
5060 {
5061     TAG_LOGD(AAFwkTag::APPMGR, "called");
5062     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
5063         return;
5064     }
5065 
5066     appRunningManager_->SetAbilityForegroundingFlagToAppRecord(pid);
5067 }
5068 
CheckGetRunningInfoPermission() const5069 bool AppMgrServiceInner::CheckGetRunningInfoPermission() const
5070 {
5071     if (!appRunningManager_) {
5072         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
5073         return false;
5074     }
5075 
5076     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
5077     if (!isPerm) {
5078         TAG_LOGE(AAFwkTag::APPMGR, "permission verify fail");
5079         return false;
5080     }
5081 
5082     return true;
5083 }
5084 
LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> & infos)5085 void AppMgrServiceInner::LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> &infos)
5086 {
5087     TAG_LOGI(AAFwkTag::APPMGR, "%{public}s call", __func__);
5088 
5089     TAG_LOGI(AAFwkTag::APPMGR, "info size: [%{public}zu]", infos.size());
5090     StartResidentProcess(infos, -1, true);
5091 }
5092 
StartResidentProcess(const std::vector<BundleInfo> & infos,int restartCount,bool isEmptyKeepAliveApp)5093 void AppMgrServiceInner::StartResidentProcess(const std::vector<BundleInfo> &infos, int restartCount,
5094     bool isEmptyKeepAliveApp)
5095 {
5096     TAG_LOGI(AAFwkTag::APPMGR, "startResidentProcess");
5097     if (infos.empty()) {
5098         TAG_LOGE(AAFwkTag::APPMGR, "infos null");
5099         return;
5100     }
5101 
5102     if (!appRunningManager_) {
5103         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
5104         return;
5105     }
5106 
5107     for (auto &bundle : infos) {
5108         TAG_LOGI(AAFwkTag::APPMGR, "processName: [%{public}s]", bundle.applicationInfo.process.c_str());
5109         if (bundle.applicationInfo.process.empty()) {
5110             continue;
5111         }
5112         auto processName = bundle.applicationInfo.process;
5113         // Inspection records
5114         auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
5115             bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle);
5116         if (appRecord) {
5117             TAG_LOGI(AAFwkTag::APPMGR, "processName [%{public}s] already exists", processName.c_str());
5118             continue;
5119         }
5120         TAG_LOGI(AAFwkTag::APPMGR, "processName: [%{public}s]", processName.c_str());
5121         StartEmptyResidentProcess(bundle, processName, restartCount, isEmptyKeepAliveApp);
5122     }
5123 }
5124 
StartEmptyResidentProcess(const BundleInfo & info,const std::string & processName,int restartCount,bool isEmptyKeepAliveApp)5125 void AppMgrServiceInner::StartEmptyResidentProcess(
5126     const BundleInfo &info, const std::string &processName, int restartCount, bool isEmptyKeepAliveApp)
5127 {
5128     TAG_LOGI(AAFwkTag::APPMGR, "start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(),
5129         processName.c_str());
5130     if (!CheckRemoteClient() || !appRunningManager_) {
5131         TAG_LOGI(AAFwkTag::APPMGR, "startResidentProcess fail");
5132         return;
5133     }
5134 
5135     bool appExistFlag = appRunningManager_->IsAppExist(info.applicationInfo.accessTokenId);
5136     bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(info.uid);
5137     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
5138 
5139     if (!appMultiUserExistFlag) {
5140         NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
5141     }
5142     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
5143         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
5144         return;
5145     }
5146 
5147     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info, "");
5148     if (!appRecord) {
5149         TAG_LOGE(AAFwkTag::APPMGR, "start process [%{public}s] fail", processName.c_str());
5150         return;
5151     }
5152 
5153     StartProcess(appInfo->name, processName, 0, appRecord, appInfo->uid, info, appInfo->bundleName, 0, appExistFlag);
5154 
5155     // If it is empty, the startup failed
5156     if (!appRecord) {
5157         TAG_LOGE(AAFwkTag::APPMGR, "start process [%{public}s] fail", processName.c_str());
5158         return;
5159     }
5160 
5161     if (restartCount > 0) {
5162         TAG_LOGI(AAFwkTag::APPMGR, "startEmptyResidentProcess restartCount: [%{public}d]", restartCount);
5163         appRecord->SetRestartResidentProcCount(restartCount);
5164     }
5165     appRecord->SetEmptyKeepAliveAppState(isEmptyKeepAliveApp);
5166     appRecord->SetKeepAliveEnableState(true);
5167 
5168     appRecord->SetTaskHandler(taskHandler_);
5169     appRecord->SetEventHandler(eventHandler_);
5170     std::vector<HapModuleInfo> hapModuleInfos;
5171     for (auto &iter : info.hapModuleInfos) {
5172         std::string keepAliveName = (appInfo->process.empty())?(appInfo->bundleName):(appInfo->process);
5173         std::string moduleProcessName = (iter.process.empty())?(appInfo->bundleName):(iter.process);
5174         if (keepAliveName == moduleProcessName) {
5175             hapModuleInfos.emplace_back(iter);
5176         }
5177     }
5178     appRecord->AddModules(appInfo, hapModuleInfos);
5179     TAG_LOGI(AAFwkTag::APPMGR, "StartEmptyResidentProcess of pid : [%{public}d], ",
5180         appRecord->GetPid());
5181 }
5182 
CheckRemoteClient()5183 bool AppMgrServiceInner::CheckRemoteClient()
5184 {
5185     if (!remoteClientManager_) {
5186         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
5187         return false;
5188     }
5189 
5190     if (!remoteClientManager_->GetSpawnClient()) {
5191         TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient null");
5192         return false;
5193     }
5194 
5195     if (!remoteClientManager_->GetBundleManagerHelper()) {
5196         TAG_LOGE(AAFwkTag::APPMGR, "get bundle manager helper fail");
5197         return false;
5198     }
5199     return true;
5200 }
5201 
RestartKeepAliveProcess(std::shared_ptr<AppRunningRecord> appRecord)5202 void AppMgrServiceInner::RestartKeepAliveProcess(std::shared_ptr<AppRunningRecord> appRecord)
5203 {
5204     TAG_LOGI(AAFwkTag::APPMGR, "restart keep-alive process begins.");
5205     if (appRecord == nullptr) {
5206         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
5207         return;
5208     }
5209 
5210     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
5211         TAG_LOGE(AAFwkTag::APPMGR, "restart keep-alive fail");
5212         return;
5213     }
5214 
5215     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
5216     BundleInfo bundleInfo;
5217     auto userId = GetUserIdByUid(appRecord->GetUid());
5218     auto flags = static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION)
5219         | static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE)
5220         | static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_ABILITY)
5221         | static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY);
5222     if (IN_PROCESS_CALL(bundleMgrHelper->GetCloneBundleInfo(appRecord->GetBundleName(), flags,
5223         appRecord->GetAppIndex(), bundleInfo, userId)) != ERR_OK) {
5224         TAG_LOGE(AAFwkTag::APPMGR, "getCloneBundleInfo fail");
5225         return;
5226     }
5227     std::vector<BundleInfo> infos;
5228     infos.emplace_back(bundleInfo);
5229     TAG_LOGI(AAFwkTag::APPMGR, "keepAliveProcess %{public}s", appRecord->GetProcessName().c_str());
5230     NotifyStartKeepAliveProcess(infos);
5231 }
5232 
RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)5233 void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)
5234 {
5235     if (appRecord == nullptr) {
5236         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
5237         return;
5238     }
5239     struct timespec t;
5240     t.tv_sec = 0;
5241     t.tv_nsec = 0;
5242     clock_gettime(CLOCK_MONOTONIC, &t);
5243     appRecord->SetRestartTimeMillis(static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS));
5244     appRecord->DecRestartResidentProcCount();
5245 
5246     auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
5247         return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
5248     };
5249 
5250     {
5251         std::lock_guard guard(restartResidentTaskListMutex_);
5252         auto findIter = find_if(restartResidentTaskList_.begin(), restartResidentTaskList_.end(),
5253             findRestartResidentTask);
5254         if (findIter != restartResidentTaskList_.end()) {
5255             restartResidentTaskList_.erase(findIter);
5256         }
5257     }
5258 
5259     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
5260         TAG_LOGE(AAFwkTag::APPMGR, "restart resident fail");
5261         return;
5262     }
5263 
5264     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
5265     BundleInfo bundleInfo;
5266     auto userId = GetUserIdByUid(appRecord->GetUid());
5267     auto flags = BundleFlag::GET_BUNDLE_DEFAULT | BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION;
5268     if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo(
5269         appRecord->GetBundleName(),
5270         static_cast<BundleFlag>(flags),
5271         bundleInfo, userId))) {
5272         TAG_LOGE(AAFwkTag::APPMGR, "getBundleInfo fail");
5273         return;
5274     }
5275     std::vector<BundleInfo> infos;
5276     infos.emplace_back(bundleInfo);
5277     TAG_LOGI(AAFwkTag::APPMGR, "residentProcess [%{public}s] remaining restarts num: [%{public}d]",
5278         appRecord->GetProcessName().c_str(), (int)appRecord->GetRestartResidentProcCount());
5279     StartResidentProcess(infos, appRecord->GetRestartResidentProcCount(), appRecord->IsEmptyKeepAliveApp());
5280 }
5281 
NotifyAppStatusByCommonEventName(const std::string & bundleName,const std::string & eventName,const Want & want)5282 int32_t AppMgrServiceInner::NotifyAppStatusByCommonEventName(const std::string &bundleName,
5283     const std::string &eventName, const Want &want)
5284 {
5285     EventFwk::CommonEventData commonData {want};
5286     std::set<std::string> permissionControlEvents = {
5287         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED,
5288         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED
5289     };
5290     if (permissionControlEvents.find(eventName) == permissionControlEvents.end()) {
5291         TAG_LOGI(AAFwkTag::APPMGR, "bundle name: %{public}s, normal event: %{public}s",
5292             bundleName.c_str(), eventName.c_str());
5293         EventFwk::CommonEventManager::PublishCommonEvent(commonData);
5294         return 0;
5295     }
5296     EventFwk::CommonEventPublishInfo eventPublishData;
5297     std::vector<std::string> permissions;
5298     permissions.emplace_back(AAFwk::PermissionConstants::PERMISSION_LISTEN_BUNDLE_CHANGE);
5299     eventPublishData.SetBundleName(bundleName);
5300     eventPublishData.SetSubscriberPermissions(permissions);
5301     eventPublishData.SetSubscriberType(EventFwk::SubscriberType::SYSTEM_SUBSCRIBER_TYPE);
5302     eventPublishData.SetValidationRule(EventFwk::ValidationRule::OR);
5303     EventFwk::CommonEventManager::PublishCommonEvent(commonData, eventPublishData);
5304     return 1;
5305 }
5306 
NotifyAppStatus(const std::string & bundleName,int32_t appIndex,const std::string & eventData)5307 void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, int32_t appIndex, const std::string &eventData)
5308 {
5309     TAG_LOGD(AAFwkTag::APPMGR, "bundle name is %{public}s, event is %{public}s",
5310         bundleName.c_str(), eventData.c_str());
5311     Want want;
5312     want.SetAction(eventData);
5313     ElementName element;
5314     element.SetBundleName(bundleName);
5315     want.SetElement(element);
5316     want.SetParam(Constants::USER_ID, 0);
5317     want.SetParam(Constants::APP_INDEX, appIndex);
5318     NotifyAppStatusByCommonEventName(bundleName, eventData, want);
5319 }
5320 
NotifyAppStatusByCallerUid(const std::string & bundleName,const int32_t tokenId,const int32_t userId,const int32_t callerUid,const int32_t targetUid,const std::string & eventData)5321 void AppMgrServiceInner::NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t tokenId,
5322     const int32_t userId, const int32_t callerUid, const int32_t targetUid, const std::string &eventData)
5323 {
5324     TAG_LOGI(AAFwkTag::APPMGR,
5325         "%{public}s call, bundle name: %{public}s, userId: %{public}d, event: %{public}s", __func__,
5326         bundleName.c_str(), userId, eventData.c_str());
5327     Want want;
5328     want.SetAction(eventData);
5329     ElementName element;
5330     element.SetBundleName(bundleName);
5331     want.SetElement(element);
5332     want.SetParam(TOKEN_ID, tokenId);
5333     want.SetParam(Constants::USER_ID, userId);
5334     want.SetParam(Constants::UID, callerUid);
5335     want.SetParam(Want::PARAM_RESV_CALLER_UID, callerUid);
5336     want.SetParam(TARGET_UID_KEY, targetUid);
5337     NotifyAppStatusByCommonEventName(bundleName, eventData, want);
5338 }
5339 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)5340 int32_t AppMgrServiceInner::RegisterApplicationStateObserver(
5341     const sptr<IApplicationStateObserver> &observer, const std::vector<std::string> &bundleNameList)
5342 {
5343     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterApplicationStateObserver(
5344         observer, bundleNameList);
5345 }
5346 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)5347 int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
5348 {
5349     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterApplicationStateObserver(observer);
5350 }
5351 
RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)5352 int32_t AppMgrServiceInner::RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
5353 {
5354     CHECK_CALLER_IS_SYSTEM_APP;
5355     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterAppForegroundStateObserver(observer);
5356 }
5357 
UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)5358 int32_t AppMgrServiceInner::UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
5359 {
5360     CHECK_CALLER_IS_SYSTEM_APP;
5361     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterAppForegroundStateObserver(observer);
5362 }
5363 
RegisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)5364 int32_t AppMgrServiceInner::RegisterAbilityForegroundStateObserver(
5365     const sptr<IAbilityForegroundStateObserver> &observer)
5366 {
5367     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5368     CHECK_CALLER_IS_SYSTEM_APP;
5369     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterAbilityForegroundStateObserver(observer);
5370 }
5371 
UnregisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)5372 int32_t AppMgrServiceInner::UnregisterAbilityForegroundStateObserver(
5373     const sptr<IAbilityForegroundStateObserver> &observer)
5374 {
5375     CHECK_CALLER_IS_SYSTEM_APP;
5376     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterAbilityForegroundStateObserver(observer);
5377 }
5378 
GetForegroundApplications(std::vector<AppStateData> & list)5379 int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
5380 {
5381     TAG_LOGD(AAFwkTag::APPMGR, "begin.");
5382     CHECK_CALLER_IS_SYSTEM_APP;
5383     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
5384     if (!isPerm) {
5385         TAG_LOGE(AAFwkTag::APPMGR, "permission verify fail");
5386         return ERR_PERMISSION_DENIED;
5387     }
5388 
5389     appRunningManager_->GetForegroundApplications(list);
5390     return ERR_OK;
5391 }
5392 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,int32_t userId)5393 int AppMgrServiceInner::StartUserTestProcess(
5394     const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &bundleInfo, int32_t userId)
5395 {
5396     TAG_LOGI(AAFwkTag::APPMGR, "enter");
5397     if (!observer) {
5398         TAG_LOGE(AAFwkTag::APPMGR, "observer null");
5399         return ERR_INVALID_VALUE;
5400     }
5401     if (!appRunningManager_) {
5402         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
5403         return ERR_INVALID_VALUE;
5404     }
5405 
5406     std::string bundleName = want.GetStringParam("-b");
5407     if (bundleName.empty()) {
5408         TAG_LOGE(AAFwkTag::APPMGR, "invalid bundle name");
5409         return ERR_INVALID_VALUE;
5410     }
5411 
5412     KillProcessConfig config{false, false, "StartUserTestProcess"};
5413     if (KillApplicationByUserIdLocked(bundleName, 0, userId, config)) {
5414         TAG_LOGE(AAFwkTag::APPMGR, "kill app fail");
5415         return ERR_INVALID_VALUE;
5416     }
5417 
5418     HapModuleInfo hapModuleInfo;
5419     if (GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo)) {
5420         TAG_LOGE(AAFwkTag::APPMGR, "get HapModuleInfo fail");
5421         return ERR_INVALID_VALUE;
5422     }
5423 
5424     std::string processName;
5425     MakeProcessName(std::make_shared<ApplicationInfo>(bundleInfo.applicationInfo), hapModuleInfo, processName);
5426     TAG_LOGI(AAFwkTag::APPMGR, "processName: [%{public}s]", processName.c_str());
5427 
5428     // Inspection records
5429     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
5430         bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo);
5431     if (appRecord) {
5432         TAG_LOGI(AAFwkTag::APPMGR, "processName [%{public}s] already exists", processName.c_str());
5433         return ERR_INVALID_VALUE;
5434     }
5435 
5436     return StartEmptyProcess(want, observer, bundleInfo, processName, userId);
5437 }
5438 
GetHapModuleInfoForTestRunner(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)5439 int AppMgrServiceInner::GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
5440     const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
5441 {
5442     TAG_LOGI(AAFwkTag::APPMGR, "enter");
5443     if (!observer) {
5444         TAG_LOGE(AAFwkTag::APPMGR, "observer null");
5445         return ERR_INVALID_VALUE;
5446     }
5447 
5448     bool moduleJson = false;
5449     if (!bundleInfo.hapModuleInfos.empty()) {
5450         moduleJson = bundleInfo.hapModuleInfos.back().isModuleJson;
5451     }
5452     if (moduleJson) {
5453         std::string moduleName = want.GetStringParam("-m");
5454         if (moduleName.empty()) {
5455             UserTestAbnormalFinish(observer, "No module name is specified.");
5456             return ERR_INVALID_VALUE;
5457         }
5458 
5459         bool found = false;
5460         for (auto item : bundleInfo.hapModuleInfos) {
5461             if (item.moduleName == moduleName) {
5462                 hapModuleInfo = item;
5463                 found = true;
5464                 break;
5465             }
5466         }
5467         if (!found) {
5468             UserTestAbnormalFinish(observer, "The specified module name is not found.");
5469             return ERR_INVALID_VALUE;
5470         }
5471     }
5472     return ERR_OK;
5473 }
5474 
UserTestAbnormalFinish(const sptr<IRemoteObject> & observer,const std::string & msg)5475 int AppMgrServiceInner::UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg)
5476 {
5477     sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(observer);
5478     if (!observerProxy) {
5479         TAG_LOGE(AAFwkTag::APPMGR, "get ITestObserver proxy fail");
5480         return ERR_INVALID_VALUE;
5481     }
5482     observerProxy->TestFinished(msg, -1);
5483     return ERR_OK;
5484 }
5485 
StartEmptyProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & info,const std::string & processName,const int userId)5486 int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
5487     const BundleInfo &info, const std::string &processName, const int userId)
5488 {
5489     TAG_LOGI(AAFwkTag::APPMGR, "enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(),
5490         processName.c_str());
5491     if (!CheckRemoteClient() || !appRunningManager_) {
5492         TAG_LOGE(AAFwkTag::APPMGR, "start test fail");
5493         return ERR_INVALID_VALUE;
5494     }
5495 
5496     bool appExistFlag = appRunningManager_->IsAppExist(info.applicationInfo.accessTokenId);
5497     bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(info.uid);
5498     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
5499     if (!appMultiUserExistFlag) {
5500         NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
5501     }
5502     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
5503         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
5504         return ERR_INVALID_OPERATION;
5505     }
5506     auto appRecord = CreateAppRunningRecord(appInfo, processName, info);
5507     CHECK_POINTER_AND_RETURN_VALUE(appRecord, ERR_INVALID_VALUE);
5508 
5509     auto isDebug = want.GetBoolParam(DEBUG_APP, false);
5510     TAG_LOGI(AAFwkTag::APPMGR, "setDebug: %{public}s", (isDebug ? "true" : "false"));
5511     appRecord->SetDebugApp(isDebug);
5512     bool isDebugFromLocal = want.GetBoolParam(DEBUG_FROM, false);
5513     TAG_LOGI(AAFwkTag::APPMGR, "SetDebugFromLocal: %{public}d", isDebugFromLocal);
5514     appRecord->SetDebugFromLocal(isDebugFromLocal);
5515     if (want.GetBoolParam(COLD_START, false)) {
5516         appRecord->SetDebugApp(true);
5517     }
5518 
5519     std::shared_ptr<UserTestRecord> testRecord = std::make_shared<UserTestRecord>();
5520     if (!testRecord) {
5521         TAG_LOGE(AAFwkTag::APPMGR, "make userTestRecord fail");
5522         return ERR_INVALID_VALUE;
5523     }
5524     testRecord->want = want;
5525     testRecord->observer = observer;
5526     testRecord->isFinished = false;
5527     testRecord->userId = userId;
5528     appRecord->SetUserTestInfo(testRecord);
5529 
5530     int32_t appIndex = 0;
5531     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
5532     uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, info.applicationInfo);
5533     StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, info, appInfo->bundleName,
5534         appIndex, appExistFlag);
5535 
5536     // If it is empty, the startup failed
5537     CHECK_POINTER_AND_RETURN_VALUE(appRecord, ERR_INVALID_VALUE);
5538     appRecord->SetTaskHandler(taskHandler_);
5539     appRecord->SetEventHandler(eventHandler_);
5540     appRecord->AddModules(appInfo, info.hapModuleInfos);
5541     TAG_LOGI(AAFwkTag::APPMGR, "startEmptyProcess pid: [%{public}d]", appRecord->GetPid());
5542 
5543     return ERR_OK;
5544 }
5545 
CreateAppRunningRecord(std::shared_ptr<ApplicationInfo> appInfo,const std::string & processName,const BundleInfo & bundleInfo)5546 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(std::shared_ptr<ApplicationInfo> appInfo,
5547     const std::string &processName, const BundleInfo &bundleInfo)
5548 {
5549     if (!appRunningManager_) {
5550         TAG_LOGE(AAFwkTag::APPMGR, "invalid appRunningManager");
5551         return nullptr;
5552     }
5553     auto isSupportMultiInstance = AAFwk::AppUtils::GetInstance().IsSupportMultiInstance();
5554     auto isMultiInstance =
5555         appInfo == nullptr ? false : appInfo->multiAppMode.multiAppModeType == MultiAppModeType::MULTI_INSTANCE;
5556     if (isSupportMultiInstance && isMultiInstance) {
5557         return appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo, APP_INSTANCE_KEY_0);
5558     }
5559     return appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo, "");
5560 }
5561 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName,const pid_t & pid)5562 int AppMgrServiceInner::FinishUserTest(
5563     const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid)
5564 {
5565     TAG_LOGI(AAFwkTag::APPMGR, "enter");
5566     if (bundleName.empty()) {
5567         TAG_LOGE(AAFwkTag::APPMGR, "invalid bundle name");
5568         return ERR_INVALID_VALUE;
5569     }
5570     auto appRecord = GetAppRunningRecordByPid(pid);
5571     if (!appRecord) {
5572         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord");
5573         return ERR_INVALID_VALUE;
5574     }
5575 
5576     auto userTestRecord = appRecord->GetUserTestInfo();
5577     if (!userTestRecord) {
5578         TAG_LOGE(AAFwkTag::APPMGR, "unstart user test");
5579         return ERR_INVALID_VALUE;
5580     }
5581 
5582     FinishUserTestLocked(msg, resultCode, appRecord);
5583 
5584     KillProcessConfig config{false, false, "FinishUserTest"};
5585     int ret = KillApplicationByUserIdLocked(bundleName, 0, userTestRecord->userId, config);
5586     if (ret) {
5587         TAG_LOGE(AAFwkTag::APPMGR, "kill process fail");
5588         return ret;
5589     }
5590 
5591     return ERR_OK;
5592 }
5593 
FinishUserTestLocked(const std::string & msg,const int64_t & resultCode,const std::shared_ptr<AppRunningRecord> & appRecord)5594 int AppMgrServiceInner::FinishUserTestLocked(
5595     const std::string &msg, const int64_t &resultCode, const std::shared_ptr<AppRunningRecord> &appRecord)
5596 {
5597     TAG_LOGD(AAFwkTag::APPMGR, "Enter");
5598     if (!appRecord) {
5599         TAG_LOGE(AAFwkTag::APPMGR, "invalid appRecord");
5600         return ERR_INVALID_VALUE;
5601     }
5602 
5603     std::lock_guard<ffrt::mutex> lock(userTestLock_);
5604     auto userTestRecord = appRecord->GetUserTestInfo();
5605     if (!userTestRecord) {
5606         TAG_LOGD(AAFwkTag::APPMGR, "not start user test");
5607         return ERR_INVALID_VALUE;
5608     }
5609     if (!userTestRecord->isFinished) {
5610         sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(userTestRecord->observer);
5611         if (!observerProxy) {
5612             TAG_LOGE(AAFwkTag::APPMGR, "get iTestObserver proxy fail");
5613             return ERR_INVALID_VALUE;
5614         }
5615         observerProxy->TestFinished(msg, resultCode);
5616 
5617         userTestRecord->isFinished = true;
5618     }
5619 
5620     return ERR_OK;
5621 }
5622 
StartSpecifiedAbility(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo,int32_t requestId)5623 void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
5624     int32_t requestId)
5625 {
5626     TAG_LOGD(AAFwkTag::APPMGR, "Start specified ability.");
5627     if (!CheckRemoteClient()) {
5628         return;
5629     }
5630 
5631     BundleInfo bundleInfo;
5632     HapModuleInfo hapModuleInfo;
5633     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
5634 
5635     int32_t appIndex = 0;
5636     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
5637     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
5638         return;
5639     }
5640     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
5641         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
5642         return;
5643     }
5644 
5645     std::string specifiedProcessFlag = GetSpecifiedProcessFlag(abilityInfo, want);
5646     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
5647     std::string processName;
5648     if (specifiedProcessFlag == "") {
5649         MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, "", processName, false);
5650     } else {
5651         processName = want.GetStringParam(SPECIFED_PROCESS_CALLER_PROCESS);
5652         const_cast<AAFwk::Want&>(want).RemoveParam(SPECIFED_PROCESS_CALLER_PROCESS);
5653     }
5654     bool isExtensionSandBox = IsIsolateExtensionSandBox(abilityInfoPtr, hapModuleInfo);
5655 
5656     std::vector<HapModuleInfo> hapModules;
5657     hapModules.emplace_back(hapModuleInfo);
5658 
5659     std::shared_ptr<AppRunningRecord> appRecord;
5660     auto instanceKey = want.GetStringParam(Want::APP_INSTANCE_KEY);
5661     auto customProcessFlag = abilityInfo.process;
5662     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo,
5663         "", nullptr, instanceKey, customProcessFlag);
5664     if (!appRecord) {
5665         bool appExistFlag = appRunningManager_->IsAppExist(appInfo->accessTokenId);
5666         bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid);
5667         if (!appMultiUserExistFlag) {
5668             NotifyAppRunningStatusEvent(
5669                 bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
5670         }
5671         // new app record
5672         appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo, instanceKey,
5673             customProcessFlag);
5674         if (!appRecord) {
5675             TAG_LOGE(AAFwkTag::APPMGR, "start process [%{public}s] fail", processName.c_str());
5676             return;
5677         }
5678         if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, processName)) {
5679             appRecord->SetEmptyKeepAliveAppState(false);
5680             appRecord->SetMainProcess(false);
5681             TAG_LOGD(AAFwkTag::APPMGR, "The process %{public}s will not keepalive", hapModuleInfo.process.c_str());
5682         }
5683         auto wantPtr = std::make_shared<AAFwk::Want>(want);
5684         if (wantPtr != nullptr) {
5685             appRecord->SetCallerPid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
5686             appRecord->SetCallerUid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
5687             appRecord->SetCallerTokenId(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
5688             appRecord->SetDebugApp(wantPtr->GetBoolParam(DEBUG_APP, false));
5689             appRecord->SetDebugFromLocal(wantPtr->GetBoolParam(DEBUG_FROM, false));
5690             if (appRecord->IsDebugApp()) {
5691                 ProcessAppDebug(appRecord, true);
5692             }
5693             appRecord->SetNativeDebug(wantPtr->GetBoolParam("nativeDebug", false));
5694             if (wantPtr->GetBoolParam(COLD_START, false)) {
5695                 appRecord->SetDebugApp(true);
5696             }
5697             appRecord->SetPerfCmd(wantPtr->GetStringParam(PERF_CMD));
5698             appRecord->SetErrorInfoEnhance(wantPtr->GetBoolParam(ERROR_INFO_ENHANCE, false));
5699             appRecord->SetMultiThread(wantPtr->GetBoolParam(MULTI_THREAD, false));
5700         }
5701         appRecord->SetProcessAndExtensionType(abilityInfoPtr);
5702         appRecord->SetStartupTaskData(want);
5703         appRecord->SetTaskHandler(taskHandler_);
5704         appRecord->SetEventHandler(eventHandler_);
5705         appRecord->SendEventForSpecifiedAbility();
5706         appRecord->SetAppIndex(appIndex);
5707         appRecord->SetExtensionSandBoxFlag(isExtensionSandBox);
5708         uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, abilityInfo);
5709         StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, bundleInfo, appInfo->bundleName,
5710             appIndex, appExistFlag);
5711 
5712         appRecord->SetSpecifiedAbilityFlagAndWant(requestId, want, hapModuleInfo.moduleName);
5713         appRecord->AddModules(appInfo, hapModules);
5714     } else {
5715         TAG_LOGD(AAFwkTag::APPMGR, "process is exist");
5716         auto isDebugApp = want.GetBoolParam(DEBUG_APP, false);
5717         if (isDebugApp && !appRecord->IsDebugApp()) {
5718             ProcessAppDebug(appRecord, isDebugApp);
5719         }
5720 
5721         appRecord->SetSpecifiedAbilityFlagAndWant(requestId, want, hapModuleInfo.moduleName);
5722         auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
5723         if (!moduleRecord) {
5724             TAG_LOGD(AAFwkTag::APPMGR, "module record is nullptr, add modules");
5725             appRecord->AddModules(appInfo, hapModules);
5726             appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName);
5727         } else if (!appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName)) {
5728             TAG_LOGD(AAFwkTag::APPMGR, "schedule accept want");
5729             appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName);
5730         }
5731     }
5732 }
5733 
RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> & response)5734 void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response)
5735 {
5736     if (!response) {
5737         TAG_LOGE(AAFwkTag::APPMGR, "response null");
5738         return;
5739     }
5740     startSpecifiedAbilityResponse_ = response;
5741 }
5742 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)5743 void AppMgrServiceInner::ScheduleAcceptWantDone(
5744     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
5745 {
5746     TAG_LOGD(AAFwkTag::APPMGR, "ScheduleAcceptWantDone, flag: %{private}s", flag.c_str());
5747 
5748     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
5749     if (!appRecord) {
5750         TAG_LOGE(AAFwkTag::APPMGR, "get appRecord fail");
5751         return;
5752     }
5753     auto requestId = appRecord->GetSpecifiedRequestId();
5754     appRecord->ScheduleAcceptWantDone();
5755     appRecord->ResetSpecifiedRequest();
5756 
5757     if (startSpecifiedAbilityResponse_) {
5758         startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag, requestId);
5759     }
5760 }
5761 
SchedulePrepareTerminate(const pid_t pid,const std::string & moduleName)5762 void AppMgrServiceInner::SchedulePrepareTerminate(const pid_t pid, const std::string &moduleName)
5763 {
5764     TAG_LOGD(AAFwkTag::APPKIT, "called");
5765     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
5766         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
5767         return;
5768     }
5769     auto appRecord = GetAppRunningRecordByPid(pid);
5770     if (appRecord == nullptr) {
5771         TAG_LOGE(AAFwkTag::APPMGR, "get appRecord fail");
5772         return;
5773     }
5774     appRecord->SchedulePrepareTerminate(moduleName);
5775 }
5776 
HandleStartSpecifiedAbilityTimeOut(std::shared_ptr<AppRunningRecord> appRecord)5777 void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(std::shared_ptr<AppRunningRecord> appRecord)
5778 {
5779     TAG_LOGI(AAFwkTag::APPMGR, "startSpecifiedAbility timeOut");
5780     if (!appRecord) {
5781         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
5782         return;
5783     }
5784 
5785     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
5786         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedRequestId());
5787     }
5788     appRecord->ResetSpecifiedRequest();
5789 
5790     KillApplicationByRecord(appRecord);
5791 }
5792 
ScheduleNewProcessRequestDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)5793 void AppMgrServiceInner::ScheduleNewProcessRequestDone(
5794     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
5795 {
5796     TAG_LOGD(AAFwkTag::APPMGR, "ScheduleNewProcessRequestDone, flag: %{public}s", flag.c_str());
5797 
5798     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
5799     if (!appRecord) {
5800         TAG_LOGE(AAFwkTag::APPMGR, "get appRecord fail");
5801         return;
5802     }
5803     auto requestId = appRecord->GetNewProcessRequestId();
5804     appRecord->ScheduleNewProcessRequestDone();
5805     appRecord->ResetNewProcessRequest();
5806 
5807     const std::string callerProcessName = appRecord->GetProcessName();
5808     if (startSpecifiedAbilityResponse_) {
5809         startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(flag, requestId, callerProcessName);
5810     }
5811     appRecord->ResetNewProcessRequest();
5812 }
5813 
HandleStartSpecifiedProcessTimeout(std::shared_ptr<AppRunningRecord> appRecord)5814 void AppMgrServiceInner::HandleStartSpecifiedProcessTimeout(std::shared_ptr<AppRunningRecord> appRecord)
5815 {
5816     TAG_LOGD(AAFwkTag::APPMGR, "called start specified process time out!");
5817     if (!appRecord) {
5818         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
5819         return;
5820     }
5821 
5822     if (startSpecifiedAbilityResponse_) {
5823         startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestId());
5824     }
5825     appRecord->ResetNewProcessRequest();
5826 }
5827 
DealWithUserConfiguration(const Configuration & config,const int32_t userId,int32_t & notifyUserId)5828 int32_t AppMgrServiceInner::DealWithUserConfiguration(const Configuration& config, const int32_t userId,
5829     int32_t &notifyUserId)
5830 {
5831     if (multiUserConfigurationMgr_ == nullptr) {
5832         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
5833         return ERR_INVALID_VALUE;
5834     }
5835     std::vector<std::string> changeKeyV;
5836     bool isNotifyUser0 = false;
5837     multiUserConfigurationMgr_->HandleConfiguration(userId, config, changeKeyV, isNotifyUser0);
5838     TAG_LOGI(AAFwkTag::APPMGR,
5839         "changeKeyV size: %{public}zu Config: %{public}s userId: %{public}d, NotifyUser0: %{public}d",
5840         changeKeyV.size(), config.GetName().c_str(), userId, static_cast<int32_t>(isNotifyUser0));
5841 
5842     if (!config.GetItem(AAFwk::GlobalConfigurationKey::THEME).empty() || !changeKeyV.empty()) {
5843         notifyUserId = userId;
5844         return ERR_OK;
5845     } else if (isNotifyUser0) {
5846         notifyUserId = U0_USER_ID;
5847         return ERR_OK;
5848     } else {
5849         TAG_LOGE(AAFwkTag::APPMGR, "changeKeyV empty");
5850         return ERR_INVALID_VALUE;
5851     }
5852 }
5853 
UpdateConfiguration(const Configuration & config,const int32_t userId)5854 int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config, const int32_t userId)
5855 {
5856     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5857     if (!appRunningManager_) {
5858         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
5859         return ERR_INVALID_VALUE;
5860     }
5861     CHECK_CALLER_IS_SYSTEM_APP;
5862     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateConfigurationPerm();
5863     if (ret != ERR_OK) {
5864         return ret;
5865     }
5866     int32_t notifyUserId;
5867     ret = DealWithUserConfiguration(config, userId, notifyUserId);
5868     if (ret != ERR_OK) {
5869         return ret;
5870     }
5871 
5872     // all app
5873     int32_t result = appRunningManager_->UpdateConfiguration(config, notifyUserId);
5874     HandleConfigurationChange(config, notifyUserId);
5875     if (result != ERR_OK) {
5876         TAG_LOGE(AAFwkTag::APPMGR, "update error");
5877         return result;
5878     }
5879     // notify
5880     std::lock_guard<ffrt::mutex> notifyLock(configurationObserverLock_);
5881     for (auto &item : configurationObservers_) {
5882         if (item.observer != nullptr && (notifyUserId == -1 || item.userId == 0 || item.userId == notifyUserId)) {
5883             item.observer->OnConfigurationUpdated(config);
5884         }
5885     }
5886 
5887     return result;
5888 }
5889 
GetBackgroundAppInfo(const std::vector<BackgroundAppInfo> & allowAppList)5890 std::vector<BackgroundAppInfo> AppMgrServiceInner::GetBackgroundAppInfo(
5891     const std::vector<BackgroundAppInfo>& allowAppList)
5892 {
5893     auto sceneSessionManager = SessionManagerLite::GetInstance().GetSceneSessionManagerLiteProxy();
5894     if (sceneSessionManager == nullptr) {
5895         TAG_LOGE(AAFwkTag::APPMGR, "GetSceneSessionManagerLiteProxy null");
5896         return {};
5897     }
5898     std::vector<RecentSessionInfo> recentMainSessionInfoList;
5899     auto resultCode = sceneSessionManager->GetRecentMainSessionInfoList(recentMainSessionInfoList);
5900     if (resultCode != WSError::WS_OK) {
5901         TAG_LOGE(AAFwkTag::APPMGR, "GetRecentMainSessionInfoList result:%{public}d size:%{public}zu.", resultCode,
5902             recentMainSessionInfoList.size());
5903         return {};
5904     }
5905 
5906     auto checkInAllowlist = [&allowAppList](const std::string& bundleName) {
5907         auto it =
5908             std::find_if(allowAppList.begin(), allowAppList.end(), [&bundleName](const BackgroundAppInfo& appInfo) {
5909                 if (appInfo.bandleName == bundleName) {
5910                     return true;
5911                 }
5912                 return false;
5913             });
5914         if (it != allowAppList.end()) {
5915             return true;
5916         }
5917         return false;
5918     };
5919 
5920     std::vector<AppExecFwk::BackgroundAppInfo> backgroundAppInfoResult;
5921     for (const auto& sessionInfo : recentMainSessionInfoList) {
5922         if (!checkInAllowlist(sessionInfo.bundleName)) {
5923             TAG_LOGD(AAFwkTag::APPMGR, "not in whilelist bundleName:%{public}s appIndex :%{public}d.",
5924                 sessionInfo.bundleName.c_str(), sessionInfo.appIndex);
5925             continue;
5926         }
5927         if (sessionInfo.sessionState != RecentSessionState::BACKGROUND) {
5928             TAG_LOGD(AAFwkTag::APPMGR, "not background app, bundleName:%{public}s appIndex :%{public}d.",
5929                 sessionInfo.bundleName.c_str(), sessionInfo.appIndex);
5930             continue;
5931         }
5932         TAG_LOGD(AAFwkTag::APPMGR, "get sessionInfo bundleName:%{public}s appIndex :%{public}d.",
5933             sessionInfo.bundleName.c_str(), sessionInfo.appIndex);
5934         AppExecFwk::BackgroundAppInfo appInfo;
5935         appInfo.bandleName = sessionInfo.bundleName;
5936         appInfo.appIndex = sessionInfo.appIndex;
5937         backgroundAppInfoResult.push_back(appInfo);
5938     }
5939 
5940     return backgroundAppInfoResult;
5941 }
5942 
UpdateConfigurationForBackgroundApp(const std::vector<BackgroundAppInfo> & allowAppList,const AppExecFwk::ConfigurationPolicy & policy,const int32_t userId)5943 int32_t AppMgrServiceInner::UpdateConfigurationForBackgroundApp(const std::vector<BackgroundAppInfo>& allowAppList,
5944     const AppExecFwk::ConfigurationPolicy& policy, const int32_t userId)
5945 {
5946     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5947     if (!appRunningManager_) {
5948         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
5949         return ERR_NO_INIT;
5950     }
5951     CHECK_CALLER_IS_SYSTEM_APP;
5952     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateConfigurationPerm();
5953     if (ret != ERR_OK) {
5954         TAG_LOGE(AAFwkTag::APPMGR, "permission verification failed");
5955         return ret;
5956     }
5957 
5958     std::vector<BackgroundAppInfo> appInfos = GetBackgroundAppInfo(allowAppList);
5959     if (appInfos.empty()) {
5960         TAG_LOGD(AAFwkTag::APPMGR, "no need backGround app color Switch");
5961         return ERR_INVALID_VALUE;
5962     }
5963 
5964     return appRunningManager_->UpdateConfigurationForBackgroundApp(appInfos, policy, userId);
5965 }
5966 
UpdateConfigurationByBundleName(const Configuration & config,const std::string & name,int32_t appIndex)5967 int32_t AppMgrServiceInner::UpdateConfigurationByBundleName(const Configuration &config, const std::string &name,
5968     int32_t appIndex)
5969 {
5970     if (!appRunningManager_) {
5971         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
5972         return ERR_INVALID_VALUE;
5973     }
5974     CHECK_CALLER_IS_SYSTEM_APP;
5975     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateAPPConfigurationPerm();
5976     if (ret != ERR_OK) {
5977         return ret;
5978     }
5979     int32_t result = appRunningManager_->UpdateConfigurationByBundleName(config, name, appIndex);
5980     if (result != ERR_OK) {
5981         TAG_LOGE(AAFwkTag::APPMGR, "update error");
5982         return result;
5983     }
5984     return result;
5985 }
5986 
HandleConfigurationChange(const Configuration & config,const int32_t userId)5987 void AppMgrServiceInner::HandleConfigurationChange(const Configuration& config, const int32_t userId)
5988 {
5989     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5990     std::lock_guard lock(appStateCallbacksLock_);
5991 
5992     for (const auto &item : appStateCallbacks_) {
5993         if (item.callback != nullptr && (userId == -1 || item.userId == 0 || item.userId == userId)) {
5994             item.callback->NotifyConfigurationChange(config, currentUserId_);
5995         }
5996     }
5997 }
5998 
RegisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)5999 int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
6000 {
6001     TAG_LOGD(AAFwkTag::APPMGR, "called");
6002     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
6003         TAG_LOGE(AAFwkTag::APPMGR, "caller not SA");
6004         return ERR_INVALID_VALUE;
6005     }
6006 
6007     if (observer == nullptr) {
6008         TAG_LOGE(AAFwkTag::APPMGR, "observer null");
6009         return ERR_INVALID_VALUE;
6010     }
6011     std::lock_guard<ffrt::mutex> registerLock(configurationObserverLock_);
6012     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
6013         [&observer](const ConfigurationObserverWithUserId& item) {
6014             return (item.observer && item.observer->AsObject() == observer->AsObject());
6015         });
6016     if (it != configurationObservers_.end()) {
6017         TAG_LOGE(AAFwkTag::APPMGR, "observer exist");
6018         return ERR_INVALID_VALUE;
6019     }
6020     configurationObservers_.push_back(
6021         ConfigurationObserverWithUserId { observer, GetUserIdByUid(IPCSkeleton::GetCallingUid()) });
6022     return NO_ERROR;
6023 }
6024 
UnregisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)6025 int32_t AppMgrServiceInner::UnregisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
6026 {
6027     TAG_LOGI(AAFwkTag::APPMGR, "call");
6028     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
6029         TAG_LOGE(AAFwkTag::APPMGR, "caller not SA");
6030         return ERR_INVALID_VALUE;
6031     }
6032     if (observer == nullptr) {
6033         TAG_LOGE(AAFwkTag::APPMGR, "observer null");
6034         return ERR_INVALID_VALUE;
6035     }
6036     std::lock_guard<ffrt::mutex> unregisterLock(configurationObserverLock_);
6037     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
6038         [&observer](const ConfigurationObserverWithUserId &item) {
6039             return (item.observer && item.observer->AsObject() == observer->AsObject());
6040         });
6041     if (it != configurationObservers_.end()) {
6042         configurationObservers_.erase(it);
6043         return NO_ERROR;
6044     }
6045     TAG_LOGI(AAFwkTag::APPMGR, "end");
6046     return ERR_INVALID_VALUE;
6047 }
6048 
InitGlobalConfiguration()6049 void AppMgrServiceInner::InitGlobalConfiguration()
6050 {
6051     std::shared_ptr<AppExecFwk::Configuration> globalConfiguration = std::make_shared<Configuration>();
6052     if (!globalConfiguration) {
6053         TAG_LOGE(AAFwkTag::APPMGR, "globalConfiguration null");
6054         return;
6055     }
6056 
6057 #ifdef SUPPORT_SCREEN
6058     // Currently only this interface is known
6059     auto language = OHOS::Global::I18n::LocaleConfig::GetEffectiveLanguage();
6060     TAG_LOGI(AAFwkTag::APPMGR, "current global language: %{public}s", language.c_str());
6061     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language);
6062 
6063     auto locale = OHOS::Global::I18n::LocaleConfig::GetEffectiveLocale();
6064     TAG_LOGI(AAFwkTag::APPMGR, "current global locale: %{public}s", locale.c_str());
6065     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LOCALE, locale);
6066 
6067     std::string sysHour = OHOS::Global::I18n::LocaleConfig::GetSystemHour();
6068     TAG_LOGI(AAFwkTag::APPMGR, "current 24 hour clock: %{public}s", sysHour.c_str());
6069     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_HOUR, sysHour);
6070 #endif
6071 
6072     // Assign to default colorMode "light"
6073     TAG_LOGI(AAFwkTag::APPMGR, "current global colorMode: %{public}s", ConfigurationInner::COLOR_MODE_LIGHT);
6074     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT);
6075 
6076     // Get input pointer device
6077     std::string hasPointerDevice = system::GetParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, "false");
6078     TAG_LOGI(AAFwkTag::APPMGR, "current hasPointerDevice: %{public}s", hasPointerDevice.c_str());
6079     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, hasPointerDevice);
6080 
6081     // Get DeviceType
6082     auto deviceType = GetDeviceType();
6083     TAG_LOGI(AAFwkTag::APPMGR, "current deviceType: %{public}s", deviceType);
6084     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, deviceType);
6085     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE, "1.0");
6086     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE, "1.0");
6087     if (multiUserConfigurationMgr_ == nullptr) {
6088         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
6089         return;
6090     }
6091     multiUserConfigurationMgr_->InitConfiguration(globalConfiguration);
6092     TAG_LOGI(AAFwkTag::APPMGR, "InitGlobalConfiguration Config: %{public}s", globalConfiguration->GetName().c_str());
6093 }
6094 
GetConfiguration()6095 std::shared_ptr<AppExecFwk::Configuration> AppMgrServiceInner::GetConfiguration()
6096 {
6097     if (multiUserConfigurationMgr_ == nullptr) {
6098         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
6099         return nullptr;
6100     }
6101     int32_t userId = 0;
6102     auto errNo = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
6103     if (errNo != 0) {
6104         TAG_LOGE(AAFwkTag::APPMGR, "GetForegroundOsAccountLocalId failed: %{public}d", errNo);
6105         userId = USER100;
6106     }
6107     TAG_LOGD(AAFwkTag::APPMGR, "GetForegroundOsAccountLocalId userId: %{public}d", userId);
6108     return multiUserConfigurationMgr_->GetConfigurationByUserId(userId);
6109 }
6110 
KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> & appRecord)6111 void AppMgrServiceInner::KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord)
6112 {
6113     TAG_LOGD(AAFwkTag::APPMGR, "Kill application by appRecord.");
6114     if (!appRecord || !taskHandler_) {
6115         TAG_LOGW(AAFwkTag::APPMGR, "appRecord or taskHandler_ null");
6116         return;
6117     }
6118 
6119     auto pid = appRecord->GetPid();
6120     appRecord->SetTerminating();
6121     appRecord->ScheduleProcessSecurityExit();
6122 
6123     auto startTime = SystemTimeMillisecond();
6124     std::list<pid_t> pids = {pid};
6125     if (WaitForRemoteProcessExit(pids, startTime)) {
6126         TAG_LOGI(AAFwkTag::APPMGR, "remote process exited success");
6127         return;
6128     }
6129 
6130     auto timeoutTask = [pid, innerServiceWeak = weak_from_this()]() {
6131         auto innerService = innerServiceWeak.lock();
6132         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
6133         TAG_LOGI(AAFwkTag::APPMGR, "killProcessByPid: %{public}d", pid);
6134         int32_t result = innerService->KillProcessByPid(pid, "KillApplicationByRecord");
6135         if (result < 0) {
6136             TAG_LOGE(AAFwkTag::APPMGR, "kill app fail, pid: %{public}d", pid);
6137             return;
6138         }
6139     };
6140     taskHandler_->SubmitTaskJust(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
6141 }
6142 
SendHiSysEvent(int32_t innerEventId,std::shared_ptr<AppRunningRecord> appRecord)6143 void AppMgrServiceInner::SendHiSysEvent(int32_t innerEventId, std::shared_ptr<AppRunningRecord> appRecord)
6144 {
6145     TAG_LOGD(AAFwkTag::APPMGR, "called AppMgrServiceInner SendHiSysEvent!");
6146     if (!appRecord) {
6147         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
6148         return;
6149     }
6150     const int bufferLen = 128;
6151     char paramOutBuf[bufferLen] = {0};
6152     const char *hook_mode = "startup:";
6153     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
6154     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
6155         TAG_LOGD(AAFwkTag::APPMGR, "SendHiSysEvent, Hook_mode: no handle time out");
6156         return;
6157     }
6158 
6159     std::string eventName = GetEventName(innerEventId);
6160     int32_t pid = appRecord->GetPid();
6161     int32_t uid = appRecord->GetUid();
6162     std::string packageName = appRecord->GetBundleName();
6163     std::string processName = appRecord->GetProcessName();
6164     std::string msg = eventName + ",";
6165     auto eventTypeAndMsg = GetEventTypeAndMsg(innerEventId);
6166     msg += eventTypeAndMsg.second;
6167 
6168     TAG_LOGW(AAFwkTag::APPMGR, "lifecycle_timeout, eventName: %{public}s, uid: %{public}d, pid: %{public}d, \
6169         packageName: %{public}s, processName: %{public}s, msg: %{public}s",
6170         eventName.c_str(), uid, pid, packageName.c_str(), processName.c_str(), msg.c_str());
6171     AppfreezeManager::ParamInfo info = {
6172         .typeId = eventTypeAndMsg.first,
6173         .pid = pid,
6174         .eventName = eventName,
6175         .bundleName = packageName,
6176         .msg = msg
6177     };
6178     AppfreezeManager::GetInstance()->LifecycleTimeoutHandle(info);
6179 }
6180 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)6181 int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
6182 {
6183     auto appRecord = GetAppRunningRecordByPid(pid);
6184     if (!appRecord) {
6185         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord");
6186         return ERR_NAME_NOT_FOUND;
6187     }
6188 
6189     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6190     auto callingPid = IPCSkeleton::GetCallingPid();
6191     if (!isSaCall && callingPid != pid) {
6192         TAG_LOGE(AAFwkTag::APPMGR, "permission verify fail");
6193         return ERR_PERMISSION_DENIED;
6194     }
6195     for (auto &item : appRecord->GetAbilities()) {
6196         tokens.emplace_back(item.first);
6197     }
6198     return ERR_OK;
6199 }
6200 
GetApplicationInfoByProcessID(const int pid,AppExecFwk::ApplicationInfo & application,bool & debug)6201 int AppMgrServiceInner::GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application,
6202     bool &debug)
6203 {
6204     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6205     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6206     if (!isSaCall && !isShellCall) {
6207         TAG_LOGE(AAFwkTag::APPMGR, "no permissions");
6208         return ERR_PERMISSION_DENIED;
6209     }
6210     auto appRecord = GetAppRunningRecordByPid(pid);
6211     if (!appRecord) {
6212         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord for PID:%{public}d", pid);
6213         return ERR_NAME_NOT_FOUND;
6214     }
6215 
6216     auto info = appRecord->GetApplicationInfo();
6217     if (info == nullptr) {
6218         TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
6219         return ERR_NO_INIT;
6220     }
6221     application = *info;
6222     debug = appRecord->IsDebugApp();
6223     return ERR_OK;
6224 }
6225 
NotifyAppMgrRecordExitReason(int32_t pid,int32_t reason,const std::string & exitMsg)6226 int32_t AppMgrServiceInner::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg)
6227 {
6228     TAG_LOGD(AAFwkTag::APPMGR, "NotifyAppMgrRecordExitReason pid:%{public}d, reason:%{public}d, exitMsg:%{public}s.",
6229         pid, reason, exitMsg.c_str());
6230     auto callerUid = IPCSkeleton::GetCallingUid();
6231     if (callerUid != FOUNDATION_UID) {
6232         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
6233         return ERR_PERMISSION_DENIED;
6234     }
6235     auto appRecord = GetAppRunningRecordByPid(pid);
6236     if (!appRecord) {
6237         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord for pid:%{public}d", pid);
6238         return ERR_NAME_NOT_FOUND;
6239     }
6240     appRecord->SetExitReason(reason);
6241     appRecord->SetExitMsg(exitMsg);
6242     appRecord->SetReasonExist(true);
6243     return ERR_OK;
6244 }
6245 
VerifyKillProcessPermission(const std::string & bundleName) const6246 int AppMgrServiceInner::VerifyKillProcessPermission(const std::string &bundleName) const
6247 {
6248     TAG_LOGI(AAFwkTag::APPMGR, "callerUid:%{public}d, callerPid:%{public}d",
6249         IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
6250     int32_t ret = VerifyKillProcessPermissionCommon();
6251     if (ret != ERR_PERMISSION_DENIED) {
6252         return ret;
6253     }
6254 
6255     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
6256         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
6257     if (isCallingPerm) {
6258         auto callerPid = IPCSkeleton::GetCallingPid();
6259         auto appRecord = GetAppRunningRecordByPid(callerPid);
6260         if (!appRecord || appRecord->GetBundleName() != bundleName) {
6261             TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
6262             return ERR_PERMISSION_DENIED;
6263         }
6264     } else {
6265         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
6266         return ERR_PERMISSION_DENIED;
6267     }
6268 
6269     return ERR_OK;
6270 }
6271 
VerifyKillProcessPermission(const sptr<IRemoteObject> & token) const6272 int AppMgrServiceInner::VerifyKillProcessPermission(const sptr<IRemoteObject> &token) const
6273 {
6274     TAG_LOGI(AAFwkTag::APPMGR, "callerUid:%{public}d, callerPid:%{public}d",
6275         IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
6276     int32_t ret = VerifyKillProcessPermissionCommon();
6277     if (ret != ERR_PERMISSION_DENIED) {
6278         return ret;
6279     }
6280 
6281     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
6282         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
6283     if (isCallingPerm) {
6284         auto callerUid = IPCSkeleton::GetCallingUid();
6285         auto appRecord = GetAppRunningRecordByAbilityToken(token);
6286         if (!appRecord || appRecord->GetUid() != callerUid) {
6287             TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
6288             return ERR_PERMISSION_DENIED;
6289         }
6290     } else {
6291         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
6292         return ERR_PERMISSION_DENIED;
6293     }
6294 
6295     return ERR_OK;
6296 }
6297 
VerifyKillProcessPermissionCommon() const6298 int32_t AppMgrServiceInner::VerifyKillProcessPermissionCommon() const
6299 {
6300     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
6301         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
6302     if (isCallingPerm) {
6303         return ERR_OK;
6304     }
6305 
6306     // VerifyAPL and ohos.permission.CLEAN_BACKGROUND_PROCESSES will be removed on API18
6307     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6308     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
6309     if (isSaCall || isShellCall) {
6310         return ERR_OK;
6311     }
6312 
6313     if (VerifyAPL()) {
6314         return ERR_OK;
6315     }
6316 
6317     return ERR_PERMISSION_DENIED;
6318 }
6319 
VerifyAPL() const6320 bool AppMgrServiceInner::VerifyAPL() const
6321 {
6322     if (!appRunningManager_) {
6323         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
6324         return false;
6325     }
6326 
6327     auto callerPid = IPCSkeleton::GetCallingPid();
6328     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
6329     if (!appRecord) {
6330         TAG_LOGE(AAFwkTag::APPMGR, "get app running record fail, callingPId: %{public}d", callerPid);
6331         return false;
6332     }
6333 
6334     auto applicationInfo = appRecord->GetApplicationInfo();
6335     if (!applicationInfo) {
6336         TAG_LOGE(AAFwkTag::APPMGR, "get app info fail");
6337         return false;
6338     }
6339 
6340     auto apl = applicationInfo->appPrivilegeLevel;
6341     if (apl != SYSTEM_BASIC && apl != SYSTEM_CORE) {
6342         TAG_LOGE(AAFwkTag::APPMGR, "caller is not system_basic or system_core");
6343         return false;
6344     }
6345     TAG_LOGE(AAFwkTag::APPMGR, "%{public}s without ohos.permission.KILL_APP_PROCESSES",
6346         applicationInfo->name.c_str());
6347     return true;
6348 }
6349 
VerifyAccountPermission(const std::string & permissionName,const int userId) const6350 int AppMgrServiceInner::VerifyAccountPermission(const std::string &permissionName, const int userId) const
6351 {
6352     if (userId != currentUserId_) {
6353         auto isCallingPermAccount = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
6354             AAFwk::PermissionConstants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
6355         if (!isCallingPermAccount) {
6356             TAG_LOGE(AAFwkTag::APPMGR, "permission accounts verify fail");
6357             return ERR_PERMISSION_DENIED;
6358         }
6359     }
6360     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(permissionName);
6361     return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED;
6362 }
6363 
VerifyRequestPermission() const6364 int AppMgrServiceInner::VerifyRequestPermission() const
6365 {
6366     auto callerUid = IPCSkeleton::GetCallingUid();
6367     if (callerUid == ROOT_UID || callerUid == FOUNDATION_UID) {
6368         return ERR_OK;
6369     } else {
6370         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail, callerUid: %{public}d", callerUid);
6371         return ERR_PERMISSION_DENIED;
6372     }
6373 }
6374 
IsFoundationCall() const6375 bool AppMgrServiceInner::IsFoundationCall() const
6376 {
6377     return IPCSkeleton::GetCallingUid() == FOUNDATION_UID;
6378 }
6379 
PreStartNWebSpawnProcess(const pid_t hostPid)6380 int AppMgrServiceInner::PreStartNWebSpawnProcess(const pid_t hostPid)
6381 {
6382     TAG_LOGI(AAFwkTag::APPMGR, "call");
6383     if (hostPid <= 0) {
6384         TAG_LOGE(AAFwkTag::APPMGR, "invalid param, hostPid:%{public}d", hostPid);
6385         return ERR_INVALID_VALUE;
6386     }
6387 
6388     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
6389     if (!nwebSpawnClient) {
6390         TAG_LOGE(AAFwkTag::APPMGR, "nwebSpawnClient null");
6391         return ERR_INVALID_VALUE;
6392     }
6393     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
6394         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
6395         return ERR_INVALID_OPERATION;
6396     }
6397 
6398     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(hostPid);
6399     if (!appRecord) {
6400         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", hostPid);
6401         return ERR_INVALID_VALUE;
6402     }
6403 
6404     ErrCode errCode = nwebSpawnClient->PreStartNWebSpawnProcess();
6405     if (FAILED(errCode)) {
6406         TAG_LOGE(AAFwkTag::APPMGR, "spawn new render process fail, errCode %{public}08x", errCode);
6407         return ERR_INVALID_VALUE;
6408     }
6409 
6410     return 0;
6411 }
6412 
StartRenderProcess(const pid_t hostPid,const std::string & renderParam,FdGuard && ipcFd,FdGuard && sharedFd,FdGuard && crashFd,pid_t & renderPid,bool isGPU)6413 int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam,
6414     FdGuard &&ipcFd, FdGuard &&sharedFd, FdGuard &&crashFd, pid_t &renderPid, bool isGPU)
6415 {
6416     TAG_LOGI(AAFwkTag::APPMGR, "hostPid:%{public}d", hostPid);
6417     if (hostPid <= 0 || renderParam.empty() || ipcFd.Get() <= 0 || sharedFd.Get() <= 0 || crashFd.Get() <= 0) {
6418         TAG_LOGE(AAFwkTag::APPMGR, "invalid param: hostPid:%{public}d renderParam:%{private}s "
6419                     "ipcFd:%{public}d  crashFd:%{public}d sharedFd:%{public}d",
6420             hostPid, renderParam.c_str(), ipcFd.Get(), crashFd.Get(), sharedFd.Get());
6421         return ERR_INVALID_VALUE;
6422     }
6423     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_INVALID_VALUE);
6424     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
6425         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
6426         return ERR_INVALID_OPERATION;
6427     }
6428     auto appRecord = GetAppRunningRecordByPid(hostPid);
6429     CHECK_POINTER_AND_RETURN_VALUE(appRecord, ERR_INVALID_VALUE);
6430     auto renderRecordMap = appRecord->GetRenderRecordMap();
6431     if (!isGPU && !renderRecordMap.empty() && !AAFwk::AppUtils::GetInstance().IsUseMultiRenderProcess()) {
6432         for (auto iter : renderRecordMap) {
6433             if (iter.second != nullptr) {
6434                 renderPid = iter.second->GetPid();
6435                 if (ProcessUtil::ProcessExist(renderPid)) {
6436                     TAG_LOGW(AAFwkTag::APPMGR,
6437                         "render process repeat, renderPid:%{public}d", renderPid);
6438                     return ERR_ALREADY_EXIST_RENDER;
6439                 }
6440                 auto scheduler = iter.second->GetScheduler();
6441                 if (scheduler) {
6442                     TAG_LOGW(AAFwkTag::APPMGR, "null render, renderPid:%{public}d", renderPid);
6443                     OnRenderRemoteDied(scheduler->AsObject());
6444                 }
6445             }
6446         }
6447     }
6448     appRecord->SetHasGPU(isGPU);
6449     int32_t childNumLimit = appRecord->HasGPU() ? PHONE_MAX_RENDER_PROCESS_NUM + 1 : PHONE_MAX_RENDER_PROCESS_NUM;
6450     // The phone device allows a maximum of 40 render processes to be created.
6451     if (AAFwk::AppUtils::GetInstance().IsLimitMaximumOfRenderProcess() &&
6452         !AllowChildProcessInMultiProcessFeatureApp(appRecord) &&
6453         renderRecordMap.size() >= static_cast<uint32_t>(childNumLimit)) {
6454         TAG_LOGE(AAFwkTag::APPMGR, "maximum render process limitation, hostPid:%{public}d", hostPid);
6455         return ERR_REACHING_MAXIMUM_RENDER_PROCESS_LIMITATION;
6456     }
6457 
6458     auto renderRecord = RenderRecord::CreateRenderRecord(hostPid, renderParam,
6459         std::move(ipcFd), std::move(sharedFd), std::move(crashFd), appRecord);
6460     if (!renderRecord) {
6461         TAG_LOGE(AAFwkTag::APPMGR, "create renderRecord fail, hostPid:%{public}d", hostPid);
6462         return ERR_INVALID_VALUE;
6463     }
6464 
6465     return StartRenderProcessImpl(renderRecord, appRecord, renderPid, isGPU);
6466 }
6467 
AttachRenderProcess(const pid_t pid,const sptr<IRenderScheduler> & scheduler)6468 void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr<IRenderScheduler> &scheduler)
6469 {
6470     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6471     TAG_LOGI(AAFwkTag::APPMGR, "attachRenderProcess start");
6472     if (pid <= 0) {
6473         TAG_LOGE(AAFwkTag::APPMGR, "invalid render process pid:%{public}d", pid);
6474         return;
6475     }
6476     if (!scheduler) {
6477         TAG_LOGE(AAFwkTag::APPMGR, "render scheduler null");
6478         return;
6479     }
6480 
6481     if (!appRunningManager_) {
6482         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
6483         return;
6484     }
6485 
6486     auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid);
6487     if (!appRecord) {
6488         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", pid);
6489         return;
6490     }
6491 
6492     auto renderRecord = appRecord->GetRenderRecordByPid(pid);
6493     if (!renderRecord) {
6494         TAG_LOGE(AAFwkTag::APPMGR, "no renderRecord, pid:%{public}d", pid);
6495         return;
6496     }
6497 
6498     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
6499     appDeathRecipient->SetTaskHandler(taskHandler_);
6500     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
6501     appDeathRecipient->SetIsRenderProcess(true);
6502     renderRecord->SetScheduler(scheduler);
6503     renderRecord->SetDeathRecipient(appDeathRecipient);
6504     renderRecord->RegisterDeathRecipient();
6505 
6506     TAG_LOGI(AAFwkTag::APPMGR, "attachRenderProcess_%{public}d, notify fd", pid);
6507     // notify fd to render process
6508     if (appRecord->GetBrowserHost() != nullptr && renderRecord->GetProcessType() == ProcessType::GPU) {
6509         TAG_LOGD(AAFwkTag::APPMGR, "GPU has host remote object");
6510         scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(),
6511             renderRecord->GetSharedFd(), renderRecord->GetCrashFd(), appRecord->GetBrowserHost());
6512     } else {
6513         scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(),
6514             renderRecord->GetSharedFd(), renderRecord->GetCrashFd(), nullptr);
6515     }
6516 }
6517 
SaveBrowserChannel(const pid_t hostPid,sptr<IRemoteObject> browser)6518 void AppMgrServiceInner::SaveBrowserChannel(const pid_t hostPid, sptr<IRemoteObject> browser)
6519 {
6520     std::lock_guard<ffrt::mutex> lock(browserHostLock_);
6521     TAG_LOGD(AAFwkTag::APPMGR, "save browser channel.");
6522     auto appRecord = GetAppRunningRecordByPid(hostPid);
6523     if (!appRecord) {
6524         TAG_LOGE(AAFwkTag::APPMGR, "save browser host no appRecord, pid:%{public}d",
6525             hostPid);
6526         return;
6527     }
6528     appRecord->SetBrowserHost(browser);
6529 }
6530 
GenerateRenderUid(int32_t & renderUid)6531 bool AppMgrServiceInner::GenerateRenderUid(int32_t &renderUid)
6532 {
6533     std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
6534     int32_t uid = lastRenderUid_ + 1;
6535     bool needSecondScan = true;
6536     if (uid > Constants::END_UID_FOR_RENDER_PROCESS) {
6537         uid = Constants::START_UID_FOR_RENDER_PROCESS;
6538         needSecondScan = false;
6539     }
6540 
6541     if (renderUidSet_.empty()) {
6542         renderUid = uid;
6543         renderUidSet_.insert(renderUid);
6544         lastRenderUid_ = renderUid;
6545         return true;
6546     }
6547 
6548     for (int32_t i = uid; i <= Constants::END_UID_FOR_RENDER_PROCESS; i++) {
6549         if (renderUidSet_.find(i) == renderUidSet_.end()) {
6550             renderUid = i;
6551             renderUidSet_.insert(renderUid);
6552             lastRenderUid_ = renderUid;
6553             return true;
6554         }
6555     }
6556 
6557     if (needSecondScan) {
6558         for (int32_t i = Constants::START_UID_FOR_RENDER_PROCESS; i <= lastRenderUid_; i++) {
6559             if (renderUidSet_.find(i) == renderUidSet_.end()) {
6560                 renderUid = i;
6561                 renderUidSet_.insert(renderUid);
6562                 lastRenderUid_ = renderUid;
6563                 return true;
6564             }
6565         }
6566     }
6567 
6568     return false;
6569 }
6570 
StartRenderProcessImpl(const std::shared_ptr<RenderRecord> & renderRecord,const std::shared_ptr<AppRunningRecord> appRecord,pid_t & renderPid,bool isGPU)6571 int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr<RenderRecord> &renderRecord,
6572     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &renderPid, bool isGPU)
6573 {
6574     if (!renderRecord || !appRecord) {
6575         TAG_LOGE(AAFwkTag::APPMGR, "renderRecord or appRecord null");
6576         return ERR_INVALID_VALUE;
6577     }
6578 
6579     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
6580     if (!nwebSpawnClient) {
6581         TAG_LOGE(AAFwkTag::APPMGR, "nwebSpawnClient null");
6582         AppMgrEventUtil::SendRenderProcessStartFailedEvent(renderRecord,
6583             ProcessStartFailedReason::GET_SPAWN_CLIENT_FAILED, AAFwk::ERR_GET_SPAWN_CLIENT_FAILED);
6584         return ERR_INVALID_VALUE;
6585     }
6586     int32_t renderUid = Constants::INVALID_UID;
6587     if (!GenerateRenderUid(renderUid)) {
6588         TAG_LOGE(AAFwkTag::APPMGR, "generate renderUid fail");
6589         AppMgrEventUtil::SendRenderProcessStartFailedEvent(renderRecord,
6590             ProcessStartFailedReason::GENERATE_RENDER_UID_FAILED, ERR_INVALID_OPERATION);
6591         return ERR_INVALID_OPERATION;
6592     }
6593     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
6594     SetRenderStartMsg(startMsg, renderRecord, renderUid, isGPU);
6595     pid_t pid = 0;
6596     ErrCode errCode = nwebSpawnClient->StartProcess(startMsg, pid);
6597     if (FAILED(errCode)) {
6598         TAG_LOGE(AAFwkTag::APPMGR, "spawn new render process fail, errCode %{public}08x", errCode);
6599         std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
6600         renderUidSet_.erase(renderUid);
6601         AppMgrEventUtil::SendRenderProcessStartFailedEvent(renderRecord,
6602             ProcessStartFailedReason::APPSPAWN_FAILED, static_cast<int32_t>(errCode));
6603         return ERR_INVALID_VALUE;
6604     }
6605     renderPid = pid;
6606     renderRecord->SetPid(pid);
6607     renderRecord->SetUid(renderUid);
6608     renderRecord->SetProcessName(startMsg.procName);
6609     if (isGPU) {
6610         renderRecord->SetProcessType(ProcessType::GPU);
6611         appRecord->SetGPUPid(pid);
6612     }
6613     appRecord->AddRenderRecord(renderRecord);
6614     bool isPreload = appRecord->IsNWebPreload();
6615     TAG_LOGI(AAFwkTag::APPMGR,
6616         "startRenderProcess success, hostPid:%{public}d, hostUid:%{public}d, pid:%{public}d, uid:%{public}d"
6617         "isPreload:%{public}d", renderRecord->GetHostPid(), renderRecord->GetHostUid(), pid, renderUid, isPreload);
6618     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessCreated(renderRecord, isPreload);
6619     return 0;
6620 }
6621 
SetRenderStartMsg(AppSpawnStartMsg & startMsg,std::shared_ptr<RenderRecord> renderRecord,const int32_t renderUid,const bool isGPU)6622 void AppMgrServiceInner::SetRenderStartMsg(AppSpawnStartMsg &startMsg, std::shared_ptr<RenderRecord> renderRecord,
6623     const int32_t renderUid, const bool isGPU)
6624 {
6625     startMsg.renderParam = renderRecord->GetRenderParam();
6626     startMsg.uid = renderUid;
6627     startMsg.gid = renderUid;
6628     if (isGPU) {
6629         startMsg.procName += GPU_PROCESS_NAME;
6630         startMsg.processType = GPU_PROCESS_TYPE;
6631         startMsg.hostProcessUid = renderRecord->GetHostUid();
6632         if (std::find(startMsg.gids.begin(), startMsg.gids.end(), SHADER_CACHE_GROUPID) == startMsg.gids.end()) {
6633             startMsg.gids.push_back(SHADER_CACHE_GROUPID);
6634         }
6635     } else {
6636         startMsg.procName += RENDER_PROCESS_NAME;
6637         startMsg.processType = RENDER_PROCESS_TYPE;
6638     }
6639     startMsg.code = 0; // 0: DEFAULT
6640 }
6641 
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)6642 int AppMgrServiceInner::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
6643 {
6644     auto callingPid = IPCSkeleton::GetCallingPid();
6645     TAG_LOGD(AAFwkTag::APPMGR, "GetRenderProcessTerminationStatus, callingPid:%{public}d, renderPid:%{public}d",
6646         callingPid, renderPid);
6647     if (!appRunningManager_) {
6648         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
6649         return ERR_INVALID_VALUE;
6650     }
6651     auto hostRecord = appRunningManager_->GetAppRunningRecordByPid(callingPid);
6652     if (!hostRecord) {
6653         TAG_LOGE(AAFwkTag::APPMGR, "hostRecord null");
6654         return ERR_INVALID_VALUE;
6655     }
6656     if (!hostRecord->ConstainsRenderPid(renderPid)) {
6657         TAG_LOGE(AAFwkTag::APPMGR,
6658             "permission denied, callingPid:%{public}d, renderPid:%{public}d",
6659             callingPid, renderPid);
6660         return ERR_PERMISSION_DENIED;
6661     }
6662     if (remoteClientManager_ == nullptr) {
6663         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
6664         return ERR_INVALID_VALUE;
6665     }
6666     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
6667     if (!nwebSpawnClient) {
6668         TAG_LOGE(AAFwkTag::APPMGR, "nwebSpawnClient null");
6669         return ERR_INVALID_VALUE;
6670     }
6671 
6672     AppSpawnStartMsg startMsg;
6673     startMsg.pid = renderPid;
6674     startMsg.code = MSG_GET_RENDER_TERMINATION_STATUS;
6675     ErrCode errCode = nwebSpawnClient->GetRenderProcessTerminationStatus(startMsg, status);
6676     if (FAILED(errCode)) {
6677         TAG_LOGE(AAFwkTag::APPMGR, "get render process termination status fail, errCode %{public}08x", errCode);
6678         return ERR_INVALID_VALUE;
6679     }
6680     TAG_LOGD(AAFwkTag::APPMGR, "Get render process termination status success, renderPid:%{public}d, status:%{public}d",
6681         renderPid, status);
6682     hostRecord->RemoveRenderPid(renderPid);
6683     RemoveRenderRecordNoAttach(hostRecord, renderPid);
6684     return 0;
6685 }
6686 
RemoveRenderRecordNoAttach(const std::shared_ptr<AppRunningRecord> & hostRecord,int32_t renderPid)6687 void AppMgrServiceInner::RemoveRenderRecordNoAttach(const std::shared_ptr<AppRunningRecord> &hostRecord,
6688     int32_t renderPid)
6689 {
6690     if (!hostRecord) {
6691         TAG_LOGE(AAFwkTag::APPMGR, "hostRecord null");
6692         return;
6693     }
6694     auto renderRecord = hostRecord->GetRenderRecordByPid(renderPid);
6695     if (!renderRecord) {
6696         TAG_LOGD(AAFwkTag::APPMGR, "renderRecord null");
6697         return;
6698     }
6699     if (renderRecord->GetScheduler() == nullptr) {
6700         hostRecord->RemoveRenderRecord(renderRecord);
6701         {
6702             std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
6703             renderUidSet_.erase(renderRecord->GetUid());
6704         }
6705         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
6706     }
6707 }
6708 
OnRenderRemoteDied(const wptr<IRemoteObject> & remote)6709 void AppMgrServiceInner::OnRenderRemoteDied(const wptr<IRemoteObject> &remote)
6710 {
6711     TAG_LOGE(AAFwkTag::APPMGR, "on render remote died");
6712     if (appRunningManager_) {
6713         auto renderRecord = appRunningManager_->OnRemoteRenderDied(remote);
6714         if (renderRecord) {
6715             {
6716                 std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
6717                 renderUidSet_.erase(renderRecord->GetUid());
6718             }
6719             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
6720         }
6721     }
6722 }
6723 
AddWatchParameter()6724 void AppMgrServiceInner::AddWatchParameter()
6725 {
6726     TAG_LOGI(AAFwkTag::APPMGR, "call");
6727     auto context = new (std::nothrow) std::weak_ptr<AppMgrServiceInner>(shared_from_this());
6728     int ret = WatchParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, PointerDeviceEventCallback,
6729         context);
6730     if (ret != 0) {
6731         TAG_LOGE(AAFwkTag::APPMGR, "watch parameter %{public}s fail with %{public}d",
6732             AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, ret);
6733     }
6734 }
6735 
InitFocusListener()6736 void AppMgrServiceInner::InitFocusListener()
6737 {
6738     TAG_LOGI(AAFwkTag::APPMGR, "begin initFocusListener");
6739 #ifdef SUPPORT_SCREEN
6740     if (focusListener_) {
6741         return;
6742     }
6743 
6744     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
6745 #endif // SUPPORT_SCREEN
6746     auto registerTask = [innerServiceWeak = weak_from_this()]() {
6747         auto innerService = innerServiceWeak.lock();
6748         if (innerService) {
6749             TAG_LOGI(AAFwkTag::APPMGR, "registerFocusListenerTask");
6750             innerService->RegisterFocusListener();
6751         }
6752     };
6753     if (taskHandler_) {
6754         taskHandler_->SubmitTaskJust(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
6755         TAG_LOGI(AAFwkTag::APPMGR, "submit registerFocusListenerTask");
6756     }
6757 }
6758 
RegisterFocusListener()6759 void AppMgrServiceInner::RegisterFocusListener()
6760 {
6761     TAG_LOGI(AAFwkTag::APPMGR, "registerFocusListener begin");
6762 #ifdef SUPPORT_SCREEN
6763     if (!focusListener_) {
6764         TAG_LOGE(AAFwkTag::APPMGR, "no focusListener_");
6765         return;
6766     }
6767     WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
6768 #endif // SUPPORT_SCREEN
6769     TAG_LOGI(AAFwkTag::APPMGR, "registerFocusListener end");
6770 }
6771 
FreeFocusListener()6772 void AppMgrServiceInner::FreeFocusListener()
6773 {
6774     TAG_LOGI(AAFwkTag::APPMGR, "freeFocusListener begin");
6775 #ifdef SUPPORT_SCREEN
6776     if (!focusListener_) {
6777         TAG_LOGE(AAFwkTag::APPMGR, "no focusListener_");
6778         return;
6779     }
6780     WindowManager::GetInstance().UnregisterFocusChangedListener(focusListener_);
6781     focusListener_ = nullptr;
6782 #endif // SUPPORT_SCREEN
6783     TAG_LOGI(AAFwkTag::APPMGR, "freeFocusListener end");
6784 }
6785 #ifdef SUPPORT_SCREEN
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)6786 void AppMgrServiceInner::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
6787 {
6788     if (!focusChangeInfo) {
6789         TAG_LOGW(AAFwkTag::APPMGR, "invalid focusChangeInfo");
6790         return;
6791     }
6792     TAG_LOGI(AAFwkTag::APPMGR, "uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
6793 
6794     if (focusChangeInfo->pid_ <= 0) {
6795         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}d", focusChangeInfo->pid_);
6796         return;
6797     }
6798 
6799     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
6800     if (!appRecord) {
6801         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", focusChangeInfo->pid_);
6802         return;
6803     }
6804 
6805     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, true)) {
6806         TAG_LOGD(
6807             AAFwkTag::APPMGR, "only change ability focus state, do not change process or application focus state.");
6808         return;
6809     }
6810 
6811     bool needNotifyApp = appRunningManager_->IsApplicationFirstFocused(*appRecord);
6812     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
6813         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp, true);
6814     }
6815     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord, true);
6816 }
6817 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)6818 void AppMgrServiceInner::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
6819 {
6820     if (!focusChangeInfo) {
6821         TAG_LOGW(AAFwkTag::APPMGR, "invalid focusChangeInfo");
6822         return;
6823     }
6824     TAG_LOGD(
6825         AAFwkTag::APPMGR, "unfocused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
6826 
6827     if (focusChangeInfo->pid_ <= 0) {
6828         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}d", focusChangeInfo->pid_);
6829         return;
6830     }
6831 
6832     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
6833     if (!appRecord) {
6834         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", focusChangeInfo->pid_);
6835         return;
6836     }
6837 
6838     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, false)) {
6839         TAG_LOGD(AAFwkTag::APPMGR,
6840             "only change ability from focus to unfocus, do not change process or application focus state.");
6841         return;
6842     }
6843 
6844     bool needNotifyApp = appRunningManager_->IsApplicationUnfocused(appRecord->GetBundleName());
6845     OnAppStateChanged(appRecord, appRecord->GetState(), needNotifyApp, true);
6846     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord, true);
6847 }
6848 
InitWindowVisibilityChangedListener()6849 void AppMgrServiceInner::InitWindowVisibilityChangedListener()
6850 {
6851     TAG_LOGD(AAFwkTag::APPMGR, "Begin.");
6852     if (windowVisibilityChangedListener_ != nullptr) {
6853         TAG_LOGW(AAFwkTag::APPMGR, "visibility listener already initiate");
6854         return;
6855     }
6856     windowVisibilityChangedListener_ =
6857         new (std::nothrow) WindowVisibilityChangedListener(weak_from_this(), taskHandler_);
6858     if (windowVisibilityChangedListener_ == nullptr) {
6859         TAG_LOGE(AAFwkTag::APPMGR, "window visibility changed listener null");
6860         return;
6861     }
6862     WindowManager::GetInstance().RegisterVisibilityChangedListener(windowVisibilityChangedListener_);
6863 
6864     std::vector<sptr<WindowVisibilityInfo>> windowVisibilityInfos;
6865     windowVisibilityInfos.clear();
6866     WindowManager::GetInstance().GetVisibilityWindowInfo(windowVisibilityInfos);
6867 
6868     if (windowVisibilityInfos.empty()) {
6869         TAG_LOGW(AAFwkTag::APPMGR, "window visibility info is empty");
6870         return;
6871     }
6872 
6873     for (const auto &info : windowVisibilityInfos) {
6874         if (info == nullptr) {
6875             TAG_LOGE(AAFwkTag::APPMGR, "info null");
6876             continue;
6877         }
6878         auto appRecord = GetAppRunningRecordByPid(info->pid_);
6879         if (appRecord == nullptr) {
6880             TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
6881             continue;
6882         }
6883         appRecord->ChangeWindowVisibility(info);
6884     }
6885 
6886     TAG_LOGD(AAFwkTag::APPMGR, "End.");
6887 }
6888 
FreeWindowVisibilityChangedListener()6889 void AppMgrServiceInner::FreeWindowVisibilityChangedListener()
6890 {
6891     TAG_LOGD(AAFwkTag::APPMGR, "called");
6892     if (windowVisibilityChangedListener_ == nullptr) {
6893         TAG_LOGW(AAFwkTag::APPMGR, "visibility listener already free");
6894         return;
6895     }
6896     WindowManager::GetInstance().UnregisterVisibilityChangedListener(windowVisibilityChangedListener_);
6897     windowVisibilityChangedListener_  = nullptr;
6898 }
6899 
HandleWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)6900 void AppMgrServiceInner::HandleWindowVisibilityChanged(
6901     const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
6902 {
6903     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
6904     TAG_LOGD(AAFwkTag::APPMGR, "called");
6905     if (windowVisibilityInfos.empty()) {
6906         TAG_LOGW(AAFwkTag::APPMGR, "window visibility info empty");
6907         return;
6908     }
6909     if (appRunningManager_ == nullptr) {
6910         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
6911         return;
6912     }
6913     appRunningManager_->OnWindowVisibilityChanged(windowVisibilityInfos);
6914 }
6915 
InitWindowPidVisibilityChangedListener()6916 void AppMgrServiceInner::InitWindowPidVisibilityChangedListener()
6917 {
6918     TAG_LOGD(AAFwkTag::APPMGR, "called");
6919     if (windowPidVisibilityChangedListener_ != nullptr) {
6920         TAG_LOGW(AAFwkTag::APPMGR, "Pid visibility listener has been initiated.");
6921         return;
6922     }
6923     windowPidVisibilityChangedListener_ =
6924         sptr<WindowPidVisibilityChangedListener>::MakeSptr(weak_from_this(), taskHandler_);
6925     auto registerTask = [innerService = weak_from_this()] () {
6926         auto inner = innerService.lock();
6927         if (inner == nullptr) {
6928             TAG_LOGE(AAFwkTag::APPMGR, "Service inner is nullptr.");
6929             return;
6930         }
6931         if (inner->windowPidVisibilityChangedListener_ == nullptr) {
6932             TAG_LOGE(AAFwkTag::APPMGR, "Window pid visibility changed listener is nullptr.");
6933             return;
6934         }
6935         WMError ret = WindowManager::GetInstance().RegisterWindowPidVisibilityChangedListener(
6936             inner->windowPidVisibilityChangedListener_);
6937         if (ret != WMError::WM_OK) {
6938             TAG_LOGE(AAFwkTag::APPMGR, "RegisterWindowPidVisibilityChangedListener failed.");
6939             return;
6940         }
6941     };
6942 
6943     if (taskHandler_ == nullptr) {
6944         TAG_LOGE(AAFwkTag::APPMGR, "Task handler is nullptr.");
6945         return;
6946     }
6947     taskHandler_->SubmitTaskJust(registerTask, "RegisterPidVisibilityListener.", REGISTER_PID_VISIBILITY_DELAY);
6948 }
6949 
FreeWindowPidVisibilityChangedListener()6950 void AppMgrServiceInner::FreeWindowPidVisibilityChangedListener()
6951 {
6952     TAG_LOGD(AAFwkTag::APPMGR, "called");
6953     if (windowPidVisibilityChangedListener_ == nullptr) {
6954         TAG_LOGW(AAFwkTag::APPMGR, "pid visibility changed listener has been freed.");
6955         return;
6956     }
6957     WindowManager::GetInstance().UnregisterWindowPidVisibilityChangedListener(windowPidVisibilityChangedListener_);
6958     windowPidVisibilityChangedListener_ = nullptr;
6959 }
6960 
HandleWindowPidVisibilityChanged(const sptr<WindowPidVisibilityInfo> & windowPidVisibilityInfo)6961 void AppMgrServiceInner::HandleWindowPidVisibilityChanged(
6962     const sptr<WindowPidVisibilityInfo>& windowPidVisibilityInfo)
6963 {
6964     TAG_LOGD(AAFwkTag::APPMGR, "called");
6965     if (!windowPidVisibilityInfo) {
6966         TAG_LOGW(AAFwkTag::APPMGR, "Window pid visibility info is empty.");
6967         return;
6968     }
6969     auto appRecord = GetAppRunningRecordByPid(windowPidVisibilityInfo->pid_);
6970     if (appRecord == nullptr) {
6971         TAG_LOGE(AAFwkTag::APPMGR, "App running record is nullptr.");
6972         return;
6973     }
6974 
6975     if (windowPidVisibilityInfo->visibilityState_ == OHOS::Rosen::WindowPidVisibilityState::VISIBILITY_STATE) {
6976         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnWindowShow(appRecord);
6977     }
6978     if (windowPidVisibilityInfo->visibilityState_ == OHOS::Rosen::WindowPidVisibilityState::INVISIBILITY_STATE) {
6979         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnWindowHidden(appRecord);
6980     }
6981 }
6982 #endif // SUPPORT_SCREEN
PointerDeviceEventCallback(const char * key,const char * value,void * context)6983 void AppMgrServiceInner::PointerDeviceEventCallback(const char *key, const char *value, void *context)
6984 {
6985     TAG_LOGI(AAFwkTag::APPMGR, "call");
6986     auto weak = static_cast<std::weak_ptr<AppMgrServiceInner>*>(context);
6987     if (weak == nullptr) {
6988         TAG_LOGE(AAFwkTag::APPMGR, "context null");
6989         return;
6990     }
6991 
6992     auto appMgrServiceInner = weak->lock();
6993     if (appMgrServiceInner == nullptr) {
6994         TAG_LOGE(AAFwkTag::APPMGR, "manager service inner null");
6995         return;
6996     }
6997 
6998     if ((strcmp(key, AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE) != 0) ||
6999         ((strcmp(value, "true") != 0) && (strcmp(value, "false") != 0))) {
7000         TAG_LOGE(AAFwkTag::APPMGR, "key %{public}s or value %{public}s mismatch", key, value);
7001         return;
7002     }
7003 
7004     Configuration changeConfig;
7005     if (!changeConfig.AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, value)) {
7006         TAG_LOGE(AAFwkTag::APPMGR, "add %{public}s item fail", key);
7007         return;
7008     }
7009 
7010     TAG_LOGD(AAFwkTag::APPMGR, "update config %{public}s to %{public}s", key, value);
7011     auto result = IN_PROCESS_CALL(appMgrServiceInner->UpdateConfiguration(changeConfig));
7012     if (result != 0) {
7013         TAG_LOGE(AAFwkTag::APPMGR, "update config fail with %{public}d, key: %{public}s, value: %{public}s", result,
7014             key, value);
7015         return;
7016     }
7017 }
7018 
GetAppRunningStateByBundleName(const std::string & bundleName)7019 bool AppMgrServiceInner::GetAppRunningStateByBundleName(const std::string &bundleName)
7020 {
7021     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7022     TAG_LOGD(AAFwkTag::APPMGR, "called");
7023     if (!appRunningManager_) {
7024         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
7025         return false;
7026     }
7027 
7028     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
7029         TAG_LOGE(AAFwkTag::APPMGR, "permission deny not SA");
7030         return false;
7031     }
7032 
7033     return appRunningManager_->GetAppRunningStateByBundleName(bundleName);
7034 }
7035 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)7036 int32_t AppMgrServiceInner::NotifyLoadRepairPatch(const std::string &bundleName,
7037     const sptr<IQuickFixCallback> &callback)
7038 {
7039     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7040     TAG_LOGD(AAFwkTag::APPMGR, "called");
7041     if (!appRunningManager_) {
7042         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
7043         return ERR_INVALID_OPERATION;
7044     }
7045 
7046     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
7047         TAG_LOGE(AAFwkTag::APPMGR, "not quick_fix");
7048         return ERR_PERMISSION_DENIED;
7049     }
7050 
7051     return appRunningManager_->NotifyLoadRepairPatch(bundleName, callback);
7052 }
7053 
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)7054 int32_t AppMgrServiceInner::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
7055 {
7056     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7057     TAG_LOGD(AAFwkTag::APPMGR, "called");
7058     if (!appRunningManager_) {
7059         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
7060         return ERR_INVALID_OPERATION;
7061     }
7062 
7063     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
7064         TAG_LOGE(AAFwkTag::APPMGR, "not quick_fix");
7065         return ERR_PERMISSION_DENIED;
7066     }
7067 
7068     return appRunningManager_->NotifyHotReloadPage(bundleName, callback);
7069 }
7070 
7071 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
SetContinuousTaskProcess(int32_t pid,bool isContinuousTask)7072 int32_t AppMgrServiceInner::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask)
7073 {
7074     if (!appRunningManager_) {
7075         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
7076         return ERR_INVALID_OPERATION;
7077     }
7078 
7079     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(pid);
7080     if (!appRecord) {
7081         TAG_LOGE(AAFwkTag::APPMGR, "get running record fail, pid: %{public}d", pid);
7082         return ERR_INVALID_VALUE;
7083     }
7084     appRecord->SetContinuousTaskAppState(isContinuousTask);
7085     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
7086 
7087     return ERR_OK;
7088 }
7089 #endif
7090 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)7091 int32_t AppMgrServiceInner::NotifyUnLoadRepairPatch(const std::string &bundleName,
7092     const sptr<IQuickFixCallback> &callback)
7093 {
7094     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
7095     TAG_LOGD(AAFwkTag::APPMGR, "called");
7096     if (!appRunningManager_) {
7097         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
7098         return ERR_INVALID_OPERATION;
7099     }
7100 
7101     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
7102         TAG_LOGE(AAFwkTag::APPMGR, "not quick_fix");
7103         return ERR_PERMISSION_DENIED;
7104     }
7105 
7106     return appRunningManager_->NotifyUnLoadRepairPatch(bundleName, callback);
7107 }
7108 
AppRecoveryNotifyApp(int32_t pid,const std::string & bundleName,FaultDataType faultType,const std::string & markers)7109 void AppMgrServiceInner::AppRecoveryNotifyApp(int32_t pid, const std::string& bundleName,
7110     FaultDataType faultType, const std::string& markers)
7111 {
7112     if (faultType != FaultDataType::APP_FREEZE) {
7113         TAG_LOGI(AAFwkTag::APPMGR,
7114             "kill appRecovery NotifyApp bundleName: %{public}s, faultType: "
7115             "%{public}d, pid: %{public}d", bundleName.c_str(), faultType, pid);
7116         KillProcessByPid(pid, "AppRecoveryNotifyApp");
7117         return;
7118     }
7119 
7120     std::string timeOutName = "waitSaveTask" + std::to_string(pid) + bundleName;
7121     if (markers == "appRecovery") {
7122         TAG_LOGI(AAFwkTag::APPMGR, "waitSaveTask finish, but not kill process "
7123             "immediately, wait for dump stack util 2s timeout");
7124         return;
7125     }
7126 
7127     if (markers != "recoveryTimeout") {
7128         return;
7129     }
7130     auto waitSaveTask = [pid, bundleName, innerServiceWeak = weak_from_this()]() {
7131         auto innerService = innerServiceWeak.lock();
7132         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
7133         auto appRecord = innerService->GetAppRunningRecordByPid(pid);
7134         if (appRecord == nullptr) {
7135             TAG_LOGE(AAFwkTag::APPMGR, "no appRecord");
7136             return;
7137         }
7138         std::string name = appRecord->GetBundleName();
7139         if (bundleName == name) {
7140             TAG_LOGI(AAFwkTag::APPMGR,
7141                 "waitSaveTask timeout %{public}s,pid: %{public}d will exit",
7142                 bundleName.c_str(), pid);
7143             innerService->KillProcessByPid(pid, "AppRecoveryNotifyApp");
7144         }
7145     };
7146     constexpr int32_t timeOut = 2000;
7147     CHECK_POINTER_AND_RETURN_LOG(taskHandler_, "no taskHandler_");
7148     taskHandler_->SubmitTaskJust(waitSaveTask, timeOutName, timeOut);
7149 }
7150 
ParseInfoToAppfreeze(const FaultData & faultData,int32_t pid,int32_t uid,const std::string & bundleName,const std::string & processName,const bool isOccurException)7151 void AppMgrServiceInner::ParseInfoToAppfreeze(const FaultData &faultData, int32_t pid, int32_t uid,
7152     const std::string &bundleName, const std::string &processName, const bool isOccurException)
7153 {
7154     if (faultData.faultType == FaultDataType::APP_FREEZE) {
7155         AppfreezeManager::AppInfo info = {
7156             .isOccurException = isOccurException,
7157             .pid = pid,
7158             .uid = uid,
7159             .bundleName = bundleName,
7160             .processName = processName,
7161         };
7162         AppExecFwk::AppfreezeManager::GetInstance()->AppfreezeHandleWithStack(faultData, info);
7163     }
7164 
7165     TAG_LOGW(AAFwkTag::APPMGR,
7166         "name: %{public}s, faultType: %{public}d, uid: %{public}d, pid: %{public}d, bundleName: %{public}s,"
7167         " processName: %{public}s, faultData.forceExit:%{public}d, faultData.waitSaveState:%{public}d,"
7168         " isOccurException:%{public}d, stuckTimeout:%{public}u",
7169         faultData.errorObject.name.c_str(), faultData.faultType, uid, pid, bundleName.c_str(),
7170         processName.c_str(), faultData.forceExit, faultData.waitSaveState, isOccurException, faultData.stuckTimeout);
7171 }
7172 
7173 
GetExceptionTimerId(const FaultData & faultData,const std::string & bundleName,const std::shared_ptr<AppRunningRecord> & appRecord,const int32_t pid,const int32_t callerUid)7174 int AppMgrServiceInner::GetExceptionTimerId(const FaultData &faultData, const std::string &bundleName,
7175     const std::shared_ptr<AppRunningRecord> &appRecord, const int32_t pid, const int32_t callerUid)
7176 {
7177     auto exceptionCallback = [faultData, bundleName, appRecord, pid, callerUid,
7178         innerService = shared_from_this()](void *) {
7179         auto threadTask = [faultData, bundleName, appRecord, pid, callerUid, innerService]() {
7180             if (innerService->CheckAppFault(appRecord, faultData)) {
7181                 TAG_LOGI(AAFwkTag::APPMGR, "Ffrt Exception current dfx task is working.");
7182                 return;
7183             }
7184             bool isOccurException = true;
7185             innerService->ParseInfoToAppfreeze(faultData, pid, callerUid, bundleName, appRecord->GetProcessName(),
7186                 isOccurException);
7187             if (faultData.errorObject.name != AppFreezeType::THREAD_BLOCK_3S &&
7188                 faultData.errorObject.name != AppFreezeType::LIFECYCLE_HALF_TIMEOUT &&
7189                 faultData.errorObject.name != AppFreezeType::LIFECYCLE_HALF_TIMEOUT_WARNING) {
7190                 TAG_LOGI(AAFwkTag::APPMGR, "Ffrt Exception faultData: %{public}s,pid: %{public}d "
7191                     "will exit because"" %{public}s", bundleName.c_str(), pid,
7192                     innerService->FaultTypeToString(faultData.faultType).c_str());
7193                 innerService->KillProcessByPid(pid, faultData.errorObject.name);
7194                 return;
7195             }
7196         };
7197         std::thread dfxThread(threadTask);
7198         if (dfxThread.joinable()) {
7199             dfxThread.join();
7200         }
7201     };
7202     constexpr uint32_t timeout = 30; // 30s
7203     int exceptionId = -1;
7204 #ifdef APP_MGR_SERVICE_HICOLLIE_ENABLE
7205     exceptionId = HiviewDFX::XCollie::GetInstance().SetTimer("DfxFault::Exception", timeout,
7206         exceptionCallback, nullptr, HiviewDFX::XCOLLIE_FLAG_NOOP);
7207 #endif
7208     return exceptionId;
7209 }
7210 
SubmitDfxFaultTask(const FaultData & faultData,const std::string & bundleName,const std::shared_ptr<AppRunningRecord> & appRecord,const int32_t pid)7211 int32_t AppMgrServiceInner::SubmitDfxFaultTask(const FaultData &faultData, const std::string &bundleName,
7212     const std::shared_ptr<AppRunningRecord> &appRecord, const int32_t pid)
7213 {
7214     int32_t callerUid = IPCSkeleton::GetCallingUid();
7215     std::string processName = appRecord->GetProcessName();
7216     int exceptionId = GetExceptionTimerId(faultData, bundleName, appRecord, pid, callerUid);
7217     auto notifyAppTask = [appRecord, pid, callerUid, bundleName, processName, faultData, exceptionId,
7218         innerServiceWeak = weak_from_this()]() {
7219 #ifdef APP_MGR_SERVICE_HICOLLIE_ENABLE
7220         HiviewDFX::XCollie::GetInstance().CancelTimer(exceptionId);
7221 #endif
7222         auto innerService = innerServiceWeak.lock();
7223         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
7224         innerService->ParseInfoToAppfreeze(faultData, pid, callerUid, bundleName, processName);
7225     };
7226 
7227     if (!dfxTaskHandler_) {
7228         TAG_LOGW(AAFwkTag::APPMGR, "get dfx handler fail");
7229         return ERR_INVALID_VALUE;
7230     }
7231     int64_t startTime = AbilityRuntime::TimeUtil::CurrentTimeMillis();
7232     dfxTaskHandler_->SubmitTask(notifyAppTask, "NotifyAppFaultTask");
7233     TAG_LOGW(AAFwkTag::APPDFR, "submit NotifyAppFaultTask, eventName:%{public}s, bundleName:%{public}s, "
7234         "endTime:%{public}s, interval:%{public}" PRId64 " ms", faultData.errorObject.name.c_str(),
7235         bundleName.c_str(), AbilityRuntime::TimeUtil::DefaultCurrentTimeStr().c_str(),
7236         AbilityRuntime::TimeUtil::CurrentTimeMillis() - startTime);
7237 
7238     constexpr int delayTime = 15 * 1000; // 15s
7239     auto task = [pid]() {
7240         AppExecFwk::AppfreezeManager::GetInstance()->DeleteStack(pid);
7241     };
7242     dfxTaskHandler_->SubmitTaskJust(task, "DeleteStack", delayTime);
7243 
7244     return ERR_OK;
7245 }
7246 
NotifyAppFault(const FaultData & faultData)7247 int32_t AppMgrServiceInner::NotifyAppFault(const FaultData &faultData)
7248 {
7249     TAG_LOGI(AAFwkTag::APPMGR, "call");
7250     int32_t pid = IPCSkeleton::GetCallingPid();
7251     auto appRecord = GetAppRunningRecordByPid(pid);
7252     if (appRecord == nullptr) {
7253         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", pid);
7254         return ERR_INVALID_VALUE;
7255     }
7256     if (appRecord->GetState() == ApplicationState::APP_STATE_TERMINATED ||
7257         appRecord->GetState() == ApplicationState::APP_STATE_END) {
7258         TAG_LOGE(AAFwkTag::APPMGR, "appfreeze detect end");
7259         return ERR_OK;
7260     }
7261     std::string bundleName = appRecord->GetBundleName();
7262     std::string eventName = faultData.errorObject.name;
7263 
7264     TAG_LOGW(AAFwkTag::APPDFR, "called, eventName:%{public}s, pid:%{public}d, bundleName:%{public}s, "
7265         "currentTime:%{public}s", eventName.c_str(), pid, bundleName.c_str(),
7266         AbilityRuntime::TimeUtil::DefaultCurrentTimeStr().c_str());
7267     if (AppExecFwk::AppfreezeManager::GetInstance()->IsProcessDebug(pid, bundleName)) {
7268         TAG_LOGW(AAFwkTag::APPMGR, "don't report event and kill:%{public}s, pid:%{public}d, bundleName:%{public}s",
7269             eventName.c_str(), pid, bundleName.c_str());
7270         return ERR_OK;
7271     }
7272 
7273     if (faultData.faultType == FaultDataType::APP_FREEZE) {
7274         if (CheckAppFault(appRecord, faultData)) {
7275             return ERR_OK;
7276         }
7277 
7278         if (faultData.waitSaveState) {
7279             AppRecoveryNotifyApp(pid, bundleName, FaultDataType::APP_FREEZE, "recoveryTimeout");
7280         }
7281     }
7282     if (eventName == AppFreezeType::LIFECYCLE_TIMEOUT || eventName == AppFreezeType::APP_INPUT_BLOCK ||
7283         eventName == AppFreezeType::THREAD_BLOCK_6S || eventName == AppFreezeType::THREAD_BLOCK_3S ||
7284         eventName == AppFreezeType::BUSSINESS_THREAD_BLOCK_3S || eventName == AppFreezeType::BUSSINESS_THREAD_BLOCK_6S) {
7285         if (AppExecFwk::AppfreezeManager::GetInstance()->IsNeedIgnoreFreezeEvent(pid, eventName)) {
7286             TAG_LOGE(AAFwkTag::APPDFR, "appFreeze happend, pid:%{public}d, eventName:%{public}s",
7287                 pid, eventName.c_str());
7288             return ERR_OK;
7289         }
7290     }
7291 
7292     if (appRunningManager_ && eventName.find("THREAD_BLOCK_") != std::string::npos) {
7293         std::string appRunningUniqueId;
7294         int32_t ret = appRunningManager_->GetAppRunningUniqueIdByPid(pid, appRunningUniqueId);
7295         TAG_LOGI(AAFwkTag::APPDFR, "ret=%{public}d, appRunningUniqueId=%{public}s", ret, appRunningUniqueId.c_str());
7296         FaultData& nonConstFaultData = const_cast<FaultData&>(faultData);
7297         nonConstFaultData.appRunningUniqueId = appRunningUniqueId;
7298     }
7299 
7300     if (SubmitDfxFaultTask(faultData, bundleName, appRecord, pid) != ERR_OK) {
7301         return ERR_INVALID_VALUE;
7302     }
7303 
7304     if (appRecord->GetApplicationInfo()->asanEnabled) {
7305         TAG_LOGI(AAFwkTag::APPMGR, "asan enable, bundleName:%{public}s, pid:%{public}d", bundleName.c_str(), pid);
7306         return ERR_OK;
7307     }
7308 
7309 #ifdef APP_NO_RESPONSE_DIALOG
7310     // A dialog box is displayed when the PC appfreeze
7311     bool isDialogExist = appRunningManager_ ?
7312         appRunningManager_->CheckAppRunningRecordIsExist(APP_NO_RESPONSE_BUNDLENAME, APP_NO_RESPONSE_ABILITY) : false;
7313     auto killFaultApp = std::bind(&AppMgrServiceInner::KillFaultApp, this, pid, bundleName, faultData, false);
7314     ModalSystemAppFreezeUIExtension::GetInstance().ProcessAppFreeze(appRecord->GetFocusFlag(), faultData,
7315         std::to_string(pid), bundleName, killFaultApp, isDialogExist);
7316 #else
7317     KillFaultApp(pid, bundleName, faultData);
7318 #endif
7319 
7320     return ERR_OK;
7321 }
7322 
CheckAppFault(const std::shared_ptr<AppRunningRecord> & appRecord,const FaultData & faultData)7323 bool AppMgrServiceInner::CheckAppFault(const std::shared_ptr<AppRunningRecord> &appRecord, const FaultData &faultData)
7324 {
7325     if (faultData.timeoutMarkers != "" && !dfxTaskHandler_->CancelTask(faultData.timeoutMarkers)) {
7326         return true;
7327     }
7328 
7329     if (appRecord->IsDebugging()) {
7330         return true;
7331     }
7332     return false;
7333 }
7334 
KillFaultApp(int32_t pid,const std::string & bundleName,const FaultData & faultData,bool isNeedExit)7335 int32_t AppMgrServiceInner::KillFaultApp(int32_t pid, const std::string &bundleName, const FaultData &faultData,
7336     bool isNeedExit)
7337 {
7338     auto killAppTask = [pid, bundleName, faultData, isNeedExit, innerServiceWeak = weak_from_this()]() {
7339         auto innerService = innerServiceWeak.lock();
7340         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
7341         if (isNeedExit || (faultData.forceExit && !faultData.waitSaveState)) {
7342             TAG_LOGW(AAFwkTag::APPMGR, "faultData: %{public}s,pid: %{public}d will exit because %{public}s",
7343                 bundleName.c_str(), pid, innerService->FaultTypeToString(faultData.faultType).c_str());
7344             innerService->KillProcessByPid(pid, faultData.errorObject.name);
7345             return;
7346         }
7347     };
7348     constexpr int32_t waitTime = 3500;
7349     // wait 3.5s before kill application
7350     CHECK_POINTER_AND_RETURN_VALUE(taskHandler_, ERR_NO_INIT);
7351     taskHandler_->SubmitTaskJust(killAppTask, "killAppTask", waitTime);
7352     return ERR_OK;
7353 }
7354 
TimeoutNotifyApp(int32_t pid,int32_t uid,const std::string & bundleName,const std::string & processName,const FaultData & faultData)7355 void AppMgrServiceInner::TimeoutNotifyApp(int32_t pid, int32_t uid,
7356     const std::string& bundleName, const std::string& processName, const FaultData &faultData)
7357 {
7358     bool isNeedExit = (faultData.errorObject.name == AppFreezeType::APP_INPUT_BLOCK) ||
7359         (faultData.errorObject.name == AppFreezeType::LIFECYCLE_TIMEOUT);
7360 #ifdef APP_NO_RESPONSE_DIALOG
7361     bool isDialogExist = appRunningManager_ ?
7362         appRunningManager_->CheckAppRunningRecordIsExist(APP_NO_RESPONSE_BUNDLENAME, APP_NO_RESPONSE_ABILITY) :
7363         false;
7364     auto killFaultApp = std::bind(&AppMgrServiceInner::KillFaultApp, this, pid, bundleName, faultData, isNeedExit);
7365     ModalSystemAppFreezeUIExtension::GetInstance().ProcessAppFreeze(true, faultData, std::to_string(pid),
7366         bundleName, killFaultApp, isDialogExist);
7367 #else
7368     KillFaultApp(pid, bundleName, faultData, isNeedExit);
7369 #endif
7370     if (faultData.faultType == FaultDataType::APP_FREEZE) {
7371         AppfreezeManager::AppInfo info = {
7372             .pid = pid,
7373             .uid = uid,
7374             .bundleName = bundleName,
7375             .processName = processName,
7376         };
7377         AppExecFwk::AppfreezeManager::GetInstance()->AppfreezeHandleWithStack(faultData, info);
7378     }
7379 }
7380 
TransformedNotifyAppFault(const AppFaultDataBySA & faultData)7381 int32_t AppMgrServiceInner::TransformedNotifyAppFault(const AppFaultDataBySA &faultData)
7382 {
7383     int32_t pid = faultData.pid;
7384     auto record = GetAppRunningRecordByPid(pid);
7385     if (record == nullptr) {
7386         TAG_LOGE(AAFwkTag::APPMGR, "no such AppRunningRecord");
7387         return ERR_INVALID_VALUE;
7388     }
7389 
7390     FaultData transformedFaultData = ConvertDataTypes(faultData);
7391     int32_t uid = record->GetUid();
7392     std::string bundleName = record->GetBundleName();
7393     std::string processName = record->GetProcessName();
7394     if (AppExecFwk::AppfreezeManager::GetInstance()->IsProcessDebug(pid, bundleName)) {
7395         TAG_LOGW(AAFwkTag::APPMGR,
7396             "don't report event and kill:%{public}s, pid:%{public}d, bundleName:%{public}s.",
7397             faultData.errorObject.name.c_str(), pid, bundleName.c_str());
7398         return ERR_OK;
7399     }
7400     if (faultData.errorObject.name == "appRecovery") {
7401         AppRecoveryNotifyApp(pid, bundleName, faultData.faultType, "appRecovery");
7402         return ERR_OK;
7403     }
7404 
7405     if (transformedFaultData.timeoutMarkers.empty()) {
7406         transformedFaultData.timeoutMarkers = "notifyFault:" + transformedFaultData.errorObject.name +
7407             std::to_string(pid) + "-" + std::to_string(SystemTimeMillisecond());
7408     }
7409     const int64_t timeout = 1000;
7410     if (faultData.faultType == FaultDataType::APP_FREEZE) {
7411         if (!AppExecFwk::AppfreezeManager::GetInstance()->IsHandleAppfreeze(bundleName) || record->IsDebugging()) {
7412             return ERR_OK;
7413         }
7414         auto timeoutNotifyApp = [this, pid, uid, bundleName, processName, transformedFaultData]() {
7415             this->TimeoutNotifyApp(pid, uid, bundleName, processName, transformedFaultData);
7416         };
7417         dfxTaskHandler_->SubmitTask(timeoutNotifyApp, transformedFaultData.timeoutMarkers, timeout);
7418     }
7419     record->NotifyAppFault(transformedFaultData);
7420     TAG_LOGW(AAFwkTag::APPMGR, "FaultDataBySA is: name: %{public}s, faultType: %{public}s, uid: %{public}d,"
7421         "pid: %{public}d, bundleName: %{public}s, eventId: %{public}d", faultData.errorObject.name.c_str(),
7422         FaultTypeToString(faultData.faultType).c_str(), uid, pid, bundleName.c_str(), faultData.eventId);
7423     return ERR_OK;
7424 }
7425 
NotifyAppFaultBySA(const AppFaultDataBySA & faultData)7426 int32_t AppMgrServiceInner::NotifyAppFaultBySA(const AppFaultDataBySA &faultData)
7427 {
7428     if (remoteClientManager_ == nullptr) {
7429         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
7430         return ERR_NO_INIT;
7431     }
7432     std::string callerBundleName;
7433     if (auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); bundleMgrHelper != nullptr) {
7434         int32_t callingUid = IPCSkeleton::GetCallingUid();
7435         IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName));
7436     }
7437 #ifdef ABILITY_FAULT_AND_EXIT_TEST
7438     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) ||
7439         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
7440 #else
7441     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) || callerBundleName == SCENE_BOARD_BUNDLE_NAME) {
7442 #endif
7443         return TransformedNotifyAppFault(faultData);
7444     }
7445     TAG_LOGD(AAFwkTag::APPMGR, "this is not called by SA.");
7446     return AAFwk::CHECK_PERMISSION_FAILED;
7447 }
7448 
7449 bool AppMgrServiceInner::SetAppFreezeFilter(int32_t pid)
7450 {
7451     int32_t callingPid = IPCSkeleton::GetCallingPid();
7452     auto callerRecord = GetAppRunningRecordByPid(pid);
7453     if (callerRecord == nullptr) {
7454         TAG_LOGE(AAFwkTag::APPMGR, "callerRecord null");
7455         return false;
7456     }
7457     std::string bundleName = callerRecord->GetBundleName();
7458     if (callingPid == pid && AppExecFwk::AppfreezeManager::GetInstance()->IsValidFreezeFilter(pid, bundleName)) {
7459         bool result = AppExecFwk::AppfreezeManager::GetInstance()->CancelAppFreezeDetect(pid, bundleName);
7460         if (result) {
7461             auto resetAppfreezeTask = [pid, bundleName]() {
7462                 AppExecFwk::AppfreezeManager::GetInstance()->ResetAppfreezeState(pid, bundleName);
7463             };
7464             constexpr int32_t waitTime = 120000; // wait 2min
7465             CHECK_POINTER_AND_RETURN_VALUE(dfxTaskHandler_, false);
7466             dfxTaskHandler_->SubmitTaskJust(resetAppfreezeTask, "resetAppfreezeTask", waitTime);
7467         }
7468         TAG_LOGW(AAFwkTag::APPDFR, "SetAppFreezeFilter: %{public}d, bundleName=%{public}s, pid:%{public}d, ",
7469             result, bundleName.c_str(), pid);
7470         return result;
7471     }
7472     TAG_LOGE(AAFwkTag::APPDFR, "SetAppFreezeFilter: failed, pid %{public}d calling pid %{public}d "
7473         "bundleName %{public}s", pid, callingPid, bundleName.c_str());
7474     return false;
7475 }
7476 
7477 FaultData AppMgrServiceInner::ConvertDataTypes(const AppFaultDataBySA &faultData)
7478 {
7479     FaultData newfaultData;
7480     newfaultData.faultType = faultData.faultType;
7481     newfaultData.errorObject.message =
7482         "\nFault time:" + AbilityRuntime::TimeUtil::FormatTime("%Y/%m/%d-%H:%M:%S") + "\n";
7483     newfaultData.errorObject.message += faultData.errorObject.message;
7484     newfaultData.errorObject.name = faultData.errorObject.name;
7485     newfaultData.errorObject.stack = faultData.errorObject.stack;
7486     newfaultData.timeoutMarkers = faultData.timeoutMarkers;
7487     newfaultData.waitSaveState = faultData.waitSaveState;
7488     newfaultData.notifyApp = faultData.notifyApp;
7489     newfaultData.forceExit = faultData.forceExit;
7490     newfaultData.token = faultData.token;
7491     newfaultData.state = faultData.state;
7492     newfaultData.eventId = faultData.eventId;
7493     newfaultData.needKillProcess = faultData.needKillProcess;
7494     newfaultData.appfreezeInfo = faultData.appfreezeInfo;
7495     newfaultData.procStatm = faultData.procStatm;
7496     if (appRunningManager_) {
7497         std::string appRunningUniqueId;
7498         int32_t ret = appRunningManager_->GetAppRunningUniqueIdByPid(faultData.pid, appRunningUniqueId);
7499         TAG_LOGI(AAFwkTag::APPDFR, "ret=%{public}d, appRunningUniqueId=%{public}s", ret, appRunningUniqueId.c_str());
7500         newfaultData.appRunningUniqueId = appRunningUniqueId;
7501     }
7502     return newfaultData;
7503 }
7504 
7505 std::string AppMgrServiceInner::FaultTypeToString(AppExecFwk::FaultDataType type)
7506 {
7507     std::string typeStr = "UNKNOWN";
7508     switch (type) {
7509         case AppExecFwk::FaultDataType::CPP_CRASH:
7510             typeStr = "CPP_CRASH";
7511             break;
7512         case AppExecFwk::FaultDataType::JS_ERROR:
7513             typeStr = "JS_ERROR";
7514             break;
7515         case AppExecFwk::FaultDataType::APP_FREEZE:
7516             typeStr = "APP_FREEZE";
7517             break;
7518         case AppExecFwk::FaultDataType::PERFORMANCE_CONTROL:
7519             typeStr = "PERFORMANCE_CONTROL";
7520             break;
7521         case AppExecFwk::FaultDataType::RESOURCE_CONTROL:
7522             typeStr = "RESOURCE_CONTROL";
7523             break;
7524         default:
7525             break;
7526     }
7527     return typeStr;
7528 }
7529 
7530 bool AppMgrServiceInner::IsSharedBundleRunning(const std::string &bundleName, uint32_t versionCode)
7531 {
7532     if (!CheckGetRunningInfoPermission()) {
7533         return false;
7534     }
7535 
7536     std::lock_guard lock(runningSharedBundleListMutex_);
7537     for (const auto &it : runningSharedBundleList_) {
7538         for (const auto &item : it.second) {
7539             if (item.bundleName == bundleName && item.versionCode == versionCode) {
7540                 return true;
7541             }
7542         }
7543     }
7544     return false;
7545 }
7546 
7547 int32_t AppMgrServiceInner::IsApplicationRunning(const std::string &bundleName, bool &isRunning)
7548 {
7549     TAG_LOGD(AAFwkTag::APPMGR, "Called, bundleName: %{public}s", bundleName.c_str());
7550     CHECK_CALLER_IS_SYSTEM_APP;
7551     if (!CheckGetRunningInfoPermission()) {
7552         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
7553         return ERR_PERMISSION_DENIED;
7554     }
7555 
7556     return appRunningManager_->CheckAppCloneRunningRecordIsExistByBundleName(bundleName, 0, isRunning);
7557 }
7558 
7559 int32_t AppMgrServiceInner::IsAppRunning(const std::string &bundleName, int32_t appCloneIndex,
7560     bool &isRunning)
7561 {
7562     TAG_LOGD(AAFwkTag::APPMGR, "Called, bundleName: %{public}s", bundleName.c_str());
7563     if (!CheckGetRunningInfoPermission()) {
7564         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
7565         return ERR_PERMISSION_DENIED;
7566     }
7567     if (appCloneIndex < 0 || appCloneIndex > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
7568         TAG_LOGE(AAFwkTag::APPMGR, "appCloneIndex invalid");
7569         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
7570     }
7571     if (remoteClientManager_ == nullptr) {
7572         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager null");
7573         return ERR_INVALID_OPERATION;
7574     }
7575     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
7576     if (bundleMgrHelper == nullptr) {
7577         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
7578         return ERR_INVALID_OPERATION;
7579     }
7580     BundleInfo bundleInfo;
7581     auto userId = GetCurrentAccountId();
7582     int32_t bundleMgrResult;
7583     if (appCloneIndex == 0) {
7584         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfoV9(bundleName,
7585             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) |
7586             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) |
7587             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) |
7588             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION), bundleInfo, userId));
7589     } else {
7590         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetCloneBundleInfo(bundleName,
7591             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
7592             appCloneIndex, bundleInfo, userId));
7593     }
7594 
7595     if (bundleMgrResult != ERR_OK) {
7596         TAG_LOGE(AAFwkTag::APPMGR, "query bundleInfo fail");
7597         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
7598     }
7599 
7600     return appRunningManager_->CheckAppCloneRunningRecordIsExistByBundleName(bundleName, appCloneIndex, isRunning);
7601 }
7602 
7603 int32_t AppMgrServiceInner::IsAppRunningByBundleNameAndUserId(const std::string &bundleName, int32_t userId,
7604     bool &isRunning)
7605 {
7606     TAG_LOGD(AAFwkTag::APPMGR, "Called, bundleName=%{public}s,userId=%{public}d", bundleName.c_str(), userId);
7607     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
7608         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
7609         return ERR_PERMISSION_DENIED;
7610     }
7611 
7612     if (appRunningManager_ == nullptr) {
7613         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
7614         return ERR_NO_INIT;
7615     }
7616 
7617     if (userId < 0) {
7618         userId = GetCurrentAccountId();
7619     }
7620 
7621     return appRunningManager_->IsAppRunningByBundleNameAndUserId(bundleName, userId, isRunning);
7622 }
7623 
7624 bool AppMgrServiceInner::CreateAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo)
7625 {
7626     auto&& bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
7627     if (!bundleMgrHelper) {
7628         TAG_LOGE(AAFwkTag::APPMGR, "get bundle manager helper error");
7629         return false;
7630     }
7631     auto userId = GetCurrentAccountId();
7632     auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
7633     if (IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(want, abilityInfoFlag, userId, abilityInfo))) {
7634         TAG_LOGI(AAFwkTag::APPMGR, "queryAbilityInfo ok");
7635         return true;
7636     }
7637     std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
7638     int32_t appIndex = want.GetIntParam(AppspawnUtil::DLP_PARAMS_INDEX, 0);
7639     if (appIndex == 0) {
7640         if (!IN_PROCESS_CALL(bundleMgrHelper->QueryExtensionAbilityInfos(want, abilityInfoFlag,
7641             userId, extensionInfos))) {
7642             TAG_LOGE(AAFwkTag::APPMGR, "queryExtensionAbilityInfos fail");
7643             return false;
7644         }
7645     } else {
7646         if (!IN_PROCESS_CALL(bundleMgrHelper->GetSandboxExtAbilityInfos(want, appIndex,
7647             abilityInfoFlag, userId, extensionInfos))) {
7648             TAG_LOGE(AAFwkTag::APPMGR, "getSandboxExtAbilityInfos fail");
7649             return false;
7650         }
7651     }
7652     if (extensionInfos.size() <= 0) {
7653         TAG_LOGE(AAFwkTag::APPMGR, "get extension info fail");
7654         return ERR_INVALID_OPERATION;
7655     }
7656     AppExecFwk::ExtensionAbilityInfo extensionInfo = extensionInfos.front();
7657     AbilityRuntime::StartupUtil::InitAbilityInfoFromExtension(extensionInfo, abilityInfo);
7658     return true;
7659 }
7660 
7661 int32_t AppMgrServiceInner::StartNativeProcessForDebugger(const AAFwk::Want &want)
7662 {
7663     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_INVALID_OPERATION);
7664     TAG_LOGI(AAFwkTag::APPMGR, "bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
7665         want.GetElement().GetBundleName().c_str(), want.GetElement().GetModuleName().c_str(),
7666         want.GetElement().GetAbilityName().c_str());
7667     AbilityInfo abilityInfo;
7668     if (!CreateAbilityInfo(want, abilityInfo)) {
7669         TAG_LOGE(AAFwkTag::APPMGR, "createAbilityInfo fail");
7670         return ERR_INVALID_OPERATION;
7671     }
7672     BundleInfo bundleInfo;
7673     HapModuleInfo hapModuleInfo;
7674     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
7675     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, 0)) {
7676         TAG_LOGE(AAFwkTag::APPMGR, "getBundleAndHapInfo fail");
7677         return ERR_INVALID_OPERATION;
7678     }
7679 
7680     std::string processName;
7681     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
7682     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, 0, "", processName, false);
7683     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
7684         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
7685         return ERR_INVALID_OPERATION;
7686     }
7687     auto&& appRecord =
7688         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
7689     AppSpawnStartMsg startMsg;
7690     bool isDevelopeMode = system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
7691     if (appRecord) {
7692         startMsg = appRecord->GetStartMsg();
7693     } else if (!isDevelopeMode || CreatNewStartMsg(want, abilityInfo, appInfo, processName, startMsg) != ERR_OK) {
7694         TAG_LOGE(AAFwkTag::APPMGR, "invalid Operation");
7695         return ERR_INVALID_OPERATION;
7696     }
7697 
7698     bool isSandboxApp = want.GetBoolParam(ENTER_SANDBOX, false);
7699     auto&& pefCmd = want.GetStringParam(PERF_CMD);
7700     std::string debugCmd = "";
7701     if (pefCmd.empty()) {
7702         if (!appInfo->debug) {
7703             TAG_LOGE(AAFwkTag::APPMGR, "app don't debug mode");
7704             return ERR_INVALID_OPERATION;
7705         }
7706         debugCmd = want.GetStringParam(DEBUG_CMD);
7707     }
7708     return StartPerfProcessByStartMsg(startMsg, pefCmd, debugCmd, isSandboxApp);
7709 }
7710 
7711 int32_t AppMgrServiceInner::GetCurrentAccountId() const
7712 {
7713     std::vector<int32_t> osActiveAccountIds;
7714     ErrCode ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
7715         QueryActiveOsAccountIds(osActiveAccountIds);
7716     if (ret != ERR_OK) {
7717         TAG_LOGE(AAFwkTag::APPMGR, "queryActiveOsAccountIds fail");
7718         return DEFAULT_USER_ID;
7719     }
7720     if (osActiveAccountIds.empty()) {
7721         TAG_LOGE(AAFwkTag::APPMGR, "queryActiveOsAccountIds empty");
7722         return DEFAULT_USER_ID;
7723     }
7724     TAG_LOGD(AAFwkTag::APPMGR, "osActiveAccountId: %{public}d", osActiveAccountIds.front());
7725     return osActiveAccountIds.front();
7726 }
7727 
7728 void AppMgrServiceInner::SetRunningSharedBundleList(const std::string &bundleName,
7729     const std::vector<BaseSharedBundleInfo> baseSharedBundleInfoList)
7730 {
7731     std::lock_guard lock(runningSharedBundleListMutex_);
7732     runningSharedBundleList_.try_emplace(bundleName, baseSharedBundleInfoList);
7733 }
7734 
7735 void AppMgrServiceInner::RemoveRunningSharedBundleList(const std::string &bundleName)
7736 {
7737     std::lock_guard lock(runningSharedBundleListMutex_);
7738     auto iterator = runningSharedBundleList_.find(bundleName);
7739     if (iterator == runningSharedBundleList_.end()) {
7740         return;
7741     }
7742     runningSharedBundleList_.erase(iterator);
7743 }
7744 
7745 void AppMgrServiceInner::SetCurrentUserId(const int32_t userId)
7746 {
7747     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
7748         return;
7749     }
7750     TAG_LOGD(AAFwkTag::APPMGR, "set current userId: %{public}d", userId);
7751     currentUserId_ = userId;
7752 }
7753 
7754 void AppMgrServiceInner::SetEnableStartProcessFlagByUserId(int32_t userId, bool enableStartProcess)
7755 {
7756     UserRecordManager::GetInstance().SetEnableStartProcessFlagByUserId(userId, enableStartProcess);
7757 }
7758 
7759 int32_t AppMgrServiceInner::GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid)
7760 {
7761     TAG_LOGD(AAFwkTag::APPMGR, "called");
7762     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
7763         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
7764         return ERR_PERMISSION_DENIED;
7765     }
7766     auto callerRecord = GetAppRunningRecordByPid(pid);
7767     if (callerRecord == nullptr) {
7768         TAG_LOGE(AAFwkTag::APPMGR, "callerRecord null");
7769         return ERR_INVALID_OPERATION;
7770     }
7771     bundleName = callerRecord->GetBundleName();
7772     uid = callerRecord->GetUid();
7773     return ERR_OK;
7774 }
7775 
7776 void AppMgrServiceInner::KillRenderProcess(const std::shared_ptr<AppRunningRecord> &appRecord) {
7777     if (appRecord == nullptr) {
7778         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
7779         return;
7780     }
7781     auto renderRecordMap = appRecord->GetRenderRecordMap();
7782     if (!renderRecordMap.empty()) {
7783         for (auto iter : renderRecordMap) {
7784             auto renderRecord = iter.second;
7785             if (renderRecord && renderRecord->GetPid() > 0) {
7786                 auto pid = renderRecord->GetPid();
7787                 auto uid = renderRecord->GetUid();
7788                 TAG_LOGI(AAFwkTag::APPMGR, "pid:%{public}d, uid:%{public}d",
7789                     pid, uid);
7790                 KillProcessByPid(pid, "KillRenderProcess");
7791                 {
7792                     std::lock_guard lock(renderUidSetLock_);
7793                     renderUidSet_.erase(uid);
7794                 }
7795                 DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
7796             }
7797         }
7798     }
7799 }
7800 
7801 int32_t AppMgrServiceInner::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize)
7802 {
7803     CHECK_CALLER_IS_SYSTEM_APP;
7804     uint64_t memSize = OHOS::MemInfo::GetPssByPid(pid);
7805     memorySize = static_cast<int32_t>(memSize);
7806     return ERR_OK;
7807 }
7808 
7809 int32_t AppMgrServiceInner::GetRunningProcessInformation(
7810     const std::string &bundleName, int32_t userId, std::vector<RunningProcessInfo> &info)
7811 {
7812     CHECK_CALLER_IS_SYSTEM_APP;
7813     if (!appRunningManager_) {
7814         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
7815         return ERR_NO_INIT;
7816     }
7817 
7818     if (remoteClientManager_ == nullptr) {
7819         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
7820         return ERR_NO_INIT;
7821     }
7822     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
7823     if (bundleMgrHelper == nullptr) {
7824         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
7825         return ERR_NO_INIT;
7826     }
7827     TAG_LOGI(AAFwkTag::APPMGR, "uid value: %{public}d", userId);
7828     const auto &appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
7829     for (const auto &item : appRunningRecordMap) {
7830         const auto &appRecord = item.second;
7831         if (appRecord == nullptr) {
7832             continue;
7833         }
7834         if (GetUserIdByUid(appRecord->GetUid()) != userId) {
7835             continue;
7836         }
7837         auto appInfoList = appRecord->GetAppInfoList();
7838         for (const auto &appInfo : appInfoList) {
7839             if (appInfo == nullptr) {
7840                 continue;
7841             }
7842             if (appInfo->bundleName == bundleName) {
7843                 GetRunningProcesses(appRecord, info);
7844                 break;
7845             }
7846         }
7847     }
7848     return ERR_OK;
7849 }
7850 
7851 int32_t AppMgrServiceInner::ChangeAppGcState(pid_t pid, int32_t state, uint64_t tid)
7852 {
7853     auto callerUid = IPCSkeleton::GetCallingUid();
7854     TAG_LOGD(AAFwkTag::APPMGR, "called, pid:%{public}d, state:%{public}d, uid:%{public}d.", pid, state, callerUid);
7855     if (callerUid != RESOURCE_MANAGER_UID) { // The current UID for resource management is 1096
7856         TAG_LOGE(AAFwkTag::APPMGR, "caller is not resource manager");
7857         return ERR_INVALID_VALUE;
7858     }
7859     auto appRecord = GetAppRunningRecordByPid(pid);
7860     if (!appRecord) {
7861         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord");
7862         return ERR_INVALID_VALUE;
7863     }
7864     return appRecord->ChangeAppGcState(state, tid);
7865 }
7866 
7867 int32_t AppMgrServiceInner::RegisterAppDebugListener(const sptr<IAppDebugListener> &listener)
7868 {
7869     TAG_LOGD(AAFwkTag::APPMGR, "called");
7870     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
7871         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
7872         return ERR_PERMISSION_DENIED;
7873     }
7874 
7875     if (appDebugManager_ == nullptr) {
7876         TAG_LOGE(AAFwkTag::APPMGR, "appDebugManager_ null");
7877         return ERR_NO_INIT;
7878     }
7879     return appDebugManager_->RegisterAppDebugListener(listener);
7880 }
7881 
7882 int32_t AppMgrServiceInner::UnregisterAppDebugListener(const sptr<IAppDebugListener> &listener)
7883 {
7884     TAG_LOGD(AAFwkTag::APPMGR, "called");
7885     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
7886         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
7887         return ERR_PERMISSION_DENIED;
7888     }
7889 
7890     if (appDebugManager_ == nullptr) {
7891         TAG_LOGE(AAFwkTag::APPMGR, "appDebugManager_ null");
7892         return ERR_NO_INIT;
7893     }
7894     return appDebugManager_->UnregisterAppDebugListener(listener);
7895 }
7896 
7897 int32_t AppMgrServiceInner::AttachAppDebug(const std::string &bundleName, bool isDebugFromLocal)
7898 {
7899     TAG_LOGD(AAFwkTag::APPMGR, "called");
7900     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
7901         TAG_LOGE(AAFwkTag::APPMGR, "developer mode false");
7902         return ERR_INVALID_OPERATION;
7903     }
7904 
7905     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
7906         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
7907         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
7908         return ERR_PERMISSION_DENIED;
7909     }
7910 
7911     if (appRunningManager_ == nullptr) {
7912         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
7913         return ERR_NO_INIT;
7914     }
7915     appRunningManager_->SetAttachAppDebug(bundleName, true, isDebugFromLocal);
7916 
7917     auto debugInfos = appRunningManager_->GetAppDebugInfosByBundleName(bundleName, false);
7918     if (!debugInfos.empty() && appDebugManager_ != nullptr) {
7919         appDebugManager_->StartDebug(debugInfos);
7920     }
7921 
7922     NotifyAbilitiesDebugChange(bundleName, true);
7923     return ERR_OK;
7924 }
7925 
7926 int32_t AppMgrServiceInner::DetachAppDebug(const std::string &bundleName)
7927 {
7928     TAG_LOGD(AAFwkTag::APPMGR, "called");
7929     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
7930         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
7931         TAG_LOGE(AAFwkTag::APPMGR, "permission verification fail");
7932         return ERR_PERMISSION_DENIED;
7933     }
7934 
7935     if (appRunningManager_ == nullptr) {
7936         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
7937         return ERR_NO_INIT;
7938     }
7939 
7940     auto debugInfos = appRunningManager_->GetAppDebugInfosByBundleName(bundleName, true);
7941     if (!debugInfos.empty()) {
7942         appRunningManager_->SetAttachAppDebug(bundleName, false, false);
7943         if (appDebugManager_ != nullptr) {
7944             appDebugManager_->StopDebug(debugInfos);
7945         }
7946     }
7947 
7948     NotifyAbilitiesDebugChange(bundleName, false);
7949     return ERR_OK;
7950 }
7951 
7952 int32_t AppMgrServiceInner::SetAppWaitingDebug(const std::string &bundleName, bool isPersist)
7953 {
7954     TAG_LOGI(AAFwkTag::APPMGR, "SetWaitDebug bundlename %{public}s, persist %{public}d", bundleName.c_str(), isPersist);
7955     if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
7956         TAG_LOGE(AAFwkTag::APPMGR, "not shell call");
7957         return ERR_PERMISSION_DENIED;
7958     }
7959 
7960     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
7961         TAG_LOGE(AAFwkTag::APPMGR, "developer mode false");
7962         return AAFwk::ERR_NOT_DEVELOPER_MODE;
7963     }
7964 
7965     if (bundleName.empty()) {
7966         TAG_LOGE(AAFwkTag::APPMGR, "bundle name empty");
7967         return ERR_INVALID_VALUE;
7968     }
7969 
7970     if (!CheckIsDebugApp(bundleName)) {
7971         TAG_LOGE(AAFwkTag::APPMGR, "is not debug app");
7972         return AAFwk::ERR_NOT_DEBUG_APP;
7973     }
7974 
7975     InitAppWaitingDebugList();
7976 
7977     bool isClear = false;
7978     {
7979         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
7980         if (!waitingDebugBundleList_.empty()) {
7981             waitingDebugBundleList_.clear();
7982             isClear = true;
7983         }
7984     }
7985     if (isClear) {
7986         DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->ClearAppWaitingDebugInfo();
7987     }
7988 
7989     {
7990         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
7991         waitingDebugBundleList_.try_emplace(bundleName, isPersist);
7992     }
7993     if (isPersist) {
7994         return DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->SetAppWaitingDebugInfo(
7995             bundleName);
7996     }
7997     return ERR_OK;
7998 }
7999 
8000 int32_t AppMgrServiceInner::CancelAppWaitingDebug()
8001 {
8002     TAG_LOGD(AAFwkTag::APPMGR, "called");
8003     if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
8004         TAG_LOGE(AAFwkTag::APPMGR, "not shell call");
8005         return ERR_PERMISSION_DENIED;
8006     }
8007 
8008     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
8009         TAG_LOGE(AAFwkTag::APPMGR, "developer mode false");
8010         return AAFwk::ERR_NOT_DEVELOPER_MODE;
8011     }
8012 
8013     {
8014         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
8015         waitingDebugBundleList_.clear();
8016     }
8017     return DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->ClearAppWaitingDebugInfo();
8018 }
8019 
8020 int32_t AppMgrServiceInner::GetWaitingDebugApp(std::vector<std::string> &debugInfoList)
8021 {
8022     TAG_LOGD(AAFwkTag::APPMGR, "called");
8023     if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
8024         TAG_LOGE(AAFwkTag::APPMGR, "not shell call");
8025         return ERR_PERMISSION_DENIED;
8026     }
8027 
8028     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
8029         TAG_LOGE(AAFwkTag::APPMGR, "developer mode false");
8030         return AAFwk::ERR_NOT_DEVELOPER_MODE;
8031     }
8032 
8033     InitAppWaitingDebugList();
8034 
8035     std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
8036     if (waitingDebugBundleList_.empty()) {
8037         TAG_LOGD(AAFwkTag::APPMGR, "The waiting debug bundle list is empty.");
8038         return ERR_OK;
8039     }
8040 
8041     for (const auto &item : waitingDebugBundleList_) {
8042         std::string debugBundleInfo;
8043         debugBundleInfo.append("bundle name : ").append(item.first).append(", persist : ")
8044             .append(item.second ? "true" : "false");
8045         debugInfoList.emplace_back(debugBundleInfo);
8046     }
8047     return ERR_OK;
8048 }
8049 
8050 void AppMgrServiceInner::InitAppWaitingDebugList()
8051 {
8052     TAG_LOGD(AAFwkTag::APPMGR, "called");
8053     {
8054         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
8055         if (isInitAppWaitingDebugListExecuted_) {
8056             TAG_LOGD(AAFwkTag::APPMGR, "No need to initialize again.");
8057             return;
8058         }
8059         isInitAppWaitingDebugListExecuted_ = true;
8060     }
8061 
8062     std::vector<std::string> bundleNameList;
8063     DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->GetAppWaitingDebugList(bundleNameList);
8064     if (!bundleNameList.empty()) {
8065         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
8066         for (const auto &item : bundleNameList) {
8067             waitingDebugBundleList_.try_emplace(item, true);
8068         }
8069     }
8070 }
8071 
8072 bool AppMgrServiceInner::CheckIsDebugApp(const std::string &bundleName)
8073 {
8074     TAG_LOGD(AAFwkTag::APPMGR, "called");
8075     CHECK_POINTER_AND_RETURN_VALUE(remoteClientManager_, false);
8076     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
8077     CHECK_POINTER_AND_RETURN_VALUE(bundleMgrHelper, false);
8078 
8079     BundleInfo bundleInfo;
8080     auto ret = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfoV9(bundleName,
8081         static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION), bundleInfo, currentUserId_));
8082     if (ret != ERR_OK) {
8083         TAG_LOGE(AAFwkTag::APPMGR, "getBundleInfo fail");
8084         return false;
8085     }
8086 
8087     return bundleInfo.applicationInfo.debug &&
8088            (bundleInfo.applicationInfo.appProvisionType == AppExecFwk::Constants::APP_PROVISION_TYPE_DEBUG);
8089 }
8090 
8091 bool AppMgrServiceInner::IsWaitingDebugApp(const std::string &bundleName)
8092 {
8093     TAG_LOGD(AAFwkTag::APPMGR, "called");
8094 
8095     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
8096         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
8097         return false;
8098     }
8099     return IsWaitingDebugAppInner(bundleName);
8100 }
8101 
8102 bool AppMgrServiceInner::IsWaitingDebugAppInner(const std::string &bundleName)
8103 {
8104     TAG_LOGD(AAFwkTag::APPMGR, "called");
8105     InitAppWaitingDebugList();
8106 
8107     std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
8108     if (waitingDebugBundleList_.empty()) {
8109         TAG_LOGD(AAFwkTag::APPMGR, "The waiting debug bundles list is empty.");
8110         return false;
8111     }
8112 
8113     for (const auto &item : waitingDebugBundleList_) {
8114         if (item.first == bundleName) {
8115             TAG_LOGI(AAFwkTag::APPMGR, "bundlename %{public}s isWaitingDebug", bundleName.c_str());
8116             return true;
8117         }
8118     }
8119     return false;
8120 }
8121 
8122 void AppMgrServiceInner::ClearNonPersistWaitingDebugFlag()
8123 {
8124     TAG_LOGD(AAFwkTag::APPMGR, "called");
8125 
8126     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
8127         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
8128         return;
8129     }
8130 
8131     bool isClear = false;
8132     {
8133         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
8134         for (const auto &item : waitingDebugBundleList_) {
8135             if (!item.second) {
8136                 isClear = true;
8137                 break;
8138             }
8139         }
8140         if (isClear) {
8141             waitingDebugBundleList_.clear();
8142         }
8143     }
8144 
8145     if (isClear) {
8146         DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->ClearAppWaitingDebugInfo();
8147     }
8148 }
8149 
8150 int32_t AppMgrServiceInner::RegisterAbilityDebugResponse(const sptr<IAbilityDebugResponse> &response)
8151 {
8152     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
8153         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
8154         return ERR_PERMISSION_DENIED;
8155     }
8156     if (response == nullptr) {
8157         TAG_LOGE(AAFwkTag::APPMGR, "response null");
8158         return ERR_INVALID_VALUE;
8159     }
8160 
8161     abilityDebugResponse_ = response;
8162     return ERR_OK;
8163 }
8164 
8165 int32_t AppMgrServiceInner::NotifyAbilitiesDebugChange(const std::string &bundleName, const bool &isAppDebug)
8166 {
8167     if (appRunningManager_ == nullptr || abilityDebugResponse_ == nullptr) {
8168         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ or abilityDebugResponse null");
8169         return ERR_NO_INIT;
8170     }
8171 
8172     std::vector<sptr<IRemoteObject>> tokens;
8173     appRunningManager_->GetAbilityTokensByBundleName(bundleName, tokens);
8174     if (!tokens.empty()) {
8175         isAppDebug ? abilityDebugResponse_->OnAbilitysDebugStarted(tokens) :
8176             abilityDebugResponse_->OnAbilitysDebugStoped(tokens);
8177     }
8178     return ERR_OK;
8179 }
8180 
8181 int32_t AppMgrServiceInner::NotifyAbilitiesAssertDebugChange(
8182     const std::shared_ptr<AppRunningRecord> &appRecord, bool isAssertDebug)
8183 {
8184     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
8185     if (appRecord == nullptr || abilityDebugResponse_ == nullptr) {
8186         TAG_LOGE(AAFwkTag::APPMGR, "record or abilityDebugResponse null");
8187         return ERR_NO_INIT;
8188     }
8189 
8190     std::vector<sptr<IRemoteObject>> abilityTokens;
8191     auto abilities = appRecord->GetAbilities();
8192     for (const auto &token : abilities) {
8193         abilityTokens.emplace_back(token.first);
8194     }
8195 
8196     if (!abilityTokens.empty()) {
8197         abilityDebugResponse_->OnAbilitysAssertDebugChange(abilityTokens, isAssertDebug);
8198     }
8199     return ERR_OK;
8200 }
8201 
8202 bool AppMgrServiceInner::IsAttachDebug(const std::string &bundleName)
8203 {
8204     TAG_LOGD(AAFwkTag::APPMGR, "called");
8205     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
8206     if (!isSaCall) {
8207         TAG_LOGE(AAFwkTag::APPMGR, "caller token not SA");
8208         return false;
8209     }
8210     if (appRunningManager_ == nullptr || bundleName.empty()) {
8211         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ or bundleName null");
8212         return false;
8213     }
8214     return appDebugManager_->IsAttachDebug(bundleName);
8215 }
8216 
8217 void AppMgrServiceInner::ApplicationTerminatedSendProcessEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
8218 {
8219     if (appRecord == nullptr) {
8220         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
8221         return;
8222     }
8223 
8224     OnProcessDied(appRecord);
8225     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
8226     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
8227         RemoveRunningSharedBundleList(appRecord->GetBundleName());
8228     }
8229 
8230     if (appRunningManager_ == nullptr) {
8231         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
8232         return;
8233     }
8234     auto appInfo = appRecord->GetApplicationInfo();
8235     if (appInfo != nullptr && !appRunningManager_->IsAppExist(appInfo->accessTokenId)) {
8236         OnAppStopped(appRecord);
8237     }
8238 
8239     if (appDebugManager_ == nullptr) {
8240         TAG_LOGE(AAFwkTag::APPMGR, "debug manager null");
8241         return;
8242     }
8243     auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
8244     appDebugManager_->RemoveAppDebugInfo(info);
8245 
8246     TAG_LOGD(AAFwkTag::APPMGR, "Application is terminated.");
8247     SendProcessExitEvent(appRecord);
8248 }
8249 
8250 void AppMgrServiceInner::SubscribeScreenOffEvent()
8251 {
8252     TAG_LOGD(AAFwkTag::APPMGR, "called");
8253     EventFwk::MatchingSkills matchingSkills;
8254     matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
8255     EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills);
8256     subscribeInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON);
8257     auto callback = [innerServiceWeak = weak_from_this()]() {
8258         auto innerService = innerServiceWeak.lock();
8259         CHECK_POINTER_AND_RETURN_LOG(innerService, "on screen off");
8260         std::vector<ExitResidentProcessInfo> exitProcessInfos;
8261         if (ExitResidentProcessManager::GetInstance().HandleNoRequireBigMemoryOptimization(exitProcessInfos) ==
8262             ERR_OK && !exitProcessInfos.empty()) {
8263             std::vector<AppExecFwk::BundleInfo> exitBundleInfos;
8264             ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(exitProcessInfos, exitBundleInfos);
8265             innerService->NotifyStartResidentProcess(exitBundleInfos);
8266             innerService->NotifyStartKeepAliveProcess(exitBundleInfos);
8267         } else {
8268             TAG_LOGE(AAFwkTag::APPMGR, "HandleNoRequireBigMemoryOptimization fail");
8269         }
8270         auto unSubscribeScreenOffEvent = [innerService]() {
8271             innerService->UnSubscribeScreenOffEvent();
8272         };
8273         ffrt::submit(std::move(unSubscribeScreenOffEvent),
8274             ffrt::task_attr().timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
8275     };
8276     std::lock_guard<std::mutex> lock(screenOffSubscriberMutex_);
8277     if (screenOffSubscriber_ != nullptr) {
8278         TAG_LOGE(AAFwkTag::APPMGR, "don't repeat subscribe screen off event.");
8279         return;
8280     }
8281     screenOffSubscriber_ = std::make_shared<AppExecFwk::AppMgrEventSubscriber>(subscribeInfo, callback);
8282     bool subResult = EventFwk::CommonEventManager::SubscribeCommonEvent(screenOffSubscriber_);
8283     if (!subResult) {
8284         TAG_LOGE(AAFwkTag::APPMGR, "subscribe screen off failed");
8285     }
8286 }
8287 
8288 void AppMgrServiceInner::UnSubscribeScreenOffEvent()
8289 {
8290     TAG_LOGD(AAFwkTag::APPMGR, "called");
8291     std::lock_guard<std::mutex> lock(screenOffSubscriberMutex_);
8292     bool subResult = EventFwk::CommonEventManager::UnSubscribeCommonEvent(screenOffSubscriber_);
8293     screenOffSubscriber_ = nullptr;
8294     TAG_LOGD(AAFwkTag::APPMGR, "Screen off event subscriber unsubscribe result is %{public}d.", subResult);
8295 }
8296 
8297 bool AppMgrServiceInner::IsNeedRestartKeepAliveProcess(const std::string &bundleName, int32_t uid)
8298 {
8299     if (ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(bundleName)) {
8300         TAG_LOGI(AAFwkTag::APPMGR, "is killed for upgrade web");
8301         return false;
8302     }
8303 
8304     if (!AAFwk::AppUtils::GetInstance().IsAllowResidentInExtremeMemory(bundleName) &&
8305         ExitResidentProcessManager::GetInstance().RecordExitResidentBundleName(bundleName, uid)) {
8306         TAG_LOGI(AAFwkTag::APPMGR, "memory size insufficient");
8307         return false;
8308     }
8309 
8310     if (AAFwk::AppUtils::GetInstance().IsBigMemoryUnrelatedKeepAliveProc(bundleName) &&
8311         ExitResidentProcessManager::GetInstance().RecordExitResidentBundleNameOnRequireBigMemory(bundleName, uid)) {
8312         TAG_LOGI(AAFwkTag::APPMGR, "required big memory %{public}s.", bundleName.c_str());
8313         return false;
8314     }
8315     return true;
8316 }
8317 
8318 void AppMgrServiceInner::ClearAppRunningDataForKeepAlive(const std::shared_ptr<AppRunningRecord> &appRecord)
8319 {
8320     ClearResidentProcessAppRunningData(appRecord);
8321     ClearNonResidentKeepAliveAppRunningData(appRecord);
8322 }
8323 
8324 void AppMgrServiceInner::ClearResidentProcessAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord)
8325 {
8326     if (appRecord == nullptr) {
8327         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
8328         return;
8329     }
8330     auto userId = GetUserIdByUid(appRecord->GetUid());
8331     if (appRecord->IsKeepAliveApp() && (userId == 0 || userId == currentUserId_) &&
8332         appRecord->GetBundleName() != SCENE_BOARD_BUNDLE_NAME) {
8333         if (!IsNeedRestartKeepAliveProcess(appRecord->GetBundleName(), appRecord->GetUid())) {
8334             return;
8335         }
8336         TAG_LOGI(AAFwkTag::APPMGR, "memory size sufficient");
8337         auto restartProcess = [appRecord, innerService = shared_from_this()]() {
8338             innerService->RestartResidentProcess(appRecord);
8339         };
8340         if (taskHandler_ == nullptr) {
8341             TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
8342             return;
8343         }
8344         if (appRecord->CanRestartResidentProc()) {
8345             taskHandler_->SubmitTask(restartProcess, "RestartResidentProcess");
8346         } else {
8347             auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
8348                 return (appRecord != nullptr && appRunningRecord != nullptr &&
8349                         appRecord->GetBundleName() == appRunningRecord->GetBundleName());
8350             };
8351             {
8352                 std::lock_guard guard(restartResidentTaskListMutex_);
8353                 auto findIter = find_if(restartResidentTaskList_.begin(),
8354                     restartResidentTaskList_.end(),
8355                     findRestartResidentTask);
8356                 if (findIter != restartResidentTaskList_.end()) {
8357                     TAG_LOGW(AAFwkTag::APPMGR, "reboot task already registered");
8358                     return;
8359                 }
8360                 restartResidentTaskList_.emplace_back(appRecord);
8361             }
8362             TAG_LOGD(AAFwkTag::APPMGR, "Post restart resident process delay task.");
8363             taskHandler_->SubmitTaskJust(restartProcess, "RestartResidentProcessDelayTask", RESTART_INTERVAL_TIME);
8364         }
8365     }
8366 }
8367 
8368 void AppMgrServiceInner::ClearNonResidentKeepAliveAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord)
8369 {
8370     if (appRecord == nullptr) {
8371         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
8372         return;
8373     }
8374 
8375     auto userId = GetUserIdByUid(appRecord->GetUid());
8376     bool isDefaultInstance = appRecord->GetInstanceKey().empty() || appRecord->GetInstanceKey() == APP_INSTANCE_KEY_0;
8377     if (!appRecord->GetRestartAppFlag() && (appRecord->IsKeepAliveDkv() || appRecord->IsKeepAliveAppService()) &&
8378         isDefaultInstance && (userId == 0 || userId == 1 ||userId == currentUserId_) &&
8379         appRecord->GetBundleName() != SCENE_BOARD_BUNDLE_NAME) {
8380         if (ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(appRecord->GetBundleName())) {
8381             TAG_LOGI(AAFwkTag::APPMGR, "is killed for upgrade web");
8382             return;
8383         }
8384         if (!IsMemorySizeSufficient()) {
8385             TAG_LOGI(AAFwkTag::APPMGR, "memory size insufficient");
8386             return;
8387         }
8388         TAG_LOGI(AAFwkTag::APPMGR, "memory size sufficient");
8389         auto restartProcess = [appRecord, innerService = shared_from_this()]() {
8390             TAG_LOGI(AAFwkTag::APPMGR, "restarting keep-alive process.");
8391             innerService->RestartKeepAliveProcess(appRecord);
8392         };
8393         if (taskHandler_ == nullptr) {
8394             TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ null");
8395             return;
8396         }
8397         TAG_LOGI(AAFwkTag::APPMGR, "submit restart keep-alive process task.");
8398         taskHandler_->SubmitTask(restartProcess, "RestartKeepAliveProcess");
8399     }
8400 }
8401 
8402 int32_t AppMgrServiceInner::NotifyPageShow(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
8403 {
8404     if (!JudgeSelfCalledByToken(token, pageStateData)) {
8405         return ERR_PERMISSION_DENIED;
8406     }
8407 
8408     const_cast<PageStateData &>(pageStateData).uid = IPCSkeleton::GetCallingUid();
8409     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnPageShow(pageStateData);
8410     return ERR_OK;
8411 }
8412 
8413 int32_t AppMgrServiceInner::NotifyPageHide(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
8414 {
8415     if (!JudgeSelfCalledByToken(token, pageStateData)) {
8416         return ERR_PERMISSION_DENIED;
8417     }
8418 
8419     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnPageHide(pageStateData);
8420     return ERR_OK;
8421 }
8422 
8423 bool AppMgrServiceInner::JudgeSelfCalledByToken(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
8424 {
8425     if (!token) {
8426         TAG_LOGE(AAFwkTag::APPMGR, "token null");
8427         return false;
8428     }
8429     auto appRecord = GetAppRunningRecordByAbilityToken(token);
8430     if (!appRecord) {
8431         TAG_LOGE(AAFwkTag::APPMGR, "app unexist");
8432         return false;
8433     }
8434     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
8435     if (appRecord->GetApplicationInfo() == nullptr ||
8436         ((appRecord->GetApplicationInfo())->accessTokenId) != callingTokenId) {
8437         TAG_LOGE(AAFwkTag::APPMGR, "is not self");
8438         return false;
8439     }
8440     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
8441     if (!abilityRecord) {
8442         TAG_LOGE(AAFwkTag::APPMGR, "can't find record");
8443         return false;
8444     }
8445     if (abilityRecord->GetBundleName() != pageStateData.bundleName ||
8446         abilityRecord->GetModuleName() != pageStateData.moduleName ||
8447         abilityRecord->GetName() != pageStateData.abilityName) {
8448         TAG_LOGE(AAFwkTag::APPMGR, "can't map ability");
8449         return false;
8450     }
8451     return true;
8452 }
8453 
8454 int32_t AppMgrServiceInner::RegisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
8455 {
8456     TAG_LOGD(AAFwkTag::APPMGR, "Call.");
8457     CHECK_IS_SA_CALL(listener);
8458     auto appRunningStatusListener = iface_cast<AbilityRuntime::AppRunningStatusListenerInterface>(listener);
8459     return appRunningStatusModule_->RegisterListener(appRunningStatusListener);
8460 }
8461 
8462 int32_t AppMgrServiceInner::UnregisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
8463 {
8464     TAG_LOGD(AAFwkTag::APPMGR, "Call.");
8465     CHECK_IS_SA_CALL(listener);
8466     auto appRunningStatusListener = iface_cast<AbilityRuntime::AppRunningStatusListenerInterface>(listener);
8467     return appRunningStatusModule_->UnregisterListener(appRunningStatusListener);
8468 }
8469 
8470 #ifdef SUPPORT_CHILD_PROCESS
8471 int32_t AppMgrServiceInner::StartChildProcess(const pid_t callingPid, pid_t &childPid,
8472     const ChildProcessRequest &request)
8473 {
8474     TAG_LOGI(AAFwkTag::APPMGR, "callingPid:%{public}d", callingPid);
8475     auto errCode = StartChildProcessPreCheck(callingPid, request.childProcessType);
8476     if (errCode != ERR_OK) {
8477         return errCode;
8478     }
8479     if (!CheckCustomProcessName(request.options.customProcessName)) {
8480         TAG_LOGE(AAFwkTag::APPMGR, "invalid custom process name");
8481         return ERR_INVALID_VALUE;
8482     }
8483     auto &srcEntry = request.srcEntry;
8484     if (callingPid <= 0 || srcEntry.empty()) {
8485         TAG_LOGE(AAFwkTag::APPMGR, "invalid callingPid:%{public}d srcEntry:%{private}s", callingPid, srcEntry.c_str());
8486         return ERR_INVALID_VALUE;
8487     }
8488     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
8489         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
8490         return ERR_INVALID_OPERATION;
8491     }
8492     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_NO_INIT);
8493     auto appRecord = GetAppRunningRecordByPid(callingPid);
8494     auto childProcessRecord = ChildProcessRecord::CreateChildProcessRecord(callingPid, request, appRecord);
8495     if (!childProcessRecord) {
8496         TAG_LOGE(AAFwkTag::APPMGR, "childProcessRecord null");
8497         return ERR_NULL_OBJECT;
8498     }
8499     auto &args = request.args;
8500     auto &options = request.options;
8501     childProcessRecord->SetEntryParams(args.entryParams);
8502     TAG_LOGI(AAFwkTag::APPMGR, "srcEntry:%{private}s, args.entryParams size:%{public}zu,"
8503         " processName:%{public}s, args.fds size:%{public}zu, options.isolationMode:%{public}d",
8504         request.srcEntry.c_str(), args.entryParams.length(), childProcessRecord->GetProcessName().c_str(),
8505         args.fds.size(), options.isolationMode);
8506     return StartChildProcessImpl(childProcessRecord, appRecord, childPid, args, options);
8507 }
8508 
8509 int32_t AppMgrServiceInner::StartChildProcessPreCheck(pid_t callingPid, int32_t childProcessType)
8510 {
8511     TAG_LOGD(AAFwkTag::APPMGR, "called.");
8512     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_NO_INIT);
8513     auto childHostRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(callingPid);
8514     if (childHostRecord) {
8515         TAG_LOGE(AAFwkTag::APPMGR, "already in child process.");
8516         return AAFwk::ERR_ALREADY_IN_CHILD_PROCESS;
8517     }
8518     auto hostRecord = GetAppRunningRecordByPid(callingPid);
8519     CHECK_POINTER_AND_RETURN_VALUE(hostRecord, ERR_NULL_OBJECT);
8520     if (!AAFwk::AppUtils::GetInstance().IsMultiProcessModel() &&
8521         !AllowNativeChildProcess(childProcessType, hostRecord->GetAppIdentifier()) &&
8522         !AllowChildProcessInMultiProcessFeatureApp(hostRecord)) {
8523         TAG_LOGE(AAFwkTag::APPMGR, "not support child process.");
8524         return AAFwk::ERR_NOT_SUPPORT_CHILD_PROCESS;
8525     }
8526     auto applicationInfo = hostRecord->GetApplicationInfo();
8527     CHECK_POINTER_AND_RETURN_VALUE(applicationInfo, ERR_NULL_OBJECT);
8528     bool useMultiFeatureMaxCount = false;
8529     if (!AAFwk::AppUtils::GetInstance().IsMultiProcessModel() &&
8530         AllowChildProcessInMultiProcessFeatureApp(hostRecord)) {
8531         useMultiFeatureMaxCount = true;
8532     }
8533     if (appRunningManager_->IsChildProcessReachLimit(applicationInfo->accessTokenId, useMultiFeatureMaxCount)) {
8534         TAG_LOGE(AAFwkTag::APPMGR, "child process count reach limit.");
8535         return AAFwk::ERR_CHILD_PROCESS_REACH_LIMIT;
8536     }
8537     return ERR_OK;
8538 }
8539 
8540 bool AppMgrServiceInner::AllowNativeChildProcess(int32_t childProcessType, const std::string appIdentifier)
8541 {
8542     bool checkAllowList = childProcessType == CHILD_PROCESS_TYPE_NATIVE_ARGS ||
8543         childProcessType == CHILD_PROCESS_TYPE_NATIVE;
8544     return checkAllowList && AAFwk::AppUtils::GetInstance().IsAllowNativeChildProcess(appIdentifier);
8545 }
8546 
8547 bool AppMgrServiceInner::AllowChildProcessInMultiProcessFeatureApp(std::shared_ptr<AppRunningRecord> appRecord)
8548 {
8549     if (!AAFwk::AppUtils::GetInstance().AllowChildProcessInMultiProcessFeatureApp()) {
8550         return false;
8551     }
8552     CHECK_POINTER_AND_RETURN_VALUE(appRecord, false);
8553     auto support = appRecord->IsSupportMultiProcessDeviceFeature();
8554     if (support.has_value()) {
8555         return support.value();
8556     }
8557     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
8558     CHECK_POINTER_AND_RETURN_VALUE(bundleMgrHelper, false);
8559     BundleInfo bundleInfo;
8560     auto ret = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfoV9(appRecord->GetBundleName(),
8561         static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE), bundleInfo, appRecord->GetUserId()));
8562     if (ret != ERR_OK) {
8563         TAG_LOGE(AAFwkTag::APPMGR, "getBundleInfo fail");
8564         return false;
8565     }
8566     for (const auto &info : bundleInfo.hapModuleInfos) {
8567         if (info.moduleType != AppExecFwk::ModuleType::ENTRY) {
8568             continue;
8569         }
8570         auto deviceType = OHOS::system::GetDeviceType();
8571         auto it = info.requiredDeviceFeatures.find(deviceType);
8572         if (it == info.requiredDeviceFeatures.end()) {
8573             return false;
8574         }
8575         auto &deviceFeatures = it->second;
8576         auto supportMultiProcess =
8577             std::find(deviceFeatures.begin(), deviceFeatures.end(), LARGE_SCREEN) != deviceFeatures.end();
8578         appRecord->SetSupportMultiProcessDeviceFeature(supportMultiProcess);
8579         return supportMultiProcess;
8580     }
8581     return false;
8582 }
8583 
8584 int32_t AppMgrServiceInner::StartChildProcessImpl(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
8585     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &childPid, const ChildProcessArgs &args,
8586     const ChildProcessOptions &options)
8587 {
8588     TAG_LOGD(AAFwkTag::APPMGR, "called");
8589     if (!appRecord) {
8590         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, childPid:%{public}d", childPid);
8591         return ERR_NAME_NOT_FOUND;
8592     }
8593     if (!childProcessRecord) {
8594         TAG_LOGE(AAFwkTag::APPMGR, "no child process record, childPid:%{public}d", childPid);
8595         return ERR_NAME_NOT_FOUND;
8596     }
8597     bool isNativeFromJs = childProcessRecord->GetChildProcessType() == CHILD_PROCESS_TYPE_NATIVE_ARGS;
8598     auto spawnClient =  isNativeFromJs ? remoteClientManager_->GetNativeSpawnClient() :
8599         remoteClientManager_->GetSpawnClient();
8600     if (!spawnClient) {
8601         TAG_LOGE(AAFwkTag::APPMGR, "spawnClient null");
8602         AppMgrEventUtil::SendChildProcessStartFailedEvent(childProcessRecord,
8603             ProcessStartFailedReason::GET_SPAWN_CLIENT_FAILED, AAFwk::ERR_GET_SPAWN_CLIENT_FAILED);
8604         return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
8605     }
8606     if (!args.CheckFdsSize() || !args.CheckFdsKeyLength()) {
8607         AppMgrEventUtil::SendChildProcessStartFailedEvent(childProcessRecord,
8608             ProcessStartFailedReason::CHECK_CHILD_FDS_FAILED, ERR_INVALID_VALUE);
8609         return ERR_INVALID_VALUE;
8610     }
8611 
8612     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
8613     startMsg.procName = childProcessRecord->GetProcessName();
8614     startMsg.childProcessType = childProcessRecord->GetChildProcessType();
8615     startMsg.fds = args.fds;
8616     startMsg.isolationMode = options.isolationMode;
8617     pid_t pid = 0;
8618     {
8619         std::lock_guard<ffrt::mutex> lock(startChildProcessLock_);
8620         ErrCode errCode = spawnClient->StartProcess(startMsg, pid);
8621         if (FAILED(errCode)) {
8622             TAG_LOGE(AAFwkTag::APPMGR, "spawn new child process fail, errCode %{public}08x", errCode);
8623             AppMgrEventUtil::SendChildProcessStartFailedEvent(childProcessRecord,
8624                 ProcessStartFailedReason::APPSPAWN_FAILED, static_cast<int32_t>(errCode));
8625             return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
8626         }
8627         childPid = pid;
8628         childProcessRecord->SetPid(pid);
8629         childProcessRecord->SetUid(startMsg.uid);
8630         appRecord->AddChildProcessRecord(pid, childProcessRecord);
8631     }
8632     TAG_LOGI(AAFwkTag::APPMGR, "start childProcess success,pid:%{public}d,hostPid:%{public}d,uid:%{public}d,"
8633         "processName:%{public}s", pid, childProcessRecord->GetHostPid(), startMsg.uid,
8634         childProcessRecord->GetProcessName().c_str());
8635     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessCreated(childProcessRecord);
8636     return ERR_OK;
8637 }
8638 
8639 int32_t AppMgrServiceInner::GetChildProcessInfoForSelf(ChildProcessInfo &info)
8640 {
8641     TAG_LOGD(AAFwkTag::APPMGR, "called");
8642     if (!appRunningManager_) {
8643         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8644         return ERR_NO_INIT;
8645     }
8646     auto callingPid = IPCSkeleton::GetCallingPid();
8647     if (appRunningManager_->GetAppRunningRecordByPid(callingPid)) {
8648         TAG_LOGD(AAFwkTag::APPMGR, "record of callingPid is not child record.");
8649         return ERR_NAME_NOT_FOUND;
8650     }
8651     std::lock_guard<ffrt::mutex> lock(startChildProcessLock_);
8652     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(callingPid);
8653     if (!appRecord) {
8654         TAG_LOGW(AAFwkTag::APPMGR, "no appRecord, childPid:%{public}d", callingPid);
8655         return ERR_NAME_NOT_FOUND;
8656     }
8657     auto childRecordMap = appRecord->GetChildProcessRecordMap();
8658     auto iter = childRecordMap.find(callingPid);
8659     if (iter != childRecordMap.end()) {
8660         auto childProcessRecord = iter->second;
8661         return GetChildProcessInfo(childProcessRecord, appRecord, info);
8662     }
8663     return ERR_NAME_NOT_FOUND;
8664 }
8665 
8666 int32_t AppMgrServiceInner::GetChildProcessInfo(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
8667     const std::shared_ptr<AppRunningRecord> appRecord, ChildProcessInfo &info, bool isCallFromGetChildrenProcesses)
8668 {
8669     TAG_LOGD(AAFwkTag::APPMGR, "called");
8670     if (!childProcessRecord) {
8671         TAG_LOGE(AAFwkTag::APPMGR, "no child process record");
8672         return ERR_NAME_NOT_FOUND;
8673     }
8674     if (!appRecord) {
8675         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord");
8676         return ERR_NAME_NOT_FOUND;
8677     }
8678     auto osAccountMgr = DelayedSingleton<OsAccountManagerWrapper>::GetInstance();
8679     if (osAccountMgr == nullptr) {
8680         TAG_LOGE(AAFwkTag::APPMGR, "osAccountMgr is nullptr");
8681         return ERR_INVALID_VALUE;
8682     }
8683     int32_t userId = -1;
8684     int errCode = osAccountMgr->GetOsAccountLocalIdFromUid(appRecord->GetUid(), userId);
8685     if (errCode != ERR_OK) {
8686         TAG_LOGE(AAFwkTag::APPMGR, "GetOsAccountLocalIdFromUid failed,errcode=%{public}d", errCode);
8687         return errCode;
8688     }
8689     TAG_LOGD(AAFwkTag::APPMGR, "GetOsAccountLocalIdFromUid userId: %{public}d", userId);
8690     info.userId = userId;
8691     info.pid = childProcessRecord->GetPid();
8692     info.hostPid = childProcessRecord->GetHostPid();
8693     info.uid = childProcessRecord->GetUid();
8694     info.hostUid = appRecord->GetUid();
8695     info.bundleName = appRecord->GetBundleName();
8696     info.processName = childProcessRecord->GetProcessName();
8697     if (!isCallFromGetChildrenProcesses) {
8698         info.childProcessType = childProcessRecord->GetChildProcessType();
8699         info.srcEntry = childProcessRecord->GetSrcEntry();
8700         info.entryFunc = childProcessRecord->GetEntryFunc();
8701         info.entryParams = childProcessRecord->GetEntryParams();
8702         info.jitEnabled = appRecord->IsJITEnabled();
8703         info.isStartWithDebug = childProcessRecord->isStartWithDebug();
8704         auto applicationInfo = appRecord->GetApplicationInfo();
8705         if (applicationInfo) {
8706             TAG_LOGD(AAFwkTag::APPMGR, "applicationInfo is exist, debug:%{public}d", applicationInfo->debug);
8707             info.isDebugApp = applicationInfo->debug;
8708         }
8709         info.isStartWithNative = appRecord->isNativeStart();
8710     }
8711     return ERR_OK;
8712 }
8713 
8714 void AppMgrServiceInner::AttachChildProcess(const pid_t pid, const sptr<IChildScheduler> &childScheduler)
8715 {
8716     TAG_LOGI(AAFwkTag::APPMGR, "attachChildProcess pid:%{public}d", pid);
8717     if (pid <= 0) {
8718         TAG_LOGE(AAFwkTag::APPMGR, "invalid child process pid:%{public}d", pid);
8719         return;
8720     }
8721     if (!childScheduler) {
8722         TAG_LOGE(AAFwkTag::APPMGR, "childScheduler null");
8723         return;
8724     }
8725     if (!appRunningManager_) {
8726         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8727         return;
8728     }
8729     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(pid);
8730     if (!appRecord) {
8731         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", pid);
8732         return;
8733     }
8734     auto childRecord = appRecord->GetChildProcessRecordByPid(pid);
8735     if (!childRecord) {
8736         TAG_LOGE(AAFwkTag::APPMGR, "no child process record, pid:%{public}d", pid);
8737         return;
8738     }
8739 
8740     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
8741     appDeathRecipient->SetTaskHandler(taskHandler_);
8742     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
8743     appDeathRecipient->SetIsChildProcess(true);
8744     childRecord->SetScheduler(childScheduler);
8745     childRecord->SetDeathRecipient(appDeathRecipient);
8746     childRecord->RegisterDeathRecipient();
8747 
8748     if (childRecord->GetChildProcessType() != CHILD_PROCESS_TYPE_NATIVE) {
8749         childScheduler->ScheduleLoadChild();
8750     } else {
8751         childScheduler->ScheduleRunNativeProc(childRecord->GetMainProcessCallback());
8752         childRecord->ClearMainProcessCallback();
8753     }
8754 }
8755 
8756 void AppMgrServiceInner::OnChildProcessRemoteDied(const wptr<IRemoteObject> &remote)
8757 {
8758     if (appRunningManager_) {
8759         auto childRecord = appRunningManager_->OnChildProcessRemoteDied(remote);
8760         if (childRecord) {
8761             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessDied(childRecord);
8762         }
8763     }
8764 }
8765 
8766 void AppMgrServiceInner::KillChildProcess(const std::shared_ptr<AppRunningRecord> &appRecord) {
8767     if (appRecord == nullptr) {
8768         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
8769         return;
8770     }
8771     auto childRecordMap = appRecord->GetChildProcessRecordMap();
8772     if (childRecordMap.empty()) {
8773         return;
8774     }
8775     for (auto iter : childRecordMap) {
8776         auto childRecord = iter.second;
8777         if (!childRecord) {
8778             continue;
8779         }
8780         auto childPid = childRecord->GetPid();
8781         if (childPid > 0) {
8782             TAG_LOGI(AAFwkTag::APPMGR, "kill child process, childPid:%{public}d, childUid:%{public}d",
8783                 childPid, childRecord->GetUid());
8784             KillProcessByPid(childPid, "KillChildProcess");
8785             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessDied(childRecord);
8786         }
8787     }
8788 }
8789 
8790 void AppMgrServiceInner::ExitChildProcessSafelyByChildPid(const pid_t pid)
8791 {
8792     if (pid <= 0) {
8793         TAG_LOGE(AAFwkTag::APPMGR, "pid <= 0");
8794         return;
8795     }
8796     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(pid);
8797     if (!appRecord) {
8798         TAG_LOGE(AAFwkTag::APPMGR, "no apprecord, pid:%{public}d", pid);
8799         return;
8800     }
8801     auto childRecord = appRecord->GetChildProcessRecordByPid(pid);
8802     if (!childRecord) {
8803         TAG_LOGE(AAFwkTag::APPMGR, "no child process record, pid:%{public}d", pid);
8804         return;
8805     }
8806     childRecord->ScheduleExitProcessSafely();
8807     childRecord->RemoveDeathRecipient();
8808     int64_t startTime = SystemTimeMillisecond();
8809     std::list<pid_t> pids;
8810     pids.push_back(pid);
8811     if (WaitForRemoteProcessExit(pids, startTime)) {
8812         appRunningManager_->HandleChildRelation(childRecord, appRecord);
8813         TAG_LOGI(AAFwkTag::APPMGR, "remote child process exited, pid:%{public}d", pid);
8814         appRecord->RemoveChildProcessRecord(childRecord);
8815         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessDied(childRecord);
8816         return;
8817     }
8818     childRecord->RegisterDeathRecipient();
8819     TAG_LOGI(AAFwkTag::APPMGR, "kill child process, childPid:%{public}d, childUid:%{public}d",
8820         pid, childRecord->GetUid());
8821     int32_t result = KillProcessByPid(pid, "ExitChildProcessSafelyByChildPid");
8822     if (result < 0) {
8823         TAG_LOGE(AAFwkTag::APPMGR, "kill killChildProcessByPid fail");
8824         return;
8825     }
8826 }
8827 
8828 void AppMgrServiceInner::KillAttachedChildProcess(const std::shared_ptr<AppRunningRecord> &appRecord)
8829 {
8830     if (appRecord == nullptr) {
8831         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
8832         return;
8833     }
8834     auto parentAppRecord = appRecord->GetParentAppRecord();
8835     if (parentAppRecord) {
8836         parentAppRecord->RemoveChildAppRecord(appRecord->GetPid());
8837     }
8838     std::vector<pid_t> pids;
8839     std::queue<std::shared_ptr<AppRunningRecord>> queue;
8840     queue.push(appRecord);
8841     while (!queue.empty()) {
8842         auto front = queue.front();
8843         queue.pop();
8844         if (front == nullptr) {
8845             continue;
8846         }
8847         auto childAppRecordMap = front->GetChildAppRecordMap();
8848         for (const auto& [pid, weakChildAppRecord] : childAppRecordMap) {
8849             auto childRecord = weakChildAppRecord.lock();
8850             if (childRecord) {
8851                 queue.push(childRecord);
8852                 pids.push_back(pid);
8853             }
8854         }
8855         front->ClearChildAppRecordMap();
8856     }
8857     for (const auto& pid : pids) {
8858         KillProcessByPid(pid, "KillAttachedChildProcess");
8859     }
8860 }
8861 #endif // SUPPORT_CHILD_PROCESS
8862 
8863 int AppMgrServiceInner::DumpIpcAllStart(std::string& result)
8864 {
8865     TAG_LOGD(AAFwkTag::APPMGR, "called");
8866     if (!appRunningManager_) {
8867         result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
8868             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
8869             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
8870         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8871         return DumpErrorCode::ERR_INTERNAL_ERROR;
8872     }
8873     return appRunningManager_->DumpIpcAllStart(result);
8874 }
8875 
8876 int AppMgrServiceInner::DumpIpcAllStop(std::string& result)
8877 {
8878     TAG_LOGD(AAFwkTag::APPMGR, "called");
8879     if (!appRunningManager_) {
8880         result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
8881             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
8882             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
8883         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8884         return DumpErrorCode::ERR_INTERNAL_ERROR;
8885     }
8886     return appRunningManager_->DumpIpcAllStop(result);
8887 }
8888 
8889 int AppMgrServiceInner::DumpIpcAllStat(std::string& result)
8890 {
8891     TAG_LOGD(AAFwkTag::APPMGR, "called");
8892     if (!appRunningManager_) {
8893         result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
8894             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
8895             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
8896         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8897         return DumpErrorCode::ERR_INTERNAL_ERROR;
8898     }
8899     return appRunningManager_->DumpIpcAllStat(result);
8900 }
8901 
8902 int AppMgrServiceInner::DumpIpcStart(const int32_t pid, std::string& result)
8903 {
8904     TAG_LOGD(AAFwkTag::APPMGR, "called");
8905     if (!appRunningManager_) {
8906         result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
8907             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
8908             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
8909         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8910         return DumpErrorCode::ERR_INTERNAL_ERROR;
8911     }
8912     return appRunningManager_->DumpIpcStart(pid, result);
8913 }
8914 
8915 int AppMgrServiceInner::DumpIpcStop(const int32_t pid, std::string& result)
8916 {
8917     TAG_LOGD(AAFwkTag::APPMGR, "called");
8918     if (!appRunningManager_) {
8919         result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
8920             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
8921             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
8922         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8923         return DumpErrorCode::ERR_INTERNAL_ERROR;
8924     }
8925     return appRunningManager_->DumpIpcStop(pid, result);
8926 }
8927 
8928 int AppMgrServiceInner::DumpIpcStat(const int32_t pid, std::string& result)
8929 {
8930     TAG_LOGD(AAFwkTag::APPMGR, "called");
8931     if (!appRunningManager_) {
8932         result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
8933             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
8934             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
8935         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8936         return DumpErrorCode::ERR_INTERNAL_ERROR;
8937     }
8938     return appRunningManager_->DumpIpcStat(pid, result);
8939 }
8940 
8941 int AppMgrServiceInner::DumpFfrt(const std::vector<int32_t>& pids, std::string& result)
8942 {
8943     TAG_LOGD(AAFwkTag::APPMGR, "called");
8944     if (!appRunningManager_) {
8945         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
8946             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
8947         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
8948         return DumpErrorCode::ERR_INTERNAL_ERROR;
8949     }
8950     return appRunningManager_->DumpFfrt(pids, result);
8951 }
8952 
8953 void AppMgrServiceInner::NotifyAppRunningStatusEvent(
8954     const std::string &bundle, int32_t uid, AbilityRuntime::RunningStatus runningStatus)
8955 {
8956     if (appRunningStatusModule_ == nullptr) {
8957         TAG_LOGE(AAFwkTag::APPMGR, "get running status module object null");
8958         return;
8959     }
8960     appRunningStatusModule_->NotifyAppRunningStatusEvent(bundle, uid, runningStatus);
8961 }
8962 
8963 void AppMgrServiceInner::SendAppLaunchEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
8964 {
8965     if (!appRecord) {
8966         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
8967         return;
8968     }
8969     AAFwk::EventInfo eventInfo;
8970     auto applicationInfo = appRecord->GetApplicationInfo();
8971     if (!applicationInfo) {
8972         TAG_LOGE(AAFwkTag::APPMGR, "appInfo null");
8973     } else {
8974         eventInfo.bundleName = applicationInfo->name;
8975         eventInfo.versionName = applicationInfo->versionName;
8976         eventInfo.versionCode = applicationInfo->versionCode;
8977     }
8978     if (appRecord->GetPriorityObject() != nullptr) {
8979         eventInfo.pid = appRecord->GetPid();
8980     }
8981     eventInfo.processName = appRecord->GetProcessName();
8982     int32_t callerPid = appRecord->GetCallerPid() == -1 ?
8983         IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
8984     auto callerRecord = GetAppRunningRecordByPid(callerPid);
8985     if (callerRecord != nullptr) {
8986         eventInfo.callerBundleName = callerRecord->GetBundleName();
8987         eventInfo.callerUid = callerRecord->GetUid();
8988         eventInfo.callerState = static_cast<int32_t>(callerRecord->GetState());
8989         auto callerApplicationInfo = callerRecord->GetApplicationInfo();
8990         if (callerApplicationInfo != nullptr) {
8991             eventInfo.callerVersionName = callerApplicationInfo->versionName;
8992             eventInfo.callerVersionCode = callerApplicationInfo->versionCode;
8993         }
8994     }
8995     AAFwk::EventReport::SendAppLaunchEvent(AAFwk::EventName::APP_LAUNCH, eventInfo);
8996 }
8997 
8998 bool AppMgrServiceInner::IsFinalAppProcessByBundleName(const std::string &bundleName)
8999 {
9000     if (appRunningManager_ == nullptr) {
9001         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
9002         return false;
9003     }
9004 
9005     auto name = bundleName;
9006     if (bundleName.empty()) {
9007         auto callingPid = IPCSkeleton::GetCallingPid();
9008         auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callingPid);
9009         if (appRecord == nullptr) {
9010             TAG_LOGE(AAFwkTag::APPMGR, "get running record null");
9011             return false;
9012         }
9013         name = appRecord->GetBundleName();
9014     }
9015 
9016     auto count = appRunningManager_->GetAllAppRunningRecordCountByBundleName(name);
9017     TAG_LOGD(AAFwkTag::APPMGR, "Get application %{public}s process list size[%{public}d].", name.c_str(), count);
9018     return count == 1;
9019 }
9020 
9021 void AppMgrServiceInner::ParseServiceExtMultiProcessWhiteList()
9022 {
9023     auto serviceExtMultiProcessWhiteList =
9024         OHOS::system::GetParameter(SERVICE_EXT_MULTI_PROCESS_WHITE_LIST, "");
9025     if (serviceExtMultiProcessWhiteList.empty()) {
9026         TAG_LOGW(AAFwkTag::APPMGR, "no multi process white list");
9027         return;
9028     }
9029     SplitStr(serviceExtMultiProcessWhiteList, ";", serviceExtensionWhiteList_);
9030 }
9031 
9032 void AppMgrServiceInner::ClearProcessByToken(sptr<IRemoteObject> token)
9033 {
9034     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9035     if (token == nullptr) {
9036         TAG_LOGE(AAFwkTag::APPMGR, "token null");
9037         return;
9038     }
9039 
9040     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
9041     {
9042         std::lock_guard lock(exceptionLock_);
9043         appRecord = GetAppRunningRecordByAbilityToken(token);
9044         if (appRecord == nullptr) {
9045             TAG_LOGI(AAFwkTag::APPMGR, "null appRecord");
9046             return;
9047         }
9048         appRecord->SetApplicationClient(nullptr);
9049         auto recordId = appRecord->GetRecordId();
9050         if (appRunningManager_ == nullptr) {
9051             TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
9052             return;
9053         }
9054         appRunningManager_->RemoveAppRunningRecordById(recordId);
9055     }
9056     ClearData(appRecord);
9057 }
9058 
9059 void AppMgrServiceInner::ClearData(std::shared_ptr<AppRunningRecord> appRecord)
9060 {
9061     if (appRecord == nullptr) {
9062         TAG_LOGW(AAFwkTag::APPMGR, "null appRecord");
9063         return;
9064     }
9065     ClearAppRunningData(appRecord);
9066     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
9067         RemoveRunningSharedBundleList(appRecord->GetBundleName());
9068     }
9069 }
9070 
9071 int32_t AppMgrServiceInner::RegisterRenderStateObserver(const sptr<IRenderStateObserver> &observer)
9072 {
9073     if (observer == nullptr) {
9074         TAG_LOGE(AAFwkTag::APPMGR, "observer null");
9075         return ERR_INVALID_VALUE;
9076     }
9077     return DelayedSingleton<RenderStateObserverManager>::GetInstance()->RegisterRenderStateObserver(observer);
9078 }
9079 
9080 int32_t AppMgrServiceInner::UnregisterRenderStateObserver(const sptr<IRenderStateObserver> &observer)
9081 {
9082     if (observer == nullptr) {
9083         TAG_LOGE(AAFwkTag::APPMGR, "observer null");
9084         return ERR_INVALID_VALUE;
9085     }
9086     return DelayedSingleton<RenderStateObserverManager>::GetInstance()->UnregisterRenderStateObserver(observer);
9087 }
9088 
9089 void AppMgrServiceInner::SetAppAssertionPauseState(bool flag)
9090 {
9091     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9092     TAG_LOGD(AAFwkTag::APPMGR, "called");
9093     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
9094         TAG_LOGE(AAFwkTag::APPMGR, "product of assert fault dialog not enabled");
9095         return;
9096     }
9097     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
9098         TAG_LOGE(AAFwkTag::APPMGR, "developer mode false");
9099         return;
9100     }
9101 
9102     auto callerPid = IPCSkeleton::GetCallingPid();
9103     auto appRecord = GetAppRunningRecordByPid(callerPid);
9104     if (appRecord == nullptr) {
9105         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord pid: %{public}d", callerPid);
9106         return;
9107     }
9108     appRecord->SetAssertionPauseFlag(flag);
9109     auto isDebugStart = appRecord->IsDebugApp() || appRecord->IsAttachDebug();
9110     if (!isDebugStart) {
9111         std::vector<AppDebugInfo> debugInfos;
9112         debugInfos.emplace_back(MakeAppDebugInfo(appRecord, flag));
9113         flag ? appDebugManager_->StartDebug(debugInfos) : appDebugManager_->StopDebug(debugInfos);
9114     }
9115 
9116     NotifyAbilitiesAssertDebugChange(appRecord, flag);
9117 }
9118 
9119 int32_t AppMgrServiceInner::UpdateRenderState(pid_t renderPid, int32_t state)
9120 {
9121     int32_t hostPid = IPCSkeleton::GetCallingPid();
9122     auto appRecord = GetAppRunningRecordByPid(hostPid);
9123     if (!appRecord) {
9124         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, hostPid:%{public}d", hostPid);
9125         return ERR_INVALID_VALUE;
9126     }
9127 
9128     auto renderRecord = appRecord->GetRenderRecordByPid(renderPid);
9129     if (renderRecord == nullptr) {
9130         TAG_LOGE(AAFwkTag::APPMGR, "renderPid:%{pubclic}d unexist", renderPid);
9131         return ERR_INVALID_VALUE;
9132     }
9133     renderRecord->SetState(state);
9134     return DelayedSingleton<RenderStateObserverManager>::GetInstance()->OnRenderStateChanged(
9135         renderRecord, state);
9136 }
9137 
9138 int32_t AppMgrServiceInner::SignRestartAppFlag(int32_t uid, const std::string &instanceKey)
9139 {
9140     TAG_LOGD(AAFwkTag::APPMGR, "call.");
9141     if (!appRunningManager_) {
9142         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
9143         return ERR_NO_INIT;
9144     }
9145     return appRunningManager_->SignRestartAppFlag(uid, instanceKey);
9146 }
9147 
9148 int32_t AppMgrServiceInner::GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId)
9149 {
9150     TAG_LOGD(AAFwkTag::APPMGR, "call.");
9151     if (!appRunningManager_) {
9152         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
9153         return ERR_NO_INIT;
9154     }
9155     bool isCallingPermission = AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
9156         AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
9157     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
9158     bool isDevelopMode = system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
9159     if (!isCallingPermission && !(isShellCall && isDevelopMode)) {
9160         TAG_LOGE(AAFwkTag::APPMGR, "GetAppRunningUniqueIdByPid not SA call or verification failed");
9161         return ERR_PERMISSION_DENIED;
9162     }
9163     return appRunningManager_->GetAppRunningUniqueIdByPid(pid, appRunningUniqueId);
9164 }
9165 
9166 bool AppMgrServiceInner::NotifyMemMgrPriorityChanged(const std::shared_ptr<AppRunningRecord> appRecord)
9167 {
9168     if (!appRecord) {
9169         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
9170         return false;
9171     }
9172     auto priorityObject = appRecord->GetPriorityObject();
9173     if (!priorityObject) {
9174         TAG_LOGE(AAFwkTag::APPMGR, "priorityObject null");
9175         return false;
9176     }
9177     int32_t pid = priorityObject->GetPid();
9178     int32_t uid = appRecord->GetUid();
9179     TAG_LOGI(AAFwkTag::APPMGR, "pid:%{public}d, uid:%{public}d", pid, uid);
9180 
9181     Memory::MemMgrProcessStateInfo info;
9182     info.pid_ = pid;
9183     info.uid_ = uid;
9184     info.reason_ = Memory::ProcPriorityUpdateReason::START_ABILITY;
9185     int32_t result = ERR_OK;
9186     {
9187         HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9188         result = Memory::MemMgrClient::GetInstance().NotifyProcessStateChangedAsync(info);
9189     }
9190     if (result != ERR_OK) {
9191         TAG_LOGE(AAFwkTag::APPMGR, "notifyPriorityChangedSync error, result:%{public}d", result);
9192         return false;
9193     }
9194     return true;
9195 }
9196 
9197 int32_t AppMgrServiceInner::GetAllUIExtensionRootHostPid(pid_t pid, std::vector<pid_t> &hostPids)
9198 {
9199     if (!appRunningManager_) {
9200         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
9201         return ERR_NO_INIT;
9202     }
9203 
9204     CHECK_CALLER_IS_SYSTEM_APP;
9205     if (!AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm()) {
9206         TAG_LOGE(AAFwkTag::APPMGR, "permission deny");
9207         return ERR_PERMISSION_DENIED;
9208     }
9209 
9210     return appRunningManager_->GetAllUIExtensionRootHostPid(pid, hostPids);
9211 }
9212 
9213 int32_t AppMgrServiceInner::GetAllUIExtensionProviderPid(pid_t hostPid, std::vector<pid_t> &providerPids)
9214 {
9215     if (!appRunningManager_) {
9216         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
9217         return ERR_NO_INIT;
9218     }
9219 
9220     CHECK_CALLER_IS_SYSTEM_APP;
9221     if (!AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm()) {
9222         TAG_LOGE(AAFwkTag::APPMGR, "permission deny");
9223         return ERR_PERMISSION_DENIED;
9224     }
9225 
9226     return appRunningManager_->GetAllUIExtensionProviderPid(hostPid, providerPids);
9227 }
9228 
9229 int32_t AppMgrServiceInner::NotifyMemorySizeStateChanged(int32_t memorySizeState)
9230 {
9231     TAG_LOGI(AAFwkTag::APPMGR, "memorySizeState: %{public}d", memorySizeState);
9232     bool isMemmgrCall = AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(
9233         MEMMGR_PROC_NAME);
9234     bool isSupportCall = OHOS::system::GetBoolParameter(SUPPORT_CALL_NOTIFY_MEMORY_CHANGED, false);
9235     if (!isMemmgrCall && !isSupportCall) {
9236         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not %{public}s", MEMMGR_PROC_NAME);
9237         return ERR_PERMISSION_DENIED;
9238     }
9239     int32_t ret = ERR_OK;
9240     std::vector<ExitResidentProcessInfo> exitProcessInfos;
9241     switch (memorySizeState) {
9242         case MemoryState::LOW_MEMORY:
9243             ret = ExitResidentProcessManager::GetInstance().HandleMemorySizeInSufficent();
9244             if (ret != ERR_OK) {
9245                 TAG_LOGE(AAFwkTag::APPMGR, "handleMemorySizeInSufficent fail, ret: %{public}d", ret);
9246             }
9247             break;
9248         case MemoryState::REQUIRE_BIG_MEMORY:
9249             SubscribeScreenOffEvent();
9250             ret = ExitResidentProcessManager::GetInstance().HandleRequireBigMemoryOptimization();
9251             if (ret != ERR_OK) {
9252                 TAG_LOGE(AAFwkTag::APPMGR, "HandleRequireBigMemoryOptimization fail, ret: %{public}d", ret);
9253             }
9254             break;
9255         case MemoryState::MEMORY_RECOVERY:
9256             ret = ExitResidentProcessManager::GetInstance().HandleMemorySizeSufficient(exitProcessInfos);
9257             if (ret != ERR_OK) {
9258                 TAG_LOGE(AAFwkTag::APPMGR, "HandleMemorySizeSufficient fail, ret: %{public}d", ret);
9259             }
9260             ret = RestartExitKeepAliveProcess(exitProcessInfos);
9261             if (ret != ERR_OK) {
9262                 TAG_LOGE(AAFwkTag::APPMGR, "RestartExitKeepAliveProcess fail");
9263             }
9264             break;
9265         case MemoryState::NO_REQUIRE_BIG_MEMORY:
9266             ret = ExitResidentProcessManager::GetInstance().HandleNoRequireBigMemoryOptimization(exitProcessInfos);
9267             if (ret != ERR_OK) {
9268                 TAG_LOGE(AAFwkTag::APPMGR, "HandleNoRequireBigMemoryOptimization fail, ret: %{public}d", ret);
9269             }
9270             ret = RestartExitKeepAliveProcess(exitProcessInfos);
9271             if (ret != ERR_OK) {
9272                 TAG_LOGE(AAFwkTag::APPMGR, "RestartExitKeepAliveProcess fail");
9273             }
9274             break;
9275         default:
9276             TAG_LOGE(AAFwkTag::APPMGR, "NotifyMemory failed, memorySizeState is %{public}d.", memorySizeState);
9277     }
9278     return ret;
9279 }
9280 
9281 int32_t AppMgrServiceInner::RestartExitKeepAliveProcess(const std::vector<ExitResidentProcessInfo> &exitProcessInfos)
9282 {
9283     auto StartExitKeepAliveProcessTask = [exitProcessInfos, innerServiceWeak = weak_from_this()]() {
9284         auto innerService = innerServiceWeak.lock();
9285         CHECK_POINTER_AND_RETURN_LOG(innerService, "get appMgrServiceInner fail");
9286         std::vector<AppExecFwk::BundleInfo> exitBundleInfos;
9287         ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(exitProcessInfos, exitBundleInfos);
9288 
9289         innerService->NotifyStartResidentProcess(exitBundleInfos);
9290         innerService->NotifyStartKeepAliveProcess(exitBundleInfos);
9291     };
9292     CHECK_POINTER_AND_RETURN_VALUE(taskHandler_, ERR_NO_INIT);
9293     taskHandler_->SubmitTask(StartExitKeepAliveProcessTask, "startexitkeepaliveprocess");
9294     return ERR_OK;
9295 }
9296 
9297 bool AppMgrServiceInner::IsMemorySizeSufficient()
9298 {
9299     return ExitResidentProcessManager::GetInstance().IsMemorySizeSufficient();
9300 }
9301 
9302 bool AppMgrServiceInner::IsNoRequireBigMemory()
9303 {
9304     return ExitResidentProcessManager::GetInstance().IsNoRequireBigMemory();
9305 }
9306 
9307 void AppMgrServiceInner::NotifyAppPreCache(int32_t pid, int32_t userId)
9308 {
9309     std::lock_guard lock(appStateCallbacksLock_);
9310     for (const auto &item : appStateCallbacks_) {
9311         if (item.callback != nullptr) {
9312             item.callback->NotifyAppPreCache(pid, userId);
9313         }
9314     }
9315 }
9316 
9317 void AppMgrServiceInner::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
9318 {
9319     std::lock_guard lock(appStateCallbacksLock_);
9320     for (const auto &item : appStateCallbacks_) {
9321         if (item.callback != nullptr) {
9322             item.callback->NotifyStartResidentProcess(bundleInfos);
9323         }
9324     }
9325 }
9326 
9327 void AppMgrServiceInner::NotifyStartKeepAliveProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
9328 {
9329     std::lock_guard lock(appStateCallbacksLock_);
9330     for (const auto &item : appStateCallbacks_) {
9331         if (item.callback != nullptr) {
9332             item.callback->NotifyStartKeepAliveProcess(bundleInfos);
9333         }
9334     }
9335 }
9336 
9337 void AppMgrServiceInner::SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid)
9338 {
9339     TAG_LOGD(AAFwkTag::APPMGR, "called");
9340     if (bundleName.empty()) {
9341         TAG_LOGE(AAFwkTag::APPMGR, "bundle name empty");
9342         return;
9343     }
9344 
9345     if (appRunningManager_ == nullptr) {
9346         TAG_LOGE(AAFwkTag::APPMGR, "running manager error");
9347         return;
9348     }
9349 
9350     auto callerUid = IPCSkeleton::GetCallingUid();
9351     if (callerUid != FOUNDATION_UID) {
9352         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
9353         return;
9354     }
9355 
9356     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
9357         const auto &appRecord = item.second;
9358         if (appRecord != nullptr && appRecord->GetBundleName() == bundleName &&
9359             (uid == 0 || appRecord->GetUid() == uid)) {
9360             TAG_LOGD(AAFwkTag::APPMGR, "%{public}s update state: %{public}d",
9361                 bundleName.c_str(), static_cast<int32_t>(enable));
9362             SetKeepAliveEnableStateAndNotify(appRecord, enable);
9363         }
9364     }
9365 }
9366 
9367 void AppMgrServiceInner::SetKeepAliveEnableStateAndNotify(
9368     const std::shared_ptr<AppRunningRecord>& appRecord, bool enable)
9369 {
9370     if (appRecord == nullptr) {
9371         TAG_LOGE(AAFwkTag::APPMGR, "SetKeepAliveEnableStateAndNotify appRecord is nullptr");
9372         return;
9373     }
9374     auto beforState = GetKeepAliveState(appRecord);
9375     appRecord->SetKeepAliveEnableState(enable);
9376     auto afterState = GetKeepAliveState(appRecord);
9377     if (beforState != afterState) {
9378         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnKeepAliveStateChanged(appRecord);
9379     }
9380 }
9381 
9382 void AppMgrServiceInner::SetKeepAliveDkv(const std::string &bundleName, bool enable, int32_t uid)
9383 {
9384     TAG_LOGD(AAFwkTag::APPMGR, "called");
9385     if (bundleName.empty()) {
9386         TAG_LOGE(AAFwkTag::APPMGR, "bundle name empty");
9387         return;
9388     }
9389 
9390     if (appRunningManager_ == nullptr) {
9391         TAG_LOGE(AAFwkTag::APPMGR, "running manager error");
9392         return;
9393     }
9394 
9395     auto callerUid = IPCSkeleton::GetCallingUid();
9396     if (callerUid != FOUNDATION_UID) {
9397         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
9398         return;
9399     }
9400 
9401     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
9402         const auto &appRecord = item.second;
9403         if (appRecord != nullptr && appRecord->GetBundleName() == bundleName &&
9404             (uid == 0 || appRecord->GetUid() == uid) && appRecord->IsMainElementRunning()) {
9405             TAG_LOGD(AAFwkTag::APPMGR, "%{public}s update state: %{public}d",
9406                 bundleName.c_str(), static_cast<int32_t>(enable));
9407                 appRecord->SetKeepAliveDkv(enable);
9408         }
9409     }
9410 }
9411 
9412 void AppMgrServiceInner::SetKeepAliveAppService(const std::string& bundleName, bool enable, int32_t uid)
9413 {
9414     TAG_LOGD(AAFwkTag::APPMGR, "SetKeepAliveAppService called");
9415     if (bundleName.empty()) {
9416         TAG_LOGE(AAFwkTag::APPMGR, "SetKeepAliveAppService bundle name empty");
9417         return;
9418     }
9419 
9420     if (appRunningManager_ == nullptr) {
9421         TAG_LOGE(AAFwkTag::APPMGR, "SetKeepAliveAppService running manager error");
9422         return;
9423     }
9424 
9425     auto callerUid = IPCSkeleton::GetCallingUid();
9426     if (callerUid != FOUNDATION_UID) {
9427         TAG_LOGE(AAFwkTag::APPMGR, "SetKeepAliveAppService not foundation call");
9428         return;
9429     }
9430 
9431     for (const auto& item : appRunningManager_->GetAppRunningRecordMap()) {
9432         const auto& appRecord = item.second;
9433         if (appRecord != nullptr && appRecord->GetBundleName() == bundleName &&
9434             appRecord->GetUid() == uid) {
9435             TAG_LOGD(AAFwkTag::APPMGR, "%{public}s update app service keep alive state: %{public}d", bundleName.c_str(),
9436                 static_cast<int32_t>(enable));
9437             SetKeepAliveAppServiceAndNotify(appRecord, enable);
9438         }
9439     }
9440 }
9441 
9442 void AppMgrServiceInner::SetKeepAliveAppServiceAndNotify(
9443     const std::shared_ptr<AppRunningRecord>& appRecord, bool enable)
9444 {
9445     if (appRecord == nullptr) {
9446         TAG_LOGE(AAFwkTag::APPMGR, "SetKeepAliveAppServiceAndNotify appRecord is nullptr");
9447         return;
9448     }
9449     auto beforState = GetKeepAliveState(appRecord);
9450     appRecord->SetKeepAliveAppService(enable);
9451     auto afterState = GetKeepAliveState(appRecord);
9452     if (beforState != afterState) {
9453         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnKeepAliveStateChanged(appRecord);
9454     }
9455 }
9456 
9457 bool AppMgrServiceInner::GetKeepAliveState(const std::shared_ptr<AppRunningRecord> &appRecord)
9458 {
9459     if (appRecord == nullptr) {
9460         TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr");
9461         return false;
9462     }
9463     return appRecord->IsKeepAliveApp() || appRecord->IsKeepAliveAppService();
9464 }
9465 
9466 int32_t AppMgrServiceInner::SetSupportedProcessCacheSelf(bool isSupport)
9467 {
9468     TAG_LOGI(AAFwkTag::APPMGR, "call");
9469     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9470     if (!appRunningManager_) {
9471         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
9472         return ERR_NO_INIT;
9473     }
9474 
9475     auto callerPid = IPCSkeleton::GetCallingPid();
9476     auto appRecord = GetAppRunningRecordByPid(callerPid);
9477     if (!appRecord) {
9478         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, callerPid:%{public}d", callerPid);
9479         return ERR_INVALID_VALUE;
9480     }
9481 
9482     if (!DelayedSingleton<CacheProcessManager>::GetInstance()->QueryEnableProcessCache()) {
9483         TAG_LOGE(AAFwkTag::APPMGR, "process cache feature is disabled.");
9484         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
9485     }
9486     appRecord->SetSupportedProcessCache(isSupport);
9487     return ERR_OK;
9488 }
9489 
9490 int32_t AppMgrServiceInner::IsProcessCacheSupported(int32_t pid, bool &isSupported)
9491 {
9492     TAG_LOGI(AAFwkTag::APPMGR, "get supported process cache, pid:%{public}d", pid);
9493     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9494     if (!appRunningManager_) {
9495         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
9496         return AAFwk::ERR_NULL_APP_RUNNING_MANAGER;
9497     }
9498 
9499     auto appRecord = GetAppRunningRecordByPid(pid);
9500     if (!appRecord) {
9501         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, pid:%{public}d", pid);
9502         return AAFwk::ERR_NO_APP_RECORD;
9503     }
9504 
9505     if (!DelayedSingleton<CacheProcessManager>::GetInstance()->QueryEnableProcessCache()) {
9506         TAG_LOGE(AAFwkTag::APPMGR, "process cache feature disabled");
9507         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
9508     }
9509     isSupported = (appRecord->GetSupportProcessCacheState() == SupportProcessCacheState::SUPPORT);
9510     return ERR_OK;
9511 }
9512 
9513 int32_t AppMgrServiceInner::SetProcessCacheEnable(int32_t pid, bool enable)
9514 {
9515     TAG_LOGI(AAFwkTag::APPMGR, "set enable process cache, pid:%{public}d, enable:%{public}d", pid, enable);
9516     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9517     if (!appRunningManager_) {
9518         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
9519         return AAFwk::ERR_NULL_APP_RUNNING_MANAGER;
9520     }
9521 
9522     auto appRecord = GetAppRunningRecordByPid(pid);
9523     if (!appRecord) {
9524         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, pid:%{public}d", pid);
9525         return AAFwk::ERR_NO_APP_RECORD;
9526     }
9527 
9528     if (!DelayedSingleton<CacheProcessManager>::GetInstance()->QueryEnableProcessCache()) {
9529         TAG_LOGE(AAFwkTag::APPMGR, "process cache feature disabled");
9530         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
9531     }
9532 
9533     appRecord->SetEnableProcessCache(enable);
9534     return ERR_OK;
9535 }
9536 
9537 int32_t AppMgrServiceInner::SetSupportedProcessCache(int32_t pid, bool isSupport)
9538 {
9539     TAG_LOGI(AAFwkTag::APPMGR, "called");
9540     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9541     if (!appRunningManager_) {
9542         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
9543         return ERR_NO_INIT;
9544     }
9545 
9546     auto appRecord = GetAppRunningRecordByPid(pid);
9547     if (!appRecord) {
9548         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, pid:%{public}d", pid);
9549         return ERR_INVALID_VALUE;
9550     }
9551 
9552     if (!DelayedSingleton<CacheProcessManager>::GetInstance()->QueryEnableProcessCache()) {
9553         TAG_LOGE(AAFwkTag::APPMGR, "process cache feature disabled");
9554         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
9555     }
9556     appRecord->SetEnableProcessCache(isSupport);
9557     return ERR_OK;
9558 }
9559 
9560 bool AppMgrServiceInner::IsAppProcessesAllCached(const std::string &bundleName, int32_t uid,
9561                                                  const std::set<std::shared_ptr<AppRunningRecord>> &cachedSet)
9562 {
9563     if (!appRunningManager_) {
9564         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
9565         return false;
9566     }
9567     return appRunningManager_->IsAppProcessesAllCached(bundleName, uid, cachedSet);
9568 }
9569 
9570 int32_t AppMgrServiceInner::CheckCallingIsUserTestModeInner(const pid_t pid, bool &isUserTest)
9571 {
9572     if (!IsSceneBoardCall()) {
9573         TAG_LOGE(AAFwkTag::APPMGR, "not call");
9574         return AAFwk::CHECK_PERMISSION_FAILED;
9575     }
9576     if (pid <= 0) {
9577         TAG_LOGE(AAFwkTag::APPMGR, "hht-invalid pid:%{public}d", pid);
9578         return ERR_INVALID_VALUE;
9579     }
9580     auto appRecord = GetAppRunningRecordByPid(pid);
9581     if (!appRecord) {
9582         TAG_LOGE(AAFwkTag::APPMGR, "hht-no appRecord");
9583         return ERR_INVALID_VALUE;
9584     }
9585     if (appRecord->GetUserTestInfo() == nullptr) {
9586         TAG_LOGE(AAFwkTag::APPMGR, "hht-no user test info");
9587         return ERR_INVALID_VALUE;
9588     }
9589     isUserTest = true;
9590     return ERR_OK;
9591 }
9592 
9593 bool AppMgrServiceInner::IsSceneBoardCall() {
9594     if (!AAFwk::PermissionVerification::GetInstance()->IsSystemAppCall()) {
9595         TAG_LOGE(AAFwkTag::APPMGR, "not system app call");
9596         return false;
9597     }
9598     if (remoteClientManager_ == nullptr) {
9599         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
9600         return false;
9601     }
9602     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
9603     if (bundleMgrHelper != nullptr) {
9604         int32_t callingUid = IPCSkeleton::GetCallingUid();
9605         std::string callerBundleName;
9606         IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName));
9607         return callerBundleName == SCENE_BOARD_BUNDLE_NAME;
9608     }
9609     return false;
9610 }
9611 
9612 void AppMgrServiceInner::OnAppCacheStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord,
9613     ApplicationState state)
9614 {
9615     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9616     if (!appRecord) {
9617         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
9618         return;
9619     }
9620 
9621     if (appRecord->GetPriorityObject() == nullptr) {
9622         TAG_LOGE(AAFwkTag::APPMGR, "priorityobject null");
9623         return;
9624     }
9625 
9626     TAG_LOGD(AAFwkTag::APPMGR, "OnAppCacheStateChanged begin, bundleName is %{public}s, pid:%{public}d",
9627         appRecord->GetBundleName().c_str(), appRecord->GetPid());
9628 
9629     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppCacheStateChanged(appRecord, state);
9630 }
9631 
9632 #ifdef SUPPORT_CHILD_PROCESS
9633 int32_t AppMgrServiceInner::CreateNativeChildProcess(const pid_t hostPid, const std::string &libName,
9634     int32_t childProcessCount, const sptr<IRemoteObject> &callback, const std::string &customProcessName)
9635 {
9636     TAG_LOGI(AAFwkTag::APPMGR, "hostPid:%{public}d", hostPid);
9637     if (hostPid <= 0 || libName.empty() || !callback) {
9638         TAG_LOGE(AAFwkTag::APPMGR, "invalid param: hostPid:%{public}d libName:%{private}s",
9639             hostPid, libName.c_str());
9640         return ERR_INVALID_VALUE;
9641     }
9642 
9643     if (!CheckCustomProcessName(customProcessName)) {
9644         TAG_LOGE(AAFwkTag::APPMGR, "invalid custom process name");
9645         return ERR_INVALID_VALUE;
9646     }
9647 
9648     int32_t errCode = StartChildProcessPreCheck(hostPid, CHILD_PROCESS_TYPE_NATIVE);
9649     if (errCode != ERR_OK) {
9650         return errCode;
9651     }
9652 
9653     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
9654         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
9655         return ERR_INVALID_OPERATION;
9656     }
9657 
9658     auto appRecord = GetAppRunningRecordByPid(hostPid);
9659     if (!appRecord) {
9660         TAG_LOGI(AAFwkTag::APPMGR, "get record(hostPid:%{public}d) fail", hostPid);
9661         return ERR_INVALID_OPERATION;
9662     }
9663 
9664     if (!AAFwk::AppUtils::GetInstance().IsSupportNativeChildProcess() &&
9665         !AllowNativeChildProcess(CHILD_PROCESS_TYPE_NATIVE, appRecord->GetAppIdentifier()) &&
9666         !AllowChildProcessInMultiProcessFeatureApp(appRecord)) {
9667         TAG_LOGE(AAFwkTag::APPMGR, "unSupport native child process");
9668         return AAFwk::ERR_NOT_SUPPORT_NATIVE_CHILD_PROCESS;
9669     }
9670 
9671     std::lock_guard<std::mutex> lock(childProcessRecordMapMutex_);
9672     auto childRecordMap = appRecord->GetChildProcessRecordMap();
9673     auto count = count_if(childRecordMap.begin(), childRecordMap.end(), [] (const auto &pair) -> bool {
9674         return pair.second->GetChildProcessType() == CHILD_PROCESS_TYPE_NATIVE;
9675     });
9676 
9677     if (count >= PC_MAX_CHILD_PROCESS_NUM) {
9678         TAG_LOGI(AAFwkTag::APPMGR, "The number of native child process reached the limit (hostPid:%{public}d)",
9679             hostPid);
9680         return ERR_OVERFLOW;
9681     }
9682 
9683     pid_t dummyChildPid = 0;
9684     auto nativeChildRecord = ChildProcessRecord::CreateNativeChildProcessRecord(
9685         hostPid, libName, appRecord, callback, childProcessCount, false, customProcessName);
9686     ChildProcessArgs args;
9687     ChildProcessOptions options;
9688     return StartChildProcessImpl(nativeChildRecord, appRecord, dummyChildPid, args, options);
9689 }
9690 
9691 bool AppMgrServiceInner::CheckCustomProcessName(const std::string &customProcessName)
9692 {
9693     if (customProcessName.empty()) {
9694         return true;
9695     }
9696     if (customProcessName.size() > MAX_PROCESS_NAME_LENGTH) {
9697         return false;
9698     }
9699     try {
9700         std::regex regex("^[a-zA-Z0-9_]+$");
9701         if (regex_match(customProcessName, regex)) {
9702             return true;
9703         }
9704     } catch(...) {
9705         TAG_LOGE(AAFwkTag::ABILITYMGR, "regex error");
9706         return false;
9707     }
9708     return false;
9709 }
9710 #endif // SUPPORT_CHILD_PROCESS
9711 
9712 int32_t AppMgrServiceInner::RegisterNativeChildExitNotify(const sptr<INativeChildNotify> &callback)
9713 {
9714     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9715     return AppNativeSpawnManager::GetInstance().RegisterNativeChildExitNotify(callback);
9716 }
9717 
9718 int32_t AppMgrServiceInner::UnregisterNativeChildExitNotify(const sptr<INativeChildNotify> &callback)
9719 {
9720     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9721     return AppNativeSpawnManager::GetInstance().UnregisterNativeChildExitNotify(callback);
9722 }
9723 
9724 void AppMgrServiceInner::CacheLoadAbilityTask(const LoadAbilityTaskFunc&& func)
9725 {
9726     std::lock_guard lock(loadTaskListMutex_);
9727     loadAbilityTaskFuncList_.emplace_back(std::move(func));
9728 }
9729 
9730 void AppMgrServiceInner::SubmitCacheLoadAbilityTask()
9731 {
9732     std::lock_guard lock(loadTaskListMutex_);
9733     std::weak_ptr<AAFwk::TaskHandlerWrap> taskHandler = taskHandler_;
9734     for_each(loadAbilityTaskFuncList_.begin(), loadAbilityTaskFuncList_.end(),
9735         [taskHandler](LoadAbilityTaskFunc loadAbilityFunc) {
9736             auto LoadAbilityhandler = taskHandler.lock();
9737             if (LoadAbilityhandler != nullptr && loadAbilityFunc) {
9738                 LoadAbilityhandler->SubmitTask(loadAbilityFunc, "loadAbilityFunc");
9739             }
9740         });
9741     loadAbilityTaskFuncList_.clear();
9742 }
9743 
9744 bool AppMgrServiceInner::GetSceneBoardAttachFlag() const
9745 {
9746     return sceneBoardAttachFlag_;
9747 }
9748 
9749 void AppMgrServiceInner::SetSceneBoardAttachFlag(bool flag)
9750 {
9751     sceneBoardAttachFlag_ = flag;
9752 }
9753 
9754 void AppMgrServiceInner::AttachedToStatusBar(const sptr<IRemoteObject> &token)
9755 {
9756     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
9757     auto appRecord = GetAppRunningRecordByAbilityToken(token);
9758     if (appRecord == nullptr) {
9759         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord null");
9760         return;
9761     }
9762     appRecord->SetAttachedToStatusBar(true);
9763 }
9764 
9765 int32_t AppMgrServiceInner::NotifyProcessDependedOnWeb()
9766 {
9767     int32_t pid = IPCSkeleton::GetCallingPid();
9768     auto appRecord = GetAppRunningRecordByPid(pid);
9769     if (appRecord == nullptr) {
9770         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord");
9771         return ERR_INVALID_VALUE;
9772     }
9773     TAG_LOGD(AAFwkTag::APPMGR, "call");
9774     appRecord->SetIsDependedOnArkWeb(true);
9775     return ERR_OK;
9776 }
9777 
9778 void AppMgrServiceInner::KillProcessDependedOnWeb()
9779 {
9780     TAG_LOGI(AAFwkTag::APPMGR, "call");
9781     CHECK_POINTER_AND_RETURN_LOG(appRunningManager_, "appRunningManager_ is nullptr");
9782     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
9783         const auto &appRecord = item.second;
9784         if (!appRecord || !appRecord->GetSpawned() ||
9785             !appRecord->GetPriorityObject() || !appRecord->IsDependedOnArkWeb()) {
9786             continue;
9787         }
9788 
9789         std::string bundleName = appRecord->GetBundleName();
9790         pid_t pid = appRecord->GetPid();
9791         if (appRecord->IsKeepAliveApp()) {
9792             ExitResidentProcessManager::GetInstance().RecordExitResidentBundleDependedOnWeb(bundleName,
9793                 appRecord->GetUid());
9794         }
9795         KillProcessByPid(pid, "KillProcessDependedOnWeb");
9796     }
9797 }
9798 
9799 void AppMgrServiceInner::RestartResidentProcessDependedOnWeb()
9800 {
9801     TAG_LOGD(AAFwkTag::APPMGR, "call");
9802     std::vector<ExitResidentProcessInfo> bundleNames;
9803     ExitResidentProcessManager::GetInstance().HandleExitResidentBundleDependedOnWeb(bundleNames);
9804     if (bundleNames.empty()) {
9805         TAG_LOGE(AAFwkTag::APPMGR, "exit resident bundle names empty");
9806         return;
9807     }
9808 
9809     auto RestartResidentProcessDependedOnWebTask = [bundleNames, innerServiceWeak = weak_from_this()]() {
9810         auto innerService = innerServiceWeak.lock();
9811         CHECK_POINTER_AND_RETURN_LOG(innerService, "get AppMgrServiceInner failed");
9812         std::vector<AppExecFwk::BundleInfo> exitBundleInfos;
9813         ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(bundleNames, exitBundleInfos);
9814 
9815         innerService->NotifyStartResidentProcess(exitBundleInfos);
9816         innerService->NotifyStartKeepAliveProcess(exitBundleInfos);
9817     };
9818     CHECK_POINTER_AND_RETURN_LOG(taskHandler_, "taskHandler_ null");
9819     taskHandler_->SubmitTask(RestartResidentProcessDependedOnWebTask, "RestartResidentProcessDependedOnWeb");
9820 }
9821 
9822 void AppMgrServiceInner::BlockProcessCacheByPids(const std::vector<int32_t>& pids)
9823 {
9824     for (const auto& pid : pids) {
9825         auto appRecord = GetAppRunningRecordByPid(pid);
9826         if (appRecord == nullptr) {
9827             TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
9828             continue;
9829         }
9830         appRecord->SetProcessCacheBlocked(true);
9831         DelayedSingleton<CacheProcessManager>::GetInstance()->OnAppProcessCacheBlocked(appRecord);
9832     }
9833 }
9834 
9835 bool AppMgrServiceInner::CleanAbilityByUserRequest(const sptr<IRemoteObject> &token)
9836 {
9837     TAG_LOGD(AAFwkTag::APPMGR, "call");
9838     if (!token) {
9839         TAG_LOGE(AAFwkTag::APPMGR, "token invalid");
9840         return false;
9841     }
9842 
9843     if (!appRunningManager_) {
9844         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ invalid");
9845         return false;
9846     }
9847 
9848     pid_t targetPid = 0;
9849     int32_t targetUid = 0;
9850     if (!appRunningManager_->HandleUserRequestClean(token, targetPid, targetUid)) {
9851         TAG_LOGW(AAFwkTag::APPMGR, "can not clean process");
9852         return false;
9853     }
9854 
9855     if (targetPid <= 0 || targetUid <= 0) {
9856         TAG_LOGE(AAFwkTag::APPMGR, "get pid or uid invalid, pid:%{public}d, uid:%{public}d", targetPid, targetUid);
9857         return false;
9858     }
9859     TAG_LOGI(AAFwkTag::APPMGR, "clean ability set up bg, force kill pid:%{public}d", targetPid);
9860     willKillPidsNum_ += 1;
9861     int32_t delayTime = (willKillPidsNum_ * KILL_PROCESS_BY_USER_INTERVAL + KILL_PROCESS_BY_USER_DELAY_BASE) *
9862         AbilityRuntime::GlobalConstant::TIMEOUT_UNIT_TIME;
9863     TAG_LOGD(AAFwkTag::APPMGR, "delayTime:%{public}d", delayTime);
9864     auto delayKillTask = [targetPid, innerServiceWeak = weak_from_this()]() {
9865         auto self = innerServiceWeak.lock();
9866         CHECK_POINTER_AND_RETURN_LOG(self, "get AppMgrServiceInner failed");
9867         self->KillProcessByPid(targetPid, KILL_REASON_USER_REQUEST);
9868         self->DecreaseWillKillPidsNum();
9869         TAG_LOGD(AAFwkTag::APPMGR, "pid:%{public}d killed", targetPid);
9870     };
9871     ffrt::submit(std::move(delayKillTask), ffrt::task_attr().name("delayKillUIAbility").delay(delayTime)
9872         .timeout(AbilityRuntime::GlobalConstant::DEFAULT_FFRT_TASK_TIMEOUT));
9873 
9874     return true;
9875 }
9876 
9877 void AppMgrServiceInner::CheckCleanAbilityByUserRequest(const std::shared_ptr<AppRunningRecord> &appRecord,
9878     const std::shared_ptr<AbilityRunningRecord> &abilityRecord, const AbilityState state)
9879 {
9880     if (!appRecord || !abilityRecord) {
9881         return;
9882     }
9883 
9884     if (state != AbilityState::ABILITY_STATE_BACKGROUND) {
9885         return;
9886     }
9887 
9888     if (abilityRecord->GetAbilityInfo() && abilityRecord->GetAbilityInfo()->type != AppExecFwk::AbilityType::PAGE) {
9889         return;
9890     }
9891 
9892     if (appRecord->IsKeepAliveApp()) {
9893         return;
9894     }
9895 
9896     if (!appRecord->IsAllAbilityReadyToCleanedByUserRequest()) {
9897         TAG_LOGD(AAFwkTag::APPMGR,
9898             "not ready to clean when user request. bundleName:%{public}s", appRecord->GetBundleName().c_str());
9899         return;
9900     }
9901     appRecord->SetUserRequestCleaning();
9902 
9903     pid_t pid = 0;
9904     if (appRecord->GetPriorityObject()) {
9905         pid = appRecord->GetPid();
9906     }
9907     TAG_LOGI(AAFwkTag::APPMGR, "clean ability set up bg, force kill, pid:%{public}d", pid);
9908     KillProcessByPid(pid, KILL_REASON_USER_REQUEST);
9909 }
9910 
9911 bool AppMgrServiceInner::IsKilledForUpgradeWeb(const std::string &bundleName) const
9912 {
9913     auto callerUid = IPCSkeleton::GetCallingUid();
9914     if (callerUid != FOUNDATION_UID) {
9915         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
9916         return false;
9917     }
9918     return ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(bundleName);
9919 }
9920 
9921 int32_t AppMgrServiceInner::GetPidsByAccessTokenId(const uint32_t accessTokenId, std::vector<pid_t> &pids)
9922 {
9923     if (!appRunningManager_) {
9924         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
9925         return ERR_NO_INIT;
9926     }
9927     std::vector<pid_t> foregroundPids;
9928     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
9929         const auto &appRecord = item.second;
9930         if (!appRecord || !appRecord->GetSpawned()) {
9931             continue;
9932         }
9933         auto applicationInfo = appRecord->GetApplicationInfo();
9934         if (!applicationInfo) {
9935             continue;
9936         }
9937         if (accessTokenId == applicationInfo->accessTokenId) {
9938             pid_t curPid = appRecord->GetPid();
9939             if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
9940                 foregroundPids.push_back(curPid);
9941                 continue;
9942             }
9943             pids.push_back(curPid);
9944         }
9945     }
9946     for (pid_t foregroundPid : foregroundPids) {
9947         pids.push_back(foregroundPid);
9948     }
9949     return ERR_OK;
9950 }
9951 
9952 bool AppMgrServiceInner::IsProcessContainsOnlyUIAbility(const pid_t pid)
9953 {
9954     auto appRecord = GetAppRunningRecordByPid(pid);
9955     if (appRecord == nullptr) {
9956         return false;
9957     }
9958 
9959     auto abilityRecordList = appRecord->GetAbilities();
9960 
9961     for (auto it = abilityRecordList.begin(); it != abilityRecordList.end(); ++it) {
9962         if (it->second == nullptr) {
9963             return false;
9964         }
9965         auto abilityInfo = it->second->GetAbilityInfo();
9966         if (abilityInfo == nullptr) {
9967             return false;
9968         }
9969 
9970         bool isUIAbility = (abilityInfo->type == AppExecFwk::AbilityType::PAGE);
9971         if (!isUIAbility) {
9972             return false;
9973         }
9974     }
9975     return true;
9976 }
9977 
9978 bool AppMgrServiceInner::IsIsolateExtensionSandBox(const std::shared_ptr<AbilityInfo> &abilityInfo,
9979     const HapModuleInfo &hapModuleInfo) const
9980 {
9981     if (abilityInfo == nullptr) {
9982         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo nullptr");
9983         return false;
9984     }
9985     auto type = abilityInfo->type;
9986     auto extensionType = abilityInfo->extensionAbilityType;
9987     if (type != AppExecFwk::AbilityType::EXTENSION ||
9988         extensionType == AppExecFwk::ExtensionAbilityType::DATASHARE ||
9989         extensionType == AppExecFwk::ExtensionAbilityType::SERVICE) {
9990         return false;
9991     }
9992     for (const auto& extensionInfo: hapModuleInfo.extensionInfos) {
9993         if (extensionInfo.name == abilityInfo->name) {
9994             return extensionInfo.needCreateSandbox;
9995         }
9996     }
9997     return false;
9998 }
9999 
10000 bool AppMgrServiceInner::IsProcessAttached(sptr<IRemoteObject> token) const
10001 {
10002     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
10003     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
10004         TAG_LOGE(AAFwkTag::APPMGR, "not foundation call");
10005         return false;
10006     }
10007     auto appRecord = GetAppRunningRecordByAbilityToken(token);
10008     if (appRecord == nullptr) {
10009         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord null");
10010         return false;
10011     }
10012     return appRecord->IsProcessAttached();
10013 }
10014 
10015 bool AppMgrServiceInner::IsCallerKilling(const std::string& callerKey) const
10016 {
10017     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
10018     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
10019         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
10020         return false;
10021     }
10022     return KillingProcessManager::GetInstance().IsCallerKilling(callerKey);
10023 }
10024 
10025 int32_t AppMgrServiceInner::GetSupportedProcessCachePids(const std::string &bundleName,
10026     std::vector<int32_t> &pidList)
10027 {
10028     auto cachePrcoMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
10029     auto osAccountMgr = DelayedSingleton<OsAccountManagerWrapper>::GetInstance();
10030     if (cachePrcoMgr == nullptr || osAccountMgr == nullptr || appRunningManager_ == nullptr) {
10031         TAG_LOGE(AAFwkTag::APPMGR, "inner manager null");
10032         return AAFwk::INNER_ERR;
10033     }
10034     pidList.clear();
10035     int32_t callderUserId = -1;
10036     int32_t getOsAccountRet = osAccountMgr->GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), callderUserId);
10037     if (getOsAccountRet != 0) {
10038         TAG_LOGE(AAFwkTag::APPMGR, "get caller local id fail. ret: %{public}d", getOsAccountRet);
10039         return AAFwk::INNER_ERR;
10040     }
10041     TAG_LOGD(AAFwkTag::APPMGR, "callderUserId: %{public}d", callderUserId);
10042     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
10043         auto appRecord = item.second;
10044         if (appRecord == nullptr) {
10045             continue;
10046         }
10047         int32_t procUserId = -1;
10048         int32_t procGetOsAccountRet = osAccountMgr->GetOsAccountLocalIdFromUid(appRecord->GetUid(), procUserId);
10049         if (appRecord->GetBundleName() == bundleName && procGetOsAccountRet == 0 &&
10050             procUserId == callderUserId && cachePrcoMgr->IsAppSupportProcessCache(appRecord) &&
10051             appRecord->GetPriorityObject() != nullptr) {
10052             TAG_LOGD(AAFwkTag::APPMGR,
10053                 "procUserId: %{public}d, procGetOsAccountRet: %{public}d", procUserId, procGetOsAccountRet);
10054             pidList.push_back(appRecord->GetPid());
10055         }
10056     }
10057     return ERR_OK;
10058 }
10059 
10060 int AppMgrServiceInner::RegisterKiaInterceptor(const sptr<IKiaInterceptor> &interceptor)
10061 {
10062     TAG_LOGI(AAFwkTag::APPMGR, "call");
10063     if (!AAFwk::AppUtils::GetInstance().IsStartOptionsWithAnimation() ||
10064         !AAFwk::PermissionVerification::GetInstance()->VerifySuperviseKiaServicePermission()) {
10065         TAG_LOGE(AAFwkTag::APPMGR, "no kia permission.");
10066         return ERR_PERMISSION_DENIED;
10067     }
10068     if (interceptor == nullptr) {
10069         TAG_LOGE(AAFwkTag::APPMGR, "interceptor is nullptr.");
10070         return ERR_INVALID_VALUE;
10071     }
10072     kiaInterceptor_ = interceptor;
10073     return ERR_OK;
10074 }
10075 
10076 int32_t AppMgrServiceInner::CheckIsKiaProcess(pid_t pid, bool &isKia)
10077 {
10078     TAG_LOGI(AAFwkTag::APPMGR, "call");
10079     if (!AAFwk::AppUtils::GetInstance().IsStartOptionsWithAnimation() ||
10080         !AAFwk::PermissionVerification::GetInstance()->VerifySuperviseKiaServicePermission()) {
10081         TAG_LOGE(AAFwkTag::APPMGR, "no kia permission.");
10082         return ERR_PERMISSION_DENIED;
10083     }
10084     if (!appRunningManager_) {
10085         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
10086         return ERR_INVALID_VALUE;
10087     }
10088     return appRunningManager_->CheckIsKiaProcess(pid, isKia);
10089 }
10090 
10091 void AppMgrServiceInner::UpdateInstanceKeyBySpecifiedId(int32_t specifiedId, std::string &instanceKey)
10092 {
10093     if (!appRunningManager_) {
10094         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
10095         return;
10096     }
10097     appRunningManager_->UpdateInstanceKeyBySpecifiedId(specifiedId, instanceKey);
10098 }
10099 
10100 void AppMgrServiceInner::SendAppSpawnUninstallDebugHapMsg(int32_t userId)
10101 {
10102     if (remoteClientManager_ == nullptr) {
10103         TAG_LOGE(AAFwkTag::APPMGR, "null remoteClientManager_");
10104         return;
10105     }
10106     auto spawnClient = remoteClientManager_->GetSpawnClient();
10107     if (spawnClient == nullptr) {
10108         TAG_LOGE(AAFwkTag::APPMGR, "null spawnClient");
10109         return;
10110     }
10111     auto errCode = spawnClient->SendAppSpawnUninstallDebugHapMsg(userId);
10112     if (FAILED(errCode)) {
10113         TAG_LOGE(AAFwkTag::APPMGR, "SendAppSpawnUninstallDebugHapMsg failed, errCode %{public}08x", errCode);
10114     }
10115 }
10116 
10117 bool AppMgrServiceInner::IsSpecifiedModuleLoaded(const AAFwk::Want &want, const AbilityInfo &abilityInfo,
10118     bool &isDebug)
10119 {
10120     if (!CheckRemoteClient() || !appRunningManager_) {
10121         return false;
10122     }
10123     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
10124     int32_t appIndex = 0;
10125     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
10126     BundleInfo bundleInfo;
10127     HapModuleInfo hapModuleInfo;
10128     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
10129         return false;
10130     }
10131 
10132     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
10133     std::string processName;
10134     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, "", processName, false);
10135     auto instanceKey = want.GetStringParam(Want::APP_INSTANCE_KEY);
10136     auto customProcessFlag = abilityInfo.process;
10137     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name,
10138         processName, appInfo->uid, bundleInfo, "", nullptr, instanceKey, customProcessFlag);
10139     if (appRecord == nullptr) {
10140         return false;
10141     }
10142     isDebug = appRecord->IsDebug();
10143 
10144     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
10145     if (moduleRecord == nullptr) {
10146         return false;
10147     }
10148     TAG_LOGD(AAFwkTag::APPMGR, "IsSpecifiedModuleLoaded state %{public}d", moduleRecord->GetModuleRecordState());
10149     return moduleRecord->IsLoaded();
10150 }
10151 
10152 void AppMgrServiceInner::SendAbilityEvent(const std::shared_ptr<AbilityRunningRecord> &abilityRecord,
10153     const AbilityState &state)
10154 {
10155     if (abilityRecord == nullptr) {
10156         TAG_LOGE(AAFwkTag::APPMGR, "null abilityRecord");
10157         return;
10158     }
10159 
10160     auto abilityInfo = abilityRecord->GetAbilityInfo();
10161     if (abilityInfo == nullptr) {
10162         TAG_LOGE(AAFwkTag::APPMGR, "null abilityInfo");
10163         return;
10164     }
10165 
10166     auto want = abilityRecord->GetWant();
10167     if (want == nullptr) {
10168         TAG_LOGE(AAFwkTag::APPMGR, "null want");
10169         return;
10170     }
10171 
10172     AAFwk::EventInfo eventInfo;
10173     eventInfo.abilityName = abilityRecord->GetName();
10174     eventInfo.moduleName = abilityRecord->GetModuleName();
10175     eventInfo.bundleName = abilityRecord->GetBundleName();
10176     eventInfo.bundleType = static_cast<int32_t>(abilityInfo->applicationInfo.bundleType);
10177     eventInfo.appIndex = abilityInfo->applicationInfo.appIndex;
10178     if (state == AppExecFwk::AbilityState::ABILITY_STATE_FOREGROUND) {
10179         eventInfo.callerBundleName = want->GetStringParam(Want::PARAM_RESV_CALLER_BUNDLE_NAME);
10180         eventInfo.lifeCycleState = LIFE_CYCLE_STATE_START_FOREGROUND;
10181         AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::ABILITY_ONFOREGROUND,
10182             HiSysEventType::BEHAVIOR, eventInfo);
10183     } else if (state == AppExecFwk::AbilityState::ABILITY_STATE_BACKGROUND) {
10184         eventInfo.lifeCycleState = LIFE_CYCLE_STATE_START_BACKGROUND;
10185         AAFwk::EventReport::SendAbilityEvent(AAFwk::EventName::ABILITY_ONBACKGROUND,
10186             HiSysEventType::BEHAVIOR, eventInfo);
10187     }
10188 }
10189 
10190 int32_t AppMgrServiceInner::LaunchAbility(sptr<IRemoteObject> token)
10191 {
10192     auto appRecord = GetAppRunningRecordByAbilityToken(token);
10193     if (appRecord == nullptr) {
10194         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
10195         return AAFwk::ERR_NULL_APP_RUNNING_MANAGER;
10196     }
10197     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
10198     if (ability == nullptr) {
10199         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord null");
10200         return ERR_INVALID_VALUE;
10201     }
10202     auto want = ability->GetWant();
10203     if (want == nullptr) {
10204         TAG_LOGE(AAFwkTag::APPMGR, "want null");
10205         return ERR_INVALID_VALUE;
10206     }
10207     want->SetParam(REUSING_WINDOW, true);
10208     appRecord->LaunchAbility(ability);
10209     return ERR_OK;
10210 }
10211 
10212 void AppMgrServiceInner::AddUIExtensionBindItem(
10213     std::shared_ptr<AAFwk::Want> want, std::shared_ptr<AppRunningRecord> appRecord, sptr<IRemoteObject> token)
10214 {
10215     if (want == nullptr || appRecord == nullptr || token == nullptr || appRunningManager_ == nullptr) {
10216         TAG_LOGE(AAFwkTag::APPMGR, "invalid input params");
10217         return;
10218     }
10219 
10220     auto notifyProcessBind = want->GetIntParam(UIEXTENSION_NOTIFY_BIND, -1);
10221     if (notifyProcessBind != 1) {
10222         TAG_LOGE(AAFwkTag::APPMGR, "no bind permission");
10223         return;
10224     }
10225 
10226     UIExtensionProcessBindInfo bindInfo;
10227     if (!WrapBindInfo(want, appRecord, bindInfo)) {
10228         TAG_LOGE(AAFwkTag::APPMGR, "wrap bindInfo fail");
10229         return;
10230     }
10231     auto uiExtensionBindAbilityId = want->GetIntParam(UIEXTENSION_BIND_ABILITY_ID, -1);
10232     appRunningManager_->AddUIExtensionBindItem(uiExtensionBindAbilityId, bindInfo);
10233     BindUIExtensionProcess(appRecord, bindInfo);
10234     want->RemoveParam(UIEXTENSION_HOST_PID);
10235     want->RemoveParam(UIEXTENSION_HOST_UID);
10236     want->RemoveParam(UIEXTENSION_HOST_BUNDLENAME);
10237     want->RemoveParam(UIEXTENSION_NOTIFY_BIND);
10238 }
10239 
10240 void AppMgrServiceInner::RemoveUIExtensionBindItem(
10241     std::shared_ptr<AppRunningRecord> appRecord, sptr<IRemoteObject> token)
10242 {
10243     if (appRecord == nullptr || token == nullptr || appRunningManager_ == nullptr) {
10244         TAG_LOGE(AAFwkTag::APPMGR, "invalid input params");
10245         return;
10246     }
10247 
10248     auto abilityRunningRecord = appRecord->GetAbilityRunningRecordByToken(token);
10249     if (abilityRunningRecord == nullptr) {
10250         TAG_LOGW(AAFwkTag::APPMGR, "invalid ability");
10251         return;
10252     }
10253 
10254     auto abilityInfo = abilityRunningRecord->GetAbilityInfo();
10255     if (abilityInfo == nullptr) {
10256         TAG_LOGW(AAFwkTag::APPMGR, "invalid ability");
10257         return;
10258     }
10259 
10260     if (!AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
10261         TAG_LOGE(AAFwkTag::APPMGR, "not uiextension");
10262         return;
10263     }
10264 
10265     auto uiExtensionBindAbilityId = abilityRunningRecord->GetUIExtensionBindAbilityId();
10266     UIExtensionProcessBindInfo bindInfo;
10267     auto result = appRunningManager_->QueryUIExtensionBindItemById(uiExtensionBindAbilityId, bindInfo);
10268     if (result != ERR_OK) {
10269         TAG_LOGE(AAFwkTag::APPMGR, "bindInfo not exist");
10270         return;
10271     }
10272     if (bindInfo.notifyProcessBind != 1) {
10273         TAG_LOGE(AAFwkTag::APPMGR, "no unbind permission");
10274         return;
10275     }
10276     UnBindUIExtensionProcess(appRecord, bindInfo);
10277     appRunningManager_->RemoveUIExtensionBindItemById(uiExtensionBindAbilityId);
10278 }
10279 
10280 void AppMgrServiceInner::BindUIExtensionProcess(
10281     const std::shared_ptr<AppRunningRecord> &appRecord, const UIExtensionProcessBindInfo &bindInfo)
10282 {
10283     std::lock_guard guard(uiExtensionBindReleationsLock_);
10284     auto pid = bindInfo.pid;
10285     auto callerPid = bindInfo.callerPid;
10286     auto it = uiExtensionBindReleations_.find(pid);
10287 
10288     if (it == uiExtensionBindReleations_.end() || it->second.find(callerPid) == it->second.end()) {
10289         uiExtensionBindReleations_[pid][callerPid] = 1;
10290         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessBindingRelationChanged(
10291             appRecord, bindInfo, 1);
10292     } else {
10293         it->second[callerPid]++;
10294     }
10295 }
10296 
10297 void AppMgrServiceInner::UnBindUIExtensionProcess(
10298     const std::shared_ptr<AppRunningRecord> &appRecord, const UIExtensionProcessBindInfo &bindInfo)
10299 {
10300     std::lock_guard guard(uiExtensionBindReleationsLock_);
10301     auto pid = bindInfo.pid;
10302     auto callerPid = bindInfo.callerPid;
10303     auto it = uiExtensionBindReleations_.find(pid);
10304 
10305     if (it != uiExtensionBindReleations_.end()) {
10306         auto &innerMap = it->second;
10307         auto innerIt = innerMap.find(callerPid);
10308         if (innerIt != innerMap.end()) {
10309             innerIt->second--;
10310             if (innerIt->second == 0) {
10311                 DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessBindingRelationChanged(
10312                     appRecord, bindInfo, 0);
10313                 innerMap.erase(innerIt);
10314             }
10315         }
10316         if (innerMap.empty()) {
10317             uiExtensionBindReleations_.erase(it);
10318         }
10319     }
10320 }
10321 
10322 bool AppMgrServiceInner::WrapBindInfo(std::shared_ptr<AAFwk::Want> &want, std::shared_ptr<AppRunningRecord> &appRecord,
10323     UIExtensionProcessBindInfo &bindInfo)
10324 {
10325     auto notifyProcessBind = want->GetIntParam(UIEXTENSION_NOTIFY_BIND, -1);
10326     auto uiExtensionBindAbilityId = want->GetIntParam(UIEXTENSION_BIND_ABILITY_ID, -1);
10327     auto callerPid = want->GetIntParam(UIEXTENSION_HOST_PID, -1);
10328     auto callerUid = want->GetIntParam(UIEXTENSION_HOST_UID, -1);
10329     auto callerBundleName = want->GetStringParam(UIEXTENSION_HOST_BUNDLENAME);
10330     pid_t providerPid = -1;
10331     pid_t providerUid = -1;
10332     if (appRecord->GetPriorityObject() != nullptr) {
10333         providerPid = appRecord->GetPid();
10334         providerUid = appRecord->GetUid();
10335     }
10336     TAG_LOGI(AAFwkTag::APPMGR,
10337         "uiExtensionBindAbilityId: %{public}d, providerUid: "
10338         "%{public}d,providerPid: %{public}d,callerUid: %{public}d, "
10339         "callerPid: %{public}d,callerBundleName: %{public}s",
10340         uiExtensionBindAbilityId,
10341         providerUid,
10342         providerPid,
10343         callerUid,
10344         callerPid,
10345         callerBundleName.c_str());
10346     if (uiExtensionBindAbilityId == -1 || providerPid == -1 || providerUid == -1 || callerPid == -1 ||
10347         callerUid == -1 || callerBundleName.empty()) {
10348         TAG_LOGE(AAFwkTag::APPMGR, "invalid want params");
10349         return false;
10350     }
10351     bindInfo.pid = providerPid;
10352     bindInfo.uid = providerUid;
10353     bindInfo.callerPid = callerPid;
10354     bindInfo.callerUid = callerUid;
10355     bindInfo.callerBundleName = callerBundleName;
10356     bindInfo.notifyProcessBind = notifyProcessBind;
10357     bindInfo.isKeepAlive = appRecord->IsKeepAliveApp();
10358     bindInfo.extensionType = appRecord->GetExtensionType();
10359     bindInfo.processType = appRecord->GetProcessType();
10360     return true;
10361 }
10362 
10363 int32_t AppMgrServiceInner::PromoteCurrentToCandidateMasterProcess(bool isInsertToHead)
10364 {
10365     TAG_LOGI(AAFwkTag::APPMGR, "call");
10366     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
10367 
10368     if (!appRunningManager_) {
10369         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ null");
10370         return AAFwk::ERR_NOT_ISOLATION_PROCESS;
10371     }
10372 
10373     auto callerPid = IPCSkeleton::GetCallingPid();
10374     auto appRecord = GetAppRunningRecordByPid(callerPid);
10375     if (!appRecord) {
10376         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, callerPid:%{public}d", callerPid);
10377         return AAFwk::ERR_NOT_ISOLATION_PROCESS;
10378     }
10379 
10380     if (!AAFwk::AppUtils::GetInstance().IsStartSpecifiedProcess()) {
10381         TAG_LOGE(AAFwkTag::APPMGR, "Capability not support");
10382         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
10383     }
10384 
10385     if (appRecord->GetSpecifiedProcessFlag() == "" &&
10386         !appRecord->GetIsMasterProcess()) {
10387         TAG_LOGE(AAFwkTag::APPMGR, "Current process is not running a component "
10388                                     "configured with \"isolationProcess\".");
10389         return AAFwk::ERR_NOT_ISOLATION_PROCESS;
10390     }
10391 
10392     auto now = std::chrono::steady_clock::now().time_since_epoch();
10393     int64_t timeStamp = std::chrono::duration_cast<std::chrono::nanoseconds>(now).count();
10394     if(!isInsertToHead){
10395         timeStamp = -timeStamp;
10396     }
10397     appRecord->SetTimeStamp(timeStamp);
10398     return ERR_OK;
10399 }
10400 
10401 int32_t AppMgrServiceInner::DemoteCurrentFromCandidateMasterProcess()
10402 {
10403     TAG_LOGD(AAFwkTag::APPMGR, "call");
10404     int32_t pid = IPCSkeleton::GetCallingPid();
10405     auto appRecord = GetAppRunningRecordByPid(pid);
10406     if (appRecord == nullptr) {
10407         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord");
10408         return AAFwk::ERR_NOT_CANDIDATE_MASTER_PROCESS;
10409     }
10410 
10411     if (!AAFwk::AppUtils::GetInstance().IsStartSpecifiedProcess()) {
10412         TAG_LOGE(AAFwkTag::APPMGR, "Capability not support");
10413         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
10414     }
10415 
10416     if (appRecord->GetIsMasterProcess()) {
10417         TAG_LOGE(AAFwkTag::APPMGR, "Current process is already a master process");
10418         return AAFwk::ERR_ALREADY_MASTER_PROCESS;
10419     }
10420 
10421     if (appRecord->GetTimeStamp() == 0) {
10422         TAG_LOGE(AAFwkTag::APPMGR, "Current process is not a candidate master process");
10423         return AAFwk::ERR_NOT_CANDIDATE_MASTER_PROCESS;
10424     }
10425 
10426     appRecord->SetTimeStamp(0);
10427 
10428     return ERR_OK;
10429 }
10430 
10431 void AppMgrServiceInner::OnProcessDied(std::shared_ptr<AppRunningRecord> appRecord)
10432 {
10433     if (appRunningManager_ == nullptr) {
10434         TAG_LOGE(AAFwkTag::APPMGR, "running manager null");
10435         return;
10436     }
10437     if (appRunningManager_->NeedNotifyAppStateChangeWhenProcessDied(appRecord)) {
10438         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND, true, false);
10439     }
10440     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
10441 }
10442 
10443 bool AppMgrServiceInner::IsBlockedByDisposeRules(const std::string &bundleName, int32_t userId,
10444     int32_t appIndex)
10445 {
10446     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10447     // get bms
10448     auto bundleMgrHelper = DelayedSingleton<AppExecFwk::BundleMgrHelper>::GetInstance();
10449     if (bundleMgrHelper == nullptr) {
10450         TAG_LOGE(AAFwkTag::ABILITYMGR, "null bundleMgrHelper");
10451         return false;
10452     }
10453 
10454     // get disposed status
10455     auto appControlMgr = bundleMgrHelper->GetAppControlProxy();
10456     if (appControlMgr == nullptr) {
10457         TAG_LOGE(AAFwkTag::ABILITYMGR, "null appControlMgr");
10458         return false;
10459     }
10460     std::vector<AppExecFwk::DisposedRule> disposedRuleList;
10461     {
10462         HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, "GetAbilityRunningControlRule");
10463         int32_t ret = ERR_OK;
10464         if (appIndex > 0 && appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
10465             ret = IN_PROCESS_CALL(appControlMgr->GetAbilityRunningControlRule(bundleName,
10466                 userId, disposedRuleList, appIndex));
10467         } else {
10468             ret = IN_PROCESS_CALL(appControlMgr->GetAbilityRunningControlRule(bundleName,
10469                 userId, disposedRuleList, 0));
10470         }
10471         if (ret != ERR_OK || disposedRuleList.empty()) {
10472             TAG_LOGD(AAFwkTag::ABILITYMGR, "Get No DisposedRule");
10473             return false;
10474         }
10475     }
10476 
10477     for (auto &rule: disposedRuleList) {
10478         if (rule.controlType == AppExecFwk::ControlType::DISALLOWED_LIST &&
10479             rule.disposedType == AppExecFwk::DisposedType::BLOCK_APPLICATION) {
10480             return true;
10481         }
10482     }
10483 
10484     return false;
10485 }
10486 
10487 int32_t AppMgrServiceInner:: PreCheckStartProcess(const std::string &bundleName, int32_t uid,
10488     std::shared_ptr<AAFwk::Want> &want)
10489 {
10490     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10491     if (!IsUninstallingOrUpgrading(uid)) {
10492         return ERR_OK;
10493     }
10494     int32_t userId = uid / BASE_USER_RANGE;
10495     int32_t appIndex = 0;
10496     if (want != nullptr) {
10497         (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, appIndex);
10498     }
10499     if (IsBlockedByDisposeRules(bundleName, userId, appIndex)) {
10500         return AAFwk::ERR_UNINSTALLING_OR_UPGRADING_APP;
10501     }
10502     RemoveUninstallOrUpgradeUidSet(uid);
10503     return ERR_OK;
10504 }
10505 
10506 int32_t AppMgrServiceInner::QueryRunningSharedBundles(pid_t pid, std::map<std::string, uint32_t> &sharedBundles)
10507 {
10508     TAG_LOGI(AAFwkTag::APPMGR, "QueryRunningSharedBundles call, pid:%{public}d", pid);
10509     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
10510     auto appRecord = GetAppRunningRecordByPid(pid);
10511     if (!appRecord) {
10512         TAG_LOGW(AAFwkTag::APPMGR, "No app record for pid: %{public}d", pid);
10513         return AAFwk::ERR_NO_APP_RECORD;
10514     }
10515     const auto &hspList = appRecord->GetStartMsg().hspList;
10516     for (const auto &item: hspList) {
10517         sharedBundles.emplace(item.bundleName, item.versionCode);
10518     }
10519     return ERR_OK;
10520 }
10521 } // namespace AppExecFwk
10522 }  // namespace OHOS
10523