• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2021-2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include "app_mgr_service_inner.h"
17 
18 #include <cinttypes>
19 #include <csignal>
20 #include <cstdint>
21 #include <mutex>
22 #include <queue>
23 #include <securec.h>
24 #include <sstream>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 
28 #include "ability_manager_errors.h"
29 #include "ability_window_configuration.h"
30 #include "accesstoken_kit.h"
31 #include "app_config_data_manager.h"
32 #include "app_mem_info.h"
33 #include "app_mgr_service.h"
34 #include "app_mgr_event.h"
35 #include "app_process_data.h"
36 #include "app_state_observer_manager.h"
37 #include "app_utils.h"
38 #include "appfreeze_manager.h"
39 #include "application_state_observer_stub.h"
40 #include "appspawn_util.h"
41 #include "bundle_constants.h"
42 #include "common_event.h"
43 #include "common_event_manager.h"
44 #include "common_event_support.h"
45 #include "datetime_ex.h"
46 #include "distributed_data_mgr.h"
47 #include "exit_resident_process_manager.h"
48 #include "freeze_util.h"
49 #include "global_constant.h"
50 #include "hilog_tag_wrapper.h"
51 #include "hitrace_meter.h"
52 #include "in_process_call_wrapper.h"
53 #include "ipc_skeleton.h"
54 #include "iremote_object.h"
55 #include "iservice_registry.h"
56 #include "itest_observer.h"
57 #include "os_account_manager.h"
58 #ifdef SUPPORT_GRAPHICS
59 #include "locale_config.h"
60 #endif
61 #include "mem_mgr_client.h"
62 #include "mem_mgr_process_state_info.h"
63 #include "os_account_manager_wrapper.h"
64 #ifdef OHOS_ACCOUNT_ENABLED
65 #include "ohos_account_kits.h"
66 #endif // OHOS_ACCOUNT_ENABLED
67 #include "parameter.h"
68 #include "parameters.h"
69 #include "perf_profile.h"
70 #include "permission_constants.h"
71 #include "permission_verification.h"
72 #include "render_state_observer_manager.h"
73 #include "res_sched_util.h"
74 #include "startup_util.h"
75 #include "string_ex.h"
76 #ifdef ABILITY_RUNTIME_FEATURE_SANDBOXMANAGER
77 #include "sandbox_manager_kit.h"
78 #endif
79 #include "system_ability_definition.h"
80 #include "time_util.h"
81 #include "ui_extension_utils.h"
82 #include "uri_permission_manager_client.h"
83 #include "user_record_manager.h"
84 #ifdef APP_MGR_SERVICE_APPMS
85 #include "net_conn_client.h"
86 #endif
87 #include "application_info.h"
88 #include "meminfo.h"
89 #include "app_mgr_service_const.h"
90 #include "app_mgr_service_dump_error_code.h"
91 #include "param.h"
92 #include "window_focus_changed_listener.h"
93 #include "window_visibility_changed_listener.h"
94 #include "cache_process_manager.h"
95 #ifdef APP_NO_RESPONSE_DIALOG
96 #include "fault_data.h"
97 #include "modal_system_app_freeze_uiextension.h"
98 #endif
99 
100 namespace OHOS {
101 namespace AppExecFwk {
102 using namespace OHOS::Rosen;
103 using namespace OHOS::Security;
104 
105 namespace {
106 #define CHECK_CALLER_IS_SYSTEM_APP                                                             \
107     if (!AAFwk::PermissionVerification::GetInstance()->JudgeCallerIsAllowedToUseSystemAPI()) { \
108         TAG_LOGE(AAFwkTag::APPMGR, "The caller is not system-app, can not use system-api");    \
109         return AAFwk::ERR_NOT_SYSTEM_APP;                                                      \
110     }
111 
112 #define CHECK_IS_SA_CALL(listener)                                                                              \
113     auto instance = AAFwk::PermissionVerification::GetInstance();                                               \
114     if ((listener) == nullptr || instance == nullptr || appRunningStatusModule_ == nullptr) {                     \
115         TAG_LOGE(AAFwkTag::APPMGR, "Listener or getInstance is nullptr or appRunningStatusModule_ is nullptr"); \
116         return ERR_INVALID_VALUE;                                                                               \
117     }                                                                                                           \
118     if (!instance->IsSACall()) {                                                                                \
119         TAG_LOGE(AAFwkTag::APPMGR, "CallerToken not SA.");                                                      \
120         return ERR_PERMISSION_DENIED;                                                                           \
121     }
122 
123 #define CHECK_POINTER_AND_RETURN_LOG(object, log)      \
124     if (!object) {                                     \
125         TAG_LOGE(AAFwkTag::APPMGR, "%{public}s", log); \
126         return;                                        \
127     }
128 
129 #define CHECK_POINTER_AND_RETURN_VALUE(object, value) \
130     if (!object) {                              \
131         TAG_LOGE(AAFwkTag::APPMGR, "nullptr");  \
132         return value;                           \
133     }
134 
135 // NANOSECONDS mean 10^9 nano second
136 constexpr int64_t NANOSECONDS = 1000000000;
137 // MICROSECONDS mean 10^6 milli second
138 constexpr int64_t MICROSECONDS = 1000000;
139 // Kill process timeout setting
140 constexpr int KILL_PROCESS_TIMEOUT_MICRO_SECONDS = 1000;
141 // Kill process delay time setting
142 constexpr int KILL_PROCESS_DELAYTIME_MICRO_SECONDS = 200;
143 // delay register focus listener to wms
144 constexpr int REGISTER_FOCUS_DELAY = 5000;
145 constexpr int REGISTER_VISIBILITY_DELAY = 5000;
146 // Max render process number limitation for phone device.
147 constexpr int PHONE_MAX_RENDER_PROCESS_NUM = 40;
148 constexpr int PROCESS_RESTART_MARGIN_MICRO_SECONDS = 2000;
149 constexpr const int32_t API10 = 10;
150 constexpr const int32_t API_VERSION_MOD = 100;
151 constexpr const char* CLASS_NAME = "ohos.app.MainThread";
152 constexpr const char* FUNC_NAME = "main";
153 constexpr const char* RENDER_PARAM = "invalidparam";
154 constexpr const char* COLD_START = "coldStart";
155 constexpr const char* PERF_CMD = "perfCmd";
156 constexpr const char* ERROR_INFO_ENHANCE = "errorInfoEnhance";
157 constexpr const char* MULTI_THREAD = "multiThread";
158 constexpr const char* DEBUG_CMD = "debugCmd";
159 constexpr const char* ENTER_SANDBOX = "sandboxApp";
160 constexpr const char* PERMISSION_INTERNET = "ohos.permission.INTERNET";
161 constexpr const char* PERMISSION_MANAGE_VPN = "ohos.permission.MANAGE_VPN";
162 constexpr const char* PERMISSION_ACCESS_BUNDLE_DIR = "ohos.permission.ACCESS_BUNDLE_DIR";
163 constexpr const char* PERMISSION_TEMP_JIT_ALLOW = "TEMPJITALLOW";
164 constexpr const char* TARGET_UID_KEY = "ohos.aafwk.param.targetUid";
165 constexpr const int32_t KILL_PROCESS_BY_USER_INTERVAL = 20;
166 constexpr const int32_t KILL_PROCESS_BY_USER_DELAY_BASE = 500;
167 constexpr const int64_t PRELOAD_FREEZE_TIMEOUT = 11000;
168 
169 #ifdef WITH_DLP
170 constexpr const char* DLP_PARAMS_SECURITY_FLAG = "ohos.dlp.params.securityFlag";
171 #endif // WITH_DLP
172 
173 constexpr const char* SUPPORT_ISOLATION_MODE = "persist.bms.supportIsolationMode";
174 constexpr const char* SUPPORT_SERVICE_EXT_MULTI_PROCESS = "component.startup.extension.multiprocess.enable";
175 constexpr const char* SERVICE_EXT_MULTI_PROCESS_WHITE_LIST = "component.startup.extension.multiprocess.whitelist";
176 constexpr const char* SCENE_BOARD_BUNDLE_NAME = "com.ohos.sceneboard";
177 constexpr const char* DEBUG_APP = "debugApp";
178 constexpr const char* NATIVE_DEBUG = "nativeDebug";
179 constexpr const char* SERVICE_EXTENSION = ":ServiceExtension";
180 constexpr const char* KEEP_ALIVE = ":KeepAlive";
181 constexpr const char* PARAM_SPECIFIED_PROCESS_FLAG = "ohoSpecifiedProcessFlag";
182 constexpr const char* TSAN_FLAG_NAME = "tsanEnabled";
183 constexpr const char* HWASAN_FLAG_NAME = "hwasanEnabled";
184 constexpr const char* UIEXTENSION_ABILITY_ID = "ability.want.params.uiExtensionAbilityId";
185 constexpr const char* UIEXTENSION_ROOT_HOST_PID = "ability.want.params.uiExtensionRootHostPid";
186 constexpr const char* MEMMGR_PROC_NAME = "memmgrservice";
187 constexpr const char* STRICT_MODE = "strictMode";
188 constexpr const char* ISOLATED_SANDBOX = "isolatedSandbox";
189 constexpr const char* RENDER_PROCESS_NAME = ":render";
190 constexpr const char* RENDER_PROCESS_TYPE = "render";
191 constexpr const char* GPU_PROCESS_NAME = ":gpu";
192 constexpr const char* GPU_PROCESS_TYPE = "gpu";
193 constexpr const char* KILL_REASON_USER_REQUEST = "User Request";
194 const std::string TOKEN_ID = "TOKEN_ID";
195 const int32_t SIGNAL_KILL = 9;
196 const int32_t HIVIEW_UID = 1201;
197 constexpr int32_t USER_SCALE = 200000;
198 #define ENUM_TO_STRING(s) #s
199 #define APP_ACCESS_BUNDLE_DIR 0x20
200 #define APP_OVERLAY_FLAG 0x100
201 
202 constexpr int32_t MAX_RESTART_COUNT = 3;
203 constexpr int32_t RESTART_INTERVAL_TIME = 120000;
204 constexpr int32_t FIRST_FRAME_NOTIFY_TASK_DELAY = 5; //ms
205 
206 constexpr ErrCode APPMGR_ERR_OFFSET = ErrCodeOffset(SUBSYS_APPEXECFWK, 0x01);
207  // Error code for already exist render.
208 constexpr ErrCode ERR_ALREADY_EXIST_RENDER = APPMGR_ERR_OFFSET + 100;
209  // Error code for reaching render process number limitation.
210 constexpr ErrCode ERR_REACHING_MAXIMUM_RENDER_PROCESS_LIMITATION = APPMGR_ERR_OFFSET + 101;
211 constexpr const char* EVENT_KEY_UID = "UID";
212 constexpr const char* EVENT_KEY_PID = "PID";
213 constexpr const char* EVENT_KEY_PACKAGE_NAME = "PACKAGE_NAME";
214 constexpr const char* EVENT_KEY_PROCESS_NAME = "PROCESS_NAME";
215 constexpr const char* EVENT_KEY_MESSAGE = "MSG";
216 constexpr const char* EVENT_KEY_FOREGROUND = "FOREGROUND";
217 
218 // Developer mode param
219 constexpr const char* DEVELOPER_MODE_STATE = "const.security.developermode.state";
220 constexpr const char* PRODUCT_ASSERT_FAULT_DIALOG_ENABLED = "persisit.sys.abilityms.support_assert_fault_dialog";
221 
222 // Msg length is less than 48 characters
223 constexpr const char* EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT = "Terminate Ability TimeOut!";
224 constexpr const char* EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT = "Terminate Application TimeOut!";
225 constexpr const char* EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT = "Add Ability Stage TimeOut!";
226 constexpr const char* EVENT_MESSAGE_START_SPECIFIED_PROCESS_TIMEOUT = "Start Specified Process Timeout!";
227 constexpr const char* EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT = "Start Specified Ability TimeOut!";
228 constexpr const char* EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT =
229     "Start Process Specified Ability TimeOut!";
230 constexpr const char* EVENT_MESSAGE_DEFAULT = "AppMgrServiceInner HandleTimeOut!";
231 constexpr const char* SUPPORT_CALL_NOTIFY_MEMORY_CHANGED =
232     "persist.sys.abilityms.support_call_notify_memory_changed";
233 
234 constexpr const char* SYSTEM_BASIC = "system_basic";
235 constexpr const char* SYSTEM_CORE = "system_core";
236 constexpr const char* ABILITY_OWNER_USERID = "AbilityMS_Owner_UserId";
237 constexpr const char* PROCESS_EXIT_EVENT_TASK = "Send Process Exit Event Task";
238 constexpr const char* KILL_PROCESS_REASON_PREFIX = "Kill Reason:";
239 constexpr const char* PRELOAD_APPLIATION_TASK = "PreloadApplicactionTask";
240 
241 constexpr const char* PROC_SELF_TASK_PATH = "/proc/self/task/";
242 
243 constexpr int32_t ROOT_UID = 0;
244 constexpr int32_t FOUNDATION_UID = 5523;
245 constexpr int32_t QUICKFIX_UID = 5524;
246 constexpr int32_t DEFAULT_USER_ID = 0;
247 constexpr int32_t CURRENT_USER_ID = -1;
248 constexpr int32_t RESOURCE_MANAGER_UID = 1096;
249 
250 constexpr int32_t BLUETOOTH_GROUPID = 1002;
251 
252 #ifdef APP_MGR_SERVICE_APPMS
253 constexpr int32_t NETSYS_SOCKET_GROUPID = 1097;
254 #endif
255 
256 constexpr int32_t DEFAULT_INVAL_VALUE = -1;
257 constexpr int32_t NO_ABILITY_RECORD_ID = -1;
258 constexpr int32_t EXIT_REASON_UNKNOWN = 0;
259 constexpr int32_t PROCESS_START_FAILED_SUB_REASON_UNKNOWN = 0;
260 
261 constexpr int32_t MAX_SPECIFIED_PROCESS_NAME_LENGTH = 255;
262 constexpr int32_t LEAK_WAIT = 900000;
263 constexpr int32_t NORMAL_WAIT = 120000;
264 
265 constexpr int32_t NWEB_PRELOAD_DELAY = 3000;
266 
267 // Max child process number limitation for pc device.
268 constexpr int32_t PC_MAX_CHILD_PROCESS_NUM = 50;
269 constexpr int32_t USER100 = 100;
270 constexpr int32_t USER0 = 100;
GetUserIdByUid(int32_t uid)271 int32_t GetUserIdByUid(int32_t uid)
272 {
273     return uid / BASE_USER_RANGE;
274 }
275 
IsCjAbility(const std::string & info)276 bool IsCjAbility(const std::string& info)
277 {
278     // in cj application, the srcEntry format should be packageName.AbilityClassName.
279     std::string pattern = "^([a-zA-Z0-9_]+\\.)+[a-zA-Z0-9_]+$";
280     return std::regex_match(info, std::regex(pattern));
281 }
282 
IsCjApplication(const BundleInfo & bundleInfo)283 bool IsCjApplication(const BundleInfo &bundleInfo)
284 {
285     bool findEntryHapModuleInfo = false;
286     AppExecFwk::HapModuleInfo entryHapModuleInfo;
287     if (!bundleInfo.hapModuleInfos.empty()) {
288         for (auto hapModuleInfo : bundleInfo.hapModuleInfos) {
289             if (hapModuleInfo.moduleType == AppExecFwk::ModuleType::ENTRY) {
290                 findEntryHapModuleInfo = true;
291                 entryHapModuleInfo = hapModuleInfo;
292                 break;
293             }
294         }
295         if (!findEntryHapModuleInfo) {
296             TAG_LOGW(AAFwkTag::APPMGR, "HandleLaunchApplication find entry hap module info failed!");
297             entryHapModuleInfo = bundleInfo.hapModuleInfos.back();
298         }
299         if (entryHapModuleInfo.srcEntrance.length() > 0) {
300             return IsCjAbility(entryHapModuleInfo.srcEntrance);
301         }
302     }
303     return false;
304 }
305 }  // namespace
306 
307 using OHOS::AppExecFwk::Constants::PERMISSION_GRANTED;
308 using OHOS::AppExecFwk::Constants::PERMISSION_NOT_GRANTED;
309 
AppMgrServiceInner()310 AppMgrServiceInner::AppMgrServiceInner()
311     : remoteClientManager_(std::make_shared<RemoteClientManager>()),
312       appRunningManager_(std::make_shared<AppRunningManager>()),
313       appDebugManager_(std::make_shared<AppDebugManager>()),
314       appRunningStatusModule_(std::make_shared<AbilityRuntime::AppRunningStatusModule>()),
315       securityModeManager_(std::make_shared<AdvancedSecurityModeManager>()),
316       appPreloader_(std::make_shared<AppPreloader>(remoteClientManager_)),
317       multiUserConfigurationMgr_(std::make_shared<MultiUserConfigurationMgr>())
318 {}
319 
Init()320 void AppMgrServiceInner::Init()
321 {
322     InitGlobalConfiguration();
323     AddWatchParameter();
324     supportIsolationMode_ = OHOS::system::GetParameter(SUPPORT_ISOLATION_MODE, "false");
325     supportServiceExtMultiProcess_ = OHOS::system::GetParameter(SUPPORT_SERVICE_EXT_MULTI_PROCESS, "false");
326     ParseServiceExtMultiProcessWhiteList();
327     DelayedSingleton<AppStateObserverManager>::GetInstance()->Init();
328     DelayedSingleton<RenderStateObserverManager>::GetInstance()->Init();
329     dfxTaskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler("dfx_freeze_task_queue");
330     dfxTaskHandler_->SetPrintTaskLog(true);
331     otherTaskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler("other_app_mgr_task_queue");
332     otherTaskHandler_->SetPrintTaskLog(true);
333     willKillPidsNum_ = 0;
334     delayKillTaskHandler_ = AAFwk::TaskHandlerWrap::CreateQueueHandler("delay_kill_task_queue");
335     if (securityModeManager_) {
336         securityModeManager_->Init();
337     }
338     otherTaskHandler_->SubmitTask([pThis = shared_from_this()]() {
339         pThis->nwebPreloadSet_ = AAFwk::ResSchedUtil::GetInstance().GetNWebPreloadSet();
340         }, NWEB_PRELOAD_DELAY);
341 }
342 
~AppMgrServiceInner()343 AppMgrServiceInner::~AppMgrServiceInner()
344 {}
345 
StartSpecifiedProcess(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo,int32_t requestId)346 void AppMgrServiceInner::StartSpecifiedProcess(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
347     int32_t requestId)
348 {
349     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
350     TAG_LOGD(AAFwkTag::APPMGR, "call.");
351     BundleInfo bundleInfo;
352     HapModuleInfo hapModuleInfo;
353     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
354 
355     int32_t appIndex = 0;
356     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
357     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
358         return;
359     }
360     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
361         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
362         return;
363     }
364 
365     std::string processName;
366     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
367     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, "", processName);
368     TAG_LOGD(AAFwkTag::APPMGR, "processName = %{public}s", processName.c_str());
369     auto mainAppRecord =
370         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
371     if (mainAppRecord != nullptr) {
372         TAG_LOGI(AAFwkTag::APPMGR, "main process exists.");
373         mainAppRecord->SetScheduleNewProcessRequestState(requestId, want, hapModuleInfo.moduleName);
374         auto moduleRecord = mainAppRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
375         if (!moduleRecord) {
376             TAG_LOGI(AAFwkTag::APPMGR, "module record is nullptr, add modules");
377             std::vector<HapModuleInfo> hapModules = { hapModuleInfo };
378             mainAppRecord->AddModules(appInfo, hapModules);
379             if (mainAppRecord->GetApplicationClient() != nullptr) {
380                 mainAppRecord->AddAbilityStageBySpecifiedProcess(appInfo->bundleName);
381             }
382             return;
383         }
384         TAG_LOGD(AAFwkTag::APPMGR, "schedule new process request.");
385         mainAppRecord->ScheduleNewProcessRequest(want, hapModuleInfo.moduleName);
386         return;
387     }
388     TAG_LOGI(AAFwkTag::APPMGR, "main process do not exists.");
389     if (startSpecifiedAbilityResponse_) {
390         startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, "", requestId);
391     }
392 }
393 
PreloadApplication(const std::string & bundleName,int32_t userId,AppExecFwk::PreloadMode preloadMode,int32_t appIndex)394 int32_t AppMgrServiceInner::PreloadApplication(const std::string &bundleName, int32_t userId,
395     AppExecFwk::PreloadMode preloadMode, int32_t appIndex)
396 {
397     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
398     TAG_LOGI(AAFwkTag::APPMGR,
399         "PreloadApplication, bundleName:%{public}s, userId:%{public}d, preloadMode:%{public}d, appIndex:%{public}d",
400         bundleName.c_str(), userId, preloadMode, appIndex);
401 
402     CHECK_CALLER_IS_SYSTEM_APP;
403     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyPreloadApplicationPermission();
404     if (!isPerm) {
405         TAG_LOGE(AAFwkTag::APPMGR, "Permission verify failed");
406         return ERR_PERMISSION_DENIED;
407     }
408     if (!appPreloader_) {
409         TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication appPreloader is nullptr.");
410         return ERR_INVALID_VALUE;
411     }
412     if (userId == CURRENT_USER_ID) {
413         userId = currentUserId_;
414     }
415     if (UserRecordManager::GetInstance().IsLogoutUser(userId)) {
416         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
417         return ERR_INVALID_OPERATION;
418     }
419     auto allowPreload = appPreloader_->PreCheck(bundleName, preloadMode);
420     if (!allowPreload) {
421         TAG_LOGI(AAFwkTag::APPMGR, "BundleName: %{public}s preload preCheck: not allow.", bundleName.c_str());
422         return AAFwk::ERR_NOT_ALLOW_PRELOAD_BY_RSS;
423     }
424 
425     PreloadRequest request;
426     auto ret = appPreloader_->GeneratePreloadRequest(bundleName, userId, appIndex, request);
427     if (ret != ERR_OK) {
428         TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication GeneratePreloadRequest failed.");
429         return ret;
430     }
431 
432     request.preloadMode = preloadMode;
433     auto task = [inner = shared_from_this(), request] () {
434         if (!inner) {
435             TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication appMgrServiceInner is nullptr.");
436             return;
437         }
438         inner->HandlePreloadApplication(request);
439     };
440     if (!taskHandler_) {
441         TAG_LOGE(AAFwkTag::APPMGR, "PreloadApplication taskHandler_ is nullptr.");
442         return ERR_INVALID_VALUE;
443     }
444     TAG_LOGI(AAFwkTag::APPMGR, "PreloadApplication Submit task, bundleName:%{public}s, userId:%{public}d.",
445         bundleName.c_str(), userId);
446     taskHandler_->SubmitTask(task, PRELOAD_APPLIATION_TASK);
447     return ERR_OK;
448 }
449 
HandlePreloadApplication(const PreloadRequest & request)450 void AppMgrServiceInner::HandlePreloadApplication(const PreloadRequest &request)
451 {
452     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
453     auto abilityInfo = request.abilityInfo;
454     if (!abilityInfo) {
455         TAG_LOGE(AAFwkTag::APPMGR, "HandlePreloadApplication request.abilityInfo is nullptr.");
456         return;
457     }
458     auto bundleInfo = request.bundleInfo;
459     TAG_LOGI(AAFwkTag::APPMGR, "HandlePreloadApplication, bundleName:%{public}s, abilityName:%{public}s, \
460     appIndex:%{public}d", bundleInfo.name.c_str(), abilityInfo->name.c_str(), request.appIndex);
461 
462     auto appInfo = request.appInfo;
463     auto hapModuleInfo = request.hapModuleInfo;
464 
465     auto want = request.want;
466     std::string specifiedProcessFlag = GetSpecifiedProcessFlag(abilityInfo, want);
467 
468     std::string processName;
469     MakeProcessName(abilityInfo, appInfo, hapModuleInfo, request.appIndex, specifiedProcessFlag, processName);
470     TAG_LOGD(AAFwkTag::APPMGR, "HandlePreloadApplication processName = %{public}s", processName.c_str());
471 
472     std::shared_ptr<AppRunningRecord> appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name,
473         processName, appInfo->uid, bundleInfo, specifiedProcessFlag);
474     if (appRecord) {
475         TAG_LOGE(AAFwkTag::APPMGR, "HandlePreloadApplication AppRecord already exists, no need to preload.");
476         return;
477     }
478 
479     if (!appRunningManager_) {
480         TAG_LOGE(AAFwkTag::APPMGR, "HandlePreloadApplication failed, appRunningManager_ is nullptr");
481         return;
482     }
483     bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name);
484     bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid);
485     if (!appMultiUserExistFlag) {
486         NotifyAppRunningStatusEvent(
487             bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
488     }
489     appRecord = CreateAppRunningRecord(nullptr, nullptr, appInfo, abilityInfo, processName, bundleInfo,
490         hapModuleInfo, want, NO_ABILITY_RECORD_ID);
491     appRecord->SetPreloadState(PreloadState::PRELOADING);
492     appRecord->SetPreloadMode(request.preloadMode);
493     appRecord->SetNeedPreloadModule(request.preloadMode == AppExecFwk::PreloadMode::PRELOAD_MODULE);
494     appRecord->SetNeedLimitPrio(request.preloadMode != PreloadMode::PRESS_DOWN);
495     LoadAbilityNoAppRecord(appRecord, false, appInfo, abilityInfo, processName, specifiedProcessFlag, bundleInfo,
496         hapModuleInfo, want, appExistFlag, true, request.preloadMode);
497     appRecord->SetNeedLimitPrio(false);
498     if (request.preloadMode == AppExecFwk::PreloadMode::PRELOAD_MODULE) {
499             reportpreLoadTask(appRecord);
500     }
501 }
502 
reportpreLoadTask(const std::shared_ptr<AppRunningRecord> appRecord)503 void AppMgrServiceInner::reportpreLoadTask(const std::shared_ptr<AppRunningRecord> appRecord)
504 {
505     auto reportLoadTask = [appRecord]() {
506         auto priorityObj = appRecord->GetPriorityObject();
507         if (priorityObj) {
508             AAFwk::ResSchedUtil::GetInstance().ReportLoadingEventToRss(AAFwk::LoadingStage::PRELOAD_BEGIN,
509                 priorityObj->GetPid(), appRecord->GetUid(), PRELOAD_FREEZE_TIMEOUT, 0);
510         }
511     };
512     if (taskHandler_) {
513         taskHandler_->SubmitTask(reportLoadTask, "reportpreLoadTask");
514     }
515 }
516 
LoadAbility(std::shared_ptr<AbilityInfo> abilityInfo,std::shared_ptr<ApplicationInfo> appInfo,std::shared_ptr<AAFwk::Want> want,std::shared_ptr<AbilityRuntime::LoadParam> loadParam)517 void AppMgrServiceInner::LoadAbility(std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<ApplicationInfo> appInfo,
518     std::shared_ptr<AAFwk::Want> want, std::shared_ptr<AbilityRuntime::LoadParam> loadParam)
519 {
520     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
521     if (loadParam == nullptr) {
522         TAG_LOGE(AAFwkTag::APPMGR, "loadParam is nullptr");
523         return;
524     }
525     if (!CheckLoadAbilityConditions(loadParam->token, abilityInfo, appInfo)) {
526         TAG_LOGE(AAFwkTag::APPMGR, "CheckLoadAbilityConditions failed");
527         return;
528     }
529     {
530         std::lock_guard lock(killedBundleSetMutex_);
531         if (killedBundleSet_.find(abilityInfo->bundleName) != killedBundleSet_.end()) {
532             TAG_LOGW(AAFwkTag::APPMGR, "%{public}s is being killed", abilityInfo->bundleName.c_str());
533             return;
534         }
535     }
536     if (abilityInfo->type == AbilityType::PAGE) {
537         AbilityRuntime::FreezeUtil::LifecycleFlow flow = {loadParam->token,
538             AbilityRuntime::FreezeUtil::TimeoutState::LOAD};
539         std::string entry = "AppMgrServiceInner::LoadAbility; the load lifecycle.";
540         AbilityRuntime::FreezeUtil::GetInstance().AddLifecycleEvent(flow, entry);
541     }
542 
543     if (!appRunningManager_) {
544         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
545         return;
546     }
547 
548     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
549         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
550         return;
551     }
552 
553     BundleInfo bundleInfo;
554     HapModuleInfo hapModuleInfo;
555     int32_t appIndex = 0;
556     if (want != nullptr) {
557         (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, appIndex);
558     }
559     if (!GetBundleAndHapInfo(*abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
560         TAG_LOGE(AAFwkTag::APPMGR, "GetBundleAndHapInfo failed");
561         return;
562     }
563     // for isolation process
564     std::string specifiedProcessFlag = GetSpecifiedProcessFlag(abilityInfo, want);
565     std::string processName;
566     MakeProcessName(abilityInfo, appInfo, hapModuleInfo, appIndex, specifiedProcessFlag, processName);
567     TAG_LOGI(AAFwkTag::APPMGR, "%{public}s name:%{public}s-%{public}s processName = %{public}s",
568         __func__, abilityInfo->bundleName.c_str(), abilityInfo->name.c_str(), processName.c_str());
569 
570     std::shared_ptr<AppRunningRecord> appRecord;
571     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name,
572         processName, appInfo->uid, bundleInfo, specifiedProcessFlag);
573     if (appRecord && appRecord->IsCaching()) {
574         appRecord->SetProcessCacheBlocked(true);
575         appRecord = nullptr;
576     }
577     if (appRecord && abilityInfo->type == AppExecFwk::AbilityType::PAGE) {
578         NotifyMemMgrPriorityChanged(appRecord);
579     }
580 
581     if (!appRecord) {
582         TAG_LOGD(AAFwkTag::APPMGR, "appRecord null");
583         bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name);
584         bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid);
585         if (!appMultiUserExistFlag) {
586             NotifyAppRunningStatusEvent(
587                 bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
588         }
589         appRecord = CreateAppRunningRecord(loadParam->token, loadParam->preToken, appInfo, abilityInfo,
590             processName, bundleInfo, hapModuleInfo, want, loadParam->abilityRecordId);
591         LoadAbilityNoAppRecord(appRecord, loadParam->isShellCall, appInfo, abilityInfo, processName,
592             specifiedProcessFlag, bundleInfo, hapModuleInfo, want, appExistFlag, false,
593             AppExecFwk::PreloadMode::PRESS_DOWN, loadParam->token);
594     } else {
595         TAG_LOGI(AAFwkTag::APPMGR, "have apprecord");
596         SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::MULTI_INSTANCE);
597         if (appRecord->IsPreloaded()) {
598             SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::COLD);
599             appRecord->SetPreloadState(PreloadState::NONE);
600         }
601         int32_t requestProcCode = (want == nullptr) ? 0 : want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0);
602         if (requestProcCode != 0 && appRecord->GetRequestProcCode() == 0) {
603             appRecord->SetRequestProcCode(requestProcCode);
604             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessReused(appRecord);
605         }
606         StartAbility(loadParam->token, loadParam->preToken, abilityInfo, appRecord, hapModuleInfo, want,
607             loadParam->abilityRecordId);
608         if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
609             AddUIExtensionLauncherItem(want, appRecord, loadParam->token);
610         }
611     }
612 
613     if (AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType) &&
614         appRecord != nullptr && want != nullptr) {
615         auto abilityRunningRecord = appRecord->GetAbilityRunningRecordByToken(loadParam->token);
616         auto uiExtensionAbilityId = want->GetIntParam(UIEXTENSION_ABILITY_ID, -1);
617         if (abilityRunningRecord != nullptr) {
618             abilityRunningRecord->SetUIExtensionAbilityId(uiExtensionAbilityId);
619         }
620     }
621     AfterLoadAbility(appRecord, abilityInfo, loadParam);
622 }
623 
AfterLoadAbility(std::shared_ptr<AppRunningRecord> appRecord,std::shared_ptr<AbilityInfo> abilityInfo,std::shared_ptr<AbilityRuntime::LoadParam> loadParam)624 void AppMgrServiceInner::AfterLoadAbility(std::shared_ptr<AppRunningRecord> appRecord,
625     std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<AbilityRuntime::LoadParam> loadParam)
626 {
627     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
628     if (!appRecord || !abilityInfo || !loadParam) {
629         return;
630     }
631     if (abilityInfo->type == AppExecFwk::AbilityType::PAGE && appRecord != nullptr) {
632         appRecord->SetUIAbilityLaunched(true);
633     }
634     PerfProfile::GetInstance().SetAbilityLoadEndTime(GetTickCount());
635     PerfProfile::GetInstance().Dump();
636     PerfProfile::GetInstance().Reset();
637     appRecord->UpdateAbilityState(loadParam->token, AbilityState::ABILITY_STATE_CREATE);
638 
639     auto reportLoadTask = [appRecord, abilityRecordId = loadParam->abilityRecordId]() {
640         auto priorityObj = appRecord->GetPriorityObject();
641         if (priorityObj) {
642             auto timeOut = AbilityRuntime::GlobalConstant::GetLoadTimeOutBase() *
643                 AAFwk::AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
644             if (appRecord->GetExtensionType() == ExtensionAbilityType::SERVICE) {
645                 timeOut = AbilityRuntime::GlobalConstant::GetLoadAndInactiveTimeout() *
646                     AAFwk::AppUtils::GetInstance().GetTimeoutUnitTimeRatio();
647             }
648 
649             AAFwk::ResSchedUtil::GetInstance().ReportLoadingEventToRss(AAFwk::LoadingStage::LOAD_BEGIN,
650                 priorityObj->GetPid(), appRecord->GetUid(), timeOut, static_cast<int64_t>(abilityRecordId));
651         }
652     };
653     if (taskHandler_) {
654         taskHandler_->SubmitTask(reportLoadTask, "reportLoadTask");
655     }
656 }
657 
AddUIExtensionLauncherItem(std::shared_ptr<AAFwk::Want> want,std::shared_ptr<AppRunningRecord> appRecord,sptr<IRemoteObject> token)658 void AppMgrServiceInner::AddUIExtensionLauncherItem(std::shared_ptr<AAFwk::Want> want,
659     std::shared_ptr<AppRunningRecord> appRecord, sptr<IRemoteObject> token)
660 {
661     if (want == nullptr || appRecord == nullptr || token == nullptr || appRunningManager_ == nullptr) {
662         TAG_LOGE(AAFwkTag::APPMGR, "Invalid input params.");
663         return;
664     }
665 
666     auto uiExtensionAbilityId = want->GetIntParam(UIEXTENSION_ABILITY_ID, -1);
667     auto hostPid = want->GetIntParam(UIEXTENSION_ROOT_HOST_PID, -1);
668     pid_t providerPid = -1;
669     if (appRecord->GetPriorityObject() != nullptr) {
670         providerPid = appRecord->GetPriorityObject()->GetPid();
671     }
672     if (uiExtensionAbilityId == -1 || hostPid == -1 || providerPid == -1) {
673         TAG_LOGE(AAFwkTag::APPMGR, "Invalid want params.");
674         return;
675     }
676 
677     TAG_LOGI(AAFwkTag::APPMGR, "Add uiextension launcher info, uiExtensionAbilityId: %{public}d, hostPid: %{public}d, "
678         "providerPid: %{public}d.", uiExtensionAbilityId, hostPid, providerPid);
679     appRunningManager_->AddUIExtensionLauncherItem(uiExtensionAbilityId, hostPid, providerPid);
680 
681     want->RemoveParam(UIEXTENSION_ABILITY_ID);
682     want->RemoveParam(UIEXTENSION_ROOT_HOST_PID);
683 }
684 
RemoveUIExtensionLauncherItem(std::shared_ptr<AppRunningRecord> appRecord,sptr<IRemoteObject> token)685 void AppMgrServiceInner::RemoveUIExtensionLauncherItem(std::shared_ptr<AppRunningRecord> appRecord,
686     sptr<IRemoteObject> token)
687 {
688     if (appRecord == nullptr || token == nullptr || appRunningManager_ == nullptr) {
689         TAG_LOGE(AAFwkTag::APPMGR, "Invalid input params.");
690         return;
691     }
692 
693     auto abilityRunningRecord = appRecord->GetAbilityRunningRecordByToken(token);
694     if (abilityRunningRecord == nullptr) {
695         TAG_LOGW(AAFwkTag::APPMGR, "Invalid ability record.");
696         return;
697     }
698 
699     auto abilityInfo = abilityRunningRecord->GetAbilityInfo();
700     if (abilityInfo == nullptr) {
701         TAG_LOGW(AAFwkTag::APPMGR, "Invalid ability info.");
702         return;
703     }
704 
705     if (!AAFwk::UIExtensionUtils::IsUIExtension(abilityInfo->extensionAbilityType)) {
706         return;
707     }
708 
709     auto uiExtensionAbilityId = abilityRunningRecord->GetUIExtensionAbilityId();
710     appRunningManager_->RemoveUIExtensionLauncherItemById(uiExtensionAbilityId);
711 }
712 
CheckLoadAbilityConditions(const sptr<IRemoteObject> & token,const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo)713 bool AppMgrServiceInner::CheckLoadAbilityConditions(const sptr<IRemoteObject> &token,
714     const std::shared_ptr<AbilityInfo> &abilityInfo, const std::shared_ptr<ApplicationInfo> &appInfo)
715 {
716     if (!token || !abilityInfo || !appInfo) {
717         TAG_LOGE(AAFwkTag::APPMGR, "param error");
718         return false;
719     }
720     if (abilityInfo->name.empty() || appInfo->name.empty()) {
721         TAG_LOGE(AAFwkTag::APPMGR, "error abilityInfo or appInfo");
722         return false;
723     }
724     if (abilityInfo->applicationName != appInfo->name) {
725         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo and appInfo have different appName, don't load for it");
726         return false;
727     }
728 
729     return true;
730 }
731 
MakeServiceExtProcessName(const std::shared_ptr<AbilityInfo> & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,std::string & processName) const732 void AppMgrServiceInner::MakeServiceExtProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
733     const std::shared_ptr<ApplicationInfo> &appInfo, std::string &processName) const
734 {
735     if (abilityInfo == nullptr || appInfo == nullptr) {
736         TAG_LOGE(AAFwkTag::APPMGR, "Ability info or app info is nullptr.");
737         return;
738     }
739 
740     if (supportServiceExtMultiProcess_.compare("true") != 0) {
741         return;
742     }
743 
744     if (processName == appInfo->bundleName &&
745         abilityInfo->extensionAbilityType == ExtensionAbilityType::SERVICE) {
746         auto iter = std::find(
747             serviceExtensionWhiteList_.begin(), serviceExtensionWhiteList_.end(), processName);
748         if (iter != serviceExtensionWhiteList_.end()) {
749             TAG_LOGD(AAFwkTag::APPMGR, "Application is in whiteList, skipping!");
750             return;
751         }
752 
753         processName += SERVICE_EXTENSION;
754         if (appInfo->keepAlive) {
755             processName += KEEP_ALIVE;
756         }
757     }
758 }
759 
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) const760 void AppMgrServiceInner::MakeProcessName(const std::shared_ptr<AbilityInfo> &abilityInfo,
761     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, int32_t appIndex,
762     const std::string &specifiedProcessFlag, std::string &processName) const
763 {
764     if (!abilityInfo || !appInfo) {
765         TAG_LOGE(AAFwkTag::APPMGR, "param error");
766         return;
767     }
768     if (!abilityInfo->process.empty()) {
769         TAG_LOGD(AAFwkTag::APPMGR, "Process not null");
770         processName = abilityInfo->process;
771         return;
772     }
773     MakeProcessName(appInfo, hapModuleInfo, processName);
774     MakeServiceExtProcessName(abilityInfo, appInfo, processName);
775     if (appIndex != 0) {
776         processName += std::to_string(appIndex);
777     }
778 
779     if (!specifiedProcessFlag.empty()) {
780         processName = (processName + ":" + specifiedProcessFlag).substr(0, MAX_SPECIFIED_PROCESS_NAME_LENGTH);
781         TAG_LOGI(AAFwkTag::APPMGR, "specifiedProcessFlag = %{public}s, processName = %{public}s",
782             specifiedProcessFlag.c_str(), processName.c_str());
783     }
784 }
785 
MakeProcessName(const std::shared_ptr<ApplicationInfo> & appInfo,const HapModuleInfo & hapModuleInfo,std::string & processName) const786 void AppMgrServiceInner::MakeProcessName(
787     const std::shared_ptr<ApplicationInfo> &appInfo, const HapModuleInfo &hapModuleInfo, std::string &processName) const
788 {
789     if (!appInfo) {
790         TAG_LOGE(AAFwkTag::APPMGR, "appInfo nill");
791         return;
792     }
793     // check after abilityInfo, because abilityInfo contains extension process.
794     if (hapModuleInfo.isStageBasedModel && !hapModuleInfo.process.empty()
795         && hapModuleInfo.process != appInfo->bundleName) {
796         processName = hapModuleInfo.process;
797         TAG_LOGI(AAFwkTag::APPMGR, "Stage mode, Make processName:%{public}s", processName.c_str());
798         return;
799     }
800     bool isRunInIsolationMode = CheckIsolationMode(hapModuleInfo);
801     if (hapModuleInfo.isStageBasedModel && isRunInIsolationMode) {
802         processName = appInfo->bundleName;
803         processName.append(":");
804         processName.append(hapModuleInfo.name);
805         return;
806     }
807     if (!appInfo->process.empty()) {
808         processName = appInfo->process;
809         return;
810     }
811     processName = appInfo->bundleName;
812 }
813 
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)814 void AppMgrServiceInner::LoadAbilityNoAppRecord(const std::shared_ptr<AppRunningRecord> appRecord,
815     bool isShellCall, std::shared_ptr<ApplicationInfo> appInfo,
816     std::shared_ptr<AbilityInfo> abilityInfo, const std::string &processName,
817     const std::string &specifiedProcessFlag, const BundleInfo &bundleInfo, const HapModuleInfo &hapModuleInfo,
818     std::shared_ptr<AAFwk::Want> want, bool appExistFlag, bool isPreload, AppExecFwk::PreloadMode preloadMode,
819     sptr<IRemoteObject> token)
820 {
821     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
822     TAG_LOGI(AAFwkTag::APPMGR, "pname:%{public}s, isPreload:%{public}d",
823         processName.c_str(), isPreload);
824     if (!appRecord) {
825         TAG_LOGE(AAFwkTag::APPMGR, "CreateAppRunningRecord failed, null appRecord");
826         return;
827     }
828     if (!specifiedProcessFlag.empty()) {
829         appRecord->SetSpecifiedProcessFlag(specifiedProcessFlag);
830     }
831     if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, processName)) {
832         appRecord->SetEmptyKeepAliveAppState(false);
833         appRecord->SetMainProcess(false);
834         TAG_LOGI(AAFwkTag::APPMGR, "The process %{public}s will not keepalive", hapModuleInfo.process.c_str());
835     }
836     // As taskHandler_ is busy now, the task should be submit to other task queue.
837     if (otherTaskHandler_ != nullptr) {
838         otherTaskHandler_->SubmitTask([appRecord, abilityInfo, pThis = shared_from_this()]() {
839             pThis->OnAppStateChanged(appRecord, ApplicationState::APP_STATE_SET_COLD_START, false, false);
840             pThis->SendAppStartupTypeEvent(appRecord, abilityInfo, AppStartType::COLD);
841             }, "AppStateChangedNotify", FIRST_FRAME_NOTIFY_TASK_DELAY);
842     }
843     uint32_t startFlags = (want == nullptr) ? 0 : AppspawnUtil::BuildStartFlags(*want, *abilityInfo);
844     int32_t bundleIndex = 0;
845     if (want != nullptr) {
846         (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, bundleIndex);
847     }
848     bool strictMode = (want == nullptr) ? false : want->GetBoolParam(STRICT_MODE, false);
849     appRecord->SetStrictMode(strictMode);
850     int32_t maxChildProcess = 0;
851     PresetMaxChildProcess(abilityInfo, maxChildProcess);
852     if (StartProcess(abilityInfo->applicationName, processName, startFlags, appRecord, appInfo->uid,
853         bundleInfo, appInfo->bundleName, bundleIndex, appExistFlag, isPreload, preloadMode, abilityInfo->moduleName,
854         abilityInfo->name, strictMode, maxChildProcess, token, want, abilityInfo->extensionAbilityType) != ERR_OK) {
855         NotifyStartProcessFailed(token);
856     }
857     if (isShellCall) {
858         std::string perfCmd = (want == nullptr) ? "" : want->GetStringParam(PERF_CMD);
859         bool isSandboxApp = (want == nullptr) ? false : want->GetBoolParam(ENTER_SANDBOX, false);
860         (void)StartPerfProcess(appRecord, perfCmd, "", isSandboxApp);
861     }
862 }
863 
GetSpecifiedProcessFlag(std::shared_ptr<AbilityInfo> abilityInfo,std::shared_ptr<AAFwk::Want> want)864 std::string AppMgrServiceInner::GetSpecifiedProcessFlag(std::shared_ptr<AbilityInfo> abilityInfo,
865     std::shared_ptr<AAFwk::Want> want)
866 {
867     if (!abilityInfo) {
868         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo is nullptr.");
869         return "";
870     }
871     if (!want) {
872         TAG_LOGE(AAFwkTag::APPMGR, "want is nullptr.");
873         return "";
874     }
875     return GetSpecifiedProcessFlag(*abilityInfo, *want);
876 }
877 
GetSpecifiedProcessFlag(const AbilityInfo & abilityInfo,const AAFwk::Want & want)878 std::string AppMgrServiceInner::GetSpecifiedProcessFlag(const AbilityInfo &abilityInfo, const AAFwk::Want &want)
879 {
880     std::string specifiedProcessFlag;
881     bool isUIAbility = (abilityInfo.type == AppExecFwk::AbilityType::PAGE && abilityInfo.isStageBasedModel);
882     bool isSpecifiedProcess = abilityInfo.isolationProcess &&
883         AAFwk::AppUtils::GetInstance().IsStartSpecifiedProcess() && isUIAbility;
884     if (isSpecifiedProcess) {
885         specifiedProcessFlag = want.GetStringParam(PARAM_SPECIFIED_PROCESS_FLAG);
886         TAG_LOGI(AAFwkTag::APPMGR, "specifiedProcessFlag = %{public}s", specifiedProcessFlag.c_str());
887     }
888     return specifiedProcessFlag;
889 }
890 
IsMainProcess(const std::shared_ptr<ApplicationInfo> & appInfo,const std::string & processName) const891 bool AppMgrServiceInner::IsMainProcess(const std::shared_ptr<ApplicationInfo> &appInfo,
892     const std::string &processName) const
893 {
894     if (!appInfo) {
895         return true;
896     }
897     if (!appInfo->process.empty()) {
898         if (processName == appInfo->process) {
899             return true;
900         }
901     } else {
902         if (processName == appInfo->bundleName) {
903             return true;
904         }
905     }
906     return false;
907 }
908 
CheckIsolationMode(const HapModuleInfo & hapModuleInfo) const909 bool AppMgrServiceInner::CheckIsolationMode(const HapModuleInfo &hapModuleInfo) const
910 {
911     IsolationMode isolationMode = hapModuleInfo.isolationMode;
912     if (supportIsolationMode_.compare("true") == 0) {
913         switch (isolationMode) {
914             case IsolationMode::ISOLATION_FIRST:
915                 return true;
916             case IsolationMode::ISOLATION_ONLY:
917                 return true;
918             default:
919                 return false;
920         }
921     }
922     return false;
923 }
924 
GetBundleAndHapInfo(const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo,int32_t appIndex) const925 bool AppMgrServiceInner::GetBundleAndHapInfo(const AbilityInfo &abilityInfo,
926     const std::shared_ptr<ApplicationInfo> &appInfo, BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo,
927     int32_t appIndex) const
928 {
929     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
930     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
931     if (bundleMgrHelper == nullptr) {
932         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
933         return false;
934     }
935 
936     auto userId = GetUserIdByUid(appInfo->uid);
937     TAG_LOGD(AAFwkTag::APPMGR, "UserId:%{public}d.", userId);
938     int32_t bundleMgrResult;
939     if (appIndex == 0) {
940         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfoV9(appInfo->bundleName,
941             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) +
942             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) +
943             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) +
944             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION), bundleInfo, userId));
945     } else if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
946         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetCloneBundleInfo(appInfo->bundleName,
947             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION), appIndex, bundleInfo, userId));
948     } else {
949         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetSandboxBundleInfo(appInfo->bundleName,
950             appIndex, userId, bundleInfo));
951     }
952 
953     if (bundleMgrResult != ERR_OK) {
954         TAG_LOGE(AAFwkTag::APPMGR, "GetBundleInfo is fail.");
955         return false;
956     }
957     bool hapQueryResult = false;
958     if (appIndex <= AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
959         hapQueryResult = bundleMgrHelper->GetHapModuleInfo(abilityInfo, userId, hapModuleInfo);
960     } else {
961         hapQueryResult = (bundleMgrHelper->GetSandboxHapModuleInfo(abilityInfo, appIndex, userId, hapModuleInfo) == 0);
962     }
963     if (!hapQueryResult) {
964         TAG_LOGE(AAFwkTag::APPMGR, "GetHapModuleInfo is fail.");
965         return false;
966     }
967     return true;
968 }
969 
AttachApplication(const pid_t pid,const sptr<IAppScheduler> & appScheduler)970 void AppMgrServiceInner::AttachApplication(const pid_t pid, const sptr<IAppScheduler> &appScheduler)
971 {
972     TAG_LOGI(AAFwkTag::APPMGR, "%{public}s called", __func__);
973     if (pid <= 0) {
974         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}d", pid);
975         return;
976     }
977     AbilityRuntime::FreezeUtil::GetInstance().AddAppLifecycleEvent(pid, "ServiceInner::AttachApplication");
978     auto appRecord = GetAppRunningRecordByPid(pid);
979     CHECK_POINTER_AND_RETURN_LOG(appRecord, "no such appRecord");
980     auto applicationInfo = appRecord->GetApplicationInfo();
981     AAFwk::EventInfo eventInfo;
982     if (!applicationInfo) {
983         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations");
984     } else {
985         eventInfo.bundleName = applicationInfo->name;
986         eventInfo.versionName = applicationInfo->versionName;
987         eventInfo.versionCode = applicationInfo->versionCode;
988     }
989     std::string connector = "##";
990     std::string traceName = __PRETTY_FUNCTION__ + connector + eventInfo.bundleName;
991     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
992     if (appScheduler == nullptr) {
993         TAG_LOGE(AAFwkTag::APPMGR, "Attach null, pid:%{public}d. bundleName: %{public}s.", pid,
994             eventInfo.bundleName.c_str());
995         NotifyAppAttachFailed(appRecord);
996         return;
997     }
998     TAG_LOGI(AAFwkTag::APPMGR, "attach pid:%{public}d, bundle:%{public}s", pid, eventInfo.bundleName.c_str());
999     sptr<AppDeathRecipient> appDeathRecipient = new (std::nothrow) AppDeathRecipient();
1000     CHECK_POINTER_AND_RETURN_LOG(appDeathRecipient, "Failed to create death recipient.");
1001     appDeathRecipient->SetTaskHandler(taskHandler_);
1002     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
1003     auto object = appScheduler->AsObject();
1004     if (!object || !object->AddDeathRecipient(appDeathRecipient)) {
1005         TAG_LOGE(AAFwkTag::APPMGR, "Failed to add DeathRecipient for %{public}s.", appRecord->GetProcessName().c_str());
1006         return;
1007     }
1008 
1009     appRecord->SetAppDeathRecipient(appDeathRecipient);
1010     appRecord->SetApplicationClient(appScheduler);
1011     if (appRecord->GetState() == ApplicationState::APP_STATE_CREATE) {
1012         LaunchApplicationExt(appRecord);
1013     }
1014 
1015     // submit cached load ability task after scene board attach
1016     if (appRecord->GetBundleName() == SCENE_BOARD_BUNDLE_NAME) {
1017         sceneBoardAttachFlag_ = true;
1018         SubmitCacheLoadAbilityTask();
1019     }
1020     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
1021     eventInfo.processName = appRecord->GetProcessName();
1022     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_ATTACH, HiSysEventType::BEHAVIOR, eventInfo);
1023 }
1024 
LaunchApplicationExt(const std::shared_ptr<AppRunningRecord> & appRecord)1025 void AppMgrServiceInner::LaunchApplicationExt(const std::shared_ptr<AppRunningRecord> &appRecord)
1026 {
1027     auto isPreload = IsAllowedNWebPreload(appRecord->GetProcessName());
1028     appRecord->SetNWebPreload(isPreload);
1029     LaunchApplication(appRecord);
1030 }
1031 
IsAllowedNWebPreload(const std::string & processName)1032 bool AppMgrServiceInner::IsAllowedNWebPreload(const std::string &processName)
1033 {
1034     // nwebPreloadSet_ only be initialized in Init(), no lock required.
1035     return nwebPreloadSet_.count(processName);
1036 }
1037 
NotifyAppAttachFailed(std::shared_ptr<AppRunningRecord> appRecord)1038 void AppMgrServiceInner::NotifyAppAttachFailed(std::shared_ptr<AppRunningRecord> appRecord)
1039 {
1040     CHECK_POINTER_AND_RETURN_LOG(appRecord, "AppRecord null.");
1041     std::vector<sptr<IRemoteObject>> abilityTokens;
1042     for (const auto &token : appRecord->GetAbilities()) {
1043         abilityTokens.emplace_back(token.first);
1044     }
1045     TAG_LOGI(AAFwkTag::APPMGR, "Attach failed name: %{public}s %{public}zu", appRecord->GetProcessName().c_str(),
1046         abilityTokens.size());
1047     std::lock_guard lock(appStateCallbacksLock_);
1048     for (const auto &item : appStateCallbacks_) {
1049         if (item.callback != nullptr) {
1050             item.callback->OnAppRemoteDied(abilityTokens);
1051         }
1052     }
1053 }
1054 
NotifyStartProcessFailed(sptr<IRemoteObject> token)1055 void AppMgrServiceInner::NotifyStartProcessFailed(sptr<IRemoteObject> token)
1056 {
1057     CHECK_POINTER_AND_RETURN_LOG(token, "token null.");
1058     std::lock_guard lock(appStateCallbacksLock_);
1059     for (const auto &item : appStateCallbacks_) {
1060         if (item.callback != nullptr) {
1061             item.callback->OnStartProcessFailed(token);
1062         }
1063     }
1064 }
1065 
LaunchApplication(const std::shared_ptr<AppRunningRecord> & appRecord)1066 void AppMgrServiceInner::LaunchApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
1067 {
1068     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord null");
1069     appRecord->AddAppLifecycleEvent("ServiceInner::LaunchApplication");
1070     auto applicationInfo = appRecord->GetApplicationInfo();
1071     std::string bundleName = "";
1072     if (!applicationInfo) {
1073         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations");
1074     } else {
1075         bundleName = applicationInfo->name;
1076     }
1077     std::string connector = "##";
1078     std::string traceName = __PRETTY_FUNCTION__ + connector + bundleName;
1079     HITRACE_METER_NAME(HITRACE_TAG_APP, traceName);
1080 
1081     if (appRecord->GetState() != ApplicationState::APP_STATE_CREATE) {
1082         TAG_LOGE(AAFwkTag::APPMGR, "wrong app state:%{public}d", appRecord->GetState());
1083         return;
1084     }
1085     if (multiUserConfigurationMgr_ == nullptr) {
1086         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
1087         return;
1088     }
1089     int32_t userId = appRecord->GetUid() / BASE_USER_RANGE;
1090     auto config = multiUserConfigurationMgr_->GetConfigurationByUserId(userId);
1091     if (config == nullptr) {
1092         TAG_LOGE(AAFwkTag::APPMGR, "config null");
1093         return;
1094     }
1095 
1096     TAG_LOGD(AAFwkTag::APPMGR, "LaunchApplication configuration:%{public}s", config->GetName().c_str());
1097     appRecord->LaunchApplication(*config);
1098     appRecord->SetState(ApplicationState::APP_STATE_READY);
1099     int restartResidentProcCount = MAX_RESTART_COUNT;
1100     appRecord->SetRestartResidentProcCount(restartResidentProcCount);
1101 
1102     // There is no ability when the empty resident process starts
1103     // The status of all resident processes is ready
1104     // There is no process of switching the foreground, waiting for his first ability to start
1105     if (appRecord->IsEmptyKeepAliveApp()) {
1106         appRecord->AddAbilityStage();
1107         return;
1108     }
1109     appRecord->LaunchPendingAbilities();
1110     AddAbilityStageForSpecified(appRecord);
1111 
1112     if (appRecord->IsPreloading()) {
1113         appRecord->SetPreloadState(PreloadState::PRELOADED);
1114     }
1115     SendAppLaunchEvent(appRecord);
1116 }
1117 
AddAbilityStageForSpecified(std::shared_ptr<AppRunningRecord> appRecord)1118 void AppMgrServiceInner::AddAbilityStageForSpecified(std::shared_ptr<AppRunningRecord> appRecord)
1119 {
1120     CHECK_POINTER_AND_RETURN_LOG(appRecord, "appRecord null");
1121     if (appRecord->IsStartSpecifiedAbility()) {
1122         TAG_LOGI(AAFwkTag::APPMGR, "start specified ability");
1123         auto moduleRecordList = appRecord->GetAllModuleRecord();
1124         for (const auto iter : moduleRecordList) {
1125             iter->SetModuleRecordState(ModuleRecordState::INITIALIZED_STATE);
1126         }
1127         appRecord->AddAbilityStageBySpecifiedAbility(appRecord->GetBundleName());
1128     }
1129 
1130     if (appRecord->IsNewProcessRequest()) {
1131         appRecord->AddAbilityStageBySpecifiedProcess(appRecord->GetBundleName());
1132     }
1133 }
1134 
AddAbilityStageDone(const int32_t recordId)1135 void AppMgrServiceInner::AddAbilityStageDone(const int32_t recordId)
1136 {
1137     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1138     if (!appRecord) {
1139         TAG_LOGE(AAFwkTag::APPMGR, "get app record failed");
1140         return;
1141     }
1142     appRecord->AddAbilityStageDone();
1143 }
1144 
ApplicationForegrounded(const int32_t recordId)1145 void AppMgrServiceInner::ApplicationForegrounded(const int32_t recordId)
1146 {
1147     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1148     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1149     if (!appRecord) {
1150         TAG_LOGE(AAFwkTag::APPMGR, "get app record failed");
1151         return;
1152     }
1153     appRecord->AddAppLifecycleEvent("ServiceInner::AppForegrounded");
1154     // Prevent forged requests from changing the app's state.
1155     if (appRecord->GetApplicationScheduleState() != ApplicationScheduleState::SCHEDULE_FOREGROUNDING) {
1156         TAG_LOGE(AAFwkTag::APPMGR, "app is not scheduling to foreground.");
1157         return;
1158     }
1159     appRecord->SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_READY);
1160     ApplicationState appState = appRecord->GetState();
1161     if (appState == ApplicationState::APP_STATE_READY || appState == ApplicationState::APP_STATE_BACKGROUND) {
1162         if (appState == ApplicationState::APP_STATE_BACKGROUND) {
1163             appRunningManager_->UpdateConfigurationDelayed(appRecord);
1164         }
1165         appRecord->SetState(ApplicationState::APP_STATE_FOREGROUND);
1166         bool needNotifyApp = appRunningManager_->IsApplicationFirstForeground(*appRecord);
1167         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp, false);
1168         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
1169     } else {
1170         TAG_LOGW(AAFwkTag::APPMGR, "app name(%{public}s), app state(%{public}d)!",
1171             appRecord->GetName().c_str(), static_cast<ApplicationState>(appState));
1172     }
1173     appRecord->PopForegroundingAbilityTokens();
1174 
1175     TAG_LOGI(AAFwkTag::APPMGR, "ApplicationForegrounded, bundle: %{public}s", appRecord->GetBundleName().c_str());
1176     if (appRecord->GetApplicationPendingState() == ApplicationPendingState::BACKGROUNDING) {
1177         appRecord->ScheduleBackgroundRunning();
1178     } else if (appRecord->GetApplicationPendingState() == ApplicationPendingState::FOREGROUNDING) {
1179         appRecord->SetApplicationPendingState(ApplicationPendingState::READY);
1180     }
1181     auto eventInfo = BuildEventInfo(appRecord);
1182     int32_t callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
1183     auto callerRecord = GetAppRunningRecordByPid(callerPid);
1184     if (callerRecord != nullptr) {
1185         eventInfo.callerBundleName = callerRecord->GetBundleName();
1186     } else {
1187         TAG_LOGE(AAFwkTag::APPMGR, "null callerRecord can't get callerBundleName");
1188     }
1189     AAFwk::EventReport::SendAppForegroundEvent(AAFwk::EventName::APP_FOREGROUND, eventInfo);
1190 }
1191 
ApplicationBackgrounded(const int32_t recordId)1192 void AppMgrServiceInner::ApplicationBackgrounded(const int32_t recordId)
1193 {
1194     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1195     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1196     if (!appRecord) {
1197         TAG_LOGE(AAFwkTag::APPMGR, "get app record failed");
1198         return;
1199     }
1200     // Prevent forged requests from changing the app's state.
1201     appRecord->AddAppLifecycleEvent("ServiceInner::ForeForegrounded");
1202     if (appRecord->GetApplicationScheduleState() != ApplicationScheduleState::SCHEDULE_BACKGROUNDING) {
1203         TAG_LOGE(AAFwkTag::APPMGR, "app is not scheduling to background.");
1204         return;
1205     }
1206     appRecord->SetApplicationScheduleState(ApplicationScheduleState::SCHEDULE_READY);
1207     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
1208         appRecord->SetState(ApplicationState::APP_STATE_BACKGROUND);
1209         bool needNotifyApp = !AAFwk::UIExtensionUtils::IsUIExtension(appRecord->GetExtensionType())
1210             && !AAFwk::UIExtensionUtils::IsWindowExtension(appRecord->GetExtensionType())
1211             && appRunningManager_->IsApplicationBackground(*appRecord);
1212         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_BACKGROUND, needNotifyApp, false);
1213         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
1214     } else {
1215         TAG_LOGW(AAFwkTag::APPMGR, "app name(%{public}s), app state(%{public}d)!",
1216             appRecord->GetName().c_str(), static_cast<ApplicationState>(appRecord->GetState()));
1217     }
1218     auto pendingState = appRecord->GetApplicationPendingState();
1219     TAG_LOGI(AAFwkTag::APPMGR, "app backgrounded: %{public}s, pState: %{public}d", appRecord->GetBundleName().c_str(),
1220         pendingState);
1221     if (pendingState == ApplicationPendingState::FOREGROUNDING) {
1222         appRecord->ScheduleForegroundRunning();
1223     } else if (pendingState == ApplicationPendingState::BACKGROUNDING) {
1224         appRecord->SetApplicationPendingState(ApplicationPendingState::READY);
1225     }
1226     auto eventInfo = BuildEventInfo(appRecord);
1227     AAFwk::EventReport::SendAppBackgroundEvent(AAFwk::EventName::APP_BACKGROUND, eventInfo);
1228 }
1229 
BuildEventInfo(std::shared_ptr<AppRunningRecord> appRecord) const1230 AAFwk::EventInfo AppMgrServiceInner::BuildEventInfo(std::shared_ptr<AppRunningRecord> appRecord) const
1231 {
1232     AAFwk::EventInfo eventInfo;
1233     if (appRecord == nullptr) {
1234         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1235         return eventInfo;
1236     }
1237     auto applicationInfo = appRecord->GetApplicationInfo();
1238     if (!applicationInfo) {
1239         TAG_LOGW(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations");
1240     } else {
1241         eventInfo.bundleName = applicationInfo->name;
1242         eventInfo.versionName = applicationInfo->versionName;
1243         eventInfo.versionCode = applicationInfo->versionCode;
1244         eventInfo.bundleType = static_cast<int32_t>(applicationInfo->bundleType);
1245     }
1246     if (appRecord->GetPriorityObject() != nullptr) {
1247         eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
1248     }
1249     eventInfo.processName = appRecord->GetProcessName();
1250     eventInfo.processType = static_cast<int32_t>(appRecord->GetProcessType());
1251     return eventInfo;
1252 }
1253 
ApplicationTerminated(const int32_t recordId)1254 void AppMgrServiceInner::ApplicationTerminated(const int32_t recordId)
1255 {
1256     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1257     if (!appRunningManager_) {
1258         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
1259         return;
1260     }
1261 
1262     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
1263     if (!appRecord) {
1264         TAG_LOGE(AAFwkTag::APPMGR, "get app record failed");
1265         return;
1266     }
1267     appRecord->ApplicationTerminated();
1268     if (appRecord->GetState() != ApplicationState::APP_STATE_BACKGROUND) {
1269         TAG_LOGD(AAFwkTag::APPMGR, "current state is not background");
1270         return;
1271     }
1272 
1273     KillRenderProcess(appRecord);
1274     KillChildProcess(appRecord);
1275     KillAttachedChildProcess(appRecord);
1276     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
1277     appRecord->RemoveAppDeathRecipient();
1278     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED);
1279     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false, false);
1280     appRunningManager_->RemoveAppRunningRecordById(recordId);
1281     AAFwk::EventInfo eventInfo;
1282     auto applicationInfo = appRecord->GetApplicationInfo();
1283     if (!applicationInfo) {
1284         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations");
1285     } else {
1286         eventInfo.bundleName = applicationInfo->name;
1287         eventInfo.versionName = applicationInfo->versionName;
1288         eventInfo.versionCode = applicationInfo->versionCode;
1289     }
1290     ClearAppRunningDataForKeepAlive(appRecord);
1291     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
1292     eventInfo.processName = appRecord->GetProcessName();
1293     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
1294 
1295     ApplicationTerminatedSendProcessEvent(appRecord);
1296 
1297     auto uid = appRecord->GetUid();
1298     bool foreground = appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND ||
1299         appRecord->GetState() == ApplicationState::APP_STATE_FOCUS;
1300     auto result = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL",
1301         OHOS::HiviewDFX::HiSysEvent::EventType::BEHAVIOR, EVENT_KEY_PID, std::to_string(eventInfo.pid),
1302         EVENT_KEY_PROCESS_NAME, eventInfo.processName, EVENT_KEY_MESSAGE, "app exit", EVENT_KEY_FOREGROUND, foreground);
1303     TAG_LOGI(AAFwkTag::APPMGR, "hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL], pid="
1304         "%{public}d, processName=%{public}s, FOREGROUND = %{public}d",
1305         result, eventInfo.pid, eventInfo.processName.c_str(), foreground);
1306     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
1307 }
1308 
UpdateApplicationInfoInstalled(const std::string & bundleName,const int uid)1309 int32_t AppMgrServiceInner::UpdateApplicationInfoInstalled(const std::string &bundleName, const int uid)
1310 {
1311     if (!appRunningManager_) {
1312         TAG_LOGE(AAFwkTag::APPMGR, "The appRunningManager_ is nullptr.");
1313         return ERR_NO_INIT;
1314     }
1315 
1316     int32_t result = VerifyRequestPermission();
1317     if (result != ERR_OK) {
1318         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
1319         return result;
1320     }
1321 
1322     if (remoteClientManager_ == nullptr) {
1323         TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ fail.");
1324         return ERR_NO_INIT;
1325     }
1326 
1327     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1328     if (bundleMgrHelper == nullptr) {
1329         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
1330         return ERR_NO_INIT;
1331     }
1332     auto userId = GetUserIdByUid(uid);
1333     ApplicationInfo appInfo;
1334     HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetApplicationInfo");
1335     bool bundleMgrResult = bundleMgrHelper->GetApplicationInfo(bundleName,
1336         ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo);
1337     if (!bundleMgrResult) {
1338         TAG_LOGE(AAFwkTag::APPMGR, "Failed to get applicationInfo.");
1339         return ERR_INVALID_OPERATION;
1340     }
1341 
1342     TAG_LOGD(AAFwkTag::APPMGR, "uid value is %{public}d", uid);
1343     result = appRunningManager_->ProcessUpdateApplicationInfoInstalled(appInfo);
1344     if (result != ERR_OK) {
1345         TAG_LOGI(AAFwkTag::APPMGR, "The process corresponding to the package name did not start.");
1346     }
1347 
1348     return result;
1349 }
1350 
KillApplication(const std::string & bundleName,const bool clearPageStack)1351 int32_t AppMgrServiceInner::KillApplication(const std::string &bundleName, const bool clearPageStack)
1352 {
1353     if (!appRunningManager_) {
1354         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
1355         return ERR_NO_INIT;
1356     }
1357 
1358     if (CheckCallerIsAppGallery()) {
1359         return KillApplicationByBundleName(bundleName, clearPageStack, "KillApplicationByAppGallery");
1360     }
1361 
1362     auto result = VerifyKillProcessPermission(bundleName);
1363     if (result != ERR_OK) {
1364         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
1365         return result;
1366     }
1367 
1368     return KillApplicationByBundleName(bundleName, clearPageStack, "KillApplication");
1369 }
1370 
ForceKillApplication(const std::string & bundleName,const int userId,const int appIndex)1371 int32_t AppMgrServiceInner::ForceKillApplication(const std::string &bundleName,
1372     const int userId, const int appIndex)
1373 {
1374     TAG_LOGI(AAFwkTag::APPMGR, "Called.");
1375     if (!IsSceneBoardCall()) {
1376         TAG_LOGE(AAFwkTag::APPMGR, "this is not called by SceneBoard.");
1377         return AAFwk::CHECK_PERMISSION_FAILED;
1378     }
1379 
1380     return ForceKillApplicationInner(bundleName, userId, appIndex);
1381 }
1382 
ForceKillApplicationInner(const std::string & bundleName,const int userId,const int appIndex)1383 int32_t AppMgrServiceInner::ForceKillApplicationInner(const std::string &bundleName,
1384     const int userId, const int appIndex)
1385 {
1386     TAG_LOGD(AAFwkTag::APPMGR, "Called.");
1387     if (!appRunningManager_) {
1388         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
1389         return ERR_NO_INIT;
1390     }
1391 
1392     std::list<pid_t> pids;
1393     int32_t newUserId = userId;
1394     if (userId == DEFAULT_INVAL_VALUE) {
1395         newUserId = GetUserIdByUid(IPCSkeleton::GetCallingUid());
1396     }
1397     int32_t result = ERR_OK;
1398     if (!appRunningManager_->GetPidsByBundleNameUserIdAndAppIndex(bundleName, newUserId, appIndex, pids)) {
1399         TAG_LOGI(AAFwkTag::APPMGR, "not start");
1400         return result;
1401     }
1402     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1403         result = KillProcessByPid(*iter, "ForceKillApplicationByBundleName");
1404         if (result < 0) {
1405             TAG_LOGE(AAFwkTag::APPMGR,
1406                 "ForceKillApplicationByBundleName failed for bundleName:%{public}s pid:%{public}d",
1407                 bundleName.c_str(), *iter);
1408             return result;
1409         }
1410     }
1411     return result;
1412 }
1413 
WaitProcessesExitAndKill(std::list<pid_t> & pids,const int64_t startTime,const std::string & reason)1414 int32_t AppMgrServiceInner::WaitProcessesExitAndKill(std::list<pid_t> &pids, const int64_t startTime,
1415     const std::string& reason)
1416 {
1417     int32_t result = ERR_OK;
1418     if (WaitForRemoteProcessExit(pids, startTime)) {
1419         TAG_LOGI(AAFwkTag::APPMGR, "remote process exited successs");
1420         return result;
1421     }
1422     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1423         auto singleRet = KillProcessByPid(*iter, reason);
1424         if (singleRet != 0 && singleRet != AAFwk::ERR_KILL_PROCESS_NOT_EXIST) {
1425             TAG_LOGE(AAFwkTag::APPMGR, "killApplication fail for pid:%{public}d", *iter);
1426             result = singleRet;
1427         }
1428     }
1429     return result;
1430 }
1431 
KillProcessesByAccessTokenId(const uint32_t accessTokenId)1432 int32_t AppMgrServiceInner::KillProcessesByAccessTokenId(const uint32_t accessTokenId)
1433 {
1434     TAG_LOGI(AAFwkTag::APPMGR, "Called.");
1435     CHECK_CALLER_IS_SYSTEM_APP;
1436     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
1437         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
1438     if (!isCallingPerm) {
1439         TAG_LOGE(AAFwkTag::APPMGR, "no permission to kill processes.");
1440         return ERR_PERMISSION_DENIED;
1441     }
1442 
1443     std::vector<pid_t> pids;
1444     GetPidsByAccessTokenId(accessTokenId, pids);
1445     if (pids.empty()) {
1446         TAG_LOGI(AAFwkTag::APPMGR, "no pids matching the given accessTokenId.");
1447         return ERR_OK;
1448     }
1449 
1450     if (!appRunningManager_) {
1451         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
1452         return ERR_NO_INIT;
1453     }
1454 
1455     int32_t result = ERR_OK;
1456     for (auto iter = pids.begin(); iter != pids.end(); ++iter) {
1457         result = KillProcessByPid(*iter, "KillProcessesByAccessTokenId");
1458         if (result < 0) {
1459             TAG_LOGE(AAFwkTag::APPMGR,
1460                 "KillProcessesByAccessTokenId failed for accessTokenId:%{public}d,pid:%{public}d",
1461                 accessTokenId, *iter);
1462             return result;
1463         }
1464     }
1465     return result;
1466 }
1467 
KillApplicationByUid(const std::string & bundleName,const int uid,const std::string & reason)1468 int32_t AppMgrServiceInner::KillApplicationByUid(const std::string &bundleName, const int uid,
1469     const std::string& reason)
1470 {
1471     if (!appRunningManager_) {
1472         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
1473         return ERR_NO_INIT;
1474     }
1475 
1476     int32_t result = ERR_OK;
1477     if (!CheckCallerIsAppGallery()) {
1478         result = VerifyKillProcessPermission(bundleName);
1479         if (result != ERR_OK) {
1480             TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
1481             return result;
1482         }
1483     }
1484 
1485     int64_t startTime = SystemTimeMillisecond();
1486     std::list<pid_t> pids;
1487     TAG_LOGI(AAFwkTag::APPMGR, "uid value is %{public}d", uid);
1488     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids)) {
1489         TAG_LOGI(AAFwkTag::APPMGR, "not start");
1490         return result;
1491     }
1492     return WaitProcessesExitAndKill(pids, startTime, reason);
1493 }
1494 
SendProcessExitEventTask(const std::shared_ptr<AppRunningRecord> & appRecord,time_t exitTime,int32_t count)1495 void AppMgrServiceInner::SendProcessExitEventTask(
1496     const std::shared_ptr<AppRunningRecord> &appRecord, time_t exitTime, int32_t count)
1497 {
1498     if (appRecord == nullptr) {
1499         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1500         return;
1501     }
1502     if (appRecord->GetPriorityObject() == nullptr) {
1503         TAG_LOGE(AAFwkTag::APPMGR, "Get priority object is nullptr.");
1504         return;
1505     }
1506     auto pid = appRecord->GetPriorityObject()->GetPid();
1507     auto exitResult = !ProcessExist(pid);
1508     constexpr int32_t EXIT_SUCESS = 0;
1509     constexpr int32_t EXIT_FAILED = -1;
1510     AAFwk::EventInfo eventInfo;
1511     eventInfo.time = exitTime;
1512     eventInfo.pid = pid;
1513     eventInfo.processName = appRecord->GetProcessName();
1514     eventInfo.extensionType = static_cast<int32_t>(appRecord->GetExtensionType());
1515 
1516     if (exitResult) {
1517         eventInfo.exitResult = EXIT_SUCESS;
1518         AAFwk::EventReport::SendProcessExitEvent(AAFwk::EventName::PROCESS_EXIT, eventInfo);
1519         TAG_LOGI(AAFwkTag::APPMGR, "time : %{public}" PRId64 ", exitResult : %{public}d, pid : %{public}d",
1520             eventInfo.time, eventInfo.exitResult, eventInfo.pid);
1521         return;
1522     }
1523 
1524     if (--count <= 0) {
1525         eventInfo.exitResult = EXIT_FAILED;
1526         AAFwk::EventReport::SendProcessExitEvent(AAFwk::EventName::PROCESS_EXIT, eventInfo);
1527         TAG_LOGI(AAFwkTag::APPMGR, "time : %{public}" PRId64 ", exitResult : %{public}d, pid : %{public}d",
1528             eventInfo.time, eventInfo.exitResult, eventInfo.pid);
1529         return;
1530     }
1531 
1532     auto sendEventTask = [inner = shared_from_this(), appRecord, exitTime, count] () {
1533         inner->SendProcessExitEventTask(appRecord, exitTime, count);
1534     };
1535     taskHandler_->SubmitTask(sendEventTask, PROCESS_EXIT_EVENT_TASK, KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
1536 }
1537 
SendProcessExitEvent(const std::shared_ptr<AppRunningRecord> & appRecord)1538 void AppMgrServiceInner::SendProcessExitEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
1539 {
1540     TAG_LOGD(AAFwkTag::APPMGR, "called");
1541     time_t currentTime;
1542     time(&currentTime);
1543     constexpr int32_t RETRY_COUNT = 5;
1544     SendProcessExitEventTask(appRecord, currentTime, RETRY_COUNT);
1545     return;
1546 }
1547 
KillApplicationSelf(const bool clearPageStack,const std::string & reason)1548 int32_t AppMgrServiceInner::KillApplicationSelf(const bool clearPageStack, const std::string& reason)
1549 {
1550     if (!appRunningManager_) {
1551         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
1552         return ERR_NO_INIT;
1553     }
1554 
1555     auto callerPid = IPCSkeleton::GetCallingPid();
1556     auto appRecord = GetAppRunningRecordByPid(callerPid);
1557     if (!appRecord) {
1558         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, callerPid:%{public}d", callerPid);
1559         return ERR_INVALID_VALUE;
1560     }
1561     int64_t startTime = SystemTimeMillisecond();
1562     auto bundleName = appRecord->GetBundleName();
1563     auto callingUid = IPCSkeleton::GetCallingUid();
1564     TAG_LOGI(AAFwkTag::APPMGR, "uid value: %{public}d", callingUid);
1565     std::list<pid_t> pids;
1566     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, callingUid, pids, clearPageStack)) {
1567         TAG_LOGI(AAFwkTag::APPMGR, "unstart");
1568         return ERR_OK;
1569     }
1570     return WaitProcessesExitAndKill(pids, startTime, reason);
1571 }
1572 
KillApplicationByBundleName(const std::string & bundleName,const bool clearPageStack,const std::string & reason)1573 int32_t AppMgrServiceInner::KillApplicationByBundleName(const std::string &bundleName, const bool clearPageStack,
1574     const std::string& reason)
1575 {
1576     int result = ERR_OK;
1577     int64_t startTime = SystemTimeMillisecond();
1578     std::list<pid_t> pids;
1579 
1580     if (!appRunningManager_->ProcessExitByBundleName(bundleName, pids, clearPageStack)) {
1581         TAG_LOGE(AAFwkTag::APPMGR, "The process corresponding to the package name did not start");
1582         return result;
1583     }
1584     result = WaitProcessesExitAndKill(pids, startTime, reason);
1585     if (result < 0) {
1586         TAG_LOGE(AAFwkTag::APPMGR, "KillApplicationSelf is failed for bundleName:%{public}s", bundleName.c_str());
1587         return result;
1588     }
1589     NotifyAppStatus(bundleName, EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED);
1590     return result;
1591 }
1592 
KillApplicationByUserId(const std::string & bundleName,int32_t appCloneIndex,int32_t userId,const bool clearPageStack,const std::string & reason)1593 int32_t AppMgrServiceInner::KillApplicationByUserId(
1594     const std::string &bundleName, int32_t appCloneIndex, int32_t userId,
1595     const bool clearPageStack, const std::string& reason)
1596 {
1597     CHECK_CALLER_IS_SYSTEM_APP;
1598     if (VerifyAccountPermission(
1599         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES, userId) == ERR_PERMISSION_DENIED &&
1600         VerifyAccountPermission(
1601             AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES, userId) == ERR_PERMISSION_DENIED) {
1602         TAG_LOGE(AAFwkTag::APPMGR, "Permission verify failed");
1603         return ERR_PERMISSION_DENIED;
1604     }
1605 
1606     return KillApplicationByUserIdLocked(bundleName, appCloneIndex, userId, clearPageStack, reason);
1607 }
1608 
KillApplicationByUserIdLocked(const std::string & bundleName,int32_t appCloneIndex,int32_t userId,const bool clearPageStack,const std::string & reason)1609 int32_t AppMgrServiceInner::KillApplicationByUserIdLocked(
1610     const std::string &bundleName, int32_t appCloneIndex, int32_t userId, const bool clearPageStack,
1611     const std::string& reason)
1612 {
1613     if (!appRunningManager_) {
1614         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
1615         return ERR_NO_INIT;
1616     }
1617 
1618     int64_t startTime = SystemTimeMillisecond();
1619     std::list<pid_t> pids;
1620     if (remoteClientManager_ == nullptr) {
1621         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is nullptr.");
1622         return ERR_NO_INIT;
1623     }
1624     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1625     if (bundleMgrHelper == nullptr) {
1626         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
1627         return ERR_NO_INIT;
1628     }
1629 
1630     TAG_LOGI(AAFwkTag::APPMGR, "userId value is %{public}d", userId);
1631     int uid = IN_PROCESS_CALL(bundleMgrHelper->GetUidByBundleName(bundleName, userId, appCloneIndex));
1632     TAG_LOGI(AAFwkTag::APPMGR, "uid value is %{public}d", uid);
1633     if (!appRunningManager_->ProcessExitByBundleNameAndUid(bundleName, uid, pids, clearPageStack)) {
1634         TAG_LOGI(AAFwkTag::APPMGR, "The process corresponding to the package name did not start.");
1635         return ERR_OK;
1636     }
1637     return WaitProcessesExitAndKill(pids, startTime, reason);
1638 }
1639 
ClearUpApplicationData(const std::string & bundleName,int32_t callerUid,pid_t callerPid,int32_t appCloneIndex,int32_t userId)1640 int32_t AppMgrServiceInner::ClearUpApplicationData(const std::string &bundleName,
1641     int32_t callerUid, pid_t callerPid, int32_t appCloneIndex, int32_t userId)
1642 {
1643     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1644     int32_t newUserId = userId;
1645     if (userId == DEFAULT_INVAL_VALUE) {
1646         newUserId = GetUserIdByUid(callerUid);
1647     }
1648     TAG_LOGI(AAFwkTag::APPMGR, "userId:%{public}d, appIndex:%{public}d", newUserId, appCloneIndex);
1649     return ClearUpApplicationDataByUserId(bundleName, callerUid, callerPid, appCloneIndex, newUserId,
1650         false, "ClearUpApplicationData");
1651 }
1652 
ClearUpApplicationDataBySelf(int32_t callerUid,pid_t callerPid,int32_t userId)1653 int32_t AppMgrServiceInner::ClearUpApplicationDataBySelf(int32_t callerUid, pid_t callerPid, int32_t userId)
1654 {
1655     auto appRecord = GetAppRunningRecordByPid(callerPid);
1656     if (!appRecord) {
1657         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, callerPid:%{public}d", callerPid);
1658         return ERR_INVALID_VALUE;
1659     }
1660     auto callerBundleName = appRecord->GetBundleName();
1661     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
1662     int32_t newUserId = userId;
1663     if (userId == DEFAULT_INVAL_VALUE) {
1664         newUserId = GetUserIdByUid(callerUid);
1665     }
1666     return ClearUpApplicationDataByUserId(callerBundleName, callerUid, callerPid, 0, newUserId, true,
1667         "ClearUpApplicationDataBySelf");
1668 }
1669 
ClearUpApplicationDataByUserId(const std::string & bundleName,int32_t callerUid,pid_t callerPid,int32_t appCloneIndex,int32_t userId,bool isBySelf,const std::string & reason)1670 int32_t AppMgrServiceInner::ClearUpApplicationDataByUserId(const std::string &bundleName, int32_t callerUid,
1671     pid_t callerPid, int32_t appCloneIndex, int32_t userId, bool isBySelf, const std::string& reason)
1672 {
1673     if (callerPid <= 0) {
1674         TAG_LOGE(AAFwkTag::APPMGR, "invalid callerPid:%{public}d", callerPid);
1675         return ERR_INVALID_OPERATION;
1676     }
1677     if (callerUid < 0) {
1678         TAG_LOGE(AAFwkTag::APPMGR, "invalid callerUid:%{public}d", callerUid);
1679         return ERR_INVALID_OPERATION;
1680     }
1681     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1682     if (bundleMgrHelper == nullptr) {
1683         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
1684         return ERR_INVALID_OPERATION;
1685     }
1686 
1687     // request to clear user information permission.
1688     auto tokenId = AccessToken::AccessTokenKit::GetHapTokenID(userId, bundleName, appCloneIndex);
1689     int32_t result = AccessToken::AccessTokenKit::ClearUserGrantedPermissionState(tokenId);
1690     if (result) {
1691         TAG_LOGE(AAFwkTag::APPMGR, "ClearUserGrantedPermissionState failed, ret:%{public}d", result);
1692         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
1693     }
1694     // 2.delete bundle side user data
1695     if (!IN_PROCESS_CALL(bundleMgrHelper->CleanBundleDataFiles(bundleName, userId, appCloneIndex))) {
1696         TAG_LOGE(AAFwkTag::APPMGR, "Delete bundle side user data is fail");
1697         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
1698     }
1699     // 3.kill application
1700     // 4.revoke user rights
1701     result =
1702         isBySelf ? KillApplicationSelf(false, reason)
1703             : KillApplicationByUserId(bundleName, appCloneIndex, userId, false, reason);
1704     if (result < 0) {
1705         TAG_LOGE(AAFwkTag::APPMGR, "Kill Application by bundle name is fail");
1706         return ERR_INVALID_OPERATION;
1707     }
1708     // 5.revoke uri permission rights
1709     auto ret = IN_PROCESS_CALL(AAFwk::UriPermissionManagerClient::GetInstance().RevokeAllUriPermissions(tokenId));
1710     if (ret != ERR_OK) {
1711         TAG_LOGE(AAFwkTag::APPMGR, "Revoke all uri permissions is failed");
1712     }
1713     auto dataMgr = OHOS::DistributedKv::DistributedDataMgr();
1714     auto dataRet = dataMgr.ClearAppStorage(bundleName, userId, appCloneIndex, tokenId);
1715     if (dataRet != 0) {
1716         TAG_LOGW(
1717             AAFwkTag::APPMGR, "Distributeddata clear app storage failed, bundleName:%{public}s", bundleName.c_str());
1718     }
1719     int targetUid = IN_PROCESS_CALL(bundleMgrHelper->GetUidByBundleName(bundleName, userId, appCloneIndex));
1720     NotifyAppStatusByCallerUid(bundleName, tokenId, userId, callerUid, targetUid,
1721         EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED);
1722     return ERR_OK;
1723 }
1724 
GetAllRunningProcesses(std::vector<RunningProcessInfo> & info)1725 int32_t AppMgrServiceInner::GetAllRunningProcesses(std::vector<RunningProcessInfo> &info)
1726 {
1727     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
1728     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
1729     // check permission
1730     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
1731         const auto &appRecord = item.second;
1732         if (!appRecord || !appRecord->GetSpawned()) {
1733             continue;
1734         }
1735         if (isPerm) {
1736             GetRunningProcesses(appRecord, info);
1737         } else {
1738             auto applicationInfo = appRecord->GetApplicationInfo();
1739             if (!applicationInfo) {
1740                 continue;
1741             }
1742             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
1743             auto tokenId = applicationInfo->accessTokenId;
1744             if (callingTokenId == tokenId) {
1745                 GetRunningProcesses(appRecord, info);
1746             }
1747         }
1748     }
1749     return ERR_OK;
1750 }
1751 
GetRunningProcessesByBundleType(BundleType bundleType,std::vector<RunningProcessInfo> & info)1752 int32_t AppMgrServiceInner::GetRunningProcessesByBundleType(BundleType bundleType,
1753     std::vector<RunningProcessInfo> &info)
1754 {
1755     TAG_LOGD(AAFwkTag::APPMGR, "called");
1756     CHECK_CALLER_IS_SYSTEM_APP;
1757     if (!AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm()) {
1758         TAG_LOGE(AAFwkTag::APPMGR, "permission deny");
1759         return ERR_PERMISSION_DENIED;
1760     }
1761     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
1762         const auto &appRecord = item.second;
1763         if (!appRecord || !appRecord->GetSpawned()) {
1764             continue;
1765         }
1766         if (GetUserIdByUid(appRecord->GetUid()) != currentUserId_) {
1767             continue;
1768         }
1769         auto appInfo = appRecord->GetApplicationInfo();
1770         if (appInfo && appInfo->bundleType == bundleType) {
1771             GetRunningProcesses(appRecord, info);
1772         }
1773     }
1774     return ERR_OK;
1775 }
1776 
GetRunningMultiAppInfoByBundleName(const std::string & bundleName,RunningMultiAppInfo & info)1777 int32_t AppMgrServiceInner::GetRunningMultiAppInfoByBundleName(const std::string &bundleName,
1778     RunningMultiAppInfo &info)
1779 {
1780     if (bundleName.empty()) {
1781         TAG_LOGE(AAFwkTag::APPMGR, "null bundleName");
1782         return AAFwk::INVALID_PARAMETERS_ERR;
1783     }
1784     if (remoteClientManager_ == nullptr) {
1785         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null");
1786         return ERR_INVALID_VALUE;
1787     }
1788     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1789     if (bundleMgrHelper == nullptr) {
1790         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
1791         return ERR_INVALID_VALUE;
1792     }
1793     ApplicationInfo appInfo;
1794     auto queryRet = IN_PROCESS_CALL(bundleMgrHelper->GetApplicationInfo(bundleName,
1795         ApplicationFlag::GET_BASIC_APPLICATION_INFO, currentUserId_, appInfo));
1796     if (!queryRet) {
1797         TAG_LOGE(AAFwkTag::APPMGR, "bundle not exist");
1798         return AAFwk::ERR_BUNDLE_NOT_EXIST;
1799     }
1800     if (appInfo.multiAppMode.multiAppModeType == MultiAppModeType::UNSPECIFIED) {
1801         TAG_LOGE(AAFwkTag::APPMGR, "bundle not support multi-app");
1802         return AAFwk::ERR_MULTI_APP_NOT_SUPPORTED;
1803     }
1804     info.bundleName = bundleName;
1805     info.mode = static_cast<int32_t>(appInfo.multiAppMode.multiAppModeType);
1806     if (!appRunningManager_) {
1807         TAG_LOGE(AAFwkTag::APPMGR, "null appRunningManager_");
1808         return ERR_INVALID_VALUE;
1809     }
1810     auto multiAppInfoMap = appRunningManager_->GetAppRunningRecordMap();
1811     for (const auto &item : multiAppInfoMap) {
1812         const std::shared_ptr<AppRunningRecord> &appRecord = item.second;
1813         if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) {
1814             continue;
1815         }
1816         if (GetUserIdByUid(appRecord->GetUid()) != currentUserId_) {
1817             continue;
1818         }
1819         GetRunningCloneAppInfo(appRecord, info);
1820     }
1821     return ERR_OK;
1822 }
1823 
GetAllRunningInstanceKeysBySelf(std::vector<std::string> & instanceKeys)1824 int32_t AppMgrServiceInner::GetAllRunningInstanceKeysBySelf(std::vector<std::string> &instanceKeys)
1825 {
1826     if (remoteClientManager_ == nullptr) {
1827         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
1828         return ERR_NO_INIT;
1829     }
1830     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1831     if (bundleMgrHelper == nullptr) {
1832         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
1833         return ERR_INVALID_VALUE;
1834     }
1835     std::string bundleName;
1836     int32_t callingUid = IPCSkeleton::GetCallingUid();
1837     auto ret = IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, bundleName));
1838     if (ret != ERR_OK) {
1839         TAG_LOGE(AAFwkTag::APPMGR, "GetNameForUid failed, ret=%{public}d", ret);
1840         return AAFwk::ERR_BUNDLE_NOT_EXIST;
1841     }
1842     return GetAllRunningInstanceKeysByBundleNameInner(bundleName, instanceKeys, currentUserId_);
1843 }
1844 
GetAllRunningInstanceKeysByBundleName(const std::string & bundleName,std::vector<std::string> & instanceKeys,int32_t userId)1845 int32_t AppMgrServiceInner::GetAllRunningInstanceKeysByBundleName(const std::string &bundleName,
1846     std::vector<std::string> &instanceKeys, int32_t userId)
1847 {
1848     if (userId == -1) {
1849         userId = currentUserId_;
1850     }
1851     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
1852         ERR_PERMISSION_DENIED) {
1853         TAG_LOGE(AAFwkTag::APPMGR, "%{public}s: Permission verification fail", __func__);
1854         return ERR_PERMISSION_DENIED;
1855     }
1856     return GetAllRunningInstanceKeysByBundleNameInner(bundleName, instanceKeys, userId);
1857 }
1858 
GetAllRunningInstanceKeysByBundleNameInner(const std::string & bundleName,std::vector<std::string> & instanceKeys,int32_t userId)1859 int32_t AppMgrServiceInner::GetAllRunningInstanceKeysByBundleNameInner(const std::string &bundleName,
1860     std::vector<std::string> &instanceKeys, int32_t userId)
1861 {
1862     if (bundleName.empty()) {
1863         TAG_LOGE(AAFwkTag::APPMGR, "bundlename null");
1864         return AAFwk::INVALID_PARAMETERS_ERR;
1865     }
1866     if (remoteClientManager_ == nullptr) {
1867         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ null");
1868         return ERR_INVALID_VALUE;
1869     }
1870     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
1871     if (bundleMgrHelper == nullptr) {
1872         TAG_LOGE(AAFwkTag::APPMGR, "bundleMgrHelper null");
1873         return ERR_INVALID_VALUE;
1874     }
1875     ApplicationInfo appInfo;
1876     auto queryRet = IN_PROCESS_CALL(bundleMgrHelper->GetApplicationInfo(bundleName,
1877         ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo));
1878     if (!queryRet) {
1879         TAG_LOGE(AAFwkTag::APPMGR, "bundle unexist");
1880         return AAFwk::ERR_BUNDLE_NOT_EXIST;
1881     }
1882     if (appInfo.multiAppMode.multiAppModeType != MultiAppModeType::MULTI_INSTANCE) {
1883         TAG_LOGE(AAFwkTag::APPMGR, "bundle unsupport multi-instance");
1884         return AAFwk::ERR_MULTI_INSTANCE_NOT_SUPPORTED;
1885     }
1886     if (!appRunningManager_) {
1887         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager null");
1888         return ERR_INVALID_VALUE;
1889     }
1890     auto multiAppInfoMap = appRunningManager_->GetAppRunningRecordMap();
1891     for (const auto &item : multiAppInfoMap) {
1892         const std::shared_ptr<AppRunningRecord> &appRecord = item.second;
1893         if (appRecord == nullptr || appRecord->GetBundleName() != bundleName) {
1894             continue;
1895         }
1896         if (GetUserIdByUid(appRecord->GetUid()) != userId) {
1897             continue;
1898         }
1899         GetRunningMultiInstanceKeys(appRecord, instanceKeys);
1900     }
1901     return ERR_OK;
1902 }
1903 
GetRunningCloneAppInfo(const std::shared_ptr<AppRunningRecord> & appRecord,RunningMultiAppInfo & info)1904 void AppMgrServiceInner::GetRunningCloneAppInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
1905     RunningMultiAppInfo &info)
1906 {
1907     if (info.mode == static_cast<int32_t>(MultiAppModeType::APP_CLONE)) {
1908         GetAppCloneInfo(appRecord, info);
1909         return;
1910     }
1911     if (info.mode == static_cast<int32_t>(MultiAppModeType::MULTI_INSTANCE)) {
1912         GetMultiInstanceInfo(appRecord, info);
1913     }
1914 }
1915 
CheckAppRecordAndPriorityObject(const std::shared_ptr<AppRunningRecord> & appRecord)1916 bool AppMgrServiceInner::CheckAppRecordAndPriorityObject(const std::shared_ptr<AppRunningRecord> &appRecord)
1917 {
1918     if (!appRecord) {
1919         TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
1920         return false;
1921     }
1922     if (appRecord->GetPriorityObject() == nullptr) {
1923         TAG_LOGE(AAFwkTag::APPMGR, "priorityObject null");
1924         return false;
1925     }
1926     return true;
1927 }
1928 
GetAppCloneInfo(const std::shared_ptr<AppRunningRecord> & appRecord,RunningMultiAppInfo & info)1929 void AppMgrServiceInner::GetAppCloneInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
1930     RunningMultiAppInfo &info)
1931 {
1932     if (!CheckAppRecordAndPriorityObject(appRecord)) {
1933         return;
1934     }
1935     auto PriorityObject = appRecord->GetPriorityObject();
1936     size_t index = 0;
1937     for (; index < info.runningAppClones.size(); index++) {
1938         if (info.runningAppClones[index].appCloneIndex == appRecord->GetAppIndex()) {
1939             break;
1940         }
1941     }
1942     auto childProcessRecordMap = appRecord->GetChildProcessRecordMap();
1943     if (index < info.runningAppClones.size()) {
1944         info.runningAppClones[index].pids.emplace_back(PriorityObject->GetPid());
1945         for (auto it : childProcessRecordMap) {
1946             info.runningAppClones[index].pids.emplace_back(it.first);
1947         }
1948         return;
1949     }
1950     RunningAppClone cloneInfo;
1951     cloneInfo.appCloneIndex = appRecord->GetAppIndex();
1952     cloneInfo.uid = appRecord->GetUid();
1953     cloneInfo.pids.emplace_back(PriorityObject->GetPid());
1954     for (auto it : childProcessRecordMap) {
1955         cloneInfo.pids.emplace_back(it.first);
1956     }
1957     info.runningAppClones.emplace_back(cloneInfo);
1958 }
1959 
GetMultiInstanceInfo(const std::shared_ptr<AppRunningRecord> & appRecord,RunningMultiAppInfo & info)1960 void AppMgrServiceInner::GetMultiInstanceInfo(const std::shared_ptr<AppRunningRecord> &appRecord,
1961     RunningMultiAppInfo &info)
1962 {
1963     if (!CheckAppRecordAndPriorityObject(appRecord)) {
1964         return;
1965     }
1966     auto PriorityObject = appRecord->GetPriorityObject();
1967     size_t index = 0;
1968     for (; index < info.runningMultiIntanceInfos.size(); index++) {
1969         if (info.runningMultiIntanceInfos[index].instanceKey == appRecord->GetInstanceKey()) {
1970             break;
1971         }
1972     }
1973     auto childProcessRecordMap = appRecord->GetChildProcessRecordMap();
1974     if (index < info.runningMultiIntanceInfos.size()) {
1975         info.runningMultiIntanceInfos[index].pids.emplace_back(PriorityObject->GetPid());
1976         for (auto it : childProcessRecordMap) {
1977             info.runningMultiIntanceInfos[index].pids.emplace_back(it.first);
1978         }
1979         return;
1980     }
1981     RunningMultiInstanceInfo instanceInfo;
1982     instanceInfo.instanceKey = appRecord->GetInstanceKey();
1983     instanceInfo.uid = appRecord->GetUid();
1984     instanceInfo.pids.emplace_back(PriorityObject->GetPid());
1985     for (auto it : childProcessRecordMap) {
1986         instanceInfo.pids.emplace_back(it.first);
1987     }
1988     info.runningMultiIntanceInfos.emplace_back(instanceInfo);
1989 }
1990 
GetRunningMultiInstanceKeys(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<std::string> & instanceKeys)1991 void AppMgrServiceInner::GetRunningMultiInstanceKeys(const std::shared_ptr<AppRunningRecord> &appRecord,
1992     std::vector<std::string> &instanceKeys)
1993 {
1994     if (!appRecord) {
1995         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
1996         return;
1997     }
1998     auto PriorityObject = appRecord->GetPriorityObject();
1999     if (!PriorityObject) {
2000         TAG_LOGE(AAFwkTag::APPMGR, "The PriorityObject is nullptr!");
2001         return;
2002     }
2003     size_t index = 0;
2004     for (; index < instanceKeys.size(); ++index) {
2005         if (instanceKeys[index] == appRecord->GetInstanceKey()) {
2006             return;
2007         }
2008     }
2009     instanceKeys.emplace_back(appRecord->GetInstanceKey());
2010 }
2011 
GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> & info,int32_t userId)2012 int32_t AppMgrServiceInner::GetProcessRunningInfosByUserId(std::vector<RunningProcessInfo> &info, int32_t userId)
2013 {
2014     if (VerifyAccountPermission(AAFwk::PermissionConstants::PERMISSION_GET_RUNNING_INFO, userId) ==
2015         ERR_PERMISSION_DENIED) {
2016         TAG_LOGE(AAFwkTag::APPMGR, "Permission verify failed");
2017         return ERR_PERMISSION_DENIED;
2018     }
2019 
2020     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2021         const auto &appRecord = item.second;
2022         if (!appRecord->GetSpawned()) {
2023             continue;
2024         }
2025         int32_t userIdTemp = static_cast<int32_t>(appRecord->GetUid() / USER_SCALE);
2026         if (userIdTemp == userId) {
2027             GetRunningProcesses(appRecord, info);
2028         }
2029     }
2030     return ERR_OK;
2031 }
2032 
GetProcessRunningInformation(RunningProcessInfo & info)2033 int32_t AppMgrServiceInner::GetProcessRunningInformation(RunningProcessInfo &info)
2034 {
2035     if (!appRunningManager_) {
2036         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
2037         return ERR_NO_INIT;
2038     }
2039     auto callerPid = IPCSkeleton::GetCallingPid();
2040     auto appRecord = GetAppRunningRecordByPid(callerPid);
2041     if (!appRecord) {
2042         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, callerPid:%{public}d", callerPid);
2043         return ERR_INVALID_VALUE;
2044     }
2045     GetRunningProcess(appRecord, info);
2046     return ERR_OK;
2047 }
2048 
GetAllRenderProcesses(std::vector<RenderProcessInfo> & info)2049 int32_t AppMgrServiceInner::GetAllRenderProcesses(std::vector<RenderProcessInfo> &info)
2050 {
2051     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2052     // check permission
2053     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2054         const auto &appRecord = item.second;
2055         if (isPerm) {
2056             GetRenderProcesses(appRecord, info);
2057         } else {
2058             auto applicationInfo = appRecord->GetApplicationInfo();
2059             if (!applicationInfo) {
2060                 continue;
2061             }
2062             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
2063             auto tokenId = applicationInfo->accessTokenId;
2064             if (callingTokenId == tokenId) {
2065                 GetRenderProcesses(appRecord, info);
2066             }
2067         }
2068     }
2069     return ERR_OK;
2070 }
2071 
GetAllChildrenProcesses(std::vector<ChildProcessInfo> & info)2072 int AppMgrServiceInner::GetAllChildrenProcesses(std::vector<ChildProcessInfo> &info)
2073 {
2074     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
2075     // check permission
2076     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
2077         const auto &appRecord = item.second;
2078         if (isPerm) {
2079             GetChildrenProcesses(appRecord, info);
2080         } else {
2081             auto applicationInfo = appRecord->GetApplicationInfo();
2082             if (!applicationInfo) {
2083                 continue;
2084             }
2085             auto callingTokenId = IPCSkeleton::GetCallingTokenID();
2086             auto tokenId = applicationInfo->accessTokenId;
2087             if (callingTokenId == tokenId) {
2088                 GetChildrenProcesses(appRecord, info);
2089             }
2090         }
2091     }
2092     return ERR_OK;
2093 }
2094 
NotifyMemoryLevel(int32_t level)2095 int32_t AppMgrServiceInner::NotifyMemoryLevel(int32_t level)
2096 {
2097     TAG_LOGI(AAFwkTag::APPMGR, "start");
2098 
2099     bool isMemmgrCall = AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(
2100         MEMMGR_PROC_NAME);
2101     if (!isMemmgrCall) {
2102         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not %{public}s", MEMMGR_PROC_NAME);
2103         return ERR_INVALID_VALUE;
2104     }
2105     if (!(level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_MODERATE ||
2106         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_CRITICAL ||
2107         level == OHOS::AppExecFwk::MemoryLevel::MEMORY_LEVEL_LOW)) {
2108         TAG_LOGE(AAFwkTag::APPMGR, "Level value error!");
2109         return ERR_INVALID_VALUE;
2110     }
2111     if (!appRunningManager_) {
2112         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager nullptr!");
2113         return ERR_INVALID_VALUE;
2114     }
2115 
2116     return appRunningManager_->NotifyMemoryLevel(level);
2117 }
2118 
NotifyProcMemoryLevel(const std::map<pid_t,MemoryLevel> & procLevelMap)2119 int32_t AppMgrServiceInner::NotifyProcMemoryLevel(const std::map<pid_t, MemoryLevel> &procLevelMap)
2120 {
2121     TAG_LOGI(AAFwkTag::APPMGR, "start");
2122 
2123     bool isMemmgrCall = AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(
2124         MEMMGR_PROC_NAME);
2125     if (!isMemmgrCall) {
2126         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not %{public}s", MEMMGR_PROC_NAME);
2127         return ERR_INVALID_VALUE;
2128     }
2129     if (!appRunningManager_) {
2130         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager nullptr!");
2131         return ERR_INVALID_VALUE;
2132     }
2133 
2134     return appRunningManager_->NotifyProcMemoryLevel(procLevelMap);
2135 }
2136 
DumpHeapMemory(const int32_t pid,OHOS::AppExecFwk::MallocInfo & mallocInfo)2137 int32_t AppMgrServiceInner::DumpHeapMemory(const int32_t pid, OHOS::AppExecFwk::MallocInfo &mallocInfo)
2138 {
2139     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2140     if (!isSaCall) {
2141         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not SA");
2142         return ERR_INVALID_VALUE;
2143     }
2144     if (pid < 0) {
2145         TAG_LOGE(AAFwkTag::APPMGR, "pid is illegal!");
2146         return ERR_INVALID_VALUE;
2147     }
2148     if (!appRunningManager_) {
2149         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager nullptr!");
2150         return ERR_INVALID_VALUE;
2151     }
2152     return appRunningManager_->DumpHeapMemory(pid, mallocInfo);
2153 }
2154 
DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo & info)2155 int32_t AppMgrServiceInner::DumpJsHeapMemory(OHOS::AppExecFwk::JsHeapDumpInfo &info)
2156 {
2157     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
2158     if (!isSaCall) {
2159         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not SA");
2160         return ERR_INVALID_VALUE;
2161     }
2162     if (info.pid == 0) {
2163         TAG_LOGE(AAFwkTag::APPMGR, "pid is illegal!");
2164         return ERR_INVALID_VALUE;
2165     }
2166     if (!appRunningManager_) {
2167         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager nullptr!");
2168         return ERR_INVALID_VALUE;
2169     }
2170     return appRunningManager_->DumpJsHeapMemory(info);
2171 }
2172 
GetRunningProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RunningProcessInfo> & info)2173 void AppMgrServiceInner::GetRunningProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
2174     std::vector<RunningProcessInfo> &info)
2175 {
2176     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
2177     RunningProcessInfo runningProcessInfo;
2178     GetRunningProcess(appRecord, runningProcessInfo);
2179     info.emplace_back(runningProcessInfo);
2180 }
2181 
GetRunningProcess(const std::shared_ptr<AppRunningRecord> & appRecord,RunningProcessInfo & info)2182 void AppMgrServiceInner::GetRunningProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
2183     RunningProcessInfo &info)
2184 {
2185     info.processName_ = appRecord->GetProcessName();
2186     info.pid_ = appRecord->GetPriorityObject()->GetPid();
2187     info.uid_ = appRecord->GetUid();
2188     info.state_ = static_cast<AppProcessState>(appRecord->GetState());
2189     info.isContinuousTask = appRecord->IsContinuousTask();
2190     info.isKeepAlive = appRecord->IsKeepAliveApp();
2191     info.isFocused = appRecord->GetFocusFlag();
2192     info.startTimeMillis_ = appRecord->GetAppStartTime();
2193     appRecord->GetBundleNames(info.bundleNames);
2194     info.processType_ = appRecord->GetProcessType();
2195     info.extensionType_ = appRecord->GetExtensionType();
2196     if (appRecord->GetUserTestInfo() != nullptr && system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
2197         info.isTestMode = true;
2198     }
2199     auto appInfo = appRecord->GetApplicationInfo();
2200     if (appInfo) {
2201         info.bundleType = static_cast<int32_t>(appInfo->bundleType);
2202         if (appInfo->multiAppMode.multiAppModeType == MultiAppModeType::APP_CLONE) {
2203             info.appCloneIndex = appRecord->GetAppIndex();
2204         }
2205     }
2206 }
2207 
GetRenderProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<RenderProcessInfo> & info)2208 void AppMgrServiceInner::GetRenderProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
2209     std::vector<RenderProcessInfo> &info)
2210 {
2211     auto renderRecordMap = appRecord->GetRenderRecordMap();
2212     if (renderRecordMap.empty()) {
2213         return;
2214     }
2215     for (auto iter : renderRecordMap) {
2216         auto renderRecord = iter.second;
2217         if (renderRecord != nullptr) {
2218             RenderProcessInfo renderProcessInfo;
2219             renderProcessInfo.bundleName_ = renderRecord->GetHostBundleName();
2220             renderProcessInfo.processName_ = renderRecord->GetProcessName();
2221             renderProcessInfo.pid_ = renderRecord->GetPid();
2222             renderProcessInfo.uid_ = renderRecord->GetUid();
2223             renderProcessInfo.hostUid_ = renderRecord->GetHostUid();
2224             renderProcessInfo.hostPid_ = renderRecord->GetHostPid();
2225             renderProcessInfo.state_ = renderRecord->GetState();
2226             info.emplace_back(renderProcessInfo);
2227         }
2228     }
2229 }
2230 
GetChildrenProcesses(const std::shared_ptr<AppRunningRecord> & appRecord,std::vector<ChildProcessInfo> & info)2231 void AppMgrServiceInner::GetChildrenProcesses(const std::shared_ptr<AppRunningRecord> &appRecord,
2232     std::vector<ChildProcessInfo> &info)
2233 {
2234     auto childProcessRecordMap = appRecord->GetChildProcessRecordMap();
2235     if (childProcessRecordMap.empty()) {
2236         return;
2237     }
2238     int32_t retCode = ERR_OK;
2239     for (auto iter : childProcessRecordMap) {
2240         auto childProcessRecord = iter.second;
2241         if (childProcessRecord != nullptr) {
2242             ChildProcessInfo childProcessInfo;
2243             retCode = GetChildProcessInfo(childProcessRecord, appRecord, childProcessInfo, true);
2244             if (retCode != ERR_OK) {
2245                 TAG_LOGW(
2246                     AAFwkTag::APPMGR, "GetChildProcessInfo failed. host pid=%{public}d, child pid=%{public}d",
2247                     appRecord->GetPriorityObject()->GetPid(), childProcessRecord->GetPid());
2248                 continue;
2249             }
2250             info.emplace_back(childProcessInfo);
2251         }
2252     }
2253 }
2254 
KillProcessByPid(const pid_t pid,const std::string & reason)2255 int32_t AppMgrServiceInner::KillProcessByPid(const pid_t pid, const std::string& reason)
2256 {
2257     if (!ProcessExist(pid)) {
2258         TAG_LOGI(AAFwkTag::APPMGR, "KillProcessByPid, process not exists, pid: %{public}d", pid);
2259         return AAFwk::ERR_KILL_PROCESS_NOT_EXIST;
2260     }
2261     std::string killReason = KILL_PROCESS_REASON_PREFIX + reason + ",callingPid=" +
2262         std::to_string(IPCSkeleton::GetCallingPid());
2263     auto appRecord = GetAppRunningRecordByPid(pid);
2264     if (appRecord && appRecord->GetExitReason() == EXIT_REASON_UNKNOWN) {
2265         appRecord->SetExitMsg(killReason);
2266     }
2267     return KillProcessByPidInner(pid, reason, killReason, appRecord);
2268 }
2269 
KillProcessByPidInner(const pid_t pid,const std::string & reason,const std::string & killReason,std::shared_ptr<AppRunningRecord> appRecord)2270 int32_t AppMgrServiceInner::KillProcessByPidInner(const pid_t pid, const std::string& reason,
2271     const std::string& killReason, std::shared_ptr<AppRunningRecord> appRecord)
2272 {
2273     int32_t ret = -1;
2274     if (pid > 0) {
2275         if (CheckIsThreadInFoundation(pid)) {
2276             TAG_LOGI(AAFwkTag::APPMGR, "pid %{public}d is thread tid in foundation, don't kill.", pid);
2277             return AAFwk::ERR_KILL_FOUNDATION_UID;
2278         }
2279         ret = kill(pid, SIGNAL_KILL);
2280         if (reason == "OnRemoteDied") {
2281             TAG_LOGI(AAFwkTag::APPMGR, "application is dead, double check, pid=%{public}d", pid);
2282         } else {
2283             TAG_LOGI(AAFwkTag::APPMGR, "kill pid %{public}d, ret:%{public}d",
2284                 pid, ret);
2285         }
2286     }
2287     AAFwk::EventInfo eventInfo;
2288     if (!appRecord) {
2289         return ret;
2290     }
2291     auto applicationInfo = appRecord->GetApplicationInfo();
2292     if (!applicationInfo) {
2293         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app informations");
2294     } else {
2295         eventInfo.bundleName = applicationInfo->name;
2296         eventInfo.versionName = applicationInfo->versionName;
2297         eventInfo.versionCode = applicationInfo->versionCode;
2298     }
2299     if (ret >= 0) {
2300         std::lock_guard lock(killpedProcessMapLock_);
2301         int64_t killTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::
2302             system_clock::now().time_since_epoch()).count();
2303         killedProcessMap_.emplace(killTime, appRecord->GetProcessName());
2304     }
2305     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
2306     eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
2307     eventInfo.processName = appRecord->GetProcessName();
2308     bool foreground = appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND ||
2309         appRecord->GetState() == ApplicationState::APP_STATE_FOCUS;
2310     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_TERMINATE, HiSysEventType::BEHAVIOR, eventInfo);
2311     int result = HiSysEventWrite(OHOS::HiviewDFX::HiSysEvent::Domain::FRAMEWORK, "PROCESS_KILL",
2312         OHOS::HiviewDFX::HiSysEvent::EventType::FAULT, EVENT_KEY_PID, std::to_string(eventInfo.pid),
2313         EVENT_KEY_PROCESS_NAME, eventInfo.processName, EVENT_KEY_MESSAGE, killReason,
2314         EVENT_KEY_FOREGROUND, foreground);
2315     TAG_LOGI(AAFwkTag::APPMGR, "hisysevent write result=%{public}d, send event [FRAMEWORK,PROCESS_KILL], pid="
2316         "%{public}d, processName=%{public}s, msg=%{public}s, FOREGROUND = %{public}d",
2317         result, pid, eventInfo.processName.c_str(), killReason.c_str(), foreground);
2318     return ret;
2319 }
2320 
CheckIsThreadInFoundation(pid_t pid)2321 bool AppMgrServiceInner::CheckIsThreadInFoundation(pid_t pid)
2322 {
2323     std::ostringstream pathBuilder;
2324     pathBuilder << PROC_SELF_TASK_PATH << pid;
2325     std::string path = pathBuilder.str();
2326     TAG_LOGD(AAFwkTag::APPMGR, "CheckIsThreadInFoundation path:%{public}s", path.c_str());
2327     return access(path.c_str(), F_OK) == 0;
2328 }
2329 
WaitForRemoteProcessExit(std::list<pid_t> & pids,const int64_t startTime)2330 bool AppMgrServiceInner::WaitForRemoteProcessExit(std::list<pid_t> &pids, const int64_t startTime)
2331 {
2332     int64_t delayTime = SystemTimeMillisecond() - startTime;
2333     if (CheckAllProcessExit(pids)) {
2334         return true;
2335     }
2336     while (delayTime < KILL_PROCESS_TIMEOUT_MICRO_SECONDS) {
2337         usleep(KILL_PROCESS_DELAYTIME_MICRO_SECONDS);
2338         if (CheckAllProcessExit(pids)) {
2339             return true;
2340         }
2341         delayTime = SystemTimeMillisecond() - startTime;
2342     }
2343     return false;
2344 }
2345 
ProcessExist(pid_t pid)2346 bool AppMgrServiceInner::ProcessExist(pid_t pid)
2347 {
2348     char pid_path[128] = {0};
2349     struct stat stat_buf;
2350     if (!pid) {
2351         return false;
2352     }
2353     if (snprintf_s(pid_path, sizeof(pid_path), sizeof(pid_path) - 1, "/proc/%d/status", pid) < 0) {
2354         return false;
2355     }
2356     if (stat(pid_path, &stat_buf) == 0) {
2357         return true;
2358     }
2359     return false;
2360 }
2361 
CheckAllProcessExit(std::list<pid_t> & pids)2362 bool AppMgrServiceInner::CheckAllProcessExit(std::list<pid_t> &pids)
2363 {
2364     for (auto iter = pids.begin(); iter != pids.end();) {
2365         if (!ProcessExist(*iter)) {
2366             iter = pids.erase(iter);
2367         } else {
2368             iter++;
2369         }
2370     }
2371     if (pids.empty()) {
2372         return true;
2373     }
2374     return false;
2375 }
2376 
SystemTimeMillisecond()2377 int64_t AppMgrServiceInner::SystemTimeMillisecond()
2378 {
2379     struct timespec t;
2380     t.tv_sec = 0;
2381     t.tv_nsec = 0;
2382     clock_gettime(CLOCK_MONOTONIC, &t);
2383     return (int64_t)((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS;
2384 }
2385 
GetAppRunningRecordByPid(const pid_t pid) const2386 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByPid(const pid_t pid) const
2387 {
2388     if (!appRunningManager_) {
2389         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager nullptr!");
2390         return nullptr;
2391     }
2392     return appRunningManager_->GetAppRunningRecordByPid(pid);
2393 }
2394 
CreateAppRunningRecord(sptr<IRemoteObject> token,sptr<IRemoteObject> preToken,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,int32_t abilityRecordId)2395 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::CreateAppRunningRecord(sptr<IRemoteObject> token,
2396     sptr<IRemoteObject> preToken, std::shared_ptr<ApplicationInfo> appInfo,
2397     std::shared_ptr<AbilityInfo> abilityInfo, const std::string &processName, const BundleInfo &bundleInfo,
2398     const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, int32_t abilityRecordId)
2399 {
2400     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2401     if (!appRunningManager_) {
2402         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager nullptr!");
2403         return nullptr;
2404     }
2405     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
2406     if (!appRecord) {
2407         TAG_LOGE(AAFwkTag::APPMGR, "get app record failed");
2408         return nullptr;
2409     }
2410 
2411     appRecord->SetProcessAndExtensionType(abilityInfo);
2412     appRecord->SetKeepAliveEnableState(bundleInfo.isKeepAlive);
2413     appRecord->SetEmptyKeepAliveAppState(false);
2414     appRecord->SetTaskHandler(taskHandler_);
2415     appRecord->SetEventHandler(eventHandler_);
2416     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want, abilityRecordId);
2417     if (want) {
2418         appRecord->SetDebugApp(want->GetBoolParam(DEBUG_APP, false));
2419         appRecord->SetNativeDebug(want->GetBoolParam("nativeDebug", false));
2420         if (want->GetBoolParam(COLD_START, false)) {
2421             appRecord->SetDebugApp(true);
2422         }
2423         appRecord->SetPerfCmd(want->GetStringParam(PERF_CMD));
2424         appRecord->SetErrorInfoEnhance(want->GetBoolParam(ERROR_INFO_ENHANCE, false));
2425         appRecord->SetMultiThread(want->GetBoolParam(MULTI_THREAD, false));
2426         int32_t appIndex = 0;
2427         (void)AbilityRuntime::StartupUtil::GetAppIndex(*want, appIndex);
2428         appRecord->SetAppIndex(appIndex);
2429 #ifdef WITH_DLP
2430         appRecord->SetSecurityFlag(want->GetBoolParam(DLP_PARAMS_SECURITY_FLAG, false));
2431 #endif // WITH_DLP
2432         appRecord->SetRequestProcCode(want->GetIntParam(Want::PARAM_RESV_REQUEST_PROC_CODE, 0));
2433         appRecord->SetCallerPid(want->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
2434         appRecord->SetCallerUid(want->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
2435         appRecord->SetCallerTokenId(want->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
2436         appRecord->SetAssignTokenId(want->GetIntParam("specifyTokenId", 0));
2437         appRecord->SetNativeStart(want->GetBoolParam("native", false));
2438     }
2439 
2440     if (preToken) {
2441         auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
2442         if (abilityRecord) {
2443             abilityRecord->SetPreToken(preToken);
2444         }
2445     }
2446 
2447     return appRecord;
2448 }
2449 
TerminateAbility(const sptr<IRemoteObject> & token,bool clearMissionFlag)2450 void AppMgrServiceInner::TerminateAbility(const sptr<IRemoteObject> &token, bool clearMissionFlag)
2451 {
2452     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2453     TAG_LOGD(AAFwkTag::APPMGR, "Terminate ability come.");
2454     if (!token) {
2455         TAG_LOGE(AAFwkTag::APPMGR, "AppMgrServiceInner::TerminateAbility token is null!");
2456         return;
2457     }
2458     auto appRecord = GetAppRunningRecordByAbilityToken(token);
2459     if (!appRecord) {
2460         TAG_LOGE(AAFwkTag::APPMGR, "AppMgrServiceInner::TerminateAbility app is not exist!");
2461         return;
2462     }
2463 
2464     RemoveUIExtensionLauncherItem(appRecord, token);
2465 
2466     if (appRunningManager_) {
2467         std::shared_ptr<AppMgrServiceInner> appMgrServiceInner = shared_from_this();
2468         appRunningManager_->TerminateAbility(token, clearMissionFlag, appMgrServiceInner);
2469     }
2470 }
2471 
UpdateAbilityState(const sptr<IRemoteObject> & token,const AbilityState state)2472 void AppMgrServiceInner::UpdateAbilityState(const sptr<IRemoteObject> &token, const AbilityState state)
2473 {
2474     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2475     TAG_LOGD(AAFwkTag::APPMGR, "state %{public}d.", static_cast<int32_t>(state));
2476     if (!token) {
2477         TAG_LOGE(AAFwkTag::APPMGR, "token is null!");
2478         return;
2479     }
2480 
2481     AbilityRuntime::FreezeUtil::LifecycleFlow flow{token, AbilityRuntime::FreezeUtil::TimeoutState::FOREGROUND};
2482     AbilityRuntime::FreezeUtil::GetInstance().AppendLifecycleEvent(flow, "ServiceInner::UpdateAbilityState");
2483     auto appRecord = GetAppRunningRecordByAbilityToken(token);
2484     if (!appRecord) {
2485         TAG_LOGE(AAFwkTag::APPMGR, "app is not exist!");
2486         return;
2487     }
2488     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
2489     if (!abilityRecord) {
2490         TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record!");
2491         return;
2492     }
2493     if (state == abilityRecord->GetState()) {
2494         TAG_LOGE(AAFwkTag::APPMGR, "current state is already, no need update!");
2495         return;
2496     }
2497     if (abilityRecord->GetAbilityInfo() == nullptr) {
2498         TAG_LOGE(AAFwkTag::APPMGR, "ability info nullptr!");
2499         return;
2500     }
2501     auto type = abilityRecord->GetAbilityInfo()->type;
2502     if (type == AppExecFwk::AbilityType::SERVICE &&
2503         (state == AbilityState::ABILITY_STATE_CREATE ||
2504         state == AbilityState::ABILITY_STATE_TERMINATED ||
2505         state == AbilityState::ABILITY_STATE_CONNECTED ||
2506         state == AbilityState::ABILITY_STATE_DISCONNECTED)) {
2507         TAG_LOGI(
2508             AAFwkTag::APPMGR, "StateChangedNotifyObserver service type, state:%{public}d", static_cast<int32_t>(state));
2509         appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), true, false);
2510         return;
2511     }
2512     if (state > AbilityState::ABILITY_STATE_BACKGROUND || state < AbilityState::ABILITY_STATE_FOREGROUND) {
2513         TAG_LOGE(AAFwkTag::APPMGR, "state is not foreground or background!");
2514         return;
2515     }
2516 
2517     appRecord->UpdateAbilityState(token, state);
2518     CheckCleanAbilityByUserRequest(appRecord, abilityRecord, state);
2519 }
2520 
UpdateExtensionState(const sptr<IRemoteObject> & token,const ExtensionState state)2521 void AppMgrServiceInner::UpdateExtensionState(const sptr<IRemoteObject> &token, const ExtensionState state)
2522 {
2523     if (!token) {
2524         TAG_LOGE(AAFwkTag::APPMGR, "token is null!");
2525         return;
2526     }
2527     auto appRecord = GetAppRunningRecordByAbilityToken(token);
2528     if (!appRecord) {
2529         TAG_LOGE(AAFwkTag::APPMGR, "app is not exist!");
2530         return;
2531     }
2532     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
2533     if (!abilityRecord) {
2534         TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record!");
2535         return;
2536     }
2537     appRecord->StateChangedNotifyObserver(abilityRecord, static_cast<int32_t>(state), false, false);
2538 }
2539 
OnStop()2540 void AppMgrServiceInner::OnStop()
2541 {
2542     if (!appRunningManager_) {
2543         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager nullptr!");
2544         return;
2545     }
2546 
2547     appRunningManager_->ClearAppRunningRecordMap();
2548     CloseAppSpawnConnection();
2549 }
2550 
OpenAppSpawnConnection()2551 ErrCode AppMgrServiceInner::OpenAppSpawnConnection()
2552 {
2553     if (remoteClientManager_ == nullptr) {
2554         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null");
2555         return ERR_INVALID_VALUE;
2556     }
2557 
2558     if (remoteClientManager_->GetSpawnClient()) {
2559         return remoteClientManager_->GetSpawnClient()->OpenConnection();
2560     }
2561     return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
2562 }
2563 
CloseAppSpawnConnection() const2564 void AppMgrServiceInner::CloseAppSpawnConnection() const
2565 {
2566     if (remoteClientManager_ == nullptr) {
2567         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null");
2568         return;
2569     }
2570 
2571     if (remoteClientManager_->GetSpawnClient()) {
2572         remoteClientManager_->GetSpawnClient()->CloseConnection();
2573     }
2574 }
2575 
QueryAppSpawnConnectionState() const2576 SpawnConnectionState AppMgrServiceInner::QueryAppSpawnConnectionState() const
2577 {
2578     if (remoteClientManager_ == nullptr) {
2579         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null");
2580         return SpawnConnectionState::STATE_NOT_CONNECT;
2581     }
2582 
2583     if (remoteClientManager_->GetSpawnClient()) {
2584         return remoteClientManager_->GetSpawnClient()->QueryConnectionState();
2585     }
2586     return SpawnConnectionState::STATE_NOT_CONNECT;
2587 }
2588 
SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)2589 void AppMgrServiceInner::SetAppSpawnClient(std::shared_ptr<AppSpawnClient> spawnClient)
2590 {
2591     if (remoteClientManager_ == nullptr) {
2592         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null");
2593         return;
2594     }
2595 
2596     remoteClientManager_->SetSpawnClient(std::move(spawnClient));
2597 }
2598 
SetBundleManagerHelper(const std::shared_ptr<BundleMgrHelper> & bundleMgrHelper)2599 void AppMgrServiceInner::SetBundleManagerHelper(const std::shared_ptr<BundleMgrHelper> &bundleMgrHelper)
2600 {
2601     if (remoteClientManager_ == nullptr) {
2602         TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ is nullptr.");
2603         return;
2604     }
2605 
2606     remoteClientManager_->SetBundleManagerHelper(bundleMgrHelper);
2607 }
2608 
RegisterAppStateCallback(const sptr<IAppStateCallback> & callback)2609 void AppMgrServiceInner::RegisterAppStateCallback(const sptr<IAppStateCallback>& callback)
2610 {
2611     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2612     if (callback != nullptr) {
2613         std::lock_guard lock(appStateCallbacksLock_);
2614         TAG_LOGI(AAFwkTag::APPMGR, "RegisterAppStateCallback");
2615         appStateCallbacks_.push_back(
2616             AppStateCallbackWithUserId { callback, GetUserIdByUid(IPCSkeleton::GetCallingUid()) });
2617         auto remoteObjedct = callback->AsObject();
2618         if (remoteObjedct) {
2619             remoteObjedct->AddDeathRecipient(sptr<AppStateCallbackDeathRecipient>(
2620                 new AppStateCallbackDeathRecipient(weak_from_this())));
2621         }
2622     }
2623 }
2624 
RemoveDeadAppStateCallback(const wptr<IRemoteObject> & remote)2625 void AppMgrServiceInner::RemoveDeadAppStateCallback(const wptr<IRemoteObject> &remote)
2626 {
2627     auto remoteObject = remote.promote();
2628     if (remoteObject == nullptr) {
2629         TAG_LOGE(AAFwkTag::APPMGR, "remoteObject null");
2630         return;
2631     }
2632 
2633     std::lock_guard lock(appStateCallbacksLock_);
2634     for (auto it = appStateCallbacks_.begin(); it != appStateCallbacks_.end(); ++it) {
2635         auto callback = it->callback;
2636         if (callback && callback->AsObject() == remoteObject) {
2637             appStateCallbacks_.erase(it);
2638             break;
2639         }
2640     }
2641 }
2642 
AbilityBehaviorAnalysis(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & preToken,const int32_t visibility,const int32_t perceptibility,const int32_t connectionState)2643 void AppMgrServiceInner::AbilityBehaviorAnalysis(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &preToken,
2644     const int32_t visibility,       // 0:false,1:true
2645     const int32_t perceptibility,   // 0:false,1:true
2646     const int32_t connectionState)  // 0:false,1:true
2647 {
2648     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2649     if (!token) {
2650         TAG_LOGE(AAFwkTag::APPMGR, "token is null");
2651         return;
2652     }
2653     auto appRecord = GetAppRunningRecordByAbilityToken(token);
2654     if (!appRecord) {
2655         TAG_LOGE(AAFwkTag::APPMGR, "app record is not exist for ability token");
2656         return;
2657     }
2658     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
2659     if (!abilityRecord) {
2660         TAG_LOGE(AAFwkTag::APPMGR, "ability record is not exist for ability previous token");
2661         return;
2662     }
2663     if (preToken) {
2664         abilityRecord->SetPreToken(preToken);
2665     }
2666     abilityRecord->SetVisibility(visibility);
2667     abilityRecord->SetPerceptibility(perceptibility);
2668     abilityRecord->SetConnectionState(connectionState);
2669 }
2670 
KillProcessByAbilityToken(const sptr<IRemoteObject> & token)2671 void AppMgrServiceInner::KillProcessByAbilityToken(const sptr<IRemoteObject> &token)
2672 {
2673     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2674     if (!token) {
2675         TAG_LOGE(AAFwkTag::APPMGR, "token is null");
2676         return;
2677     }
2678     auto appRecord = GetAppRunningRecordByAbilityToken(token);
2679     if (!appRecord) {
2680         TAG_LOGE(AAFwkTag::APPMGR, "app record is not exist for ability token");
2681         return;
2682     }
2683 
2684     // before exec ScheduleProcessSecurityExit return
2685     // The resident process won't let him die
2686     if (appRecord->IsKeepAliveApp() && IsMemorySizeSufficent()) {
2687         return;
2688     }
2689 
2690     pid_t pid = appRecord->GetPriorityObject()->GetPid();
2691     if (pid > 0) {
2692         std::list<pid_t> pids;
2693         pids.push_back(pid);
2694         appRecord->ScheduleProcessSecurityExit();
2695         if (!WaitForRemoteProcessExit(pids, SystemTimeMillisecond())) {
2696             int32_t result = KillProcessByPid(pid, "KillProcessByAbilityToken");
2697             if (result < 0) {
2698                 TAG_LOGE(AAFwkTag::APPMGR, "KillProcessByAbilityToken kill process is fail");
2699                 return;
2700             }
2701         }
2702     }
2703 }
2704 
KillProcessesByUserId(int32_t userId)2705 void AppMgrServiceInner::KillProcessesByUserId(int32_t userId)
2706 {
2707     if (!appRunningManager_) {
2708         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
2709         return;
2710     }
2711 
2712     int64_t startTime = SystemTimeMillisecond();
2713     std::list<pid_t> pids;
2714     if (!appRunningManager_->GetPidsByUserId(userId, pids)) {
2715         TAG_LOGI(AAFwkTag::APPMGR, "The process corresponding to the userId did not start");
2716         return;
2717     }
2718     WaitProcessesExitAndKill(pids, startTime, "KillProcessesByUserId");
2719 }
2720 
KillProcessesInBatch(const std::vector<int32_t> & pids)2721 int32_t AppMgrServiceInner::KillProcessesInBatch(const std::vector<int32_t> &pids)
2722 {
2723     CHECK_CALLER_IS_SYSTEM_APP;
2724     if (!AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
2725         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES)) {
2726         TAG_LOGE(AAFwkTag::APPMGR, "verify permission failed.");
2727         return ERR_PERMISSION_DENIED;
2728     }
2729     if (!AAFwk::AppUtils::GetInstance().IsStartOptionsWithAnimation()) {
2730         TAG_LOGE(AAFwkTag::APPMGR, "not supported.");
2731         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
2732     }
2733     std::vector<int32_t> killPids;
2734     for (const auto& pid: pids) {
2735         auto appRecord = GetAppRunningRecordByPid(pid);
2736         if (appRecord == nullptr) {
2737             TAG_LOGE(AAFwkTag::APPMGR, "appRecord null");
2738             continue;
2739         }
2740         killPids.emplace_back(pid);
2741         std::string bundleName = appRecord->GetBundleName();
2742         {
2743             std::lock_guard lock(killedBundleSetMutex_);
2744             killedBundleSet_.insert(bundleName);
2745         }
2746     }
2747     std::lock_guard lock(killedBundleSetMutex_);
2748     for (const auto& pid: killPids) {
2749         (void)KillProcessByPid(pid, "KillProcessesInBatch");
2750     }
2751     killedBundleSet_.clear();
2752     return ERR_OK;
2753 }
2754 
KillProcessesByPids(std::vector<int32_t> & pids)2755 void AppMgrServiceInner::KillProcessesByPids(std::vector<int32_t> &pids)
2756 {
2757     for (const auto& pid: pids) {
2758         auto appRecord = GetAppRunningRecordByPid(pid);
2759         if (appRecord == nullptr) {
2760             TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
2761             continue;
2762         }
2763         auto result = KillProcessByPid(pid, "KillProcessesByPids");
2764         if (result < 0) {
2765             TAG_LOGW(AAFwkTag::APPMGR, "KillProcessByPid is failed. pid: %{public}d", pid);
2766         }
2767     }
2768 }
2769 
AttachPidToParent(const sptr<IRemoteObject> & token,const sptr<IRemoteObject> & callerToken)2770 void AppMgrServiceInner::AttachPidToParent(const sptr<IRemoteObject> &token, const sptr<IRemoteObject> &callerToken)
2771 {
2772     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2773     auto appRecord = GetAppRunningRecordByAbilityToken(token);
2774     if (appRecord == nullptr) {
2775         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord is nullptr");
2776         return;
2777     }
2778     auto pid = appRecord->GetPriorityObject()->GetPid();
2779     if (pid <= 0) {
2780         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid");
2781         return;
2782     }
2783     auto callRecord = GetAppRunningRecordByAbilityToken(callerToken);
2784     if (callRecord == nullptr) {
2785         TAG_LOGE(AAFwkTag::APPMGR, "callRecord is nullptr");
2786         auto result = KillProcessByPid(pid, "AttachPidToParent");
2787         if (result < 0) {
2788             TAG_LOGW(AAFwkTag::APPMGR, "KillProcessByPid is failed. pid: %{public}d", pid);
2789         }
2790         return;
2791     }
2792     appRecord->SetParentAppRecord(callRecord);
2793     callRecord->AddChildAppRecord(pid, appRecord);
2794 }
2795 
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)2796 void AppMgrServiceInner::StartAbility(sptr<IRemoteObject> token, sptr<IRemoteObject> preToken,
2797     std::shared_ptr<AbilityInfo> abilityInfo, std::shared_ptr<AppRunningRecord> appRecord,
2798     const HapModuleInfo &hapModuleInfo, std::shared_ptr<AAFwk::Want> want, int32_t abilityRecordId)
2799 {
2800     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2801     TAG_LOGI(AAFwkTag::APPMGR, "start ability, ability %{public}s-%{public}s",
2802         abilityInfo->bundleName.c_str(), abilityInfo->name.c_str());
2803     if (!appRecord) {
2804         TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null");
2805         return;
2806     }
2807 
2808     if (want) {
2809 #ifdef WITH_DLP
2810         want->SetParam(DLP_PARAMS_SECURITY_FLAG, appRecord->GetSecurityFlag());
2811 #endif // WITH_DLP
2812 
2813         auto isDebugApp = want->GetBoolParam(DEBUG_APP, false);
2814         if (isDebugApp && !appRecord->IsDebugApp()) {
2815             ProcessAppDebug(appRecord, isDebugApp);
2816         }
2817     }
2818 
2819     auto ability = appRecord->GetAbilityRunningRecordByToken(token);
2820     if (abilityInfo->launchMode == LaunchMode::SINGLETON && ability != nullptr) {
2821         TAG_LOGW(AAFwkTag::APPMGR, "same ability info in singleton launch mode, will not add ability");
2822         return;
2823     }
2824 
2825     if (ability && preToken) {
2826         TAG_LOGE(AAFwkTag::APPMGR, "Ability is already started");
2827         ability->SetPreToken(preToken);
2828         return;
2829     }
2830 
2831     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo->applicationInfo);
2832     appRecord->AddModule(appInfo, abilityInfo, token, hapModuleInfo, want, abilityRecordId);
2833     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
2834     if (!moduleRecord) {
2835         TAG_LOGE(AAFwkTag::APPMGR, "add moduleRecord failed");
2836         return;
2837     }
2838 
2839     ability = moduleRecord->GetAbilityRunningRecordByToken(token);
2840     if (!ability) {
2841         TAG_LOGE(AAFwkTag::APPMGR, "add ability failed");
2842         return;
2843     }
2844 
2845     if (preToken != nullptr) {
2846         ability->SetPreToken(preToken);
2847     }
2848 
2849     ApplicationState appState = appRecord->GetState();
2850     if (appState == ApplicationState::APP_STATE_CREATE) {
2851         TAG_LOGE(AAFwkTag::APPMGR, "in create state, don't launch ability, bundleName:%{public}s, ability:%{public}s",
2852             appInfo->bundleName.c_str(), abilityInfo->name.c_str());
2853         return;
2854     }
2855     appRecord->LaunchAbility(ability);
2856 }
2857 
GetAppRunningRecordByAbilityToken(const sptr<IRemoteObject> & abilityToken) const2858 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAbilityToken(
2859     const sptr<IRemoteObject> &abilityToken) const
2860 {
2861     if (!appRunningManager_) {
2862         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
2863         return nullptr;
2864     }
2865 
2866     return appRunningManager_->GetAppRunningRecordByAbilityToken(abilityToken);
2867 }
2868 
GetTerminatingAppRunningRecord(const sptr<IRemoteObject> & token) const2869 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetTerminatingAppRunningRecord(
2870     const sptr<IRemoteObject> &token) const
2871 {
2872     if (!appRunningManager_) {
2873         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr.");
2874         return nullptr;
2875     }
2876     return appRunningManager_->GetTerminatingAppRunningRecord(token);
2877 }
2878 
AbilityTerminated(const sptr<IRemoteObject> & token)2879 void AppMgrServiceInner::AbilityTerminated(const sptr<IRemoteObject> &token)
2880 {
2881     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2882     TAG_LOGD(AAFwkTag::APPMGR, "Terminate ability come.");
2883     if (!token) {
2884         TAG_LOGE(AAFwkTag::APPMGR, "Terminate ability error, token is null!");
2885         return;
2886     }
2887 
2888     auto appRecord = appRunningManager_->GetTerminatingAppRunningRecord(token);
2889     if (!appRecord) {
2890         TAG_LOGE(AAFwkTag::APPMGR, "Terminate ability error, appRecord is not exist!");
2891         return;
2892     }
2893 
2894     appRecord->AbilityTerminated(token);
2895 }
2896 
GetAppRunningRecordByAppRecordId(const int32_t recordId) const2897 std::shared_ptr<AppRunningRecord> AppMgrServiceInner::GetAppRunningRecordByAppRecordId(const int32_t recordId) const
2898 {
2899     if (appRunningManager_ == nullptr) {
2900         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager is nullptr");
2901         return nullptr;
2902     }
2903     const auto&& appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
2904     const auto& iter = appRunningRecordMap.find(recordId);
2905     return iter != appRunningRecordMap.end() ? iter->second : nullptr;
2906 }
2907 
OnAppStateChanged(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state,bool needNotifyApp,bool isFromWindowFocusChanged)2908 void AppMgrServiceInner::OnAppStateChanged(
2909     const std::shared_ptr<AppRunningRecord> &appRecord,
2910     const ApplicationState state,
2911     bool needNotifyApp,
2912     bool isFromWindowFocusChanged)
2913 {
2914     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2915     if (!appRecord) {
2916         TAG_LOGE(AAFwkTag::APPMGR, "OnAppStateChanged come, app record is null");
2917         return;
2918     }
2919 
2920     TAG_LOGD(AAFwkTag::APPMGR, "OnAppStateChanged begin, bundleName is %{public}s, state:%{public}d",
2921         appRecord->GetBundleName().c_str(), static_cast<int32_t>(state));
2922     {
2923         std::lock_guard lock(appStateCallbacksLock_);
2924         for (const auto &item : appStateCallbacks_) {
2925             if (item.callback != nullptr) {
2926                 item.callback->OnAppStateChanged(WrapAppProcessData(appRecord, state));
2927             }
2928         }
2929     }
2930 
2931     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStateChanged(
2932         appRecord, state, needNotifyApp, isFromWindowFocusChanged);
2933 }
2934 
OnAppStarted(const std::shared_ptr<AppRunningRecord> & appRecord)2935 void AppMgrServiceInner::OnAppStarted(const std::shared_ptr<AppRunningRecord> &appRecord)
2936 {
2937     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2938     if (!appRecord) {
2939         TAG_LOGE(AAFwkTag::APPMGR, "OnAppStarted come, app record is null");
2940         return;
2941     }
2942 
2943     if (appRecord->GetPriorityObject() == nullptr) {
2944         TAG_LOGE(AAFwkTag::APPMGR, "OnAppStarted come, appRecord's priorityobject is null");
2945         return;
2946     }
2947 
2948     TAG_LOGD(AAFwkTag::APPMGR, "OnAppStarted begin, bundleName is %{public}s, pid:%{public}d",
2949         appRecord->GetBundleName().c_str(), appRecord->GetPriorityObject()->GetPid());
2950 
2951     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStarted(appRecord);
2952 }
2953 
2954 
OnAppStopped(const std::shared_ptr<AppRunningRecord> & appRecord)2955 void AppMgrServiceInner::OnAppStopped(const std::shared_ptr<AppRunningRecord> &appRecord)
2956 {
2957     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
2958     if (!appRecord) {
2959         TAG_LOGE(AAFwkTag::APPMGR, "OnAppStopped come, app record is null");
2960         return;
2961     }
2962 
2963     if (appRecord->GetPriorityObject() == nullptr) {
2964         TAG_LOGE(AAFwkTag::APPMGR, "OnAppStarted come, appRecord's priorityObject is null");
2965         return;
2966     }
2967 
2968     TAG_LOGD(AAFwkTag::APPMGR, "OnAppStopped begin, bundleName is %{public}s, pid:%{public}d",
2969         appRecord->GetBundleName().c_str(), appRecord->GetPriorityObject()->GetPid());
2970 
2971     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppStopped(appRecord);
2972 }
2973 
WrapAppProcessData(const std::shared_ptr<AppRunningRecord> & appRecord,const ApplicationState state)2974 AppProcessData AppMgrServiceInner::WrapAppProcessData(const std::shared_ptr<AppRunningRecord> &appRecord,
2975     const ApplicationState state)
2976 {
2977     AppProcessData processData;
2978     auto appInfoList = appRecord->GetAppInfoList();
2979     for (const auto &list : appInfoList) {
2980         AppData data;
2981         data.appName = list->name;
2982         data.uid = list->uid;
2983         processData.appDatas.push_back(data);
2984     }
2985     processData.processName = appRecord->GetProcessName();
2986     processData.pid = appRecord->GetPriorityObject()->GetPid();
2987     processData.appState = state;
2988     processData.isFocused = appRecord->GetFocusFlag();
2989     auto renderRecordMap = appRecord->GetRenderRecordMap();
2990     if (!renderRecordMap.empty()) {
2991         for (auto iter : renderRecordMap) {
2992             auto renderRecord = iter.second;
2993             if (renderRecord != nullptr) {
2994                 processData.renderPids.emplace_back(renderRecord->GetPid());
2995             }
2996         }
2997     }
2998     return processData;
2999 }
3000 
OnAbilityStateChanged(const std::shared_ptr<AbilityRunningRecord> & ability,const AbilityState state)3001 void AppMgrServiceInner::OnAbilityStateChanged(
3002     const std::shared_ptr<AbilityRunningRecord> &ability, const AbilityState state)
3003 {
3004     if (!ability) {
3005         TAG_LOGE(AAFwkTag::APPMGR, "ability is null");
3006         return;
3007     }
3008     std::lock_guard lock(appStateCallbacksLock_);
3009     for (const auto &item : appStateCallbacks_) {
3010         if (item.callback != nullptr) {
3011             item.callback->OnAbilityRequestDone(ability->GetToken(), state);
3012         }
3013     }
3014 }
3015 
StateChangedNotifyObserver(const AbilityStateData abilityStateData,bool isAbility,bool isFromWindowFocusChanged)3016 void AppMgrServiceInner::StateChangedNotifyObserver(
3017     const AbilityStateData abilityStateData, bool isAbility, bool isFromWindowFocusChanged)
3018 {
3019     DelayedSingleton<AppStateObserverManager>::GetInstance()->StateChangedNotifyObserver(
3020         abilityStateData, isAbility, isFromWindowFocusChanged);
3021 }
3022 
StartPerfProcessByStartMsg(AppSpawnStartMsg & startMsg,const std::string & perfCmd,const std::string & debugCmd,bool isSandboxApp)3023 int32_t AppMgrServiceInner::StartPerfProcessByStartMsg(AppSpawnStartMsg &startMsg,
3024     const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp)
3025 {
3026     if (!remoteClientManager_ || !remoteClientManager_->GetSpawnClient()) {
3027         TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient is null");
3028         return ERR_NO_INIT;
3029     }
3030     if (perfCmd.empty() && debugCmd.empty()) {
3031         TAG_LOGD(AAFwkTag::APPMGR, "perfCmd is empty");
3032         return ERR_INVALID_OPERATION;
3033     }
3034 
3035     startMsg.code = static_cast<int32_t>(MSG_SPAWN_NATIVE_PROCESS);
3036     if (!isSandboxApp) {
3037         TAG_LOGD(AAFwkTag::APPMGR, "debuggablePipe sandbox: false.");
3038         startMsg.flags |= (START_FLAG_BASE << StartFlags::NO_SANDBOX);
3039     } else {
3040         TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe sandbox: true");
3041     }
3042     if (!perfCmd.empty()) {
3043         startMsg.renderParam = perfCmd;
3044         TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe perfCmd:%{public}s", perfCmd.c_str());
3045     } else {
3046         startMsg.renderParam = debugCmd;
3047         TAG_LOGI(AAFwkTag::APPMGR, "debuggablePipe debugCmd:%{public}s", debugCmd.c_str());
3048     }
3049     pid_t pid = 0;
3050     auto errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
3051     if (FAILED(errCode)) {
3052         TAG_LOGE(AAFwkTag::APPMGR, "failed to spawn new native process, errCode %{public}08x", errCode);
3053         return errCode;
3054     }
3055     return ERR_OK;
3056 }
3057 
StartPerfProcess(const std::shared_ptr<AppRunningRecord> & appRecord,const std::string & perfCmd,const std::string & debugCmd,bool isSandboxApp)3058 int32_t AppMgrServiceInner::StartPerfProcess(const std::shared_ptr<AppRunningRecord> &appRecord,
3059     const std::string& perfCmd, const std::string& debugCmd, bool isSandboxApp)
3060 {
3061     if (!appRecord) {
3062         TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null");
3063         return ERR_INVALID_OPERATION;
3064     }
3065 
3066     auto&& startMsg = appRecord->GetStartMsg();
3067     return StartPerfProcessByStartMsg(startMsg, perfCmd, debugCmd, isSandboxApp);
3068 }
3069 
SetOverlayInfo(const std::string & bundleName,const int32_t userId,AppSpawnStartMsg & startMsg)3070 void AppMgrServiceInner::SetOverlayInfo(const std::string &bundleName,
3071                                         const int32_t userId,
3072                                         AppSpawnStartMsg &startMsg)
3073 {
3074     if (remoteClientManager_ == nullptr) {
3075         TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ is nullptr.");
3076         return;
3077     }
3078     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
3079     if (bundleMgrHelper == nullptr) {
3080         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
3081         return;
3082     }
3083     auto overlayMgrProxy = bundleMgrHelper->GetOverlayManagerProxy();
3084     if (overlayMgrProxy !=  nullptr) {
3085         std::vector<OverlayModuleInfo> overlayModuleInfo;
3086         TAG_LOGD(AAFwkTag::APPMGR, "Check overlay app begin.");
3087         HITRACE_METER_NAME(HITRACE_TAG_APP, "BMS->GetOverlayModuleInfoForTarget");
3088         auto targetRet = IN_PROCESS_CALL(overlayMgrProxy->GetOverlayModuleInfoForTarget(
3089             bundleName, "", overlayModuleInfo, userId));
3090         if (targetRet == ERR_OK && overlayModuleInfo.size() != 0) {
3091             TAG_LOGD(AAFwkTag::APPMGR, "Start an overlay app process.");
3092             startMsg.flags = startMsg.flags | APP_OVERLAY_FLAG;
3093             std::string overlayInfoPaths;
3094             for (auto it : overlayModuleInfo) {
3095                 overlayInfoPaths += (it.hapPath + "|");
3096             }
3097             startMsg.overlayInfo = overlayInfoPaths;
3098         }
3099     }
3100 }
3101 
SetAppEnvInfo(const BundleInfo & bundleInfo,AppSpawnStartMsg & startMsg)3102 void AppMgrServiceInner::SetAppEnvInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg& startMsg)
3103 {
3104     if (bundleInfo.applicationInfo.tsanEnabled) {
3105         startMsg.appEnv.emplace(TSAN_FLAG_NAME, std::to_string(1));
3106     } else {
3107         startMsg.appEnv.emplace(TSAN_FLAG_NAME, std::to_string(0));
3108     }
3109 
3110     if (bundleInfo.applicationInfo.hwasanEnabled) {
3111         startMsg.appEnv.emplace(HWASAN_FLAG_NAME, std::to_string(1));
3112     } else {
3113         startMsg.appEnv.emplace(HWASAN_FLAG_NAME, std::to_string(0));
3114     }
3115 
3116     if (!bundleInfo.applicationInfo.appEnvironments.empty()) {
3117         for (const auto& appEnvironment : bundleInfo.applicationInfo.appEnvironments) {
3118             startMsg.appEnv.emplace(appEnvironment.name, appEnvironment.value);
3119         }
3120     }
3121 }
3122 
AddMountPermission(uint32_t accessTokenId,std::set<std::string> & permissions)3123 void AppMgrServiceInner::AddMountPermission(uint32_t accessTokenId, std::set<std::string> &permissions)
3124 {
3125     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3126     auto handle = remoteClientManager_->GetSpawnClient()->GetAppSpawnClientHandle();
3127     int32_t maxPermissionIndex = GetMaxPermissionIndex(handle);
3128     for (int i = 0; i < maxPermissionIndex; i++) {
3129         std::string permission = std::string(GetPermissionByIndex(handle, i));
3130         if (Security::AccessToken::AccessTokenKit::VerifyAccessToken(accessTokenId, permission, false) ==
3131             Security::AccessToken::PERMISSION_GRANTED) {
3132             permissions.insert(permission);
3133         }
3134     }
3135 }
3136 
StartProcessVerifyPermission(const BundleInfo & bundleInfo,bool & hasAccessBundleDirReq,uint8_t & setAllowInternet,uint8_t & allowInternet,std::vector<int32_t> & gids)3137 void AppMgrServiceInner::StartProcessVerifyPermission(const BundleInfo &bundleInfo, bool &hasAccessBundleDirReq,
3138                                                       uint8_t &setAllowInternet, uint8_t &allowInternet,
3139                                                       std::vector<int32_t> &gids)
3140 {
3141     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3142     hasAccessBundleDirReq = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
3143         [] (const auto &reqPermission) {
3144             if (PERMISSION_ACCESS_BUNDLE_DIR == reqPermission) {
3145                 return true;
3146             }
3147             return false;
3148         });
3149 
3150     auto token = bundleInfo.applicationInfo.accessTokenId;
3151     {
3152         HITRACE_METER_NAME(HITRACE_TAG_APP, "AccessTokenKit::VerifyAccessToken");
3153         int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_INTERNET, false);
3154         if (result != Security::AccessToken::PERMISSION_GRANTED) {
3155             setAllowInternet = 1;
3156             allowInternet = 0;
3157     #ifdef APP_MGR_SERVICE_APPMS
3158             auto ret = OHOS::NetManagerStandard::NetConnClient::GetInstance().SetInternetPermission(bundleInfo.uid, 0);
3159             TAG_LOGD(AAFwkTag::APPMGR, "SetInternetPermission, ret = %{public}d", ret);
3160         } else {
3161             auto ret = OHOS::NetManagerStandard::NetConnClient::GetInstance().SetInternetPermission(bundleInfo.uid, 1);
3162             TAG_LOGD(AAFwkTag::APPMGR, "SetInternetPermission, ret = %{public}d", ret);
3163             gids.push_back(NETSYS_SOCKET_GROUPID);
3164     #endif
3165         }
3166 
3167         result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token, PERMISSION_MANAGE_VPN, false);
3168         if (result == Security::AccessToken::PERMISSION_GRANTED) {
3169             gids.push_back(BLUETOOTH_GROUPID);
3170         }
3171 
3172         if (hasAccessBundleDirReq) {
3173             int result = Security::AccessToken::AccessTokenKit::VerifyAccessToken(token,
3174                 PERMISSION_ACCESS_BUNDLE_DIR, false);
3175             if (result != Security::AccessToken::PERMISSION_GRANTED) {
3176                 TAG_LOGE(AAFwkTag::APPMGR, "StartProcess PERMISSION_ACCESS_BUNDLE_DIR NOT GRANTED");
3177                 hasAccessBundleDirReq = false;
3178             }
3179         }
3180     }
3181 }
3182 
CreatNewStartMsg(const Want & want,const AbilityInfo & abilityInfo,const std::shared_ptr<ApplicationInfo> & appInfo,const std::string & processName,AppSpawnStartMsg & startMsg)3183 int32_t AppMgrServiceInner::CreatNewStartMsg(const Want &want, const AbilityInfo &abilityInfo,
3184     const std::shared_ptr<ApplicationInfo> &appInfo, const std::string &processName, AppSpawnStartMsg &startMsg)
3185 {
3186     TAG_LOGD(AAFwkTag::APPMGR, "called");
3187     if (!remoteClientManager_) {
3188         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager is null.");
3189         return ERR_NO_INIT;
3190     }
3191     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
3192     if (!bundleMgrHelper) {
3193         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
3194         return ERR_NO_INIT;
3195     }
3196 
3197     BundleInfo bundleInfo;
3198     HapModuleInfo hapModuleInfo;
3199     int32_t appIndex = want.GetIntParam(AppspawnUtil::DLP_PARAMS_INDEX, 0);
3200     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
3201         TAG_LOGE(AAFwkTag::APPMGR, "GetBundleAndHapInfo failed.");
3202         return ERR_NO_INIT;
3203     }
3204 
3205     uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, abilityInfo);
3206     auto uid = appInfo->uid;
3207     auto bundleType = appInfo->bundleType;
3208     auto ret = CreateStartMsg(processName, startFlags, uid, bundleInfo, appIndex, bundleType, startMsg, nullptr);
3209     if (ret != ERR_OK) {
3210         TAG_LOGE(AAFwkTag::APPMGR, "CreateStartMsg failed.");
3211     }
3212     return ret;
3213 }
3214 
SetAtomicServiceInfo(BundleType bundleType,AppSpawnStartMsg & startMsg)3215 void AppMgrServiceInner::SetAtomicServiceInfo(BundleType bundleType, AppSpawnStartMsg &startMsg)
3216 {
3217 #ifdef OHOS_ACCOUNT_ENABLED
3218     TAG_LOGD(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED on");
3219     if (bundleType == BundleType::ATOMIC_SERVICE) {
3220         TAG_LOGI(AAFwkTag::APPMGR, "application is of atomic service type");
3221         AccountSA::OhosAccountInfo accountInfo;
3222         auto errCode = AccountSA::OhosAccountKits::GetInstance().GetOhosAccountInfo(accountInfo);
3223         if (errCode == ERR_OK) {
3224             TAG_LOGI(AAFwkTag::APPMGR, "GetOhosAccountInfo succeeds, uid %{public}s", accountInfo.uid_.c_str());
3225             startMsg.atomicServiceFlag = true;
3226             startMsg.atomicAccount = accountInfo.uid_;
3227         } else {
3228             TAG_LOGE(AAFwkTag::APPMGR, "failed to get ohos account info:%{public}d", errCode);
3229         }
3230     }
3231 #else
3232     TAG_LOGD(AAFwkTag::APPMGR, "execute with OHOS_ACCOUNT_ENABLED off");
3233 #endif // OHOS_ACCOUNT_ENABLED
3234 }
3235 
SetAppInfo(const BundleInfo & bundleInfo,AppSpawnStartMsg & startMsg)3236 void AppMgrServiceInner::SetAppInfo(const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg)
3237 {
3238     bool hasAccessBundleDirReq;
3239     bool tempJitAllow = false;
3240     uint8_t setAllowInternet = 0;
3241     uint8_t allowInternet = 1;
3242     std::vector<int32_t> gids;
3243     StartProcessVerifyPermission(bundleInfo, hasAccessBundleDirReq, setAllowInternet, allowInternet, gids);
3244     startMsg.uid = bundleInfo.uid;
3245     startMsg.gid = bundleInfo.gid;
3246     startMsg.hapFlags = bundleInfo.isPreInstallApp ? 1 : 0;
3247     startMsg.accessTokenId = bundleInfo.applicationInfo.accessTokenId;
3248     startMsg.accessTokenIdEx = bundleInfo.applicationInfo.accessTokenIdEx;
3249     startMsg.apl = bundleInfo.applicationInfo.appPrivilegeLevel;
3250     startMsg.ownerId = bundleInfo.signatureInfo.appIdentifier;
3251     startMsg.provisionType = bundleInfo.applicationInfo.appProvisionType;
3252     if (startMsg.maxChildProcess == 0) {
3253         startMsg.maxChildProcess = bundleInfo.applicationInfo.maxChildProcess;
3254     }
3255     startMsg.setAllowInternet = setAllowInternet;
3256     startMsg.allowInternet = allowInternet;
3257     startMsg.gids = gids;
3258     startMsg.flags |= hasAccessBundleDirReq ? APP_ACCESS_BUNDLE_DIR : 0;
3259     tempJitAllow = std::any_of(bundleInfo.reqPermissions.begin(), bundleInfo.reqPermissions.end(),
3260         [] (const auto &reqPermission) {
3261             if (PERMISSION_TEMP_JIT_ALLOW == reqPermission) {
3262                 return true;
3263             }
3264             return false;
3265         });
3266     startMsg.flags |= tempJitAllow ? START_FLAG_BASE << StartFlags::TEMP_JIT_ALLOW : 0;
3267     SetAppEnvInfo(bundleInfo, startMsg);
3268 }
3269 
CreateStartMsg(const std::string & processName,uint32_t startFlags,const int uid,const BundleInfo & bundleInfo,const int32_t bundleIndex,BundleType bundleType,AppSpawnStartMsg & startMsg,std::shared_ptr<AAFwk::Want> want,const std::string & moduleName,const std::string & abilityName,bool strictMode)3270 int32_t AppMgrServiceInner::CreateStartMsg(const std::string &processName, uint32_t startFlags, const int uid,
3271     const BundleInfo &bundleInfo, const int32_t bundleIndex, BundleType bundleType, AppSpawnStartMsg &startMsg,
3272     std::shared_ptr<AAFwk::Want> want, const std::string &moduleName, const std::string &abilityName, bool strictMode)
3273 {
3274     if (!remoteClientManager_ || !otherTaskHandler_) {
3275         TAG_LOGE(AAFwkTag::APPMGR, "null remoteClientManager or otherTaskHandler");
3276         return ERR_NO_INIT;
3277     }
3278 
3279     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
3280     if (!bundleMgrHelper) {
3281         TAG_LOGE(AAFwkTag::APPMGR, "Get bundle manager helper failed.");
3282         return ERR_NO_INIT;
3283     }
3284 
3285     AAFwk::AutoSyncTaskHandle autoSync(otherTaskHandler_->SubmitTask([&]() {
3286         AddMountPermission(bundleInfo.applicationInfo.accessTokenId, startMsg.permissions);
3287         }, AAFwk::TaskAttribute{
3288             .taskName_ = "AddMountPermission",
3289             .taskQos_ = AAFwk::TaskQoS::USER_INTERACTIVE
3290         }));
3291 
3292     HspList hspList;
3293     auto ret = bundleMgrHelper->GetBaseSharedBundleInfos(bundleInfo.name, hspList,
3294         AppExecFwk::GetDependentBundleInfoFlag::GET_ALL_DEPENDENT_BUNDLE_INFO);
3295     if (ret != ERR_OK) {
3296         TAG_LOGE(AAFwkTag::APPMGR, "GetBaseSharedBundleInfos failed: %{public}d.", ret);
3297         return ret;
3298     }
3299     startMsg.hspList = hspList;
3300 
3301     auto userId = GetUserIdByUid(uid);
3302     DataGroupInfoList dataGroupInfoList;
3303     bool result = bundleMgrHelper->QueryDataGroupInfos(bundleInfo.name, userId, dataGroupInfoList);
3304     if (!result || dataGroupInfoList.empty()) {
3305         TAG_LOGD(AAFwkTag::APPMGR, "the bundle has no groupInfos.");
3306     }
3307     QueryExtensionSandBox(moduleName, abilityName, bundleInfo, startMsg, dataGroupInfoList, strictMode, want);
3308     startMsg.bundleName = bundleInfo.name;
3309     startMsg.renderParam = RENDER_PARAM;
3310     startMsg.flags = startFlags;
3311     startMsg.bundleIndex = bundleIndex;
3312     startMsg.procName = processName;
3313 
3314     SetAtomicServiceInfo(bundleType, startMsg);
3315     SetOverlayInfo(bundleInfo.name, userId, startMsg);
3316     SetAppInfo(bundleInfo, startMsg);
3317     AppspawnUtil::SetJITPermissions(bundleInfo.applicationInfo.accessTokenId, startMsg.jitPermissionsList);
3318     TAG_LOGI(AAFwkTag::APPMGR, "apl: %{public}s, bundleName: %{public}s, startFlags: %{public}d",
3319         startMsg.apl.c_str(), bundleInfo.name.c_str(), startFlags);
3320 
3321     autoSync.Sync();
3322     return ERR_OK;
3323 }
3324 
PresetMaxChildProcess(const std::shared_ptr<AbilityInfo> & abilityInfo,int32_t & maxChildProcess)3325 void AppMgrServiceInner::PresetMaxChildProcess(const std::shared_ptr<AbilityInfo> &abilityInfo,
3326     int32_t &maxChildProcess)
3327 {
3328     auto type = abilityInfo->type;
3329     auto extensionType = abilityInfo->extensionAbilityType;
3330     if (type == AppExecFwk::AbilityType::EXTENSION &&
3331         extensionType != AppExecFwk::ExtensionAbilityType::DATASHARE &&
3332         extensionType != AppExecFwk::ExtensionAbilityType::SERVICE) {
3333         maxChildProcess = 1;
3334     }
3335 }
3336 
QueryExtensionSandBox(const std::string & moduleName,const std::string & abilityName,const BundleInfo & bundleInfo,AppSpawnStartMsg & startMsg,DataGroupInfoList & dataGroupInfoList,bool strictMode,std::shared_ptr<AAFwk::Want> want)3337 void AppMgrServiceInner::QueryExtensionSandBox(const std::string &moduleName, const std::string &abilityName,
3338     const BundleInfo &bundleInfo, AppSpawnStartMsg &startMsg, DataGroupInfoList &dataGroupInfoList, bool strictMode,
3339     std::shared_ptr<AAFwk::Want> want)
3340 {
3341     std::vector<ExtensionAbilityInfo> extensionInfos;
3342     for (auto hapModuleInfo: bundleInfo.hapModuleInfos) {
3343         extensionInfos.insert(extensionInfos.end(), hapModuleInfo.extensionInfos.begin(),
3344             hapModuleInfo.extensionInfos.end());
3345     }
3346     startMsg.strictMode = strictMode;
3347     auto isExist = (want == nullptr) ? false : want->HasParameter(ISOLATED_SANDBOX);
3348     bool isolatedSandbox = false;
3349     if (isExist) {
3350         isolatedSandbox = (want == nullptr) ? false : want->GetBoolParam(ISOLATED_SANDBOX, false);
3351     }
3352     auto infoExisted = [&moduleName, &abilityName, &strictMode, &isExist, &isolatedSandbox](
3353                            const ExtensionAbilityInfo &info) {
3354         auto ret = info.moduleName == moduleName && info.name == abilityName && info.needCreateSandbox && strictMode;
3355         if (isExist) {
3356             return ret && isolatedSandbox;
3357         }
3358         return ret;
3359     };
3360     auto infoIter = std::find_if(extensionInfos.begin(), extensionInfos.end(), infoExisted);
3361     DataGroupInfoList extensionDataGroupInfoList;
3362     if (infoIter != extensionInfos.end()) {
3363         startMsg.isolatedExtension = true;
3364         startMsg.extensionSandboxPath = infoIter->moduleName + "-" + infoIter->name;
3365         for (auto dataGroupInfo : dataGroupInfoList) {
3366             auto groupIdExisted = [&dataGroupInfo](const std::string &dataGroupId) {
3367                 return dataGroupInfo.dataGroupId == dataGroupId;
3368             };
3369             if (std::find_if(infoIter->dataGroupIds.begin(), infoIter->dataGroupIds.end(), groupIdExisted) !=
3370                 infoIter->dataGroupIds.end()) {
3371                 extensionDataGroupInfoList.emplace_back(dataGroupInfo);
3372             }
3373         }
3374         startMsg.dataGroupInfoList = extensionDataGroupInfoList;
3375     } else {
3376         startMsg.dataGroupInfoList = dataGroupInfoList;
3377     }
3378 }
3379 
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,bool strictMode,int32_t maxChildProcess,sptr<IRemoteObject> token,std::shared_ptr<AAFwk::Want> want,ExtensionAbilityType ExtensionAbilityType)3380 int32_t AppMgrServiceInner::StartProcess(const std::string &appName, const std::string &processName,
3381     uint32_t startFlags, std::shared_ptr<AppRunningRecord> appRecord, const int uid, const BundleInfo &bundleInfo,
3382     const std::string &bundleName, const int32_t bundleIndex, bool appExistFlag, bool isPreload,
3383     AppExecFwk::PreloadMode preloadMode, const std::string &moduleName, const std::string &abilityName,
3384     bool strictMode, int32_t maxChildProcess, sptr<IRemoteObject> token, std::shared_ptr<AAFwk::Want> want,
3385     ExtensionAbilityType ExtensionAbilityType)
3386 {
3387     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3388     TAG_LOGD(AAFwkTag::APPMGR, "bundleName: %{public}s, isPreload: %{public}d", bundleName.c_str(), isPreload);
3389     if (!appRecord) {
3390         TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null");
3391         return ERR_INVALID_VALUE;
3392     }
3393     bool isCJApp = IsCjApplication(bundleInfo);
3394     if (!remoteClientManager_ || !remoteClientManager_->GetSpawnClient()) {
3395         TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient is null");
3396         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
3397         if (!isCJApp) {
3398             SendProcessStartFailedEvent(appRecord, ProcessStartFailedReason::GET_SPAWN_CLIENT_FAILED,
3399                 PROCESS_START_FAILED_SUB_REASON_UNKNOWN);
3400         }
3401         return AAFwk::ERR_GET_SPAWN_CLIENT_FAILED;
3402     }
3403 
3404     AppSpawnStartMsg startMsg;
3405     auto appInfo = appRecord->GetApplicationInfo();
3406     auto bundleType = appInfo ? appInfo->bundleType : BundleType::APP;
3407     startMsg.maxChildProcess = maxChildProcess;
3408     auto ret = CreateStartMsg(processName, startFlags, uid, bundleInfo, bundleIndex, bundleType, startMsg, want,
3409         moduleName, abilityName, strictMode);
3410     if (ret != ERR_OK) {
3411         TAG_LOGE(AAFwkTag::APPMGR, "CreateStartMsg failed.");
3412         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
3413         if (!isCJApp) {
3414             SendProcessStartFailedEvent(appRecord, ProcessStartFailedReason::CREATE_START_MSG_FAILED, ret);
3415         }
3416         return AAFwk::ERR_CREATE_START_MSG_FAILED;
3417     };
3418 
3419     SetProcessJITState(appRecord);
3420     PerfProfile::GetInstance().SetAppForkStartTime(GetTickCount());
3421     pid_t pid = 0;
3422     ErrCode errCode = ERR_OK;
3423     if (isCJApp) {
3424         if (!remoteClientManager_->GetCJSpawnClient()) {
3425             TAG_LOGE(AAFwkTag::APPMGR, "cj appSpawnClient is null");
3426             appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
3427             return AAFwk::ERR_GET_SPAWN_CLIENT_FAILED;
3428         }
3429         SendCreateAtomicServiceProcessEvent(appRecord, bundleType, moduleName, abilityName);
3430         errCode = remoteClientManager_->GetCJSpawnClient()->StartProcess(startMsg, pid);
3431     } else {
3432         SendCreateAtomicServiceProcessEvent(appRecord, bundleType, moduleName, abilityName);
3433         errCode = remoteClientManager_->GetSpawnClient()->StartProcess(startMsg, pid);
3434     }
3435     if (FAILED(errCode)) {
3436         TAG_LOGE(AAFwkTag::APPMGR, "failed to spawn new app process, errCode %{public}08x", errCode);
3437         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
3438         if (!isCJApp) {
3439             SendProcessStartFailedEvent(appRecord, ProcessStartFailedReason::APPSPAWN_FAILED,
3440                 static_cast<int32_t>(errCode));
3441         }
3442         return AAFwk::ERR_SPAWN_PROCESS_FAILED;
3443     }
3444 
3445     #ifdef ABILITY_RUNTIME_FEATURE_SANDBOXMANAGER
3446     bool checkApiVersion = (appInfo && (appInfo->apiTargetVersion % API_VERSION_MOD == API10));
3447     TAG_LOGD(AAFwkTag::APPMGR, "version of api is %{public}d", appInfo->apiTargetVersion % API_VERSION_MOD);
3448     if (checkApiVersion && AAFwk::AppUtils::GetInstance().IsGrantPersistUriPermission()) {
3449         uint32_t tokenId = appInfo->accessTokenId;
3450         auto sandboxRet = AccessControl::SandboxManager::SandboxManagerKit::StartAccessingByTokenId(tokenId);
3451         TAG_LOGI(AAFwkTag::APPMGR, "tokenId = %{public}u, ret = %{public}d", tokenId, sandboxRet);
3452     }
3453     #endif
3454 
3455     TAG_LOGI(AAFwkTag::APPMGR, "Start process success, pid: %{public}d, processName: %{public}s.",
3456         pid, processName.c_str());
3457     SetRunningSharedBundleList(bundleName, startMsg.hspList);
3458     appRecord->GetPriorityObject()->SetPid(pid);
3459     appRecord->SetUid(startMsg.uid);
3460     appRecord->SetStartMsg(startMsg);
3461     appRecord->SetAppMgrServiceInner(weak_from_this());
3462     appRecord->SetSpawned();
3463     if (AAFwk::UIExtensionUtils::IsUIExtension(ExtensionAbilityType)) {
3464         TAG_LOGD(AAFwkTag::APPMGR, "Add UIExtension LauncherItem.");
3465         AddUIExtensionLauncherItem(want, appRecord, token);
3466     }
3467     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_CREATE, false, false);
3468     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessCreated(appRecord, isPreload);
3469     if (!appExistFlag) {
3470         OnAppStarted(appRecord);
3471     }
3472     PerfProfile::GetInstance().SetAppForkEndTime(GetTickCount());
3473     SendProcessStartEvent(appRecord, isPreload, preloadMode);
3474     ProcessAppDebug(appRecord, appRecord->IsDebugApp());
3475     return ERR_OK;
3476 }
3477 
SetProcessJITState(const std::shared_ptr<AppRunningRecord> appRecord)3478 void AppMgrServiceInner::SetProcessJITState(const std::shared_ptr<AppRunningRecord> appRecord)
3479 {
3480     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3481     TAG_LOGD(AAFwkTag::APPMGR, "called");
3482     if (!appRecord) {
3483         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
3484         return;
3485     }
3486     if (!securityModeManager_) {
3487         TAG_LOGE(AAFwkTag::APPMGR, "securityModeManager_ is nullptr.");
3488         appRecord->SetJITEnabled(true);
3489         return;
3490     }
3491     appRecord->SetJITEnabled(securityModeManager_->IsJITEnabled());
3492 }
3493 
MakeAppDebugInfo(const std::shared_ptr<AppRunningRecord> & appRecord,const bool & isDebugStart)3494 AppDebugInfo AppMgrServiceInner::MakeAppDebugInfo(
3495     const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart)
3496 {
3497     AppDebugInfo info;
3498     if (appRecord == nullptr) {
3499         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
3500         return info;
3501     }
3502 
3503     info.bundleName = appRecord->GetBundleName();
3504     auto priorityObject = appRecord->GetPriorityObject();
3505     if (priorityObject) {
3506         info.pid = priorityObject->GetPid();
3507     }
3508     info.uid = appRecord->GetUid();
3509     info.isDebugStart = isDebugStart;
3510     return info;
3511 }
3512 
ProcessAppDebug(const std::shared_ptr<AppRunningRecord> & appRecord,const bool & isDebugStart)3513 void AppMgrServiceInner::ProcessAppDebug(const std::shared_ptr<AppRunningRecord> &appRecord, const bool &isDebugStart)
3514 {
3515     TAG_LOGD(AAFwkTag::APPMGR, "called");
3516     if (appRecord == nullptr || appDebugManager_ == nullptr) {
3517         TAG_LOGE(AAFwkTag::APPMGR, "appRecord or appDebugManager_ is nullptr.");
3518         return;
3519     }
3520 
3521     auto startDebug = [this, appRecord](const bool &isDebugStart) {
3522         std::vector<AppDebugInfo> debugInfos;
3523         debugInfos.emplace_back(MakeAppDebugInfo(appRecord, isDebugStart));
3524         appDebugManager_->StartDebug(debugInfos);
3525     };
3526 
3527     if (isDebugStart && !appRecord->IsDebugApp()) {
3528         appRecord->SetDebugApp(true);
3529         startDebug(true);
3530         return;
3531     }
3532 
3533     if (appRecord->IsDebugApp()) {
3534         startDebug(true);
3535         return;
3536     }
3537 
3538     auto bundleName = appRecord->GetBundleName();
3539     if (appDebugManager_->IsAttachDebug(bundleName)) {
3540         appRecord->SetAttachDebug(true);
3541         startDebug(false);
3542     }
3543 }
3544 
SendCreateAtomicServiceProcessEvent(const std::shared_ptr<AppRunningRecord> & appRecord,const BundleType & bundleType,const std::string & moduleName,const std::string & abilityName)3545 bool AppMgrServiceInner::SendCreateAtomicServiceProcessEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
3546     const BundleType &bundleType, const std::string &moduleName, const std::string &abilityName)
3547 {
3548     if (bundleType != BundleType::ATOMIC_SERVICE) {
3549         return false;
3550     }
3551     if (!appRecord) {
3552         TAG_LOGI(AAFwkTag::APPMGR, "null appRecord");
3553         return false;
3554     }
3555     TAG_LOGI(AAFwkTag::APPMGR, "to report create atomic service process event.");
3556     auto callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
3557     auto callerAppRecord = GetAppRunningRecordByPid(callerPid);
3558     return AppMgrEventUtil::SendCreateAtomicServiceProcessEvent(callerAppRecord, appRecord, moduleName, abilityName);
3559 }
3560 
SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> & appRecord,bool isPreload,AppExecFwk::PreloadMode preloadMode)3561 bool AppMgrServiceInner::SendProcessStartEvent(const std::shared_ptr<AppRunningRecord> &appRecord, bool isPreload,
3562     AppExecFwk::PreloadMode preloadMode)
3563 {
3564     if (!appRecord) {
3565         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
3566         return false;
3567     }
3568     AAFwk::EventInfo eventInfo;
3569     auto callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
3570     auto callerAppRecord = GetAppRunningRecordByPid(callerPid);
3571     eventInfo.isPreload = isPreload;
3572     eventInfo.preloadMode = static_cast<int32_t>(preloadMode);
3573     AppMgrEventUtil::SendProcessStartEvent(callerAppRecord, appRecord, eventInfo);
3574     SendReStartProcessEvent(eventInfo, appRecord->GetUid());
3575     return true;
3576 }
3577 
SendReStartProcessEvent(AAFwk::EventInfo & eventInfo,int32_t appUid)3578 void AppMgrServiceInner::SendReStartProcessEvent(AAFwk::EventInfo &eventInfo, int32_t appUid)
3579 {
3580     TAG_LOGD(AAFwkTag::APPMGR, "called");
3581     std::lock_guard lock(killpedProcessMapLock_);
3582     int64_t restartTime = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::
3583         system_clock::now().time_since_epoch()).count();
3584     for (auto iter = killedProcessMap_.begin(); iter != killedProcessMap_.end();) {
3585         int64_t killTime = iter->first;
3586         if (restartTime - killTime > PROCESS_RESTART_MARGIN_MICRO_SECONDS) {
3587             iter = killedProcessMap_.erase(iter);
3588             continue;
3589         }
3590         if (eventInfo.bundleName == eventInfo.callerBundleName &&
3591             eventInfo.processName != eventInfo.callerProcessName) {
3592             AppMgrEventUtil::SendReStartProcessEvent(eventInfo, appUid, restartTime);
3593             iter = killedProcessMap_.erase(iter);
3594             continue;
3595         }
3596         ++iter;
3597     }
3598 }
3599 
SendProcessStartFailedEvent(std::shared_ptr<AppRunningRecord> appRecord,ProcessStartFailedReason reason,int32_t subReason)3600 bool AppMgrServiceInner::SendProcessStartFailedEvent(std::shared_ptr<AppRunningRecord> appRecord,
3601     ProcessStartFailedReason reason, int32_t subReason)
3602 {
3603     if (!appRecord) {
3604         TAG_LOGE(AAFwkTag::APPMGR, "appRecord is nullptr");
3605         return false;
3606     }
3607     TAG_LOGD(AAFwkTag::APPMGR, "processName:%{public}s, reason:%{public}d, subReason:%{public}d",
3608         appRecord->GetProcessName().c_str(), reason, subReason);
3609     AAFwk::EventInfo eventInfo;
3610     eventInfo.reason = static_cast<int32_t>(reason);
3611     eventInfo.subReason = subReason;
3612     auto callerPid = appRecord->GetCallerPid() == -1 ? IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
3613     auto callerAppRecord = GetAppRunningRecordByPid(callerPid);
3614     AppMgrEventUtil::SendProcessStartFailedEvent(callerAppRecord, appRecord, eventInfo);
3615     return true;
3616 }
3617 
SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> & appRecord,const std::shared_ptr<AbilityInfo> & abilityInfo,const AppStartType startType)3618 void AppMgrServiceInner::SendAppStartupTypeEvent(const std::shared_ptr<AppRunningRecord> &appRecord,
3619     const std::shared_ptr<AbilityInfo> &abilityInfo, const AppStartType startType)
3620 {
3621     if (!appRecord) {
3622         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
3623         return;
3624     }
3625     AAFwk::EventInfo eventInfo;
3626     auto applicationInfo = appRecord->GetApplicationInfo();
3627     if (!applicationInfo) {
3628         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr, can not get app information");
3629     } else {
3630         eventInfo.bundleName = applicationInfo->name;
3631         eventInfo.versionName = applicationInfo->versionName;
3632         eventInfo.versionCode = applicationInfo->versionCode;
3633     }
3634     if (!abilityInfo) {
3635         TAG_LOGE(AAFwkTag::APPMGR, "abilityInfo is nullptr, can not get ability information");
3636     } else {
3637         eventInfo.abilityName = abilityInfo->name;
3638     }
3639     if (appRecord->GetPriorityObject() == nullptr) {
3640         TAG_LOGE(AAFwkTag::APPMGR, "appRecord's priorityObject is null");
3641     } else {
3642         eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
3643     }
3644     eventInfo.startType = static_cast<int32_t>(startType);
3645     AAFwk::EventReport::SendAppEvent(AAFwk::EventName::APP_STARTUP_TYPE, HiSysEventType::BEHAVIOR, eventInfo);
3646 }
3647 
OnRemoteDied(const wptr<IRemoteObject> & remote,bool isRenderProcess,bool isChildProcess)3648 void AppMgrServiceInner::OnRemoteDied(const wptr<IRemoteObject> &remote, bool isRenderProcess, bool isChildProcess)
3649 {
3650     TAG_LOGD(AAFwkTag::APPMGR, "On remote died.");
3651     if (isRenderProcess) {
3652         OnRenderRemoteDied(remote);
3653         return;
3654     }
3655     if (isChildProcess) {
3656         OnChildProcessRemoteDied(remote);
3657         return;
3658     }
3659 
3660     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
3661     {
3662         std::lock_guard lock(exceptionLock_);
3663         appRecord = appRunningManager_->OnRemoteDied(remote, shared_from_this());
3664     }
3665     if (appRecord == nullptr) {
3666         TAG_LOGI(AAFwkTag::APPMGR, "app record is not exist.");
3667         return;
3668     }
3669     AppExecFwk::AppfreezeManager::GetInstance()->RemoveDeathProcess(appRecord->GetBundleName());
3670     std::vector<sptr<IRemoteObject>> abilityTokens;
3671     for (const auto &token : appRecord->GetAbilities()) {
3672         abilityTokens.emplace_back(token.first);
3673     }
3674     {
3675         std::lock_guard lock(appStateCallbacksLock_);
3676         for (const auto& item : appStateCallbacks_) {
3677             if (item.callback != nullptr) {
3678                 item.callback->OnAppRemoteDied(abilityTokens);
3679             }
3680         }
3681     }
3682     ClearData(appRecord);
3683 }
3684 
ClearAppRunningData(const std::shared_ptr<AppRunningRecord> & appRecord,bool containsApp)3685 void AppMgrServiceInner::ClearAppRunningData(const std::shared_ptr<AppRunningRecord> &appRecord, bool containsApp)
3686 {
3687     if (!appRecord) {
3688         return;
3689     }
3690 
3691     if (containsApp) {
3692         appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
3693     }
3694 
3695     FinishUserTestLocked("App died", -1, appRecord);
3696     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_REMOTE_DIED);
3697 
3698     for (const auto &item : appRecord->GetAbilities()) {
3699         const auto &abilityRecord = item.second;
3700         appRecord->StateChangedNotifyObserver(abilityRecord,
3701             static_cast<int32_t>(AbilityState::ABILITY_STATE_TERMINATED), true, false);
3702     }
3703     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
3704     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
3705 
3706     // kill render if exist.
3707     KillRenderProcess(appRecord);
3708     KillChildProcess(appRecord);
3709     KillAttachedChildProcess(appRecord);
3710 
3711     SendProcessExitEvent(appRecord);
3712 
3713     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
3714         appRecord->UnSetPolicy();
3715         OnAppStopped(appRecord);
3716     }
3717 
3718     if (appDebugManager_ != nullptr) {
3719         auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
3720         appDebugManager_->RemoveAppDebugInfo(info);
3721     }
3722 
3723     ClearAppRunningDataForKeepAlive(appRecord);
3724 
3725     auto uid = appRecord->GetUid();
3726     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
3727 }
3728 
HandleTimeOut(const AAFwk::EventWrap & event)3729 void AppMgrServiceInner::HandleTimeOut(const AAFwk::EventWrap &event)
3730 {
3731     TAG_LOGD(AAFwkTag::APPMGR, "called");
3732     if (!appRunningManager_) {
3733         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager is nullptr");
3734         return;
3735     }
3736 
3737     // check libc.hook_mode
3738     const int bufferLen = 128;
3739     char paramOutBuf[bufferLen] = {0};
3740     const char *hook_mode = "startup:";
3741     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
3742     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
3743         TAG_LOGD(AAFwkTag::APPMGR, "HandleTimeOut, Hook_mode: no handle time out");
3744         return;
3745     }
3746 
3747     switch (event.GetEventId()) {
3748         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
3749             appRunningManager_->HandleTerminateTimeOut(event.GetParam());
3750             break;
3751         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
3752             SendHiSysEvent(event.GetEventId(), event.GetParam());
3753             HandleTerminateApplicationTimeOut(event.GetParam());
3754             break;
3755         case AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG:
3756             SendHiSysEvent(event.GetEventId(), event.GetParam());
3757             HandleStartSpecifiedProcessTimeout(event.GetParam());
3758             break;
3759         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
3760         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
3761             SendHiSysEvent(event.GetEventId(), event.GetParam());
3762             HandleAddAbilityStageTimeOut(event.GetParam());
3763             break;
3764         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
3765             SendHiSysEvent(event.GetEventId(), event.GetParam());
3766             HandleStartSpecifiedAbilityTimeOut(event.GetParam());
3767             break;
3768         default:
3769             break;
3770     }
3771 }
HandleAbilityAttachTimeOut(const sptr<IRemoteObject> & token)3772 void AppMgrServiceInner::HandleAbilityAttachTimeOut(const sptr<IRemoteObject> &token)
3773 {
3774     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
3775     TAG_LOGD(AAFwkTag::APPMGR, "called");
3776     if (!appRunningManager_) {
3777         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
3778         return;
3779     }
3780     appRunningManager_->HandleAbilityAttachTimeOut(token, shared_from_this());
3781 }
3782 
PrepareTerminate(const sptr<IRemoteObject> & token,bool clearMissionFlag)3783 void AppMgrServiceInner::PrepareTerminate(const sptr<IRemoteObject> &token, bool clearMissionFlag)
3784 {
3785     TAG_LOGD(AAFwkTag::APPMGR, "called");
3786     if (!appRunningManager_) {
3787         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
3788         return;
3789     }
3790     appRunningManager_->PrepareTerminate(token, clearMissionFlag);
3791 }
3792 
HandleTerminateApplicationTimeOut(const int64_t eventId)3793 void AppMgrServiceInner::HandleTerminateApplicationTimeOut(const int64_t eventId)
3794 {
3795     TAG_LOGD(AAFwkTag::APPMGR, "called");
3796     if (!appRunningManager_) {
3797         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
3798         return;
3799     }
3800     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
3801     TerminateApplication(appRecord);
3802 }
3803 
TerminateApplication(const std::shared_ptr<AppRunningRecord> & appRecord)3804 void AppMgrServiceInner::TerminateApplication(const std::shared_ptr<AppRunningRecord> &appRecord)
3805 {
3806     if (!appRecord) {
3807         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
3808         return;
3809     }
3810     appRecord->SetState(ApplicationState::APP_STATE_TERMINATED);
3811     appRecord->RemoveAppDeathRecipient();
3812     appRecord->SetProcessChangeReason(ProcessChangeReason::REASON_APP_TERMINATED_TIMEOUT);
3813     OnAppStateChanged(appRecord, ApplicationState::APP_STATE_TERMINATED, false, false);
3814     pid_t pid = appRecord->GetPriorityObject()->GetPid();
3815     int32_t uid = appRecord->GetUid();
3816     if (pid > 0) {
3817         auto timeoutTask = [appRecord, pid, uid, innerService = shared_from_this()]() {
3818             TAG_LOGI(AAFwkTag::APPMGR, "KillProcessByPid %{public}d, uid: %{public}d", pid, uid);
3819             int32_t result = innerService->KillProcessByPid(pid, "TerminateApplication");
3820             innerService->SendProcessExitEvent(appRecord);
3821             if (result < 0) {
3822                 TAG_LOGE(AAFwkTag::APPMGR, "KillProcessByPid kill process is fail");
3823                 return;
3824             }
3825         };
3826         if (!taskHandler_) {
3827             TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ is nullptr");
3828             return;
3829         }
3830         taskHandler_->SubmitTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
3831     }
3832     appRunningManager_->RemoveAppRunningRecordById(appRecord->GetRecordId());
3833     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
3834         RemoveRunningSharedBundleList(appRecord->GetBundleName());
3835     }
3836     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
3837     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
3838     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
3839         OnAppStopped(appRecord);
3840     }
3841 
3842     if (appDebugManager_) {
3843         auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
3844         appDebugManager_->RemoveAppDebugInfo(info);
3845     }
3846     ClearAppRunningDataForKeepAlive(appRecord);
3847 
3848     NotifyAppRunningStatusEvent(appRecord->GetBundleName(), uid, AbilityRuntime::RunningStatus::APP_RUNNING_STOP);
3849 }
3850 
HandleAddAbilityStageTimeOut(const int64_t eventId)3851 void AppMgrServiceInner::HandleAddAbilityStageTimeOut(const int64_t eventId)
3852 {
3853     TAG_LOGD(AAFwkTag::APPMGR, "called");
3854     if (!appRunningManager_) {
3855         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
3856         return;
3857     }
3858     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
3859     if (!appRecord) {
3860         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
3861         return;
3862     }
3863 
3864     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
3865         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant(),
3866             appRecord->GetSpecifiedRequestId());
3867     }
3868     appRecord->ResetSpecifiedRequestId();
3869 
3870     if (appRecord->IsNewProcessRequest() && startSpecifiedAbilityResponse_) {
3871         startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant(),
3872             appRecord->GetNewProcessRequestId());
3873     }
3874     appRecord->ResetNewProcessRequestId();
3875 
3876     KillApplicationByRecord(appRecord);
3877 }
3878 
GetRunningProcessInfoByToken(const sptr<IRemoteObject> & token,AppExecFwk::RunningProcessInfo & info)3879 void AppMgrServiceInner::GetRunningProcessInfoByToken(
3880     const sptr<IRemoteObject> &token, AppExecFwk::RunningProcessInfo &info)
3881 {
3882     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
3883     TAG_LOGD(AAFwkTag::APPMGR, "called");
3884     if (!CheckGetRunningInfoPermission()) {
3885         return;
3886     }
3887 
3888     appRunningManager_->GetRunningProcessInfoByToken(token, info);
3889 }
3890 
GetRunningProcessInfoByPid(const pid_t pid,OHOS::AppExecFwk::RunningProcessInfo & info) const3891 int32_t AppMgrServiceInner::GetRunningProcessInfoByPid(const pid_t pid,
3892     OHOS::AppExecFwk::RunningProcessInfo &info) const
3893 {
3894     TAG_LOGD(AAFwkTag::APPMGR, "called");
3895     if (!CheckGetRunningInfoPermission()) {
3896         return ERR_PERMISSION_DENIED;
3897     }
3898 
3899     return appRunningManager_->GetRunningProcessInfoByPid(pid, info);
3900 }
3901 
SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const3902 void AppMgrServiceInner::SetAbilityForegroundingFlagToAppRecord(const pid_t pid) const
3903 {
3904     TAG_LOGD(AAFwkTag::APPMGR, "called");
3905     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
3906         return;
3907     }
3908 
3909     appRunningManager_->SetAbilityForegroundingFlagToAppRecord(pid);
3910 }
3911 
CheckGetRunningInfoPermission() const3912 bool AppMgrServiceInner::CheckGetRunningInfoPermission() const
3913 {
3914     if (!appRunningManager_) {
3915         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
3916         return false;
3917     }
3918 
3919     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
3920     if (!isPerm) {
3921         TAG_LOGE(AAFwkTag::APPMGR, "Permission verify failed");
3922         return false;
3923     }
3924 
3925     return true;
3926 }
3927 
LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> & infos)3928 void AppMgrServiceInner::LoadResidentProcess(const std::vector<AppExecFwk::BundleInfo> &infos)
3929 {
3930     TAG_LOGI(AAFwkTag::APPMGR, "called");
3931 
3932     TAG_LOGI(AAFwkTag::APPMGR, "bundle info size: [%{public}zu]", infos.size());
3933     StartResidentProcess(infos, -1, true);
3934 }
3935 
StartResidentProcess(const std::vector<BundleInfo> & infos,int restartCount,bool isEmptyKeepAliveApp)3936 void AppMgrServiceInner::StartResidentProcess(const std::vector<BundleInfo> &infos, int restartCount,
3937     bool isEmptyKeepAliveApp)
3938 {
3939     TAG_LOGI(AAFwkTag::APPMGR, "start resident process");
3940     if (infos.empty()) {
3941         TAG_LOGE(AAFwkTag::APPMGR, "infos is empty!");
3942         return;
3943     }
3944 
3945     if (!appRunningManager_) {
3946         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
3947         return;
3948     }
3949 
3950     for (auto &bundle : infos) {
3951         TAG_LOGI(AAFwkTag::APPMGR, "processName = [%{public}s]", bundle.applicationInfo.process.c_str());
3952         if (bundle.applicationInfo.process.empty()) {
3953             continue;
3954         }
3955         auto processName = bundle.applicationInfo.process;
3956         // Inspection records
3957         auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
3958             bundle.applicationInfo.name, processName, bundle.applicationInfo.uid, bundle);
3959         if (appRecord) {
3960             TAG_LOGI(AAFwkTag::APPMGR, "processName [%{public}s] Already exists ", processName.c_str());
3961             continue;
3962         }
3963         TAG_LOGI(AAFwkTag::APPMGR, "Start empty resident process, processName = [%{public}s]", processName.c_str());
3964         StartEmptyResidentProcess(bundle, processName, restartCount, isEmptyKeepAliveApp);
3965     }
3966 }
3967 
StartEmptyResidentProcess(const BundleInfo & info,const std::string & processName,int restartCount,bool isEmptyKeepAliveApp)3968 void AppMgrServiceInner::StartEmptyResidentProcess(
3969     const BundleInfo &info, const std::string &processName, int restartCount, bool isEmptyKeepAliveApp)
3970 {
3971     TAG_LOGI(AAFwkTag::APPMGR, "start bundle [%{public}s | processName [%{public}s]]", info.name.c_str(),
3972         processName.c_str());
3973     if (!CheckRemoteClient() || !appRunningManager_) {
3974         TAG_LOGI(AAFwkTag::APPMGR, "Failed to start resident process!");
3975         return;
3976     }
3977 
3978     bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(info.name);
3979     bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(info.uid);
3980     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
3981 
3982     if (!appMultiUserExistFlag) {
3983         NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
3984     }
3985     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
3986         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
3987         return;
3988     }
3989 
3990     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
3991     if (!appRecord) {
3992         TAG_LOGE(AAFwkTag::APPMGR, "start process [%{public}s] failed!", processName.c_str());
3993         return;
3994     }
3995 
3996     StartProcess(appInfo->name, processName, 0, appRecord, appInfo->uid, info, appInfo->bundleName, 0, appExistFlag);
3997 
3998     // If it is empty, the startup failed
3999     if (!appRecord) {
4000         TAG_LOGE(AAFwkTag::APPMGR, "start process [%{public}s] failed!", processName.c_str());
4001         return;
4002     }
4003 
4004     if (restartCount > 0) {
4005         TAG_LOGI(AAFwkTag::APPMGR, "StartEmptyResidentProcess restartCount : [%{public}d], ", restartCount);
4006         appRecord->SetRestartResidentProcCount(restartCount);
4007     }
4008     appRecord->SetEmptyKeepAliveAppState(isEmptyKeepAliveApp);
4009     appRecord->SetKeepAliveEnableState(true);
4010 
4011     appRecord->SetTaskHandler(taskHandler_);
4012     appRecord->SetEventHandler(eventHandler_);
4013     std::vector<HapModuleInfo> hapModuleInfos;
4014     for (auto &iter : info.hapModuleInfos) {
4015         std::string keepAliveName = (appInfo->process.empty())?(appInfo->bundleName):(appInfo->process);
4016         std::string moduleProcessName = (iter.process.empty())?(appInfo->bundleName):(iter.process);
4017         if (keepAliveName == moduleProcessName) {
4018             hapModuleInfos.emplace_back(iter);
4019         }
4020     }
4021     appRecord->AddModules(appInfo, hapModuleInfos);
4022     TAG_LOGI(AAFwkTag::APPMGR, "StartEmptyResidentProcess of pid : [%{public}d], ",
4023         appRecord->GetPriorityObject()->GetPid());
4024 }
4025 
CheckRemoteClient()4026 bool AppMgrServiceInner::CheckRemoteClient()
4027 {
4028     if (!remoteClientManager_) {
4029         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null");
4030         return false;
4031     }
4032 
4033     if (!remoteClientManager_->GetSpawnClient()) {
4034         TAG_LOGE(AAFwkTag::APPMGR, "appSpawnClient is null");
4035         return false;
4036     }
4037 
4038     if (!remoteClientManager_->GetBundleManagerHelper()) {
4039         TAG_LOGE(AAFwkTag::APPMGR, "Get bundle manager helper fail.");
4040         return false;
4041     }
4042     return true;
4043 }
4044 
RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)4045 void AppMgrServiceInner::RestartResidentProcess(std::shared_ptr<AppRunningRecord> appRecord)
4046 {
4047     if (appRecord == nullptr) {
4048         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
4049         return;
4050     }
4051     struct timespec t;
4052     t.tv_sec = 0;
4053     t.tv_nsec = 0;
4054     clock_gettime(CLOCK_MONOTONIC, &t);
4055     appRecord->SetRestartTimeMillis(static_cast<int64_t>(((t.tv_sec) * NANOSECONDS + t.tv_nsec) / MICROSECONDS));
4056     appRecord->DecRestartResidentProcCount();
4057 
4058     auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
4059         return (appRecord != nullptr && appRecord->GetBundleName() == appRunningRecord->GetBundleName());
4060     };
4061     auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(), findRestartResidentTask);
4062     if (findIter != restartResedentTaskList_.end()) {
4063         restartResedentTaskList_.erase(findIter);
4064     }
4065 
4066     if (!CheckRemoteClient() || !appRecord || !appRunningManager_) {
4067         TAG_LOGE(AAFwkTag::APPMGR, "restart resident process failed!");
4068         return;
4069     }
4070 
4071     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
4072     BundleInfo bundleInfo;
4073     auto userId = GetUserIdByUid(appRecord->GetUid());
4074     auto flags = BundleFlag::GET_BUNDLE_DEFAULT | BundleFlag::GET_BUNDLE_WITH_REQUESTED_PERMISSION;
4075     if (!IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfo(
4076         appRecord->GetBundleName(),
4077         static_cast<BundleFlag>(flags),
4078         bundleInfo, userId))) {
4079         TAG_LOGE(AAFwkTag::APPMGR, "getBundleInfo fail");
4080         return;
4081     }
4082     std::vector<BundleInfo> infos;
4083     infos.emplace_back(bundleInfo);
4084     TAG_LOGI(AAFwkTag::APPMGR, "the resident process [%{public}s] remaining restarts num is [%{public}d]",
4085         appRecord->GetProcessName().c_str(), (int)appRecord->GetRestartResidentProcCount());
4086     StartResidentProcess(infos, appRecord->GetRestartResidentProcCount(), appRecord->IsEmptyKeepAliveApp());
4087 }
4088 
NotifyAppStatus(const std::string & bundleName,const std::string & eventData)4089 void AppMgrServiceInner::NotifyAppStatus(const std::string &bundleName, const std::string &eventData)
4090 {
4091     TAG_LOGD(AAFwkTag::APPMGR, "bundle name is %{public}s, event is %{public}s",
4092         bundleName.c_str(), eventData.c_str());
4093     Want want;
4094     want.SetAction(eventData);
4095     ElementName element;
4096     element.SetBundleName(bundleName);
4097     want.SetElement(element);
4098     want.SetParam(Constants::USER_ID, 0);
4099     EventFwk::CommonEventData commonData {want};
4100     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
4101 }
4102 
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)4103 void AppMgrServiceInner::NotifyAppStatusByCallerUid(const std::string &bundleName, const int32_t tokenId,
4104     const int32_t userId, const int32_t callerUid, const int32_t targetUid, const std::string &eventData)
4105 {
4106     TAG_LOGI(AAFwkTag::APPMGR,
4107         "%{public}s called, bundle name is %{public}s, userId is %{public}d, event is %{public}s", __func__,
4108         bundleName.c_str(), userId, eventData.c_str());
4109     Want want;
4110     want.SetAction(eventData);
4111     ElementName element;
4112     element.SetBundleName(bundleName);
4113     want.SetElement(element);
4114     want.SetParam(TOKEN_ID, tokenId);
4115     want.SetParam(Constants::USER_ID, userId);
4116     want.SetParam(Constants::UID, callerUid);
4117     want.SetParam(TARGET_UID_KEY, targetUid);
4118     EventFwk::CommonEventData commonData {want};
4119     EventFwk::CommonEventManager::PublishCommonEvent(commonData);
4120 }
4121 
RegisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer,const std::vector<std::string> & bundleNameList)4122 int32_t AppMgrServiceInner::RegisterApplicationStateObserver(
4123     const sptr<IApplicationStateObserver> &observer, const std::vector<std::string> &bundleNameList)
4124 {
4125     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterApplicationStateObserver(
4126         observer, bundleNameList);
4127 }
4128 
UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> & observer)4129 int32_t AppMgrServiceInner::UnregisterApplicationStateObserver(const sptr<IApplicationStateObserver> &observer)
4130 {
4131     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterApplicationStateObserver(observer);
4132 }
4133 
RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)4134 int32_t AppMgrServiceInner::RegisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
4135 {
4136     CHECK_CALLER_IS_SYSTEM_APP;
4137     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterAppForegroundStateObserver(observer);
4138 }
4139 
UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> & observer)4140 int32_t AppMgrServiceInner::UnregisterAppForegroundStateObserver(const sptr<IAppForegroundStateObserver> &observer)
4141 {
4142     CHECK_CALLER_IS_SYSTEM_APP;
4143     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterAppForegroundStateObserver(observer);
4144 }
4145 
RegisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)4146 int32_t AppMgrServiceInner::RegisterAbilityForegroundStateObserver(
4147     const sptr<IAbilityForegroundStateObserver> &observer)
4148 {
4149     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4150     CHECK_CALLER_IS_SYSTEM_APP;
4151     return DelayedSingleton<AppStateObserverManager>::GetInstance()->RegisterAbilityForegroundStateObserver(observer);
4152 }
4153 
UnregisterAbilityForegroundStateObserver(const sptr<IAbilityForegroundStateObserver> & observer)4154 int32_t AppMgrServiceInner::UnregisterAbilityForegroundStateObserver(
4155     const sptr<IAbilityForegroundStateObserver> &observer)
4156 {
4157     CHECK_CALLER_IS_SYSTEM_APP;
4158     return DelayedSingleton<AppStateObserverManager>::GetInstance()->UnregisterAbilityForegroundStateObserver(observer);
4159 }
4160 
GetForegroundApplications(std::vector<AppStateData> & list)4161 int32_t AppMgrServiceInner::GetForegroundApplications(std::vector<AppStateData> &list)
4162 {
4163     TAG_LOGD(AAFwkTag::APPMGR, "begin.");
4164     CHECK_CALLER_IS_SYSTEM_APP;
4165     auto isPerm = AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm();
4166     if (!isPerm) {
4167         TAG_LOGE(AAFwkTag::APPMGR, "Permission verify failed");
4168         return ERR_PERMISSION_DENIED;
4169     }
4170 
4171     appRunningManager_->GetForegroundApplications(list);
4172     return ERR_OK;
4173 }
4174 
StartUserTestProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,int32_t userId)4175 int AppMgrServiceInner::StartUserTestProcess(
4176     const AAFwk::Want &want, const sptr<IRemoteObject> &observer, const BundleInfo &bundleInfo, int32_t userId)
4177 {
4178     TAG_LOGI(AAFwkTag::APPMGR, "Enter");
4179     if (!observer) {
4180         TAG_LOGE(AAFwkTag::APPMGR, "observer nullptr.");
4181         return ERR_INVALID_VALUE;
4182     }
4183     if (!appRunningManager_) {
4184         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
4185         return ERR_INVALID_VALUE;
4186     }
4187 
4188     std::string bundleName = want.GetStringParam("-b");
4189     if (bundleName.empty()) {
4190         TAG_LOGE(AAFwkTag::APPMGR, "Invalid bundle name");
4191         return ERR_INVALID_VALUE;
4192     }
4193 
4194     if (KillApplicationByUserIdLocked(bundleName, 0, userId, false, "StartUserTestProcess")) {
4195         TAG_LOGE(AAFwkTag::APPMGR, "Failed to kill the application");
4196         return ERR_INVALID_VALUE;
4197     }
4198 
4199     HapModuleInfo hapModuleInfo;
4200     if (GetHapModuleInfoForTestRunner(want, observer, bundleInfo, hapModuleInfo)) {
4201         TAG_LOGE(AAFwkTag::APPMGR, "Failed to get HapModuleInfo for TestRunner");
4202         return ERR_INVALID_VALUE;
4203     }
4204 
4205     std::string processName;
4206     MakeProcessName(std::make_shared<ApplicationInfo>(bundleInfo.applicationInfo), hapModuleInfo, processName);
4207     TAG_LOGI(AAFwkTag::APPMGR, "processName = [%{public}s]", processName.c_str());
4208 
4209     // Inspection records
4210     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(
4211         bundleInfo.applicationInfo.name, processName, bundleInfo.applicationInfo.uid, bundleInfo);
4212     if (appRecord) {
4213         TAG_LOGI(AAFwkTag::APPMGR, "processName [%{public}s] Already exists ", processName.c_str());
4214         return ERR_INVALID_VALUE;
4215     }
4216 
4217     return StartEmptyProcess(want, observer, bundleInfo, processName, userId);
4218 }
4219 
GetHapModuleInfoForTestRunner(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & bundleInfo,HapModuleInfo & hapModuleInfo)4220 int AppMgrServiceInner::GetHapModuleInfoForTestRunner(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
4221     const BundleInfo &bundleInfo, HapModuleInfo &hapModuleInfo)
4222 {
4223     TAG_LOGI(AAFwkTag::APPMGR, "Enter");
4224     if (!observer) {
4225         TAG_LOGE(AAFwkTag::APPMGR, "observer nullptr.");
4226         return ERR_INVALID_VALUE;
4227     }
4228 
4229     bool moduleJson = false;
4230     if (!bundleInfo.hapModuleInfos.empty()) {
4231         moduleJson = bundleInfo.hapModuleInfos.back().isModuleJson;
4232     }
4233     if (moduleJson) {
4234         std::string moduleName = want.GetStringParam("-m");
4235         if (moduleName.empty()) {
4236             UserTestAbnormalFinish(observer, "No module name is specified.");
4237             return ERR_INVALID_VALUE;
4238         }
4239 
4240         bool found = false;
4241         for (auto item : bundleInfo.hapModuleInfos) {
4242             if (item.moduleName == moduleName) {
4243                 hapModuleInfo = item;
4244                 found = true;
4245                 break;
4246             }
4247         }
4248         if (!found) {
4249             UserTestAbnormalFinish(observer, "The specified module name is not found.");
4250             return ERR_INVALID_VALUE;
4251         }
4252     }
4253     return ERR_OK;
4254 }
4255 
UserTestAbnormalFinish(const sptr<IRemoteObject> & observer,const std::string & msg)4256 int AppMgrServiceInner::UserTestAbnormalFinish(const sptr<IRemoteObject> &observer, const std::string &msg)
4257 {
4258     sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(observer);
4259     if (!observerProxy) {
4260         TAG_LOGE(AAFwkTag::APPMGR, "Failed to get ITestObserver proxy");
4261         return ERR_INVALID_VALUE;
4262     }
4263     observerProxy->TestFinished(msg, -1);
4264     return ERR_OK;
4265 }
4266 
StartEmptyProcess(const AAFwk::Want & want,const sptr<IRemoteObject> & observer,const BundleInfo & info,const std::string & processName,const int userId)4267 int AppMgrServiceInner::StartEmptyProcess(const AAFwk::Want &want, const sptr<IRemoteObject> &observer,
4268     const BundleInfo &info, const std::string &processName, const int userId)
4269 {
4270     TAG_LOGI(AAFwkTag::APPMGR, "enter bundle [%{public}s | processName [%{public}s]]", info.name.c_str(),
4271         processName.c_str());
4272     if (!CheckRemoteClient() || !appRunningManager_) {
4273         TAG_LOGE(AAFwkTag::APPMGR, "Failed to start the process being tested!");
4274         return ERR_INVALID_VALUE;
4275     }
4276 
4277     bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(info.name);
4278     bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(info.uid);
4279     auto appInfo = std::make_shared<ApplicationInfo>(info.applicationInfo);
4280     if (!appMultiUserExistFlag) {
4281         NotifyAppRunningStatusEvent(info.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
4282     }
4283     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
4284         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
4285         return ERR_INVALID_OPERATION;
4286     }
4287     auto appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, info);
4288     CHECK_POINTER_AND_RETURN_VALUE(appRecord, ERR_INVALID_VALUE);
4289 
4290     auto isDebug = want.GetBoolParam(DEBUG_APP, false);
4291     TAG_LOGI(AAFwkTag::APPMGR, "Set Debug : %{public}s", (isDebug ? "true" : "false"));
4292     appRecord->SetDebugApp(isDebug);
4293     if (want.GetBoolParam(COLD_START, false)) {
4294         appRecord->SetDebugApp(true);
4295     }
4296 
4297     std::shared_ptr<UserTestRecord> testRecord = std::make_shared<UserTestRecord>();
4298     if (!testRecord) {
4299         TAG_LOGE(AAFwkTag::APPMGR, "Failed to make UserTestRecord!");
4300         return ERR_INVALID_VALUE;
4301     }
4302     testRecord->want = want;
4303     testRecord->observer = observer;
4304     testRecord->isFinished = false;
4305     testRecord->userId = userId;
4306     appRecord->SetUserTestInfo(testRecord);
4307 
4308     int32_t appIndex = 0;
4309     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
4310     uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, info.applicationInfo);
4311     StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, info, appInfo->bundleName,
4312         appIndex, appExistFlag);
4313 
4314     // If it is empty, the startup failed
4315     CHECK_POINTER_AND_RETURN_VALUE(appRecord, ERR_INVALID_VALUE);
4316 
4317     appRecord->SetTaskHandler(taskHandler_);
4318     appRecord->SetEventHandler(eventHandler_);
4319     appRecord->AddModules(appInfo, info.hapModuleInfos);
4320     TAG_LOGI(AAFwkTag::APPMGR, "StartEmptyProcess OK pid : [%{public}d]", appRecord->GetPriorityObject()->GetPid());
4321 
4322     return ERR_OK;
4323 }
4324 
FinishUserTest(const std::string & msg,const int64_t & resultCode,const std::string & bundleName,const pid_t & pid)4325 int AppMgrServiceInner::FinishUserTest(
4326     const std::string &msg, const int64_t &resultCode, const std::string &bundleName, const pid_t &pid)
4327 {
4328     TAG_LOGI(AAFwkTag::APPMGR, "Enter");
4329     if (bundleName.empty()) {
4330         TAG_LOGE(AAFwkTag::APPMGR, "Invalid bundle name.");
4331         return ERR_INVALID_VALUE;
4332     }
4333     auto appRecord = GetAppRunningRecordByPid(pid);
4334     if (!appRecord) {
4335         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord");
4336         return ERR_INVALID_VALUE;
4337     }
4338 
4339     auto userTestRecord = appRecord->GetUserTestInfo();
4340     if (!userTestRecord) {
4341         TAG_LOGE(AAFwkTag::APPMGR, "unstart user test");
4342         return ERR_INVALID_VALUE;
4343     }
4344 
4345     FinishUserTestLocked(msg, resultCode, appRecord);
4346 
4347     int ret = KillApplicationByUserIdLocked(bundleName, 0, userTestRecord->userId, false, "FinishUserTest");
4348     if (ret) {
4349         TAG_LOGE(AAFwkTag::APPMGR, "Failed to kill process.");
4350         return ret;
4351     }
4352 
4353     return ERR_OK;
4354 }
4355 
FinishUserTestLocked(const std::string & msg,const int64_t & resultCode,const std::shared_ptr<AppRunningRecord> & appRecord)4356 int AppMgrServiceInner::FinishUserTestLocked(
4357     const std::string &msg, const int64_t &resultCode, const std::shared_ptr<AppRunningRecord> &appRecord)
4358 {
4359     TAG_LOGD(AAFwkTag::APPMGR, "Enter");
4360     if (!appRecord) {
4361         TAG_LOGE(AAFwkTag::APPMGR, "Invalid appRecord");
4362         return ERR_INVALID_VALUE;
4363     }
4364 
4365     std::lock_guard<ffrt::mutex> lock(userTestLock_);
4366     auto userTestRecord = appRecord->GetUserTestInfo();
4367     if (!userTestRecord) {
4368         TAG_LOGD(AAFwkTag::APPMGR, "not start user test");
4369         return ERR_INVALID_VALUE;
4370     }
4371     if (!userTestRecord->isFinished) {
4372         sptr<AAFwk::ITestObserver> observerProxy = iface_cast<AAFwk::ITestObserver>(userTestRecord->observer);
4373         if (!observerProxy) {
4374             TAG_LOGE(AAFwkTag::APPMGR, "Failed to get ITestObserver proxy");
4375             return ERR_INVALID_VALUE;
4376         }
4377         observerProxy->TestFinished(msg, resultCode);
4378 
4379         userTestRecord->isFinished = true;
4380     }
4381 
4382     return ERR_OK;
4383 }
4384 
StartSpecifiedAbility(const AAFwk::Want & want,const AppExecFwk::AbilityInfo & abilityInfo,int32_t requestId)4385 void AppMgrServiceInner::StartSpecifiedAbility(const AAFwk::Want &want, const AppExecFwk::AbilityInfo &abilityInfo,
4386     int32_t requestId)
4387 {
4388     TAG_LOGD(AAFwkTag::APPMGR, "Start specified ability.");
4389     if (!CheckRemoteClient()) {
4390         return;
4391     }
4392 
4393     BundleInfo bundleInfo;
4394     HapModuleInfo hapModuleInfo;
4395     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
4396 
4397     int32_t appIndex = 0;
4398     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
4399     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
4400         return;
4401     }
4402     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
4403         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
4404         return;
4405     }
4406 
4407     std::string processName;
4408     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
4409     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, "", processName);
4410 
4411     std::vector<HapModuleInfo> hapModules;
4412     hapModules.emplace_back(hapModuleInfo);
4413 
4414     std::shared_ptr<AppRunningRecord> appRecord;
4415     appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
4416     if (!appRecord) {
4417         bool appExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleInfo.name);
4418         bool appMultiUserExistFlag = appRunningManager_->CheckAppRunningRecordIsExistByUid(bundleInfo.uid);
4419         if (!appMultiUserExistFlag) {
4420             NotifyAppRunningStatusEvent(
4421                 bundleInfo.name, appInfo->uid, AbilityRuntime::RunningStatus::APP_RUNNING_START);
4422         }
4423         // new app record
4424         appRecord = appRunningManager_->CreateAppRunningRecord(appInfo, processName, bundleInfo);
4425         if (!appRecord) {
4426             TAG_LOGE(AAFwkTag::APPMGR, "start process [%{public}s] failed!", processName.c_str());
4427             return;
4428         }
4429         if (hapModuleInfo.isStageBasedModel && !IsMainProcess(appInfo, processName)) {
4430             appRecord->SetEmptyKeepAliveAppState(false);
4431             appRecord->SetMainProcess(false);
4432             TAG_LOGD(AAFwkTag::APPMGR, "The process %{public}s will not keepalive", hapModuleInfo.process.c_str());
4433         }
4434         auto wantPtr = std::make_shared<AAFwk::Want>(want);
4435         if (wantPtr != nullptr) {
4436             appRecord->SetCallerPid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_PID, -1));
4437             appRecord->SetCallerUid(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_UID, -1));
4438             appRecord->SetCallerTokenId(wantPtr->GetIntParam(Want::PARAM_RESV_CALLER_TOKEN, -1));
4439             appRecord->SetDebugApp(wantPtr->GetBoolParam(DEBUG_APP, false));
4440             if (appRecord->IsDebugApp()) {
4441                 ProcessAppDebug(appRecord, true);
4442             }
4443             appRecord->SetNativeDebug(wantPtr->GetBoolParam("nativeDebug", false));
4444             if (wantPtr->GetBoolParam(COLD_START, false)) {
4445                 appRecord->SetDebugApp(true);
4446             }
4447             appRecord->SetPerfCmd(wantPtr->GetStringParam(PERF_CMD));
4448             appRecord->SetErrorInfoEnhance(wantPtr->GetBoolParam(ERROR_INFO_ENHANCE, false));
4449             appRecord->SetMultiThread(wantPtr->GetBoolParam(MULTI_THREAD, false));
4450         }
4451         appRecord->SetProcessAndExtensionType(abilityInfoPtr);
4452         appRecord->SetTaskHandler(taskHandler_);
4453         appRecord->SetEventHandler(eventHandler_);
4454         appRecord->SendEventForSpecifiedAbility(AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG,
4455             AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT);
4456         appRecord->SetAppIndex(appIndex);
4457         uint32_t startFlags = AppspawnUtil::BuildStartFlags(want, abilityInfo);
4458         StartProcess(appInfo->name, processName, startFlags, appRecord, appInfo->uid, bundleInfo, appInfo->bundleName,
4459             appIndex, appExistFlag);
4460 
4461         appRecord->SetSpecifiedAbilityFlagAndWant(requestId, want, hapModuleInfo.moduleName);
4462         appRecord->AddModules(appInfo, hapModules);
4463     } else {
4464         TAG_LOGD(AAFwkTag::APPMGR, "process is exist");
4465         auto isDebugApp = want.GetBoolParam(DEBUG_APP, false);
4466         if (isDebugApp && !appRecord->IsDebugApp()) {
4467             ProcessAppDebug(appRecord, isDebugApp);
4468         }
4469 
4470         appRecord->SetSpecifiedAbilityFlagAndWant(requestId, want, hapModuleInfo.moduleName);
4471         auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
4472         if (!moduleRecord) {
4473             TAG_LOGD(AAFwkTag::APPMGR, "module record is nullptr, add modules");
4474             appRecord->AddModules(appInfo, hapModules);
4475             appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName);
4476         } else if (!appRecord->AddAbilityStageBySpecifiedAbility(appInfo->bundleName)) {
4477             TAG_LOGD(AAFwkTag::APPMGR, "schedule accept want");
4478             appRecord->ScheduleAcceptWant(hapModuleInfo.moduleName);
4479         }
4480     }
4481 }
4482 
RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> & response)4483 void AppMgrServiceInner::RegisterStartSpecifiedAbilityResponse(const sptr<IStartSpecifiedAbilityResponse> &response)
4484 {
4485     if (!response) {
4486         TAG_LOGE(AAFwkTag::APPMGR, "response is nullptr, register failed.");
4487         return;
4488     }
4489     startSpecifiedAbilityResponse_ = response;
4490 }
4491 
ScheduleAcceptWantDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)4492 void AppMgrServiceInner::ScheduleAcceptWantDone(
4493     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
4494 {
4495     TAG_LOGD(AAFwkTag::APPMGR, "Schedule accept want done, flag: %{public}s", flag.c_str());
4496 
4497     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
4498     if (!appRecord) {
4499         TAG_LOGE(AAFwkTag::APPMGR, "Get app record failed.");
4500         return;
4501     }
4502     appRecord->ScheduleAcceptWantDone();
4503 
4504     if (startSpecifiedAbilityResponse_) {
4505         startSpecifiedAbilityResponse_->OnAcceptWantResponse(want, flag,
4506             appRecord->GetSpecifiedRequestId());
4507     }
4508     appRecord->ResetSpecifiedRequestId();
4509 }
4510 
HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)4511 void AppMgrServiceInner::HandleStartSpecifiedAbilityTimeOut(const int64_t eventId)
4512 {
4513     TAG_LOGD(AAFwkTag::APPMGR, "called start specified ability time out!");
4514     if (!appRunningManager_) {
4515         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
4516         return;
4517     }
4518 
4519     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
4520     if (!appRecord) {
4521         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
4522         return;
4523     }
4524 
4525     if (appRecord->IsStartSpecifiedAbility() && startSpecifiedAbilityResponse_) {
4526         startSpecifiedAbilityResponse_->OnTimeoutResponse(appRecord->GetSpecifiedWant(),
4527             appRecord->GetSpecifiedRequestId());
4528     }
4529     appRecord->ResetSpecifiedRequestId();
4530 
4531     KillApplicationByRecord(appRecord);
4532 }
4533 
ScheduleNewProcessRequestDone(const int32_t recordId,const AAFwk::Want & want,const std::string & flag)4534 void AppMgrServiceInner::ScheduleNewProcessRequestDone(
4535     const int32_t recordId, const AAFwk::Want &want, const std::string &flag)
4536 {
4537     TAG_LOGD(AAFwkTag::APPMGR, "ScheduleNewProcessRequestDone, flag: %{public}s", flag.c_str());
4538 
4539     auto appRecord = GetAppRunningRecordByAppRecordId(recordId);
4540     if (!appRecord) {
4541         TAG_LOGE(AAFwkTag::APPMGR, "Get app record failed.");
4542         return;
4543     }
4544     appRecord->ScheduleNewProcessRequestDone();
4545 
4546     if (startSpecifiedAbilityResponse_) {
4547         startSpecifiedAbilityResponse_->OnNewProcessRequestResponse(want, flag,
4548             appRecord->GetNewProcessRequestId());
4549     }
4550     appRecord->ResetNewProcessRequestId();
4551 }
4552 
HandleStartSpecifiedProcessTimeout(const int64_t eventId)4553 void AppMgrServiceInner::HandleStartSpecifiedProcessTimeout(const int64_t eventId)
4554 {
4555     TAG_LOGD(AAFwkTag::APPMGR, "called start specified process time out!");
4556     if (!appRunningManager_) {
4557         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
4558         return;
4559     }
4560 
4561     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
4562     if (!appRecord) {
4563         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
4564         return;
4565     }
4566 
4567     if (startSpecifiedAbilityResponse_) {
4568         startSpecifiedAbilityResponse_->OnNewProcessRequestTimeoutResponse(appRecord->GetNewProcessRequestWant(),
4569             appRecord->GetNewProcessRequestId());
4570     }
4571     appRecord->ResetNewProcessRequestId();
4572 }
4573 
DealWithUserConfiguration(const Configuration & config,const int32_t userId,int32_t & notifyUserId)4574 int32_t AppMgrServiceInner::DealWithUserConfiguration(const Configuration& config, const int32_t userId,
4575     int32_t &notifyUserId)
4576 {
4577     if (multiUserConfigurationMgr_ == nullptr) {
4578         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
4579         return ERR_INVALID_VALUE;
4580     }
4581     std::vector<std::string> changeKeyV;
4582     bool isNotifyUser0 = false;
4583     multiUserConfigurationMgr_->HandleConfiguration(userId, config, changeKeyV, isNotifyUser0);
4584     TAG_LOGI(AAFwkTag::APPMGR,
4585         "changeKeyV size: %{public}zu Config: %{public}s userId: %{public}d, NotifyUser0: %{public}d",
4586         changeKeyV.size(), config.GetName().c_str(), userId, static_cast<int32_t>(isNotifyUser0));
4587 
4588     if (!config.GetItem(AAFwk::GlobalConfigurationKey::THEME).empty() || !changeKeyV.empty()) {
4589         notifyUserId = userId;
4590         return ERR_OK;
4591     } else if (isNotifyUser0) {
4592         notifyUserId = USER0;
4593         return ERR_OK;
4594     } else {
4595         TAG_LOGE(AAFwkTag::APPMGR, "changeKeyV empty");
4596         return ERR_INVALID_VALUE;
4597     }
4598 }
4599 
UpdateConfiguration(const Configuration & config,const int32_t userId)4600 int32_t AppMgrServiceInner::UpdateConfiguration(const Configuration &config, const int32_t userId)
4601 {
4602     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4603     if (!appRunningManager_) {
4604         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
4605         return ERR_INVALID_VALUE;
4606     }
4607     CHECK_CALLER_IS_SYSTEM_APP;
4608     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateConfigurationPerm();
4609     if (ret != ERR_OK) {
4610         return ret;
4611     }
4612     int32_t notifyUserId;
4613     ret = DealWithUserConfiguration(config, userId, notifyUserId);
4614     if (ret != ERR_OK) {
4615         return ret;
4616     }
4617 
4618     // all app
4619     int32_t result = appRunningManager_->UpdateConfiguration(config, notifyUserId);
4620     HandleConfigurationChange(config, notifyUserId);
4621     if (result != ERR_OK) {
4622         TAG_LOGE(AAFwkTag::APPMGR, "update error, not notify");
4623         return result;
4624     }
4625     // notify
4626     std::lock_guard<ffrt::mutex> notifyLock(configurationObserverLock_);
4627     for (auto &item : configurationObservers_) {
4628         if (item.observer != nullptr && (notifyUserId == -1 || item.userId == 0 || item.userId == notifyUserId)) {
4629             item.observer->OnConfigurationUpdated(config);
4630         }
4631     }
4632 
4633     return result;
4634 }
4635 
UpdateConfigurationByBundleName(const Configuration & config,const std::string & name)4636 int32_t AppMgrServiceInner::UpdateConfigurationByBundleName(const Configuration &config, const std::string &name)
4637 {
4638     if (!appRunningManager_) {
4639         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
4640         return ERR_INVALID_VALUE;
4641     }
4642     CHECK_CALLER_IS_SYSTEM_APP;
4643     auto ret = AAFwk::PermissionVerification::GetInstance()->VerifyUpdateAPPConfigurationPerm();
4644     if (ret != ERR_OK) {
4645         return ret;
4646     }
4647     int32_t result = appRunningManager_->UpdateConfigurationByBundleName(config, name);
4648     if (result != ERR_OK) {
4649         TAG_LOGE(AAFwkTag::APPMGR, "update error, not notify");
4650         return result;
4651     }
4652     return result;
4653 }
4654 
HandleConfigurationChange(const Configuration & config,const int32_t userId)4655 void AppMgrServiceInner::HandleConfigurationChange(const Configuration& config, const int32_t userId)
4656 {
4657     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
4658     std::lock_guard lock(appStateCallbacksLock_);
4659 
4660     for (const auto &item : appStateCallbacks_) {
4661         if (item.callback != nullptr && (userId == -1 || item.userId == 0 || item.userId == userId)) {
4662             item.callback->NotifyConfigurationChange(config, currentUserId_);
4663         }
4664     }
4665 }
4666 
RegisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)4667 int32_t AppMgrServiceInner::RegisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
4668 {
4669     TAG_LOGD(AAFwkTag::APPMGR, "called");
4670     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4671         TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA");
4672         return ERR_INVALID_VALUE;
4673     }
4674 
4675     if (observer == nullptr) {
4676         TAG_LOGE(AAFwkTag::APPMGR, "AppMgrServiceInner::Register error: observer is null");
4677         return ERR_INVALID_VALUE;
4678     }
4679     std::lock_guard<ffrt::mutex> registerLock(configurationObserverLock_);
4680     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
4681         [&observer](const ConfigurationObserverWithUserId& item) {
4682             return (item.observer && item.observer->AsObject() == observer->AsObject());
4683         });
4684     if (it != configurationObservers_.end()) {
4685         TAG_LOGE(AAFwkTag::APPMGR, "AppMgrServiceInner::Register error: observer exist");
4686         return ERR_INVALID_VALUE;
4687     }
4688     configurationObservers_.push_back(
4689         ConfigurationObserverWithUserId { observer, GetUserIdByUid(IPCSkeleton::GetCallingUid()) });
4690     return NO_ERROR;
4691 }
4692 
UnregisterConfigurationObserver(const sptr<IConfigurationObserver> & observer)4693 int32_t AppMgrServiceInner::UnregisterConfigurationObserver(const sptr<IConfigurationObserver>& observer)
4694 {
4695     TAG_LOGI(AAFwkTag::APPMGR, "called");
4696     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
4697         TAG_LOGE(AAFwkTag::APPMGR, "caller is not SA");
4698         return ERR_INVALID_VALUE;
4699     }
4700     if (observer == nullptr) {
4701         TAG_LOGE(AAFwkTag::APPMGR, "AppMgrServiceInner::Register error: observer is null");
4702         return ERR_INVALID_VALUE;
4703     }
4704     std::lock_guard<ffrt::mutex> unregisterLock(configurationObserverLock_);
4705     auto it = std::find_if(configurationObservers_.begin(), configurationObservers_.end(),
4706         [&observer](const ConfigurationObserverWithUserId &item) {
4707             return (item.observer && item.observer->AsObject() == observer->AsObject());
4708         });
4709     if (it != configurationObservers_.end()) {
4710         configurationObservers_.erase(it);
4711         return NO_ERROR;
4712     }
4713     TAG_LOGI(AAFwkTag::APPMGR, "end");
4714     return ERR_INVALID_VALUE;
4715 }
4716 
InitGlobalConfiguration()4717 void AppMgrServiceInner::InitGlobalConfiguration()
4718 {
4719     std::shared_ptr<AppExecFwk::Configuration> globalConfiguration = std::make_shared<Configuration>();
4720     if (!globalConfiguration) {
4721         TAG_LOGE(AAFwkTag::APPMGR, "globalConfiguration null");
4722         return;
4723     }
4724 
4725 #ifdef SUPPORT_GRAPHICS
4726     // Currently only this interface is known
4727     auto language = OHOS::Global::I18n::LocaleConfig::GetSystemLocale();
4728 
4729     TAG_LOGI(AAFwkTag::APPMGR, "current global language: %{public}s", language.c_str());
4730     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE, language);
4731 
4732     std::string sysHour = OHOS::Global::I18n::LocaleConfig::GetSystemHour();
4733     TAG_LOGI(AAFwkTag::APPMGR, "current 24 hour clock: %{public}s", sysHour.c_str());
4734     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_HOUR, sysHour);
4735 #endif
4736 
4737     // Assign to default colorMode "light"
4738 
4739     TAG_LOGI(AAFwkTag::APPMGR, "current global colorMode: %{public}s", ConfigurationInner::COLOR_MODE_LIGHT);
4740     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_COLORMODE, ConfigurationInner::COLOR_MODE_LIGHT);
4741 
4742     // Get input pointer device
4743     std::string hasPointerDevice = system::GetParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, "false");
4744     TAG_LOGI(AAFwkTag::APPMGR, "current hasPointerDevice: %{public}s", hasPointerDevice.c_str());
4745     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, hasPointerDevice);
4746 
4747     // Get DeviceType
4748     auto deviceType = GetDeviceType();
4749     TAG_LOGI(AAFwkTag::APPMGR, "current deviceType: %{public}s", deviceType);
4750     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::DEVICE_TYPE, deviceType);
4751     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_SIZE_SCALE, "1.0");
4752     globalConfiguration->AddItem(AAFwk::GlobalConfigurationKey::SYSTEM_FONT_WEIGHT_SCALE, "1.0");
4753     if (multiUserConfigurationMgr_ == nullptr) {
4754         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
4755         return;
4756     }
4757     multiUserConfigurationMgr_->InitConfiguration(globalConfiguration);
4758     TAG_LOGI(AAFwkTag::APPMGR, "InitGlobalConfiguration Config: %{public}s", globalConfiguration->GetName().c_str());
4759 }
4760 
GetConfiguration()4761 std::shared_ptr<AppExecFwk::Configuration> AppMgrServiceInner::GetConfiguration()
4762 {
4763     if (multiUserConfigurationMgr_ == nullptr) {
4764         TAG_LOGE(AAFwkTag::APPMGR, "multiUserConfigurationMgr_ null");
4765         return nullptr;
4766     }
4767     int32_t userId = 0;
4768     auto errNo = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId);
4769     if (errNo != 0) {
4770         TAG_LOGE(AAFwkTag::APPMGR, "GetForegroundOsAccountLocalId failed: %{public}d", errNo);
4771         userId = USER100;
4772     }
4773     TAG_LOGD(AAFwkTag::APPMGR, "GetForegroundOsAccountLocalId userId: %{public}d", userId);
4774     return multiUserConfigurationMgr_->GetConfigurationByUserId(userId);
4775 }
4776 
KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> & appRecord)4777 void AppMgrServiceInner::KillApplicationByRecord(const std::shared_ptr<AppRunningRecord> &appRecord)
4778 {
4779     TAG_LOGD(AAFwkTag::APPMGR, "Kill application by appRecord.");
4780     if (!appRecord || !taskHandler_) {
4781         TAG_LOGW(AAFwkTag::APPMGR, "appRecord or taskHandler_ is nullptr.");
4782         return;
4783     }
4784 
4785     auto pid = appRecord->GetPriorityObject()->GetPid();
4786     appRecord->SetTerminating(appRunningManager_);
4787     appRecord->ScheduleProcessSecurityExit();
4788 
4789     auto startTime = SystemTimeMillisecond();
4790     std::list<pid_t> pids = {pid};
4791     if (WaitForRemoteProcessExit(pids, startTime)) {
4792         TAG_LOGI(AAFwkTag::APPMGR, "The remote process exited successfully");
4793         return;
4794     }
4795 
4796     auto timeoutTask = [pid, innerService = shared_from_this()]() {
4797         TAG_LOGI(AAFwkTag::APPMGR, "KillProcessByPid %{public}d", pid);
4798         int32_t result = innerService->KillProcessByPid(pid, "KillApplicationByRecord");
4799         if (result < 0) {
4800             TAG_LOGE(AAFwkTag::APPMGR, "Kill application by app record failed, pid: %{public}d", pid);
4801             return;
4802         }
4803     };
4804     taskHandler_->SubmitTask(timeoutTask, "DelayKillProcess", AMSEventHandler::KILL_PROCESS_TIMEOUT);
4805 }
4806 
SendHiSysEvent(const int32_t innerEventId,const int64_t eventId)4807 void AppMgrServiceInner::SendHiSysEvent(const int32_t innerEventId, const int64_t eventId)
4808 {
4809     TAG_LOGD(AAFwkTag::APPMGR, "called AppMgrServiceInner SendHiSysEvent!");
4810     if (!appRunningManager_) {
4811         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
4812         return;
4813     }
4814 
4815     auto appRecord = appRunningManager_->GetAppRunningRecord(eventId);
4816     if (!appRecord) {
4817         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
4818         return;
4819     }
4820     const int bufferLen = 128;
4821     char paramOutBuf[bufferLen] = {0};
4822     const char *hook_mode = "startup:";
4823     int ret = GetParameter("libc.hook_mode", "", paramOutBuf, bufferLen);
4824     if (ret > 0 && strncmp(paramOutBuf, hook_mode, strlen(hook_mode)) == 0) {
4825         TAG_LOGD(AAFwkTag::APPMGR, "SendHiSysEvent, Hook_mode: no handle time out");
4826         return;
4827     }
4828 
4829     std::string eventName = AppExecFwk::AppFreezeType::LIFECYCLE_TIMEOUT;
4830     int32_t pid = appRecord->GetPriorityObject()->GetPid();
4831     int32_t uid = appRecord->GetUid();
4832     std::string packageName = appRecord->GetBundleName();
4833     std::string processName = appRecord->GetProcessName();
4834     std::string msg = AppExecFwk::AppFreezeType::APP_LIFECYCLE_TIMEOUT;
4835     msg += ",";
4836     int typeId = AppExecFwk::AppfreezeManager::TypeAttribute::NORMAL_TIMEOUT;
4837     switch (innerEventId) {
4838         case AMSEventHandler::TERMINATE_ABILITY_TIMEOUT_MSG:
4839             msg += EVENT_MESSAGE_TERMINATE_ABILITY_TIMEOUT;
4840             break;
4841         case AMSEventHandler::TERMINATE_APPLICATION_TIMEOUT_MSG:
4842             msg += EVENT_MESSAGE_TERMINATE_APPLICATION_TIMEOUT;
4843             break;
4844         case AMSEventHandler::ADD_ABILITY_STAGE_INFO_TIMEOUT_MSG:
4845             msg += EVENT_MESSAGE_ADD_ABILITY_STAGE_INFO_TIMEOUT;
4846             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
4847             break;
4848         case AMSEventHandler::START_PROCESS_SPECIFIED_ABILITY_TIMEOUT_MSG:
4849             msg += EVENT_MESSAGE_START_PROCESS_SPECIFIED_ABILITY_TIMEOUT;
4850             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
4851             break;
4852         case AMSEventHandler::START_SPECIFIED_ABILITY_TIMEOUT_MSG:
4853             msg += EVENT_MESSAGE_START_SPECIFIED_ABILITY_TIMEOUT;
4854             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
4855             break;
4856         case AMSEventHandler::START_SPECIFIED_PROCESS_TIMEOUT_MSG:
4857             msg += EVENT_MESSAGE_START_SPECIFIED_PROCESS_TIMEOUT;
4858             typeId = AppExecFwk::AppfreezeManager::TypeAttribute::CRITICAL_TIMEOUT;
4859             break;
4860         default:
4861             msg += EVENT_MESSAGE_DEFAULT;
4862             break;
4863     }
4864 
4865     TAG_LOGW(AAFwkTag::APPMGR, "LIFECYCLE_TIMEOUT, eventName = %{public}s, uid = %{public}d, pid = %{public}d, \
4866         packageName = %{public}s, processName = %{public}s, msg = %{public}s",
4867         eventName.c_str(), uid, pid, packageName.c_str(), processName.c_str(), msg.c_str());
4868     AppfreezeManager::ParamInfo info = {
4869         .typeId = typeId,
4870         .pid = pid,
4871         .eventName = eventName,
4872         .bundleName = packageName,
4873         .msg = msg
4874     };
4875     AppfreezeManager::GetInstance()->LifecycleTimeoutHandle(info);
4876 }
4877 
GetAbilityRecordsByProcessID(const int pid,std::vector<sptr<IRemoteObject>> & tokens)4878 int AppMgrServiceInner::GetAbilityRecordsByProcessID(const int pid, std::vector<sptr<IRemoteObject>> &tokens)
4879 {
4880     auto appRecord = GetAppRunningRecordByPid(pid);
4881     if (!appRecord) {
4882         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord");
4883         return ERR_NAME_NOT_FOUND;
4884     }
4885 
4886     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
4887     auto callingPid = IPCSkeleton::GetCallingPid();
4888     if (!isSaCall && callingPid != pid) {
4889         TAG_LOGE(AAFwkTag::APPMGR, "Permission verify failed.");
4890         return ERR_PERMISSION_DENIED;
4891     }
4892     for (auto &item : appRecord->GetAbilities()) {
4893         tokens.emplace_back(item.first);
4894     }
4895     return ERR_OK;
4896 }
4897 
GetApplicationInfoByProcessID(const int pid,AppExecFwk::ApplicationInfo & application,bool & debug)4898 int AppMgrServiceInner::GetApplicationInfoByProcessID(const int pid, AppExecFwk::ApplicationInfo &application,
4899     bool &debug)
4900 {
4901     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
4902     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
4903     if (!isSaCall && !isShellCall) {
4904         TAG_LOGE(AAFwkTag::APPMGR, "no permissions.");
4905         return ERR_PERMISSION_DENIED;
4906     }
4907     auto appRecord = GetAppRunningRecordByPid(pid);
4908     if (!appRecord) {
4909         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord for PID:%{public}d", pid);
4910         return ERR_NAME_NOT_FOUND;
4911     }
4912 
4913     auto info = appRecord->GetApplicationInfo();
4914     if (info == nullptr) {
4915         TAG_LOGE(AAFwkTag::APPMGR, "ApplicationInfo is nullptr !");
4916         return ERR_NO_INIT;
4917     }
4918     application = *info;
4919     debug = appRecord->IsDebugApp();
4920     return ERR_OK;
4921 }
4922 
NotifyAppMgrRecordExitReason(int32_t pid,int32_t reason,const std::string & exitMsg)4923 int32_t AppMgrServiceInner::NotifyAppMgrRecordExitReason(int32_t pid, int32_t reason, const std::string &exitMsg)
4924 {
4925     TAG_LOGD(AAFwkTag::APPMGR, "NotifyAppMgrRecordExitReason pid:%{public}d, reason:%{public}d, exitMsg:%{public}s.",
4926         pid, reason, exitMsg.c_str());
4927     auto callerUid = IPCSkeleton::GetCallingUid();
4928     if (callerUid != FOUNDATION_UID) {
4929         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
4930         return ERR_PERMISSION_DENIED;
4931     }
4932     auto appRecord = GetAppRunningRecordByPid(pid);
4933     if (!appRecord) {
4934         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord for pid:%{public}d", pid);
4935         return ERR_NAME_NOT_FOUND;
4936     }
4937     appRecord->SetExitReason(reason);
4938     appRecord->SetExitMsg(exitMsg);
4939     return ERR_OK;
4940 }
4941 
VerifyKillProcessPermission(const std::string & bundleName) const4942 int AppMgrServiceInner::VerifyKillProcessPermission(const std::string &bundleName) const
4943 {
4944     TAG_LOGI(AAFwkTag::APPMGR, "Check Kill permission, callerUid:%{public}d, callerPid:%{public}d",
4945         IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
4946     int32_t ret = VerifyKillProcessPermissionCommon();
4947     if (ret != ERR_PERMISSION_DENIED) {
4948         return ret;
4949     }
4950 
4951     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
4952         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
4953     if (isCallingPerm) {
4954         auto callerPid = IPCSkeleton::GetCallingPid();
4955         auto appRecord = GetAppRunningRecordByPid(callerPid);
4956         if (!appRecord || appRecord->GetBundleName() != bundleName) {
4957             TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
4958             return ERR_PERMISSION_DENIED;
4959         }
4960     } else {
4961         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
4962         return ERR_PERMISSION_DENIED;
4963     }
4964 
4965     return ERR_OK;
4966 }
4967 
VerifyKillProcessPermission(const sptr<IRemoteObject> & token) const4968 int AppMgrServiceInner::VerifyKillProcessPermission(const sptr<IRemoteObject> &token) const
4969 {
4970     TAG_LOGI(AAFwkTag::APPMGR, "Check Kill permission, callerUid:%{public}d, callerPid:%{public}d",
4971         IPCSkeleton::GetCallingUid(), IPCSkeleton::GetCallingPid());
4972     int32_t ret = VerifyKillProcessPermissionCommon();
4973     if (ret != ERR_PERMISSION_DENIED) {
4974         return ret;
4975     }
4976 
4977     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
4978         AAFwk::PermissionConstants::PERMISSION_CLEAN_BACKGROUND_PROCESSES);
4979     if (isCallingPerm) {
4980         auto callerUid = IPCSkeleton::GetCallingUid();
4981         auto appRecord = GetAppRunningRecordByAbilityToken(token);
4982         if (!appRecord || appRecord->GetUid() != callerUid) {
4983             TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
4984             return ERR_PERMISSION_DENIED;
4985         }
4986     } else {
4987         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
4988         return ERR_PERMISSION_DENIED;
4989     }
4990 
4991     return ERR_OK;
4992 }
4993 
VerifyKillProcessPermissionCommon() const4994 int32_t AppMgrServiceInner::VerifyKillProcessPermissionCommon() const
4995 {
4996     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
4997         AAFwk::PermissionConstants::PERMISSION_KILL_APP_PROCESSES);
4998     if (isCallingPerm) {
4999         return ERR_OK;
5000     }
5001 
5002     // VerifyAPL and ohos.permission.CLEAN_BACKGROUND_PROCESSES will be removed on API18
5003     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
5004     auto isShellCall = AAFwk::PermissionVerification::GetInstance()->IsShellCall();
5005     if (isSaCall || isShellCall) {
5006         return ERR_OK;
5007     }
5008 
5009     if (VerifyAPL()) {
5010         return ERR_OK;
5011     }
5012 
5013     return ERR_PERMISSION_DENIED;
5014 }
5015 
CheckCallerIsAppGallery()5016 bool AppMgrServiceInner::CheckCallerIsAppGallery()
5017 {
5018     TAG_LOGD(AAFwkTag::APPMGR, "called");
5019     if (!appRunningManager_) {
5020         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
5021         return false;
5022     }
5023     auto callerPid = IPCSkeleton::GetCallingPid();
5024     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
5025     if (!appRecord) {
5026         TAG_LOGE(AAFwkTag::APPMGR, "Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
5027         return false;
5028     }
5029     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
5030     if (!bundleMgrHelper) {
5031         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
5032         return false;
5033     }
5034     auto callerBundleName = appRecord->GetBundleName();
5035     if (callerBundleName.empty()) {
5036         TAG_LOGE(AAFwkTag::APPMGR, "callerBundleName is empty.");
5037         return false;
5038     }
5039     std::string appGalleryBundleName;
5040     if (!bundleMgrHelper->QueryAppGalleryBundleName(appGalleryBundleName)) {
5041         TAG_LOGE(AAFwkTag::APPMGR, "QueryAppGalleryBundleName failed.");
5042         return false;
5043     }
5044     TAG_LOGD(AAFwkTag::APPMGR, "callerBundleName:%{public}s, appGalleryBundleName:%{public}s", callerBundleName.c_str(),
5045         appGalleryBundleName.c_str());
5046 
5047     return callerBundleName == appGalleryBundleName;
5048 }
5049 
VerifyAPL() const5050 bool AppMgrServiceInner::VerifyAPL() const
5051 {
5052     if (!appRunningManager_) {
5053         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
5054         return false;
5055     }
5056 
5057     auto callerPid = IPCSkeleton::GetCallingPid();
5058     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callerPid);
5059     if (!appRecord) {
5060         TAG_LOGE(AAFwkTag::APPMGR, "Get app running record by calling pid failed. callingPId: %{public}d", callerPid);
5061         return false;
5062     }
5063 
5064     auto applicationInfo = appRecord->GetApplicationInfo();
5065     if (!applicationInfo) {
5066         TAG_LOGE(AAFwkTag::APPMGR, "Get application info failed.");
5067         return false;
5068     }
5069 
5070     auto apl = applicationInfo->appPrivilegeLevel;
5071     if (apl != SYSTEM_BASIC && apl != SYSTEM_CORE) {
5072         TAG_LOGE(AAFwkTag::APPMGR, "caller is not system_basic or system_core.");
5073         return false;
5074     }
5075     return true;
5076 }
5077 
VerifyAccountPermission(const std::string & permissionName,const int userId) const5078 int AppMgrServiceInner::VerifyAccountPermission(const std::string &permissionName, const int userId) const
5079 {
5080     if (userId != currentUserId_) {
5081         auto isCallingPermAccount = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(
5082             AAFwk::PermissionConstants::PERMISSION_INTERACT_ACROSS_LOCAL_ACCOUNTS);
5083         if (!isCallingPermAccount) {
5084             TAG_LOGE(AAFwkTag::APPMGR, "Permission accounts verify failed");
5085             return ERR_PERMISSION_DENIED;
5086         }
5087     }
5088     auto isCallingPerm = AAFwk::PermissionVerification::GetInstance()->VerifyCallingPermission(permissionName);
5089     return isCallingPerm ? ERR_OK : ERR_PERMISSION_DENIED;
5090 }
5091 
VerifyRequestPermission() const5092 int AppMgrServiceInner::VerifyRequestPermission() const
5093 {
5094     auto callerUid = IPCSkeleton::GetCallingUid();
5095     if (callerUid == ROOT_UID || callerUid == FOUNDATION_UID) {
5096         return ERR_OK;
5097     } else {
5098         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed, callerUid: %{public}d", callerUid);
5099         return ERR_PERMISSION_DENIED;
5100     }
5101 }
5102 
PreStartNWebSpawnProcess(const pid_t hostPid)5103 int AppMgrServiceInner::PreStartNWebSpawnProcess(const pid_t hostPid)
5104 {
5105     TAG_LOGI(AAFwkTag::APPMGR, "called");
5106     if (hostPid <= 0) {
5107         TAG_LOGE(AAFwkTag::APPMGR, "invalid param, hostPid:%{public}d", hostPid);
5108         return ERR_INVALID_VALUE;
5109     }
5110 
5111     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
5112     if (!nwebSpawnClient) {
5113         TAG_LOGE(AAFwkTag::APPMGR, "nwebSpawnClient is null");
5114         return ERR_INVALID_VALUE;
5115     }
5116     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
5117         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
5118         return ERR_INVALID_OPERATION;
5119     }
5120 
5121     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(hostPid);
5122     if (!appRecord) {
5123         TAG_LOGE(AAFwkTag::APPMGR, "no such app Record, pid:%{public}d", hostPid);
5124         return ERR_INVALID_VALUE;
5125     }
5126 
5127     ErrCode errCode = nwebSpawnClient->PreStartNWebSpawnProcess();
5128     if (FAILED(errCode)) {
5129         TAG_LOGE(AAFwkTag::APPMGR, "failed to spawn new render process, errCode %{public}08x", errCode);
5130         return ERR_INVALID_VALUE;
5131     }
5132 
5133     return 0;
5134 }
5135 
StartRenderProcess(const pid_t hostPid,const std::string & renderParam,int32_t ipcFd,int32_t sharedFd,int32_t crashFd,pid_t & renderPid,bool isGPU)5136 int AppMgrServiceInner::StartRenderProcess(const pid_t hostPid, const std::string &renderParam,
5137     int32_t ipcFd, int32_t sharedFd, int32_t crashFd, pid_t &renderPid, bool isGPU)
5138 {
5139     TAG_LOGI(AAFwkTag::APPMGR, "start render process, hostPid:%{public}d", hostPid);
5140     if (hostPid <= 0 || renderParam.empty() || ipcFd <= 0 || sharedFd <= 0 || crashFd <= 0) {
5141         TAG_LOGE(AAFwkTag::APPMGR, "invalid param: hostPid:%{public}d renderParam:%{private}s "
5142                     "ipcFd:%{public}d  crashFd:%{public}d sharedFd:%{public}d",
5143             hostPid, renderParam.c_str(), ipcFd, crashFd, sharedFd);
5144         return ERR_INVALID_VALUE;
5145     }
5146 
5147     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_INVALID_VALUE);
5148     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
5149         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
5150         return ERR_INVALID_OPERATION;
5151     }
5152 
5153     auto appRecord = GetAppRunningRecordByPid(hostPid);
5154     CHECK_POINTER_AND_RETURN_VALUE(appRecord, ERR_INVALID_VALUE);
5155 
5156     auto renderRecordMap = appRecord->GetRenderRecordMap();
5157     if (!isGPU && !renderRecordMap.empty() && !AAFwk::AppUtils::GetInstance().IsUseMultiRenderProcess()) {
5158         for (auto iter : renderRecordMap) {
5159             if (iter.second != nullptr) {
5160                 renderPid = iter.second->GetPid();
5161                 if (ProcessExist(renderPid)) {
5162                     TAG_LOGW(AAFwkTag::APPMGR,
5163                         "already exist render process,do not request again, renderPid:%{public}d", renderPid);
5164                     return ERR_ALREADY_EXIST_RENDER;
5165                 }
5166                 auto scheduler = iter.second->GetScheduler();
5167                 if (scheduler) {
5168                     TAG_LOGW(AAFwkTag::APPMGR, "render process not realy exist, renderPid:%{public}d", renderPid);
5169                     OnRenderRemoteDied(scheduler->AsObject());
5170                 }
5171             }
5172         }
5173     }
5174     appRecord->SetIsGPU(isGPU);
5175     int32_t childNumLimit = appRecord->GetIsGPU() ? PHONE_MAX_RENDER_PROCESS_NUM + 1 : PHONE_MAX_RENDER_PROCESS_NUM;
5176     // The phone device allows a maximum of 40 render processes to be created.
5177     if (AAFwk::AppUtils::GetInstance().IsLimitMaximumOfRenderProcess() &&
5178         renderRecordMap.size() >= static_cast<uint32_t>(childNumLimit)) {
5179         TAG_LOGE(AAFwkTag::APPMGR, "Reaching the maximum render process limitation, hostPid:%{public}d", hostPid);
5180         return ERR_REACHING_MAXIMUM_RENDER_PROCESS_LIMITATION;
5181     }
5182 
5183     auto renderRecord = RenderRecord::CreateRenderRecord(hostPid, renderParam, ipcFd, sharedFd, crashFd, appRecord);
5184     if (!renderRecord) {
5185         TAG_LOGE(AAFwkTag::APPMGR, "create render record failed, hostPid:%{public}d", hostPid);
5186         return ERR_INVALID_VALUE;
5187     }
5188 
5189     return StartRenderProcessImpl(renderRecord, appRecord, renderPid, isGPU);
5190 }
5191 
AttachRenderProcess(const pid_t pid,const sptr<IRenderScheduler> & scheduler)5192 void AppMgrServiceInner::AttachRenderProcess(const pid_t pid, const sptr<IRenderScheduler> &scheduler)
5193 {
5194     TAG_LOGI(AAFwkTag::APPMGR, "attach render process start");
5195     if (pid <= 0) {
5196         TAG_LOGE(AAFwkTag::APPMGR, "invalid render process pid:%{public}d", pid);
5197         return;
5198     }
5199     if (!scheduler) {
5200         TAG_LOGE(AAFwkTag::APPMGR, "render scheduler is null");
5201         return;
5202     }
5203 
5204     if (!appRunningManager_) {
5205         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
5206         return;
5207     }
5208 
5209     TAG_LOGI(AAFwkTag::APPMGR, "attach render process pid:%{public}d", pid);
5210     auto appRecord = appRunningManager_->GetAppRunningRecordByRenderPid(pid);
5211     if (!appRecord) {
5212         TAG_LOGE(AAFwkTag::APPMGR, "no such app Record, pid:%{public}d", pid);
5213         return;
5214     }
5215 
5216     auto renderRecord = appRecord->GetRenderRecordByPid(pid);
5217     if (!renderRecord) {
5218         TAG_LOGE(AAFwkTag::APPMGR, "no such render Record, pid:%{public}d", pid);
5219         return;
5220     }
5221 
5222     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
5223     appDeathRecipient->SetTaskHandler(taskHandler_);
5224     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
5225     appDeathRecipient->SetIsRenderProcess(true);
5226     renderRecord->SetScheduler(scheduler);
5227     renderRecord->SetDeathRecipient(appDeathRecipient);
5228     renderRecord->RegisterDeathRecipient();
5229 
5230     // notify fd to render process
5231     if (appRecord->GetBrowserHost() != nullptr && appRecord->GetIsGPU()) {
5232         TAG_LOGD(AAFwkTag::APPMGR, "GPU has host remote object");
5233         scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(),
5234             renderRecord->GetSharedFd(), renderRecord->GetCrashFd(), appRecord->GetBrowserHost());
5235     } else {
5236         scheduler->NotifyBrowserFd(renderRecord->GetIpcFd(),
5237             renderRecord->GetSharedFd(), renderRecord->GetCrashFd(), nullptr);
5238     }
5239 }
5240 
SaveBrowserChannel(const pid_t hostPid,sptr<IRemoteObject> browser)5241 void AppMgrServiceInner::SaveBrowserChannel(const pid_t hostPid, sptr<IRemoteObject> browser)
5242 {
5243     std::lock_guard<ffrt::mutex> lock(browserHostLock_);
5244     TAG_LOGD(AAFwkTag::APPMGR, "save browser channel.");
5245     auto appRecord = GetAppRunningRecordByPid(hostPid);
5246     if (!appRecord) {
5247         TAG_LOGE(AAFwkTag::APPMGR, "save browser host no such appRecord, pid:%{public}d",
5248             hostPid);
5249         return;
5250     }
5251     appRecord->SetBrowserHost(browser);
5252 }
5253 
GenerateRenderUid(int32_t & renderUid)5254 bool AppMgrServiceInner::GenerateRenderUid(int32_t &renderUid)
5255 {
5256     std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
5257     int32_t uid = lastRenderUid_ + 1;
5258     bool needSecondScan = true;
5259     if (uid > Constants::END_UID_FOR_RENDER_PROCESS) {
5260         uid = Constants::START_UID_FOR_RENDER_PROCESS;
5261         needSecondScan = false;
5262     }
5263 
5264     if (renderUidSet_.empty()) {
5265         renderUid = uid;
5266         renderUidSet_.insert(renderUid);
5267         lastRenderUid_ = renderUid;
5268         return true;
5269     }
5270 
5271     for (int32_t i = uid; i <= Constants::END_UID_FOR_RENDER_PROCESS; i++) {
5272         if (renderUidSet_.find(i) == renderUidSet_.end()) {
5273             renderUid = i;
5274             renderUidSet_.insert(renderUid);
5275             lastRenderUid_ = renderUid;
5276             return true;
5277         }
5278     }
5279 
5280     if (needSecondScan) {
5281         for (int32_t i = Constants::START_UID_FOR_RENDER_PROCESS; i <= lastRenderUid_; i++) {
5282             if (renderUidSet_.find(i) == renderUidSet_.end()) {
5283                 renderUid = i;
5284                 renderUidSet_.insert(renderUid);
5285                 lastRenderUid_ = renderUid;
5286                 return true;
5287             }
5288         }
5289     }
5290 
5291     return false;
5292 }
5293 
StartRenderProcessImpl(const std::shared_ptr<RenderRecord> & renderRecord,const std::shared_ptr<AppRunningRecord> appRecord,pid_t & renderPid,bool isGPU)5294 int AppMgrServiceInner::StartRenderProcessImpl(const std::shared_ptr<RenderRecord> &renderRecord,
5295     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &renderPid, bool isGPU)
5296 {
5297     if (!renderRecord || !appRecord) {
5298         TAG_LOGE(AAFwkTag::APPMGR, "null renderRecord or appRecord");
5299         return ERR_INVALID_VALUE;
5300     }
5301 
5302     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
5303     if (!nwebSpawnClient) {
5304         TAG_LOGE(AAFwkTag::APPMGR, "nwebSpawnClient is null");
5305         AppMgrEventUtil::SendRenderProcessStartFailedEvent(renderRecord,
5306             ProcessStartFailedReason::GET_SPAWN_CLIENT_FAILED, ERR_INVALID_VALUE);
5307         return ERR_INVALID_VALUE;
5308     }
5309     int32_t renderUid = Constants::INVALID_UID;
5310     if (!GenerateRenderUid(renderUid)) {
5311         TAG_LOGE(AAFwkTag::APPMGR, "Generate renderUid failed");
5312         AppMgrEventUtil::SendRenderProcessStartFailedEvent(renderRecord,
5313             ProcessStartFailedReason::GENERATE_RENDER_UID_FAILED, ERR_INVALID_OPERATION);
5314         return ERR_INVALID_OPERATION;
5315     }
5316     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
5317     SetRenderStartMsg(startMsg, renderRecord, renderUid, isGPU);
5318     pid_t pid = 0;
5319     ErrCode errCode = nwebSpawnClient->StartProcess(startMsg, pid);
5320     if (FAILED(errCode)) {
5321         TAG_LOGE(AAFwkTag::APPMGR, "failed to spawn new render process, errCode %{public}08x", errCode);
5322         std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
5323         renderUidSet_.erase(renderUid);
5324         AppMgrEventUtil::SendRenderProcessStartFailedEvent(renderRecord,
5325             ProcessStartFailedReason::APPSPAWN_FAILED, static_cast<int32_t>(errCode));
5326         return ERR_INVALID_VALUE;
5327     }
5328     renderPid = pid;
5329     renderRecord->SetPid(pid);
5330     renderRecord->SetUid(renderUid);
5331     if (isGPU) {
5332         renderRecord->SetProcessType(ProcessType::GPU);
5333         appRecord->SetGPUPid(pid);
5334     }
5335     appRecord->AddRenderRecord(renderRecord);
5336     TAG_LOGI(AAFwkTag::APPMGR,
5337         "start render process success, hostPid:%{public}d, hostUid:%{public}d, pid:%{public}d, uid:%{public}d",
5338         renderRecord->GetHostPid(), renderRecord->GetHostUid(), pid, renderUid);
5339     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessCreated(renderRecord);
5340     return 0;
5341 }
5342 
SetRenderStartMsg(AppSpawnStartMsg & startMsg,std::shared_ptr<RenderRecord> renderRecord,const int32_t renderUid,const bool isGPU)5343 void AppMgrServiceInner::SetRenderStartMsg(AppSpawnStartMsg &startMsg, std::shared_ptr<RenderRecord> renderRecord,
5344     const int32_t renderUid, const bool isGPU)
5345 {
5346     startMsg.renderParam = renderRecord->GetRenderParam();
5347     startMsg.uid = renderUid;
5348     startMsg.gid = renderUid;
5349     if (isGPU) {
5350         startMsg.procName += GPU_PROCESS_NAME;
5351         startMsg.processType = GPU_PROCESS_TYPE;
5352     } else {
5353         startMsg.procName += RENDER_PROCESS_NAME;
5354         startMsg.processType = RENDER_PROCESS_TYPE;
5355     }
5356     startMsg.code = 0; // 0: DEFAULT
5357 }
5358 
GetRenderProcessTerminationStatus(pid_t renderPid,int & status)5359 int AppMgrServiceInner::GetRenderProcessTerminationStatus(pid_t renderPid, int &status)
5360 {
5361     auto callingPid = IPCSkeleton::GetCallingPid();
5362     TAG_LOGD(AAFwkTag::APPMGR, "GetRenderProcessTerminationStatus, callingPid:%{public}d, renderPid:%{public}d",
5363         callingPid, renderPid);
5364     if (!appRunningManager_) {
5365         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
5366         return ERR_INVALID_VALUE;
5367     }
5368     auto hostRecord = appRunningManager_->GetAppRunningRecordByPid(callingPid);
5369     if (!hostRecord) {
5370         TAG_LOGE(AAFwkTag::APPMGR, "hostRecord is nullptr.");
5371         return ERR_INVALID_VALUE;
5372     }
5373     if (!hostRecord->ConstainsRenderPid(renderPid)) {
5374         TAG_LOGE(AAFwkTag::APPMGR,
5375             "Permission denied, caller is not renderPid host, callingPid:%{public}d, renderPid:%{public}d.",
5376             callingPid, renderPid);
5377         return ERR_PERMISSION_DENIED;
5378     }
5379     if (remoteClientManager_ == nullptr) {
5380         TAG_LOGE(AAFwkTag::APPMGR, "remoteClientManager_ is null");
5381         return ERR_INVALID_VALUE;
5382     }
5383     auto nwebSpawnClient = remoteClientManager_->GetNWebSpawnClient();
5384     if (!nwebSpawnClient) {
5385         TAG_LOGE(AAFwkTag::APPMGR, "nwebSpawnClient is null");
5386         return ERR_INVALID_VALUE;
5387     }
5388 
5389     AppSpawnStartMsg startMsg;
5390     startMsg.pid = renderPid;
5391     startMsg.code = MSG_GET_RENDER_TERMINATION_STATUS;
5392     ErrCode errCode = nwebSpawnClient->GetRenderProcessTerminationStatus(startMsg, status);
5393     if (FAILED(errCode)) {
5394         TAG_LOGE(AAFwkTag::APPMGR, "failed to get render process termination status, errCode %{public}08x", errCode);
5395         return ERR_INVALID_VALUE;
5396     }
5397     TAG_LOGD(AAFwkTag::APPMGR, "Get render process termination status success, renderPid:%{public}d, status:%{public}d",
5398         renderPid, status);
5399     hostRecord->RemoveRenderPid(renderPid);
5400     RemoveRenderRecordNoAttach(hostRecord, renderPid);
5401     return 0;
5402 }
5403 
RemoveRenderRecordNoAttach(const std::shared_ptr<AppRunningRecord> & hostRecord,int32_t renderPid)5404 void AppMgrServiceInner::RemoveRenderRecordNoAttach(const std::shared_ptr<AppRunningRecord> &hostRecord,
5405     int32_t renderPid)
5406 {
5407     if (!hostRecord) {
5408         TAG_LOGE(AAFwkTag::APPMGR, "hostRecord null");
5409         return;
5410     }
5411     auto renderRecord = hostRecord->GetRenderRecordByPid(renderPid);
5412     if (!renderRecord) {
5413         TAG_LOGD(AAFwkTag::APPMGR, "renderRecord null");
5414         return;
5415     }
5416     if (renderRecord->GetScheduler() == nullptr) {
5417         hostRecord->RemoveRenderRecord(renderRecord);
5418         {
5419             std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
5420             renderUidSet_.erase(renderRecord->GetUid());
5421         }
5422         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
5423     }
5424 }
5425 
OnRenderRemoteDied(const wptr<IRemoteObject> & remote)5426 void AppMgrServiceInner::OnRenderRemoteDied(const wptr<IRemoteObject> &remote)
5427 {
5428     TAG_LOGE(AAFwkTag::APPMGR, "On render remote died.");
5429     if (appRunningManager_) {
5430         auto renderRecord = appRunningManager_->OnRemoteRenderDied(remote);
5431         if (renderRecord) {
5432             {
5433                 std::lock_guard<ffrt::mutex> lock(renderUidSetLock_);
5434                 renderUidSet_.erase(renderRecord->GetUid());
5435             }
5436             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
5437         }
5438     }
5439 }
5440 
AddWatchParameter()5441 void AppMgrServiceInner::AddWatchParameter()
5442 {
5443     TAG_LOGI(AAFwkTag::APPMGR, "called");
5444     auto context = new (std::nothrow) std::weak_ptr<AppMgrServiceInner>(shared_from_this());
5445     int ret = WatchParameter(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, PointerDeviceEventCallback,
5446         context);
5447     if (ret != 0) {
5448         TAG_LOGE(AAFwkTag::APPMGR, "watch parameter %{public}s failed with %{public}d.",
5449             AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, ret);
5450     }
5451 }
5452 
InitFocusListener()5453 void AppMgrServiceInner::InitFocusListener()
5454 {
5455     TAG_LOGI(AAFwkTag::APPMGR, "begin initFocus listener.");
5456     if (focusListener_) {
5457         return;
5458     }
5459 
5460     focusListener_ = new WindowFocusChangedListener(shared_from_this(), taskHandler_);
5461     auto registerTask = [innerService = shared_from_this()]() {
5462         if (innerService) {
5463             TAG_LOGI(AAFwkTag::APPMGR, "RegisterFocusListener task");
5464             innerService->RegisterFocusListener();
5465         }
5466     };
5467     if (taskHandler_) {
5468         taskHandler_->SubmitTask(registerTask, "RegisterFocusListenerTask", REGISTER_FOCUS_DELAY);
5469         TAG_LOGI(AAFwkTag::APPMGR, "Submit RegisterFocusListenerTask");
5470     }
5471 }
5472 
RegisterFocusListener()5473 void AppMgrServiceInner::RegisterFocusListener()
5474 {
5475     TAG_LOGI(AAFwkTag::APPMGR, "RegisterFocusListener begin");
5476     if (!focusListener_) {
5477         TAG_LOGE(AAFwkTag::APPMGR, "no focusListener_");
5478         return;
5479     }
5480     WindowManager::GetInstance().RegisterFocusChangedListener(focusListener_);
5481     TAG_LOGI(AAFwkTag::APPMGR, "RegisterFocusListener end");
5482 }
5483 
FreeFocusListener()5484 void AppMgrServiceInner::FreeFocusListener()
5485 {
5486     TAG_LOGI(AAFwkTag::APPMGR, "FreeFocusListener begin");
5487     if (!focusListener_) {
5488         TAG_LOGE(AAFwkTag::APPMGR, "no focusListener_");
5489         return;
5490     }
5491     WindowManager::GetInstance().UnregisterFocusChangedListener(focusListener_);
5492     focusListener_ = nullptr;
5493     TAG_LOGI(AAFwkTag::APPMGR, "FreeFocusListener end");
5494 }
5495 
HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)5496 void AppMgrServiceInner::HandleFocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
5497 {
5498     if (!focusChangeInfo) {
5499         TAG_LOGW(AAFwkTag::APPMGR, "focused, invalid focusChangeInfo");
5500         return;
5501     }
5502     TAG_LOGI(AAFwkTag::APPMGR, "focused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
5503 
5504     if (focusChangeInfo->pid_ <= 0) {
5505         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}d", focusChangeInfo->pid_);
5506         return;
5507     }
5508 
5509     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
5510     if (!appRecord) {
5511         TAG_LOGE(AAFwkTag::APPMGR, "focused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
5512         return;
5513     }
5514 
5515     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, true)) {
5516         TAG_LOGD(
5517             AAFwkTag::APPMGR, "only change ability focus state, do not change process or application focus state.");
5518         return;
5519     }
5520 
5521     bool needNotifyApp = appRunningManager_->IsApplicationFirstFocused(*appRecord);
5522     if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
5523         OnAppStateChanged(appRecord, ApplicationState::APP_STATE_FOREGROUND, needNotifyApp, true);
5524     }
5525     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
5526 }
5527 
HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> & focusChangeInfo)5528 void AppMgrServiceInner::HandleUnfocused(const sptr<OHOS::Rosen::FocusChangeInfo> &focusChangeInfo)
5529 {
5530     if (!focusChangeInfo) {
5531         TAG_LOGW(AAFwkTag::APPMGR, "unfocused, invalid focusChangeInfo");
5532         return;
5533     }
5534     TAG_LOGD(
5535         AAFwkTag::APPMGR, "unfocused, uid:%{public}d, pid:%{public}d", focusChangeInfo->uid_, focusChangeInfo->pid_);
5536 
5537     if (focusChangeInfo->pid_ <= 0) {
5538         TAG_LOGE(AAFwkTag::APPMGR, "invalid pid:%{public}d", focusChangeInfo->pid_);
5539         return;
5540     }
5541 
5542     auto appRecord = GetAppRunningRecordByPid(focusChangeInfo->pid_);
5543     if (!appRecord) {
5544         TAG_LOGE(AAFwkTag::APPMGR, "unfocused, no such appRecord, pid:%{public}d", focusChangeInfo->pid_);
5545         return;
5546     }
5547 
5548     if (!appRecord->UpdateAbilityFocusState(focusChangeInfo->abilityToken_, false)) {
5549         TAG_LOGD(AAFwkTag::APPMGR,
5550             "only change ability from focus to unfocus, do not change process or application focus state.");
5551         return;
5552     }
5553 
5554     bool needNotifyApp = appRunningManager_->IsApplicationUnfocused(appRecord->GetBundleName());
5555     OnAppStateChanged(appRecord, appRecord->GetState(), needNotifyApp, true);
5556     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
5557 }
5558 
InitWindowVisibilityChangedListener()5559 void AppMgrServiceInner::InitWindowVisibilityChangedListener()
5560 {
5561     TAG_LOGD(AAFwkTag::APPMGR, "Begin.");
5562     if (windowVisibilityChangedListener_ != nullptr) {
5563         TAG_LOGW(AAFwkTag::APPMGR, "Visibility listener has been initiated.");
5564         return;
5565     }
5566     windowVisibilityChangedListener_ =
5567         new (std::nothrow) WindowVisibilityChangedListener(weak_from_this(), taskHandler_);
5568     auto registerTask = [innerService = weak_from_this()] () {
5569         auto inner = innerService.lock();
5570         if (inner == nullptr) {
5571             TAG_LOGE(AAFwkTag::APPMGR, "Service inner is nullptr.");
5572             return;
5573         }
5574         if (inner->windowVisibilityChangedListener_ == nullptr) {
5575             TAG_LOGE(AAFwkTag::APPMGR, "Window visibility changed listener is nullptr.");
5576             return;
5577         }
5578         WindowManager::GetInstance().RegisterVisibilityChangedListener(inner->windowVisibilityChangedListener_);
5579     };
5580 
5581     if (taskHandler_ == nullptr) {
5582         TAG_LOGE(AAFwkTag::APPMGR, "Task handler is nullptr.");
5583         return;
5584     }
5585     taskHandler_->SubmitTask(registerTask, "RegisterVisibilityListener.", REGISTER_VISIBILITY_DELAY);
5586     TAG_LOGD(AAFwkTag::APPMGR, "End.");
5587 }
5588 
FreeWindowVisibilityChangedListener()5589 void AppMgrServiceInner::FreeWindowVisibilityChangedListener()
5590 {
5591     TAG_LOGD(AAFwkTag::APPMGR, "called");
5592     if (windowVisibilityChangedListener_ == nullptr) {
5593         TAG_LOGW(AAFwkTag::APPMGR, "Visibility listener has been freed.");
5594         return;
5595     }
5596     WindowManager::GetInstance().UnregisterVisibilityChangedListener(windowVisibilityChangedListener_);
5597 }
5598 
HandleWindowVisibilityChanged(const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> & windowVisibilityInfos)5599 void AppMgrServiceInner::HandleWindowVisibilityChanged(
5600     const std::vector<sptr<OHOS::Rosen::WindowVisibilityInfo>> &windowVisibilityInfos)
5601 {
5602     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5603     TAG_LOGD(AAFwkTag::APPMGR, "called");
5604     if (windowVisibilityInfos.empty()) {
5605         TAG_LOGW(AAFwkTag::APPMGR, "Window visibility info is empty.");
5606         return;
5607     }
5608     if (appRunningManager_ == nullptr) {
5609         TAG_LOGE(AAFwkTag::APPMGR, "App running manager is nullptr.");
5610         return;
5611     }
5612     appRunningManager_->OnWindowVisibilityChanged(windowVisibilityInfos);
5613 }
5614 
PointerDeviceEventCallback(const char * key,const char * value,void * context)5615 void AppMgrServiceInner::PointerDeviceEventCallback(const char *key, const char *value, void *context)
5616 {
5617     TAG_LOGI(AAFwkTag::APPMGR, "called");
5618     auto weak = static_cast<std::weak_ptr<AppMgrServiceInner>*>(context);
5619     if (weak == nullptr) {
5620         TAG_LOGE(AAFwkTag::APPMGR, "context is nullptr.");
5621         return;
5622     }
5623 
5624     auto appMgrServiceInner = weak->lock();
5625     if (appMgrServiceInner == nullptr) {
5626         TAG_LOGE(AAFwkTag::APPMGR, "app manager service inner is nullptr.");
5627         return;
5628     }
5629 
5630     if ((strcmp(key, AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE) != 0) ||
5631         ((strcmp(value, "true") != 0) && (strcmp(value, "false") != 0))) {
5632         TAG_LOGE(AAFwkTag::APPMGR, "key %{public}s or value %{public}s mismatch.", key, value);
5633         return;
5634     }
5635 
5636     Configuration changeConfig;
5637     if (!changeConfig.AddItem(AAFwk::GlobalConfigurationKey::INPUT_POINTER_DEVICE, value)) {
5638         TAG_LOGE(AAFwkTag::APPMGR, "add %{public}s item to configuration failed.", key);
5639         return;
5640     }
5641 
5642     TAG_LOGD(AAFwkTag::APPMGR, "update config %{public}s to %{public}s", key, value);
5643     auto result = IN_PROCESS_CALL(appMgrServiceInner->UpdateConfiguration(changeConfig));
5644     if (result != 0) {
5645         TAG_LOGE(AAFwkTag::APPMGR, "update config failed with %{public}d, key: %{public}s, value: %{public}s.", result,
5646             key, value);
5647         return;
5648     }
5649 }
5650 
GetAppRunningStateByBundleName(const std::string & bundleName)5651 bool AppMgrServiceInner::GetAppRunningStateByBundleName(const std::string &bundleName)
5652 {
5653     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5654     TAG_LOGD(AAFwkTag::APPMGR, "called");
5655     if (!appRunningManager_) {
5656         TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr.");
5657         return false;
5658     }
5659 
5660     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
5661         TAG_LOGE(AAFwkTag::APPMGR, "Permission deny, not SA.");
5662         return false;
5663     }
5664 
5665     return appRunningManager_->GetAppRunningStateByBundleName(bundleName);
5666 }
5667 
NotifyLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)5668 int32_t AppMgrServiceInner::NotifyLoadRepairPatch(const std::string &bundleName,
5669     const sptr<IQuickFixCallback> &callback)
5670 {
5671     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5672     TAG_LOGD(AAFwkTag::APPMGR, "called");
5673     if (!appRunningManager_) {
5674         TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr.");
5675         return ERR_INVALID_OPERATION;
5676     }
5677 
5678     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
5679         TAG_LOGE(AAFwkTag::APPMGR, "Permission deny, not quick_fix.");
5680         return ERR_PERMISSION_DENIED;
5681     }
5682 
5683     return appRunningManager_->NotifyLoadRepairPatch(bundleName, callback);
5684 }
5685 
NotifyHotReloadPage(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)5686 int32_t AppMgrServiceInner::NotifyHotReloadPage(const std::string &bundleName, const sptr<IQuickFixCallback> &callback)
5687 {
5688     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5689     TAG_LOGD(AAFwkTag::APPMGR, "called");
5690     if (!appRunningManager_) {
5691         TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr.");
5692         return ERR_INVALID_OPERATION;
5693     }
5694 
5695     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
5696         TAG_LOGE(AAFwkTag::APPMGR, "Permission deny, not quick_fix.");
5697         return ERR_PERMISSION_DENIED;
5698     }
5699 
5700     return appRunningManager_->NotifyHotReloadPage(bundleName, callback);
5701 }
5702 
5703 #ifdef BGTASKMGR_CONTINUOUS_TASK_ENABLE
SetContinuousTaskProcess(int32_t pid,bool isContinuousTask)5704 int32_t AppMgrServiceInner::SetContinuousTaskProcess(int32_t pid, bool isContinuousTask)
5705 {
5706     if (!appRunningManager_) {
5707         TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr.");
5708         return ERR_INVALID_OPERATION;
5709     }
5710 
5711     auto appRecord = appRunningManager_->GetAppRunningRecordByPid(pid);
5712     if (!appRecord) {
5713         TAG_LOGE(AAFwkTag::APPMGR, "Get app running record by pid failed. pid: %{public}d", pid);
5714         return ERR_INVALID_VALUE;
5715     }
5716     appRecord->SetContinuousTaskAppState(isContinuousTask);
5717     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessStateChanged(appRecord);
5718 
5719     return ERR_OK;
5720 }
5721 #endif
5722 
NotifyUnLoadRepairPatch(const std::string & bundleName,const sptr<IQuickFixCallback> & callback)5723 int32_t AppMgrServiceInner::NotifyUnLoadRepairPatch(const std::string &bundleName,
5724     const sptr<IQuickFixCallback> &callback)
5725 {
5726     HITRACE_METER_NAME(HITRACE_TAG_ABILITY_MANAGER, __PRETTY_FUNCTION__);
5727     TAG_LOGD(AAFwkTag::APPMGR, "called");
5728     if (!appRunningManager_) {
5729         TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr.");
5730         return ERR_INVALID_OPERATION;
5731     }
5732 
5733     if (IPCSkeleton::GetCallingUid() != QUICKFIX_UID) {
5734         TAG_LOGE(AAFwkTag::APPMGR, "Permission deny, not quick_fix.");
5735         return ERR_PERMISSION_DENIED;
5736     }
5737 
5738     return appRunningManager_->NotifyUnLoadRepairPatch(bundleName, callback);
5739 }
5740 
AppRecoveryNotifyApp(int32_t pid,const std::string & bundleName,FaultDataType faultType,const std::string & markers)5741 void AppMgrServiceInner::AppRecoveryNotifyApp(int32_t pid, const std::string& bundleName,
5742     FaultDataType faultType, const std::string& markers)
5743 {
5744     if (faultType != FaultDataType::APP_FREEZE) {
5745         TAG_LOGI(AAFwkTag::APPMGR,
5746             "AppRecovery NotifyApp to kill is: bundleName: %{public}s, faultType: "
5747             "%{public}d, pid: %{public}d", bundleName.c_str(), faultType, pid);
5748         KillProcessByPid(pid, "AppRecoveryNotifyApp");
5749         return;
5750     }
5751 
5752     std::string timeOutName = "waitSaveTask" + std::to_string(pid) + bundleName;
5753     if (markers == "appRecovery") {
5754         TAG_LOGI(AAFwkTag::APPMGR, "waitSaveTask finish, but not kill process "
5755             "immediately, wait for dump stack util 2s timeout");
5756         return;
5757     }
5758 
5759     if (markers != "recoveryTimeout") {
5760         return;
5761     }
5762     auto waitSaveTask = [pid, bundleName, innerService = shared_from_this()]() {
5763         auto appRecord = innerService->GetAppRunningRecordByPid(pid);
5764         if (appRecord == nullptr) {
5765             TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord");
5766             return;
5767         }
5768         std::string name = appRecord->GetBundleName();
5769         if (bundleName == name) {
5770             TAG_LOGI(AAFwkTag::APPMGR,
5771                 "waitSaveTask timeout %{public}s,pid == %{public}d is going to exit due to AppRecovery.",
5772                 bundleName.c_str(), pid);
5773             innerService->KillProcessByPid(pid, "AppRecoveryNotifyApp");
5774         }
5775     };
5776     constexpr int32_t timeOut = 2000;
5777     taskHandler_->SubmitTask(waitSaveTask, timeOutName, timeOut);
5778 }
5779 
NotifyAppFault(const FaultData & faultData)5780 int32_t AppMgrServiceInner::NotifyAppFault(const FaultData &faultData)
5781 {
5782     TAG_LOGI(AAFwkTag::APPMGR, "called");
5783     int32_t callerUid = IPCSkeleton::GetCallingUid();
5784     int32_t pid = IPCSkeleton::GetCallingPid();
5785     auto appRecord = GetAppRunningRecordByPid(pid);
5786     if (appRecord == nullptr) {
5787         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord");
5788         return ERR_INVALID_VALUE;
5789     }
5790     if (appRecord->GetState() == ApplicationState::APP_STATE_TERMINATED ||
5791         appRecord->GetState() == ApplicationState::APP_STATE_END) {
5792         TAG_LOGE(AAFwkTag::APPMGR, "Appfreeze detect end.");
5793         return ERR_OK;
5794     }
5795     std::string bundleName = appRecord->GetBundleName();
5796     std::string processName = appRecord->GetProcessName();
5797     if (AppExecFwk::AppfreezeManager::GetInstance()->IsProcessDebug(pid, bundleName)) {
5798         TAG_LOGW(AAFwkTag::APPMGR,
5799             "don't report event and kill:%{public}s, pid:%{public}d, bundleName:%{public}s",
5800             faultData.errorObject.name.c_str(), pid, bundleName.c_str());
5801         return ERR_OK;
5802     }
5803 
5804     if (faultData.faultType == FaultDataType::APP_FREEZE) {
5805         if (CheckAppFault(appRecord, faultData)) {
5806             return ERR_OK;
5807         }
5808 
5809         if (faultData.waitSaveState) {
5810             AppRecoveryNotifyApp(pid, bundleName, FaultDataType::APP_FREEZE, "recoveryTimeout");
5811         }
5812     }
5813 
5814     auto notifyAppTask = [appRecord, pid, callerUid, bundleName, processName, faultData,
5815         innerService = shared_from_this()]() {
5816         if (faultData.faultType == FaultDataType::APP_FREEZE) {
5817             AppfreezeManager::AppInfo info = {
5818                 .pid = pid,
5819                 .uid = callerUid,
5820                 .bundleName = bundleName,
5821                 .processName = processName,
5822             };
5823             AppExecFwk::AppfreezeManager::GetInstance()->AppfreezeHandleWithStack(faultData, info);
5824         }
5825 
5826         TAG_LOGW(AAFwkTag::APPMGR,
5827             "name: %{public}s, faultType: %{public}d, uid: %{public}d, pid: %{public}d, bundleName: %{public}s,"
5828             " processName: %{public}s, faultData.forceExit==%{public}d, faultData.waitSaveState==%{public}d",
5829             faultData.errorObject.name.c_str(), faultData.faultType, callerUid, pid, bundleName.c_str(),
5830             processName.c_str(), faultData.forceExit, faultData.waitSaveState);
5831     };
5832 
5833     if (!dfxTaskHandler_) {
5834         TAG_LOGW(AAFwkTag::APPMGR, "get dfx ffrt handler failed!");
5835         return ERR_INVALID_VALUE;
5836     }
5837 
5838     dfxTaskHandler_->SubmitTask(notifyAppTask, "NotifyAppFaultTask");
5839     constexpr int delayTime = 15 * 1000; // 15s
5840     auto task = [pid, innerService = shared_from_this()]() {
5841         AppExecFwk::AppfreezeManager::GetInstance()->DeleteStack(pid);
5842     };
5843     dfxTaskHandler_->SubmitTask(task, "DeleteStack", delayTime);
5844 
5845     if (appRecord->GetApplicationInfo()->asanEnabled) {
5846         TAG_LOGI(AAFwkTag::APPMGR,
5847             "FaultData %{public}s, pid == %{public}d is asan app, don't kill.", bundleName.c_str(), pid);
5848         return ERR_OK;
5849     }
5850 
5851 #ifdef APP_NO_RESPONSE_DIALOG
5852     // A dialog box is displayed when the PC appfreeze
5853     bool isDialogExist = appRunningManager_ ?
5854         appRunningManager_->CheckAppRunningRecordIsExist(APP_NO_RESPONSE_BUNDLENAME, APP_NO_RESPONSE_ABILITY) : false;
5855     auto killFaultApp = std::bind(&AppMgrServiceInner::KillFaultApp, this, pid, bundleName, faultData, false);
5856     ModalSystemAppFreezeUIExtension::GetInstance().ProcessAppFreeze(appRecord->GetFocusFlag(), faultData,
5857         std::to_string(pid), bundleName, killFaultApp, isDialogExist);
5858 #else
5859     KillFaultApp(pid, bundleName, faultData);
5860 #endif
5861 
5862     return ERR_OK;
5863 }
5864 
CheckAppFault(const std::shared_ptr<AppRunningRecord> & appRecord,const FaultData & faultData)5865 bool AppMgrServiceInner::CheckAppFault(const std::shared_ptr<AppRunningRecord> &appRecord, const FaultData &faultData)
5866 {
5867     if (faultData.timeoutMarkers != "" && !dfxTaskHandler_->CancelTask(faultData.timeoutMarkers)) {
5868         return true;
5869     }
5870 
5871     if (appRecord->IsDebugging()) {
5872         return true;
5873     }
5874     return false;
5875 }
5876 
KillFaultApp(int32_t pid,const std::string & bundleName,const FaultData & faultData,bool isNeedExit)5877 int32_t AppMgrServiceInner::KillFaultApp(int32_t pid, const std::string &bundleName, const FaultData &faultData,
5878     bool isNeedExit)
5879 {
5880     auto killAppTask = [pid, bundleName, faultData, isNeedExit, innerService = shared_from_this()]() {
5881         if (isNeedExit || (faultData.forceExit && !faultData.waitSaveState)) {
5882             TAG_LOGI(AAFwkTag::APPMGR, "FaultData %{public}s,pid == %{public}d is going to exit due to %{public}s.",
5883                 bundleName.c_str(), pid, innerService->FaultTypeToString(faultData.faultType).c_str());
5884             innerService->KillProcessByPid(pid, faultData.errorObject.name);
5885             return;
5886         }
5887     };
5888     constexpr int32_t waitTime = 2000;
5889     // wait 2s before kill application
5890     taskHandler_->SubmitTask(killAppTask, "killAppTask", waitTime);
5891     return ERR_OK;
5892 }
5893 
TimeoutNotifyApp(int32_t pid,int32_t uid,const std::string & bundleName,const std::string & processName,const FaultData & faultData)5894 void AppMgrServiceInner::TimeoutNotifyApp(int32_t pid, int32_t uid,
5895     const std::string& bundleName, const std::string& processName, const FaultData &faultData)
5896 {
5897     bool isNeedExit = (faultData.errorObject.name == AppFreezeType::APP_INPUT_BLOCK) ||
5898         (faultData.errorObject.name == AppFreezeType::LIFECYCLE_TIMEOUT);
5899 #ifdef APP_NO_RESPONSE_DIALOG
5900     bool isDialogExist = appRunningManager_ ?
5901         appRunningManager_->CheckAppRunningRecordIsExist(APP_NO_RESPONSE_BUNDLENAME, APP_NO_RESPONSE_ABILITY) :
5902         false;
5903     auto killFaultApp = std::bind(&AppMgrServiceInner::KillFaultApp, this, pid, bundleName, faultData, isNeedExit);
5904     ModalSystemAppFreezeUIExtension::GetInstance().ProcessAppFreeze(true, faultData, std::to_string(pid),
5905         bundleName, killFaultApp, isDialogExist);
5906 #else
5907     KillFaultApp(pid, bundleName, faultData, isNeedExit);
5908 #endif
5909     if (faultData.faultType == FaultDataType::APP_FREEZE) {
5910         AppfreezeManager::AppInfo info = {
5911             .pid = pid,
5912             .uid = uid,
5913             .bundleName = bundleName,
5914             .processName = processName,
5915         };
5916         AppExecFwk::AppfreezeManager::GetInstance()->AppfreezeHandleWithStack(faultData, info);
5917     }
5918 }
5919 
TransformedNotifyAppFault(const AppFaultDataBySA & faultData)5920 int32_t AppMgrServiceInner::TransformedNotifyAppFault(const AppFaultDataBySA &faultData)
5921 {
5922     int32_t pid = faultData.pid;
5923     auto record = GetAppRunningRecordByPid(pid);
5924     if (record == nullptr) {
5925         TAG_LOGE(AAFwkTag::APPMGR, "no such AppRunningRecord");
5926         return ERR_INVALID_VALUE;
5927     }
5928 
5929     FaultData transformedFaultData = ConvertDataTypes(faultData);
5930     int32_t uid = record->GetUid();
5931     std::string bundleName = record->GetBundleName();
5932     std::string processName = record->GetProcessName();
5933     if (AppExecFwk::AppfreezeManager::GetInstance()->IsProcessDebug(pid, bundleName)) {
5934         TAG_LOGW(AAFwkTag::APPMGR,
5935             "don't report event and kill:%{public}s, pid:%{public}d, bundleName:%{public}s.",
5936             faultData.errorObject.name.c_str(), pid, bundleName.c_str());
5937         return ERR_OK;
5938     }
5939     if (faultData.errorObject.name == "appRecovery") {
5940         AppRecoveryNotifyApp(pid, bundleName, faultData.faultType, "appRecovery");
5941         return ERR_OK;
5942     }
5943 
5944     if (transformedFaultData.timeoutMarkers.empty()) {
5945         transformedFaultData.timeoutMarkers = "notifyFault:" + transformedFaultData.errorObject.name +
5946             std::to_string(pid) + "-" + std::to_string(SystemTimeMillisecond());
5947     }
5948     const int64_t timeout = 1000;
5949     if (faultData.faultType == FaultDataType::APP_FREEZE) {
5950         if (!AppExecFwk::AppfreezeManager::GetInstance()->IsHandleAppfreeze(bundleName) || record->IsDebugging()) {
5951             return ERR_OK;
5952         }
5953         auto timeoutNotifyApp = [this, pid, uid, bundleName, processName, transformedFaultData]() {
5954             this->TimeoutNotifyApp(pid, uid, bundleName, processName, transformedFaultData);
5955         };
5956         dfxTaskHandler_->SubmitTask(timeoutNotifyApp, transformedFaultData.timeoutMarkers, timeout);
5957     }
5958     record->NotifyAppFault(transformedFaultData);
5959     TAG_LOGW(AAFwkTag::APPMGR, "FaultDataBySA is: name: %{public}s, faultType: %{public}s, uid: %{public}d,"
5960         "pid: %{public}d, bundleName: %{public}s, eventId: %{public}d", faultData.errorObject.name.c_str(),
5961         FaultTypeToString(faultData.faultType).c_str(), uid, pid, bundleName.c_str(), faultData.eventId);
5962     return ERR_OK;
5963 }
5964 
NotifyAppFaultBySA(const AppFaultDataBySA & faultData)5965 int32_t AppMgrServiceInner::NotifyAppFaultBySA(const AppFaultDataBySA &faultData)
5966 {
5967     if (remoteClientManager_ == nullptr) {
5968         TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ is nullptr.");
5969         return ERR_NO_INIT;
5970     }
5971     std::string callerBundleName;
5972     if (auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper(); bundleMgrHelper != nullptr) {
5973         int32_t callingUid = IPCSkeleton::GetCallingUid();
5974         IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName));
5975     }
5976 #ifdef ABILITY_FAULT_AND_EXIT_TEST
5977     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) ||
5978         AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
5979 #else
5980     if ((AAFwk::PermissionVerification::GetInstance()->IsSACall()) || callerBundleName == SCENE_BOARD_BUNDLE_NAME) {
5981 #endif
5982         return TransformedNotifyAppFault(faultData);
5983     }
5984     TAG_LOGD(AAFwkTag::APPMGR, "this is not called by SA.");
5985     return AAFwk::CHECK_PERMISSION_FAILED;
5986 }
5987 
5988 bool AppMgrServiceInner::SetAppFreezeFilter(int32_t pid)
5989 {
5990     int32_t callerUid = IPCSkeleton::GetCallingUid();
5991     int32_t waitTime = 0;
5992     int32_t callingPid = 0;
5993     auto callerRecord = GetAppRunningRecordByPid(pid);
5994     if (callerRecord == nullptr) {
5995         TAG_LOGE(AAFwkTag::APPMGR, "null callerRecord");
5996         return false;
5997     }
5998     if (callerUid == HIVIEW_UID) {
5999         waitTime = LEAK_WAIT;
6000         callingPid = pid;
6001     } else {
6002         callingPid = IPCSkeleton::GetCallingPid();
6003         waitTime = NORMAL_WAIT; // wait 2min
6004     }
6005     std::string bundleName = callerRecord->GetBundleName();
6006     if (callingPid == pid && AppExecFwk::AppfreezeManager::GetInstance()->IsValidFreezeFilter(pid, bundleName)) {
6007         bool cancelResult = AppExecFwk::AppfreezeManager::GetInstance()->CancelAppFreezeDetect(pid, bundleName);
6008         auto resetAppfreezeTask = [pid, bundleName, innerService = shared_from_this()]() {
6009             AppExecFwk::AppfreezeManager::GetInstance()->ResetAppfreezeState(pid, bundleName);
6010         };
6011         taskHandler_->SubmitTask(resetAppfreezeTask, "resetAppfreezeTask", waitTime);
6012         return cancelResult;
6013     }
6014     return false;
6015 }
6016 
6017 FaultData AppMgrServiceInner::ConvertDataTypes(const AppFaultDataBySA &faultData)
6018 {
6019     FaultData newfaultData;
6020     newfaultData.faultType = faultData.faultType;
6021     newfaultData.errorObject.message =
6022         "\nFault time:" + AbilityRuntime::TimeUtil::FormatTime("%Y/%m/%d-%H:%M:%S") + "\n";
6023     newfaultData.errorObject.message += faultData.errorObject.message;
6024     newfaultData.errorObject.name = faultData.errorObject.name;
6025     newfaultData.errorObject.stack = faultData.errorObject.stack;
6026     newfaultData.timeoutMarkers = faultData.timeoutMarkers;
6027     newfaultData.waitSaveState = faultData.waitSaveState;
6028     newfaultData.notifyApp = faultData.notifyApp;
6029     newfaultData.forceExit = faultData.forceExit;
6030     newfaultData.token = faultData.token;
6031     newfaultData.state = faultData.state;
6032     newfaultData.eventId = faultData.eventId;
6033     return newfaultData;
6034 }
6035 
6036 std::string AppMgrServiceInner::FaultTypeToString(AppExecFwk::FaultDataType type)
6037 {
6038     std::string typeStr = "UNKNOWN";
6039     switch (type) {
6040         case AppExecFwk::FaultDataType::CPP_CRASH:
6041             typeStr = "CPP_CRASH";
6042             break;
6043         case AppExecFwk::FaultDataType::JS_ERROR:
6044             typeStr = "JS_ERROR";
6045             break;
6046         case AppExecFwk::FaultDataType::APP_FREEZE:
6047             typeStr = "APP_FREEZE";
6048             break;
6049         case AppExecFwk::FaultDataType::PERFORMANCE_CONTROL:
6050             typeStr = "PERFORMANCE_CONTROL";
6051             break;
6052         case AppExecFwk::FaultDataType::RESOURCE_CONTROL:
6053             typeStr = "RESOURCE_CONTROL";
6054             break;
6055         default:
6056             break;
6057     }
6058     return typeStr;
6059 }
6060 
6061 bool AppMgrServiceInner::IsSharedBundleRunning(const std::string &bundleName, uint32_t versionCode)
6062 {
6063     if (!CheckGetRunningInfoPermission()) {
6064         return false;
6065     }
6066 
6067     std::lock_guard lock(runningSharedBundleListMutex_);
6068     for (const auto &it : runningSharedBundleList_) {
6069         for (const auto &item : it.second) {
6070             if (item.bundleName == bundleName && item.versionCode == versionCode) {
6071                 return true;
6072             }
6073         }
6074     }
6075     return false;
6076 }
6077 
6078 int32_t AppMgrServiceInner::IsApplicationRunning(const std::string &bundleName, bool &isRunning)
6079 {
6080     TAG_LOGD(AAFwkTag::APPMGR, "Called, bundleName: %{public}s", bundleName.c_str());
6081     CHECK_CALLER_IS_SYSTEM_APP;
6082     if (!CheckGetRunningInfoPermission()) {
6083         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
6084         return ERR_PERMISSION_DENIED;
6085     }
6086 
6087     isRunning = appRunningManager_->CheckAppRunningRecordIsExistByBundleName(bundleName);
6088     return ERR_OK;
6089 }
6090 
6091 int32_t AppMgrServiceInner::IsAppRunning(const std::string &bundleName, int32_t appCloneIndex,
6092     bool &isRunning)
6093 {
6094     TAG_LOGD(AAFwkTag::APPMGR, "Called, bundleName: %{public}s", bundleName.c_str());
6095     if (!CheckGetRunningInfoPermission()) {
6096         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
6097         return ERR_PERMISSION_DENIED;
6098     }
6099     if (appCloneIndex < 0 || appCloneIndex > AbilityRuntime::GlobalConstant::MAX_APP_CLONE_INDEX) {
6100         TAG_LOGE(AAFwkTag::APPMGR, "appCloneIndex is invalid.");
6101         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
6102     }
6103     if (remoteClientManager_ == nullptr) {
6104         TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager is nullptr.");
6105         return ERR_INVALID_OPERATION;
6106     }
6107     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
6108     if (bundleMgrHelper == nullptr) {
6109         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr.");
6110         return ERR_INVALID_OPERATION;
6111     }
6112     BundleInfo bundleInfo;
6113     auto userId = GetCurrentAccountId();
6114     int32_t bundleMgrResult;
6115     if (appCloneIndex == 0) {
6116         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetBundleInfoV9(bundleName,
6117             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION) |
6118             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY) |
6119             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_HAP_MODULE) |
6120             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION), bundleInfo, userId));
6121     } else {
6122         bundleMgrResult = IN_PROCESS_CALL(bundleMgrHelper->GetCloneBundleInfo(bundleName,
6123             static_cast<int32_t>(GetBundleInfoFlag::GET_BUNDLE_INFO_WITH_APPLICATION),
6124             appCloneIndex, bundleInfo, userId));
6125     }
6126 
6127     if (bundleMgrResult != ERR_OK) {
6128         TAG_LOGE(AAFwkTag::APPMGR, "query bundleInfo failed from bms.");
6129         return AAFwk::ERR_APP_CLONE_INDEX_INVALID;
6130     }
6131 
6132     return appRunningManager_->CheckAppCloneRunningRecordIsExistByBundleName(bundleName, appCloneIndex, isRunning);
6133 }
6134 
6135 bool AppMgrServiceInner::CreateAbilityInfo(const AAFwk::Want &want, AbilityInfo &abilityInfo)
6136 {
6137     auto&& bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
6138     if (!bundleMgrHelper) {
6139         TAG_LOGE(AAFwkTag::APPMGR, "Get bundle manager helper error.");
6140         return false;
6141     }
6142     auto userId = GetCurrentAccountId();
6143     auto abilityInfoFlag = AbilityRuntime::StartupUtil::BuildAbilityInfoFlag();
6144     if (IN_PROCESS_CALL(bundleMgrHelper->QueryAbilityInfo(want, abilityInfoFlag, userId, abilityInfo))) {
6145         TAG_LOGI(AAFwkTag::APPMGR, "queryAbilityInfo ok");
6146         return true;
6147     }
6148     std::vector<AppExecFwk::ExtensionAbilityInfo> extensionInfos;
6149     int32_t appIndex = want.GetIntParam(AppspawnUtil::DLP_PARAMS_INDEX, 0);
6150     if (appIndex == 0) {
6151         if (!IN_PROCESS_CALL(bundleMgrHelper->QueryExtensionAbilityInfos(want, abilityInfoFlag,
6152             userId, extensionInfos))) {
6153             TAG_LOGE(AAFwkTag::APPMGR, "QueryExtensionAbilityInfos failed.");
6154             return false;
6155         }
6156     } else {
6157         if (!IN_PROCESS_CALL(bundleMgrHelper->GetSandboxExtAbilityInfos(want, appIndex,
6158             abilityInfoFlag, userId, extensionInfos))) {
6159             TAG_LOGE(AAFwkTag::APPMGR, "GetSandboxExtAbilityInfos failed.");
6160             return false;
6161         }
6162     }
6163     if (extensionInfos.size() <= 0) {
6164         TAG_LOGE(AAFwkTag::ABILITYMGR, "Get extension info failed.");
6165         return ERR_INVALID_OPERATION;
6166     }
6167     AppExecFwk::ExtensionAbilityInfo extensionInfo = extensionInfos.front();
6168     AbilityRuntime::StartupUtil::InitAbilityInfoFromExtension(extensionInfo, abilityInfo);
6169     return true;
6170 }
6171 
6172 int32_t AppMgrServiceInner::StartNativeProcessForDebugger(const AAFwk::Want &want)
6173 {
6174     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_INVALID_OPERATION);
6175     TAG_LOGI(AAFwkTag::APPMGR, "bundleName:%{public}s, moduleName:%{public}s, abilityName:%{public}s",
6176         want.GetElement().GetBundleName().c_str(), want.GetElement().GetModuleName().c_str(),
6177         want.GetElement().GetAbilityName().c_str());
6178     AbilityInfo abilityInfo;
6179     if (!CreateAbilityInfo(want, abilityInfo)) {
6180         TAG_LOGE(AAFwkTag::APPMGR, "CreateAbilityInfo failed!");
6181         return ERR_INVALID_OPERATION;
6182     }
6183     BundleInfo bundleInfo;
6184     HapModuleInfo hapModuleInfo;
6185     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
6186     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, 0)) {
6187         TAG_LOGE(AAFwkTag::APPMGR, "GetBundleAndHapInfo failed");
6188         return ERR_INVALID_OPERATION;
6189     }
6190 
6191     std::string processName;
6192     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
6193     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, 0, "", processName);
6194     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(appInfo->uid))) {
6195         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
6196         return ERR_INVALID_OPERATION;
6197     }
6198     auto&& appRecord =
6199         appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid, bundleInfo);
6200     AppSpawnStartMsg startMsg;
6201     bool isDevelopeMode = system::GetBoolParameter(DEVELOPER_MODE_STATE, false);
6202     if (appRecord) {
6203         startMsg = appRecord->GetStartMsg();
6204     } else if (!isDevelopeMode || CreatNewStartMsg(want, abilityInfo, appInfo, processName, startMsg) != ERR_OK) {
6205         TAG_LOGE(AAFwkTag::APPMGR, "Invalid Operation");
6206         return ERR_INVALID_OPERATION;
6207     }
6208 
6209     bool isSandboxApp = want.GetBoolParam(ENTER_SANDBOX, false);
6210     auto&& pefCmd = want.GetStringParam(PERF_CMD);
6211     std::string debugCmd = "";
6212     if (pefCmd.empty()) {
6213         if (!appInfo->debug) {
6214             TAG_LOGE(AAFwkTag::APPMGR, "The app is not debug mode.");
6215             return ERR_INVALID_OPERATION;
6216         }
6217         debugCmd = want.GetStringParam(DEBUG_CMD);
6218     }
6219     return StartPerfProcessByStartMsg(startMsg, pefCmd, debugCmd, isSandboxApp);
6220 }
6221 
6222 int32_t AppMgrServiceInner::GetCurrentAccountId() const
6223 {
6224     std::vector<int32_t> osActiveAccountIds;
6225     ErrCode ret = DelayedSingleton<AppExecFwk::OsAccountManagerWrapper>::GetInstance()->
6226         QueryActiveOsAccountIds(osActiveAccountIds);
6227     if (ret != ERR_OK) {
6228         TAG_LOGE(AAFwkTag::APPMGR, "QueryActiveOsAccountIds failed");
6229         return DEFAULT_USER_ID;
6230     }
6231     if (osActiveAccountIds.empty()) {
6232         TAG_LOGE(AAFwkTag::APPMGR, "QueryActiveOsAccountIds empty");
6233         return DEFAULT_USER_ID;
6234     }
6235     return osActiveAccountIds.front();
6236 }
6237 
6238 void AppMgrServiceInner::SetRunningSharedBundleList(const std::string &bundleName,
6239     const std::vector<BaseSharedBundleInfo> baseSharedBundleInfoList)
6240 {
6241     std::lock_guard lock(runningSharedBundleListMutex_);
6242     runningSharedBundleList_.try_emplace(bundleName, baseSharedBundleInfoList);
6243 }
6244 
6245 void AppMgrServiceInner::RemoveRunningSharedBundleList(const std::string &bundleName)
6246 {
6247     std::lock_guard lock(runningSharedBundleListMutex_);
6248     auto iterator = runningSharedBundleList_.find(bundleName);
6249     if (iterator == runningSharedBundleList_.end()) {
6250         return;
6251     }
6252     runningSharedBundleList_.erase(iterator);
6253 }
6254 
6255 void AppMgrServiceInner::SetCurrentUserId(const int32_t userId)
6256 {
6257     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
6258         return;
6259     }
6260     TAG_LOGD(AAFwkTag::APPMGR, "set current userId: %{public}d", userId);
6261     currentUserId_ = userId;
6262 }
6263 
6264 void AppMgrServiceInner::SetEnableStartProcessFlagByUserId(int32_t userId, bool enableStartProcess)
6265 {
6266     UserRecordManager::GetInstance().SetEnableStartProcessFlagByUserId(userId, enableStartProcess);
6267 }
6268 
6269 int32_t AppMgrServiceInner::GetBundleNameByPid(const int32_t pid, std::string &bundleName, int32_t &uid)
6270 {
6271     TAG_LOGD(AAFwkTag::APPMGR, "called");
6272     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
6273         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
6274         return ERR_PERMISSION_DENIED;
6275     }
6276     auto callerRecord = GetAppRunningRecordByPid(pid);
6277     if (callerRecord == nullptr) {
6278         TAG_LOGE(AAFwkTag::APPMGR, "null callerRecord can't get callerBundleName");
6279         return ERR_INVALID_OPERATION;
6280     }
6281     bundleName = callerRecord->GetBundleName();
6282     uid = callerRecord->GetUid();
6283     return ERR_OK;
6284 }
6285 
6286 void AppMgrServiceInner::KillRenderProcess(const std::shared_ptr<AppRunningRecord> &appRecord) {
6287     if (appRecord == nullptr) {
6288         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
6289         return;
6290     }
6291     auto renderRecordMap = appRecord->GetRenderRecordMap();
6292     if (!renderRecordMap.empty()) {
6293         for (auto iter : renderRecordMap) {
6294             auto renderRecord = iter.second;
6295             if (renderRecord && renderRecord->GetPid() > 0) {
6296                 auto pid = renderRecord->GetPid();
6297                 auto uid = renderRecord->GetUid();
6298                 TAG_LOGI(AAFwkTag::APPMGR, "Kill render process when host died, pid:%{public}d, uid:%{public}d.",
6299                     pid, uid);
6300                 KillProcessByPid(pid, "KillRenderProcess");
6301                 {
6302                     std::lock_guard lock(renderUidSetLock_);
6303                     renderUidSet_.erase(uid);
6304                 }
6305                 DelayedSingleton<AppStateObserverManager>::GetInstance()->OnRenderProcessDied(renderRecord);
6306             }
6307         }
6308     }
6309 }
6310 
6311 int32_t AppMgrServiceInner::GetProcessMemoryByPid(const int32_t pid, int32_t &memorySize)
6312 {
6313     CHECK_CALLER_IS_SYSTEM_APP;
6314     uint64_t memSize = OHOS::MemInfo::GetPssByPid(pid);
6315     memorySize = static_cast<int32_t>(memSize);
6316     return ERR_OK;
6317 }
6318 
6319 int32_t AppMgrServiceInner::GetRunningProcessInformation(
6320     const std::string &bundleName, int32_t userId, std::vector<RunningProcessInfo> &info)
6321 {
6322     CHECK_CALLER_IS_SYSTEM_APP;
6323     if (!appRunningManager_) {
6324         TAG_LOGE(AAFwkTag::APPMGR, "The appRunningManager is nullptr!");
6325         return ERR_NO_INIT;
6326     }
6327 
6328     if (remoteClientManager_ == nullptr) {
6329         TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ is nullptr!");
6330         return ERR_NO_INIT;
6331     }
6332     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
6333     if (bundleMgrHelper == nullptr) {
6334         TAG_LOGE(AAFwkTag::APPMGR, "The bundleMgrHelper is nullptr!");
6335         return ERR_NO_INIT;
6336     }
6337     TAG_LOGI(AAFwkTag::APPMGR, "userid value is %{public}d", userId);
6338     const auto &appRunningRecordMap = appRunningManager_->GetAppRunningRecordMap();
6339     for (const auto &item : appRunningRecordMap) {
6340         const auto &appRecord = item.second;
6341         if (appRecord == nullptr) {
6342             continue;
6343         }
6344         if (GetUserIdByUid(appRecord->GetUid()) != userId) {
6345             continue;
6346         }
6347         auto appInfoList = appRecord->GetAppInfoList();
6348         for (const auto &appInfo : appInfoList) {
6349             if (appInfo == nullptr) {
6350                 continue;
6351             }
6352             if (appInfo->bundleName == bundleName) {
6353                 GetRunningProcesses(appRecord, info);
6354                 break;
6355             }
6356         }
6357     }
6358     return ERR_OK;
6359 }
6360 
6361 int32_t AppMgrServiceInner::ChangeAppGcState(pid_t pid, int32_t state)
6362 {
6363     auto callerUid = IPCSkeleton::GetCallingUid();
6364     TAG_LOGD(AAFwkTag::APPMGR, "called, pid:%{public}d, state:%{public}d, uid:%{public}d.", pid, state, callerUid);
6365     if (callerUid != RESOURCE_MANAGER_UID) { // The current UID for resource management is 1096
6366         TAG_LOGE(AAFwkTag::APPMGR, "The caller is not a resource manager.");
6367         return ERR_INVALID_VALUE;
6368     }
6369     auto appRecord = GetAppRunningRecordByPid(pid);
6370     if (!appRecord) {
6371         TAG_LOGE(AAFwkTag::APPMGR, "null");
6372         return ERR_INVALID_VALUE;
6373     }
6374     return appRecord->ChangeAppGcState(state);
6375 }
6376 
6377 int32_t AppMgrServiceInner::RegisterAppDebugListener(const sptr<IAppDebugListener> &listener)
6378 {
6379     TAG_LOGD(AAFwkTag::APPMGR, "called");
6380     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
6381         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
6382         return ERR_PERMISSION_DENIED;
6383     }
6384 
6385     if (appDebugManager_ == nullptr) {
6386         TAG_LOGE(AAFwkTag::APPMGR, "appDebugManager_ is nullptr.");
6387         return ERR_NO_INIT;
6388     }
6389     return appDebugManager_->RegisterAppDebugListener(listener);
6390 }
6391 
6392 int32_t AppMgrServiceInner::UnregisterAppDebugListener(const sptr<IAppDebugListener> &listener)
6393 {
6394     TAG_LOGD(AAFwkTag::APPMGR, "called");
6395     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall()) {
6396         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
6397         return ERR_PERMISSION_DENIED;
6398     }
6399 
6400     if (appDebugManager_ == nullptr) {
6401         TAG_LOGE(AAFwkTag::APPMGR, "appDebugManager_ is nullptr.");
6402         return ERR_NO_INIT;
6403     }
6404     return appDebugManager_->UnregisterAppDebugListener(listener);
6405 }
6406 
6407 int32_t AppMgrServiceInner::AttachAppDebug(const std::string &bundleName)
6408 {
6409     TAG_LOGD(AAFwkTag::APPMGR, "called");
6410     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
6411         TAG_LOGE(AAFwkTag::APPMGR, "Developer Mode is false.");
6412         return ERR_INVALID_OPERATION;
6413     }
6414 
6415     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
6416         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
6417         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
6418         return ERR_PERMISSION_DENIED;
6419     }
6420 
6421     if (appRunningManager_ == nullptr) {
6422         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr.");
6423         return ERR_NO_INIT;
6424     }
6425     appRunningManager_->SetAttachAppDebug(bundleName, true);
6426 
6427     auto debugInfos = appRunningManager_->GetAppDebugInfosByBundleName(bundleName, false);
6428     if (!debugInfos.empty() && appDebugManager_ != nullptr) {
6429         appDebugManager_->StartDebug(debugInfos);
6430     }
6431 
6432     NotifyAbilitysDebugChange(bundleName, true);
6433     return ERR_OK;
6434 }
6435 
6436 int32_t AppMgrServiceInner::DetachAppDebug(const std::string &bundleName)
6437 {
6438     TAG_LOGD(AAFwkTag::APPMGR, "called");
6439     if (!AAFwk::PermissionVerification::GetInstance()->IsSACall() &&
6440         !AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
6441         TAG_LOGE(AAFwkTag::APPMGR, "Permission verification failed.");
6442         return ERR_PERMISSION_DENIED;
6443     }
6444 
6445     if (appRunningManager_ == nullptr) {
6446         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr.");
6447         return ERR_NO_INIT;
6448     }
6449 
6450     auto debugInfos = appRunningManager_->GetAppDebugInfosByBundleName(bundleName, true);
6451     if (!debugInfos.empty()) {
6452         appRunningManager_->SetAttachAppDebug(bundleName, false);
6453         if (appDebugManager_ != nullptr) {
6454             appDebugManager_->StopDebug(debugInfos);
6455         }
6456     }
6457 
6458     NotifyAbilitysDebugChange(bundleName, false);
6459     return ERR_OK;
6460 }
6461 
6462 int32_t AppMgrServiceInner::SetAppWaitingDebug(const std::string &bundleName, bool isPersist)
6463 {
6464     TAG_LOGD(AAFwkTag::APPMGR,
6465         "Called, bundle name is %{public}s, persist flag is %{public}d.", bundleName.c_str(), isPersist);
6466     if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
6467         TAG_LOGE(AAFwkTag::APPMGR, "Not shell call.");
6468         return ERR_PERMISSION_DENIED;
6469     }
6470 
6471     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
6472         TAG_LOGE(AAFwkTag::APPMGR, "Developer mode is false.");
6473         return AAFwk::ERR_NOT_DEVELOPER_MODE;
6474     }
6475 
6476     if (bundleName.empty()) {
6477         TAG_LOGE(AAFwkTag::APPMGR, "The bundle name is empty.");
6478         return ERR_INVALID_VALUE;
6479     }
6480 
6481     InitAppWaitingDebugList();
6482 
6483     bool isClear = false;
6484     {
6485         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6486         if (!waitingDebugBundleList_.empty()) {
6487             waitingDebugBundleList_.clear();
6488             isClear = true;
6489         }
6490     }
6491     if (isClear) {
6492         DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->ClearAppWaitingDebugInfo();
6493     }
6494 
6495     {
6496         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6497         waitingDebugBundleList_.try_emplace(bundleName, isPersist);
6498     }
6499     if (isPersist) {
6500         return DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->SetAppWaitingDebugInfo(
6501             bundleName);
6502     }
6503     return ERR_OK;
6504 }
6505 
6506 int32_t AppMgrServiceInner::CancelAppWaitingDebug()
6507 {
6508     TAG_LOGD(AAFwkTag::APPMGR, "called");
6509     if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
6510         TAG_LOGE(AAFwkTag::APPMGR, "Not shell call.");
6511         return ERR_PERMISSION_DENIED;
6512     }
6513 
6514     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
6515         TAG_LOGE(AAFwkTag::APPMGR, "Developer mode is false.");
6516         return AAFwk::ERR_NOT_DEVELOPER_MODE;
6517     }
6518 
6519     {
6520         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6521         waitingDebugBundleList_.clear();
6522     }
6523     return DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->ClearAppWaitingDebugInfo();
6524 }
6525 
6526 int32_t AppMgrServiceInner::GetWaitingDebugApp(std::vector<std::string> &debugInfoList)
6527 {
6528     TAG_LOGD(AAFwkTag::APPMGR, "called");
6529     if (!AAFwk::PermissionVerification::GetInstance()->IsShellCall()) {
6530         TAG_LOGE(AAFwkTag::APPMGR, "Not shell call.");
6531         return ERR_PERMISSION_DENIED;
6532     }
6533 
6534     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
6535         TAG_LOGE(AAFwkTag::APPMGR, "Developer mode is false.");
6536         return AAFwk::ERR_NOT_DEVELOPER_MODE;
6537     }
6538 
6539     InitAppWaitingDebugList();
6540 
6541     std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6542     if (waitingDebugBundleList_.empty()) {
6543         TAG_LOGD(AAFwkTag::APPMGR, "The waiting debug bundle list is empty.");
6544         return ERR_OK;
6545     }
6546 
6547     for (const auto &item : waitingDebugBundleList_) {
6548         std::string debugBundleInfo;
6549         debugBundleInfo.append("bundle name : ").append(item.first).append(", persist : ")
6550             .append(item.second ? "true" : "false");
6551         debugInfoList.emplace_back(debugBundleInfo);
6552     }
6553     return ERR_OK;
6554 }
6555 
6556 void AppMgrServiceInner::InitAppWaitingDebugList()
6557 {
6558     TAG_LOGD(AAFwkTag::APPMGR, "called");
6559     {
6560         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6561         if (isInitAppWaitingDebugListExecuted_) {
6562             TAG_LOGD(AAFwkTag::APPMGR, "No need to initialize again.");
6563             return;
6564         }
6565         isInitAppWaitingDebugListExecuted_ = true;
6566     }
6567 
6568     std::vector<std::string> bundleNameList;
6569     DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->GetAppWaitingDebugList(bundleNameList);
6570     if (!bundleNameList.empty()) {
6571         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6572         for (const auto &item : bundleNameList) {
6573             waitingDebugBundleList_.try_emplace(item, true);
6574         }
6575     }
6576 }
6577 
6578 bool AppMgrServiceInner::IsWaitingDebugApp(const std::string &bundleName)
6579 {
6580     TAG_LOGD(AAFwkTag::APPMGR, "called");
6581 
6582     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
6583         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
6584         return false;
6585     }
6586 
6587     InitAppWaitingDebugList();
6588 
6589     std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6590     if (waitingDebugBundleList_.empty()) {
6591         TAG_LOGD(AAFwkTag::APPMGR, "The waiting debug bundles list is empty.");
6592         return false;
6593     }
6594 
6595     for (const auto &item : waitingDebugBundleList_) {
6596         if (item.first == bundleName) {
6597             return true;
6598         }
6599     }
6600     return false;
6601 }
6602 
6603 void AppMgrServiceInner::ClearNonPersistWaitingDebugFlag()
6604 {
6605     TAG_LOGD(AAFwkTag::APPMGR, "called");
6606 
6607     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
6608         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
6609         return;
6610     }
6611 
6612     bool isClear = false;
6613     {
6614         std::lock_guard<ffrt::mutex> lock(waitingDebugLock_);
6615         for (const auto &item : waitingDebugBundleList_) {
6616             if (!item.second) {
6617                 isClear = true;
6618                 break;
6619             }
6620         }
6621         if (isClear) {
6622             waitingDebugBundleList_.clear();
6623         }
6624     }
6625 
6626     if (isClear) {
6627         DelayedSingleton<AbilityRuntime::AppConfigDataManager>::GetInstance()->ClearAppWaitingDebugInfo();
6628     }
6629 }
6630 
6631 int32_t AppMgrServiceInner::RegisterAbilityDebugResponse(const sptr<IAbilityDebugResponse> &response)
6632 {
6633     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
6634         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
6635         return ERR_PERMISSION_DENIED;
6636     }
6637     if (response == nullptr) {
6638         TAG_LOGE(AAFwkTag::APPMGR, "Response is nullptr.");
6639         return ERR_INVALID_VALUE;
6640     }
6641 
6642     abilityDebugResponse_ = response;
6643     return ERR_OK;
6644 }
6645 
6646 int32_t AppMgrServiceInner::NotifyAbilitysDebugChange(const std::string &bundleName, const bool &isAppDebug)
6647 {
6648     if (appRunningManager_ == nullptr || abilityDebugResponse_ == nullptr) {
6649         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ or abilityDebugResponse is nullptr.");
6650         return ERR_NO_INIT;
6651     }
6652 
6653     std::vector<sptr<IRemoteObject>> tokens;
6654     appRunningManager_->GetAbilityTokensByBundleName(bundleName, tokens);
6655     if (!tokens.empty()) {
6656         isAppDebug ? abilityDebugResponse_->OnAbilitysDebugStarted(tokens) :
6657             abilityDebugResponse_->OnAbilitysDebugStoped(tokens);
6658     }
6659     return ERR_OK;
6660 }
6661 
6662 int32_t AppMgrServiceInner::NotifyAbilitysAssertDebugChange(
6663     const std::shared_ptr<AppRunningRecord> &appRecord, bool isAssertDebug)
6664 {
6665     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
6666     if (appRecord == nullptr || abilityDebugResponse_ == nullptr) {
6667         TAG_LOGE(AAFwkTag::APPMGR, "Record or abilityDebugResponse is nullptr.");
6668         return ERR_NO_INIT;
6669     }
6670 
6671     std::vector<sptr<IRemoteObject>> abilityTokens;
6672     auto abilities = appRecord->GetAbilities();
6673     for (const auto &token : abilities) {
6674         abilityTokens.emplace_back(token.first);
6675     }
6676 
6677     if (!abilityTokens.empty()) {
6678         abilityDebugResponse_->OnAbilitysAssertDebugChange(abilityTokens, isAssertDebug);
6679     }
6680     return ERR_OK;
6681 }
6682 
6683 bool AppMgrServiceInner::IsAttachDebug(const std::string &bundleName)
6684 {
6685     TAG_LOGD(AAFwkTag::APPMGR, "called");
6686     auto isSaCall = AAFwk::PermissionVerification::GetInstance()->IsSACall();
6687     if (!isSaCall) {
6688         TAG_LOGE(AAFwkTag::APPMGR, "Caller token is not SA.");
6689         return false;
6690     }
6691     if (appRunningManager_ == nullptr || bundleName.empty()) {
6692         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ or bundleName is nullptr.");
6693         return false;
6694     }
6695     return appDebugManager_->IsAttachDebug(bundleName);
6696 }
6697 
6698 void AppMgrServiceInner::ApplicationTerminatedSendProcessEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
6699 {
6700     if (appRecord == nullptr) {
6701         TAG_LOGE(AAFwkTag::APPMGR, "App record is nullptr.");
6702         return;
6703     }
6704 
6705     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnProcessDied(appRecord);
6706     DelayedSingleton<CacheProcessManager>::GetInstance()->OnProcessKilled(appRecord);
6707     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
6708         RemoveRunningSharedBundleList(appRecord->GetBundleName());
6709     }
6710 
6711     if (appRunningManager_ == nullptr) {
6712         TAG_LOGE(AAFwkTag::APPMGR, "App running manager is nullptr.");
6713         return;
6714     }
6715     if (!appRunningManager_->CheckAppRunningRecordIsExistByBundleName(appRecord->GetBundleName())) {
6716         OnAppStopped(appRecord);
6717     }
6718 
6719     if (appDebugManager_ == nullptr) {
6720         TAG_LOGE(AAFwkTag::APPMGR, "App debug manager is nullptr.");
6721         return;
6722     }
6723     auto info = MakeAppDebugInfo(appRecord, appRecord->IsDebugApp());
6724     appDebugManager_->RemoveAppDebugInfo(info);
6725 
6726     TAG_LOGD(AAFwkTag::APPMGR, "Application is terminated.");
6727     SendProcessExitEvent(appRecord);
6728 }
6729 
6730 void AppMgrServiceInner::ClearAppRunningDataForKeepAlive(const std::shared_ptr<AppRunningRecord> &appRecord)
6731 {
6732     if (appRecord == nullptr) {
6733         TAG_LOGE(AAFwkTag::APPMGR, "App record is nullptr.");
6734         return;
6735     }
6736     auto userId = GetUserIdByUid(appRecord->GetUid());
6737     if (appRecord->IsKeepAliveApp() && (userId == 0 || userId == currentUserId_) &&
6738         appRecord->GetBundleName() != SCENE_BOARD_BUNDLE_NAME) {
6739         if (ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(appRecord->GetBundleName())) {
6740             TAG_LOGI(AAFwkTag::APPMGR, "Is killed for upgrade web");
6741             return;
6742         }
6743         if (!AAFwk::AppUtils::GetInstance().IsAllowResidentInExtremeMemory(appRecord->GetBundleName()) &&
6744             ExitResidentProcessManager::GetInstance().RecordExitResidentBundleName(appRecord->GetBundleName(),
6745                 appRecord->GetUid())) {
6746             TAG_LOGI(AAFwkTag::APPMGR, "memory size insufficent");
6747             return;
6748         }
6749         TAG_LOGI(AAFwkTag::APPMGR, "memory size is sufficent, restart exit resident process");
6750         auto restartProcess = [appRecord, innerService = shared_from_this()]() {
6751             innerService->RestartResidentProcess(appRecord);
6752         };
6753         if (taskHandler_ == nullptr) {
6754             TAG_LOGE(AAFwkTag::APPMGR, "taskHandler_ is nullptr.");
6755             return;
6756         }
6757         if (appRecord->CanRestartResidentProc()) {
6758             taskHandler_->SubmitTask(restartProcess, "RestartResidentProcess");
6759         } else {
6760             auto findRestartResidentTask = [appRecord](const std::shared_ptr<AppRunningRecord> &appRunningRecord) {
6761                 return (appRecord != nullptr && appRunningRecord != nullptr &&
6762                         appRecord->GetBundleName() == appRunningRecord->GetBundleName());
6763             };
6764             auto findIter = find_if(restartResedentTaskList_.begin(), restartResedentTaskList_.end(),
6765                 findRestartResidentTask);
6766             if (findIter != restartResedentTaskList_.end()) {
6767                 TAG_LOGW(AAFwkTag::APPMGR, "The restart app task has been registered.");
6768                 return;
6769             }
6770             restartResedentTaskList_.emplace_back(appRecord);
6771             TAG_LOGD(AAFwkTag::APPMGR, "Post restart resident process delay task.");
6772             taskHandler_->SubmitTask(restartProcess, "RestartResidentProcessDelayTask", RESTART_INTERVAL_TIME);
6773         }
6774     }
6775 }
6776 
6777 int32_t AppMgrServiceInner::NotifyPageShow(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
6778 {
6779     if (!JudgeSelfCalledByToken(token, pageStateData)) {
6780         return ERR_PERMISSION_DENIED;
6781     }
6782 
6783     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnPageShow(pageStateData);
6784     return ERR_OK;
6785 }
6786 
6787 int32_t AppMgrServiceInner::NotifyPageHide(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
6788 {
6789     if (!JudgeSelfCalledByToken(token, pageStateData)) {
6790         return ERR_PERMISSION_DENIED;
6791     }
6792 
6793     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnPageHide(pageStateData);
6794     return ERR_OK;
6795 }
6796 
6797 bool AppMgrServiceInner::JudgeSelfCalledByToken(const sptr<IRemoteObject> &token, const PageStateData &pageStateData)
6798 {
6799     if (!token) {
6800         TAG_LOGE(AAFwkTag::APPMGR, "token is null.");
6801         return false;
6802     }
6803     auto appRecord = GetAppRunningRecordByAbilityToken(token);
6804     if (!appRecord) {
6805         TAG_LOGE(AAFwkTag::APPMGR, "app is not exist!");
6806         return false;
6807     }
6808     auto callingTokenId = IPCSkeleton::GetCallingTokenID();
6809     if (appRecord->GetApplicationInfo() == nullptr ||
6810         ((appRecord->GetApplicationInfo())->accessTokenId) != callingTokenId) {
6811         TAG_LOGE(AAFwkTag::APPMGR, "Is not self, not enabled");
6812         return false;
6813     }
6814     auto abilityRecord = appRecord->GetAbilityRunningRecordByToken(token);
6815     if (!abilityRecord) {
6816         TAG_LOGE(AAFwkTag::APPMGR, "can not find ability record");
6817         return false;
6818     }
6819     if (abilityRecord->GetBundleName() != pageStateData.bundleName ||
6820         abilityRecord->GetModuleName() != pageStateData.moduleName ||
6821         abilityRecord->GetName() != pageStateData.abilityName) {
6822         TAG_LOGE(AAFwkTag::APPMGR, "can not map the ability");
6823         return false;
6824     }
6825     return true;
6826 }
6827 
6828 int32_t AppMgrServiceInner::RegisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
6829 {
6830     TAG_LOGD(AAFwkTag::APPMGR, "Call.");
6831     CHECK_IS_SA_CALL(listener);
6832     auto appRunningStatusListener = iface_cast<AbilityRuntime::AppRunningStatusListenerInterface>(listener);
6833     return appRunningStatusModule_->RegisterListener(appRunningStatusListener);
6834 }
6835 
6836 int32_t AppMgrServiceInner::UnregisterAppRunningStatusListener(const sptr<IRemoteObject> &listener)
6837 {
6838     TAG_LOGD(AAFwkTag::APPMGR, "Call.");
6839     CHECK_IS_SA_CALL(listener);
6840     auto appRunningStatusListener = iface_cast<AbilityRuntime::AppRunningStatusListenerInterface>(listener);
6841     return appRunningStatusModule_->UnregisterListener(appRunningStatusListener);
6842 }
6843 
6844 int32_t AppMgrServiceInner::StartChildProcess(const pid_t callingPid, pid_t &childPid,
6845     const ChildProcessRequest &request)
6846 {
6847     TAG_LOGI(AAFwkTag::APPMGR, "callingPid:%{public}d", callingPid);
6848     auto errCode = StartChildProcessPreCheck(callingPid, request.childProcessType);
6849     if (errCode != ERR_OK) {
6850         return errCode;
6851     }
6852     auto &srcEntry = request.srcEntry;
6853     if (callingPid <= 0 || srcEntry.empty()) {
6854         TAG_LOGE(AAFwkTag::APPMGR, "invalid callingPid:%{public}d srcEntry:%{private}s", callingPid, srcEntry.c_str());
6855         return ERR_INVALID_VALUE;
6856     }
6857     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
6858         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
6859         return ERR_INVALID_OPERATION;
6860     }
6861     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_NO_INIT);
6862     auto appRecord = GetAppRunningRecordByPid(callingPid);
6863     auto childProcessRecord = ChildProcessRecord::CreateChildProcessRecord(callingPid, request, appRecord);
6864     if (!childProcessRecord) {
6865         TAG_LOGE(AAFwkTag::APPMGR, "CreateChildProcessRecord failed, childProcessRecord is nullptr");
6866         return ERR_NULL_OBJECT;
6867     }
6868     auto &args = request.args;
6869     auto &options = request.options;
6870     childProcessRecord->SetEntryParams(args.entryParams);
6871     TAG_LOGI(AAFwkTag::APPMGR, "srcEntry:%{private}s, args.entryParams size:%{public}zu,"
6872         " processName:%{public}s, args.fds size:%{public}zu, options.isolationMode:%{public}d",
6873         request.srcEntry.c_str(), args.entryParams.length(), childProcessRecord->GetProcessName().c_str(),
6874         args.fds.size(), options.isolationMode);
6875     return StartChildProcessImpl(childProcessRecord, appRecord, childPid, args, options);
6876 }
6877 
6878 int32_t AppMgrServiceInner::StartChildProcessPreCheck(pid_t callingPid, int32_t childProcessType)
6879 {
6880     TAG_LOGD(AAFwkTag::APPMGR, "called.");
6881     CHECK_POINTER_AND_RETURN_VALUE(appRunningManager_, ERR_NO_INIT);
6882     auto childRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(callingPid);
6883     if (childRecord) {
6884         TAG_LOGE(AAFwkTag::APPMGR, "already in child process.");
6885         return AAFwk::ERR_ALREADY_IN_CHILD_PROCESS;
6886     }
6887     auto hostRecord = GetAppRunningRecordByPid(callingPid);
6888     CHECK_POINTER_AND_RETURN_VALUE(hostRecord, ERR_NULL_OBJECT);
6889     auto &appUtils = AAFwk::AppUtils::GetInstance();
6890     if (!appUtils.IsMultiProcessModel()) {
6891         bool checkAllowList = childProcessType == CHILD_PROCESS_TYPE_NATIVE_ARGS ||
6892             childProcessType == CHILD_PROCESS_TYPE_NATIVE;
6893         if (!checkAllowList || !appUtils.IsAllowNativeChildProcess(hostRecord->GetAppIdentifier())) {
6894             TAG_LOGE(AAFwkTag::APPMGR, "not support child process.");
6895             return AAFwk::ERR_NOT_SUPPORT_CHILD_PROCESS;
6896         }
6897     }
6898     auto applicationInfo = hostRecord->GetApplicationInfo();
6899     CHECK_POINTER_AND_RETURN_VALUE(applicationInfo, ERR_NULL_OBJECT);
6900     if (appRunningManager_->IsChildProcessReachLimit(applicationInfo->accessTokenId)) {
6901         TAG_LOGE(AAFwkTag::APPMGR, "child process count reach limit.");
6902         return AAFwk::ERR_CHILD_PROCESS_REACH_LIMIT;
6903     }
6904     return ERR_OK;
6905 }
6906 
6907 int32_t AppMgrServiceInner::StartChildProcessImpl(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
6908     const std::shared_ptr<AppRunningRecord> appRecord, pid_t &childPid, const ChildProcessArgs &args,
6909     const ChildProcessOptions &options)
6910 {
6911     TAG_LOGD(AAFwkTag::APPMGR, "called");
6912     if (!appRecord) {
6913         TAG_LOGE(AAFwkTag::APPMGR, "No such appRecord, childPid:%{public}d.", childPid);
6914         return ERR_NAME_NOT_FOUND;
6915     }
6916     if (!childProcessRecord) {
6917         TAG_LOGE(AAFwkTag::APPMGR, "No such child process record, childPid:%{public}d.", childPid);
6918         return ERR_NAME_NOT_FOUND;
6919     }
6920     bool isNativeFromJs = childProcessRecord->GetChildProcessType() == CHILD_PROCESS_TYPE_NATIVE_ARGS;
6921     auto spawnClient =  isNativeFromJs ? remoteClientManager_->GetNativeSpawnClient() :
6922         remoteClientManager_->GetSpawnClient();
6923     if (!spawnClient) {
6924         TAG_LOGE(AAFwkTag::APPMGR, "spawnClient is null");
6925         AppMgrEventUtil::SendChildProcessStartFailedEvent(childProcessRecord,
6926             ProcessStartFailedReason::GET_SPAWN_CLIENT_FAILED, ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT);
6927         return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
6928     }
6929     if (!args.CheckFdsSize() || !args.CheckFdsKeyLength()) {
6930         AppMgrEventUtil::SendChildProcessStartFailedEvent(childProcessRecord,
6931             ProcessStartFailedReason::CHECK_CHILD_FDS_FAILED, ERR_INVALID_VALUE);
6932         return ERR_INVALID_VALUE;
6933     }
6934 
6935     AppSpawnStartMsg startMsg = appRecord->GetStartMsg();
6936     startMsg.procName = childProcessRecord->GetProcessName();
6937     startMsg.childProcessType = childProcessRecord->GetChildProcessType();
6938     startMsg.fds = args.fds;
6939     startMsg.isolationMode = options.isolationMode;
6940     pid_t pid = 0;
6941     {
6942         std::lock_guard<ffrt::mutex> lock(startChildProcessLock_);
6943         ErrCode errCode = spawnClient->StartProcess(startMsg, pid);
6944         if (FAILED(errCode)) {
6945             TAG_LOGE(AAFwkTag::APPMGR, "failed to spawn new child process, errCode %{public}08x", errCode);
6946             AppMgrEventUtil::SendChildProcessStartFailedEvent(childProcessRecord,
6947                 ProcessStartFailedReason::APPSPAWN_FAILED, static_cast<int32_t>(errCode));
6948             return ERR_APPEXECFWK_BAD_APPSPAWN_CLIENT;
6949         }
6950         childPid = pid;
6951         childProcessRecord->SetPid(pid);
6952         childProcessRecord->SetUid(startMsg.uid);
6953         appRecord->AddChildProcessRecord(pid, childProcessRecord);
6954     }
6955     TAG_LOGI(AAFwkTag::APPMGR, "Start child process success,pid:%{public}d,hostPid:%{public}d,uid:%{public}d,"
6956         "processName:%{public}s", pid, childProcessRecord->GetHostPid(), startMsg.uid,
6957         childProcessRecord->GetProcessName().c_str());
6958     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessCreated(childProcessRecord);
6959     return ERR_OK;
6960 }
6961 
6962 int32_t AppMgrServiceInner::GetChildProcessInfoForSelf(ChildProcessInfo &info)
6963 {
6964     TAG_LOGD(AAFwkTag::APPMGR, "called");
6965     if (!appRunningManager_) {
6966         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
6967         return ERR_NO_INIT;
6968     }
6969     auto callingPid = IPCSkeleton::GetCallingPid();
6970     if (appRunningManager_->GetAppRunningRecordByPid(callingPid)) {
6971         TAG_LOGD(AAFwkTag::APPMGR, "record of callingPid is not child record.");
6972         return ERR_NAME_NOT_FOUND;
6973     }
6974     std::lock_guard<ffrt::mutex> lock(startChildProcessLock_);
6975     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(callingPid);
6976     if (!appRecord) {
6977         TAG_LOGW(AAFwkTag::APPMGR, "No such appRecord, childPid:%{public}d", callingPid);
6978         return ERR_NAME_NOT_FOUND;
6979     }
6980     auto childRecordMap = appRecord->GetChildProcessRecordMap();
6981     auto iter = childRecordMap.find(callingPid);
6982     if (iter != childRecordMap.end()) {
6983         auto childProcessRecord = iter->second;
6984         return GetChildProcessInfo(childProcessRecord, appRecord, info);
6985     }
6986     return ERR_NAME_NOT_FOUND;
6987 }
6988 
6989 int32_t AppMgrServiceInner::GetChildProcessInfo(const std::shared_ptr<ChildProcessRecord> childProcessRecord,
6990     const std::shared_ptr<AppRunningRecord> appRecord, ChildProcessInfo &info, bool isCallFromGetChildrenProcesses)
6991 {
6992     TAG_LOGD(AAFwkTag::APPMGR, "called");
6993     if (!childProcessRecord) {
6994         TAG_LOGE(AAFwkTag::APPMGR, "No such child process record.");
6995         return ERR_NAME_NOT_FOUND;
6996     }
6997     if (!appRecord) {
6998         TAG_LOGE(AAFwkTag::APPMGR, "No such appRecord.");
6999         return ERR_NAME_NOT_FOUND;
7000     }
7001     auto osAccountMgr = DelayedSingleton<OsAccountManagerWrapper>::GetInstance();
7002     if (osAccountMgr == nullptr) {
7003         TAG_LOGE(AAFwkTag::APPMGR, "osAccountMgr is nullptr");
7004         return ERR_INVALID_VALUE;
7005     }
7006     int32_t userId = -1;
7007     int errCode = osAccountMgr->GetOsAccountLocalIdFromUid(appRecord->GetUid(), userId);
7008     if (errCode != ERR_OK) {
7009         TAG_LOGE(AAFwkTag::APPMGR, "GetOsAccountLocalIdFromUid failed,errcode=%{public}d", errCode);
7010         return errCode;
7011     }
7012     info.userId = userId;
7013     info.pid = childProcessRecord->GetPid();
7014     info.hostPid = childProcessRecord->GetHostPid();
7015     info.uid = childProcessRecord->GetUid();
7016     info.hostUid = appRecord->GetUid();
7017     info.bundleName = appRecord->GetBundleName();
7018     info.processName = childProcessRecord->GetProcessName();
7019     if (!isCallFromGetChildrenProcesses) {
7020         info.childProcessType = childProcessRecord->GetChildProcessType();
7021         info.srcEntry = childProcessRecord->GetSrcEntry();
7022         info.entryFunc = childProcessRecord->GetEntryFunc();
7023         info.entryParams = childProcessRecord->GetEntryParams();
7024         info.jitEnabled = appRecord->IsJITEnabled();
7025         info.isStartWithDebug = childProcessRecord->isStartWithDebug();
7026         auto applicationInfo = appRecord->GetApplicationInfo();
7027         if (applicationInfo) {
7028             TAG_LOGD(AAFwkTag::APPMGR, "applicationInfo is exist, debug:%{public}d", applicationInfo->debug);
7029             info.isDebugApp = applicationInfo->debug;
7030         }
7031         info.isStartWithNative = appRecord->isNativeStart();
7032     }
7033     return ERR_OK;
7034 }
7035 
7036 void AppMgrServiceInner::AttachChildProcess(const pid_t pid, const sptr<IChildScheduler> &childScheduler)
7037 {
7038     TAG_LOGI(AAFwkTag::APPMGR, "AttachChildProcess pid:%{public}d", pid);
7039     if (pid <= 0) {
7040         TAG_LOGE(AAFwkTag::APPMGR, "invalid child process pid:%{public}d", pid);
7041         return;
7042     }
7043     if (!childScheduler) {
7044         TAG_LOGE(AAFwkTag::APPMGR, "childScheduler is null");
7045         return;
7046     }
7047     if (!appRunningManager_) {
7048         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7049         return;
7050     }
7051     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(pid);
7052     if (!appRecord) {
7053         TAG_LOGE(AAFwkTag::APPMGR, "no such app Record, pid:%{public}d", pid);
7054         return;
7055     }
7056     auto childRecord = appRecord->GetChildProcessRecordByPid(pid);
7057     if (!childRecord) {
7058         TAG_LOGE(AAFwkTag::APPMGR, "no such child process Record, pid:%{public}d", pid);
7059         return;
7060     }
7061 
7062     sptr<AppDeathRecipient> appDeathRecipient = new AppDeathRecipient();
7063     appDeathRecipient->SetTaskHandler(taskHandler_);
7064     appDeathRecipient->SetAppMgrServiceInner(shared_from_this());
7065     appDeathRecipient->SetIsChildProcess(true);
7066     childRecord->SetScheduler(childScheduler);
7067     childRecord->SetDeathRecipient(appDeathRecipient);
7068     childRecord->RegisterDeathRecipient();
7069 
7070     if (childRecord->GetChildProcessType() != CHILD_PROCESS_TYPE_NATIVE) {
7071         childScheduler->ScheduleLoadChild();
7072     } else {
7073         childScheduler->ScheduleRunNativeProc(childRecord->GetMainProcessCallback());
7074         childRecord->ClearMainProcessCallback();
7075     }
7076 }
7077 
7078 void AppMgrServiceInner::OnChildProcessRemoteDied(const wptr<IRemoteObject> &remote)
7079 {
7080     if (appRunningManager_) {
7081         auto childRecord = appRunningManager_->OnChildProcessRemoteDied(remote);
7082         if (childRecord) {
7083             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessDied(childRecord);
7084         }
7085     }
7086 }
7087 
7088 void AppMgrServiceInner::KillChildProcess(const std::shared_ptr<AppRunningRecord> &appRecord) {
7089     if (appRecord == nullptr) {
7090         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
7091         return;
7092     }
7093     auto childRecordMap = appRecord->GetChildProcessRecordMap();
7094     if (childRecordMap.empty()) {
7095         return;
7096     }
7097     for (auto iter : childRecordMap) {
7098         auto childRecord = iter.second;
7099         if (!childRecord) {
7100             continue;
7101         }
7102         auto childPid = childRecord->GetPid();
7103         if (childPid > 0) {
7104             TAG_LOGI(AAFwkTag::APPMGR, "Kill child process when host died, childPid:%{public}d, childUid:%{public}d.",
7105                 childPid, childRecord->GetUid());
7106             KillProcessByPid(childPid, "KillChildProcess");
7107             DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessDied(childRecord);
7108         }
7109     }
7110 }
7111 
7112 void AppMgrServiceInner::ExitChildProcessSafelyByChildPid(const pid_t pid)
7113 {
7114     if (pid <= 0) {
7115         TAG_LOGE(AAFwkTag::APPMGR, "pid <= 0.");
7116         return;
7117     }
7118     auto appRecord = appRunningManager_->GetAppRunningRecordByChildProcessPid(pid);
7119     if (!appRecord) {
7120         TAG_LOGE(AAFwkTag::APPMGR, "no such app Record, pid:%{public}d", pid);
7121         return;
7122     }
7123     auto childRecord = appRecord->GetChildProcessRecordByPid(pid);
7124     if (!childRecord) {
7125         TAG_LOGE(AAFwkTag::APPMGR, "no such child process Record, pid:%{public}d", pid);
7126         return;
7127     }
7128     childRecord->ScheduleExitProcessSafely();
7129     childRecord->RemoveDeathRecipient();
7130     int64_t startTime = SystemTimeMillisecond();
7131     std::list<pid_t> pids;
7132     pids.push_back(pid);
7133     if (WaitForRemoteProcessExit(pids, startTime)) {
7134         TAG_LOGI(AAFwkTag::APPMGR, "The remote child process exited successfully, pid:%{public}d.", pid);
7135         appRecord->RemoveChildProcessRecord(childRecord);
7136         DelayedSingleton<AppStateObserverManager>::GetInstance()->OnChildProcessDied(childRecord);
7137         return;
7138     }
7139     childRecord->RegisterDeathRecipient();
7140     TAG_LOGI(AAFwkTag::APPMGR, "Kill child ExitChildProcessSafely, childPid:%{public}d, childUid:%{public}d.",
7141         pid, childRecord->GetUid());
7142     int32_t result = KillProcessByPid(pid, "ExitChildProcessSafelyByChildPid");
7143     if (result < 0) {
7144         TAG_LOGE(AAFwkTag::APPMGR, "KillChildProcessByPid kill process is fail.");
7145         return;
7146     }
7147 }
7148 
7149 void AppMgrServiceInner::KillAttachedChildProcess(const std::shared_ptr<AppRunningRecord> &appRecord)
7150 {
7151     if (appRecord == nullptr) {
7152         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
7153         return;
7154     }
7155     auto parentAppRecord = appRecord->GetParentAppRecord();
7156     if (parentAppRecord) {
7157         parentAppRecord->RemoveChildAppRecord(appRecord->GetPriorityObject()->GetPid());
7158     }
7159     std::vector<pid_t> pids;
7160     std::queue<std::shared_ptr<AppRunningRecord>> queue;
7161     queue.push(appRecord);
7162     while (!queue.empty()) {
7163         auto front = queue.front();
7164         queue.pop();
7165         if (front == nullptr) {
7166             continue;
7167         }
7168         auto childAppRecordMap = front->GetChildAppRecordMap();
7169         for (const auto& [pid, weakChildAppRecord] : childAppRecordMap) {
7170             auto childRecord = weakChildAppRecord.lock();
7171             if (childRecord) {
7172                 queue.push(childRecord);
7173                 pids.push_back(pid);
7174             }
7175         }
7176         front->ClearChildAppRecordMap();
7177     }
7178     for (const auto& pid : pids) {
7179         KillProcessByPid(pid, "KillAttachedChildProcess");
7180     }
7181 }
7182 
7183 int AppMgrServiceInner::DumpIpcAllStart(std::string& result)
7184 {
7185     TAG_LOGD(AAFwkTag::APPMGR, "called");
7186     if (!appRunningManager_) {
7187         result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
7188             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
7189             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
7190         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7191         return DumpErrorCode::ERR_INTERNAL_ERROR;
7192     }
7193     return appRunningManager_->DumpIpcAllStart(result);
7194 }
7195 
7196 int AppMgrServiceInner::DumpIpcAllStop(std::string& result)
7197 {
7198     TAG_LOGD(AAFwkTag::APPMGR, "called");
7199     if (!appRunningManager_) {
7200         result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
7201             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
7202             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
7203         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7204         return DumpErrorCode::ERR_INTERNAL_ERROR;
7205     }
7206     return appRunningManager_->DumpIpcAllStop(result);
7207 }
7208 
7209 int AppMgrServiceInner::DumpIpcAllStat(std::string& result)
7210 {
7211     TAG_LOGD(AAFwkTag::APPMGR, "called");
7212     if (!appRunningManager_) {
7213         result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
7214             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
7215             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
7216         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7217         return DumpErrorCode::ERR_INTERNAL_ERROR;
7218     }
7219     return appRunningManager_->DumpIpcAllStat(result);
7220 }
7221 
7222 int AppMgrServiceInner::DumpIpcStart(const int32_t pid, std::string& result)
7223 {
7224     TAG_LOGD(AAFwkTag::APPMGR, "called");
7225     if (!appRunningManager_) {
7226         result.append(MSG_DUMP_IPC_START_STAT, strlen(MSG_DUMP_IPC_START_STAT))
7227             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
7228             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
7229         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7230         return DumpErrorCode::ERR_INTERNAL_ERROR;
7231     }
7232     return appRunningManager_->DumpIpcStart(pid, result);
7233 }
7234 
7235 int AppMgrServiceInner::DumpIpcStop(const int32_t pid, std::string& result)
7236 {
7237     TAG_LOGD(AAFwkTag::APPMGR, "called");
7238     if (!appRunningManager_) {
7239         result.append(MSG_DUMP_IPC_STOP_STAT, strlen(MSG_DUMP_IPC_STOP_STAT))
7240             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
7241             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
7242         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7243         return DumpErrorCode::ERR_INTERNAL_ERROR;
7244     }
7245     return appRunningManager_->DumpIpcStop(pid, result);
7246 }
7247 
7248 int AppMgrServiceInner::DumpIpcStat(const int32_t pid, std::string& result)
7249 {
7250     TAG_LOGD(AAFwkTag::APPMGR, "called");
7251     if (!appRunningManager_) {
7252         result.append(MSG_DUMP_IPC_STAT, strlen(MSG_DUMP_IPC_STAT))
7253             .append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
7254             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
7255         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7256         return DumpErrorCode::ERR_INTERNAL_ERROR;
7257     }
7258     return appRunningManager_->DumpIpcStat(pid, result);
7259 }
7260 
7261 int AppMgrServiceInner::DumpFfrt(const std::vector<int32_t>& pids, std::string& result)
7262 {
7263     TAG_LOGD(AAFwkTag::APPMGR, "called");
7264     if (!appRunningManager_) {
7265         result.append(MSG_DUMP_FAIL, strlen(MSG_DUMP_FAIL))
7266             .append(MSG_DUMP_FAIL_REASON_INTERNAL, strlen(MSG_DUMP_FAIL_REASON_INTERNAL));
7267         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is null");
7268         return DumpErrorCode::ERR_INTERNAL_ERROR;
7269     }
7270     return appRunningManager_->DumpFfrt(pids, result);
7271 }
7272 
7273 void AppMgrServiceInner::NotifyAppRunningStatusEvent(
7274     const std::string &bundle, int32_t uid, AbilityRuntime::RunningStatus runningStatus)
7275 {
7276     if (appRunningStatusModule_ == nullptr) {
7277         TAG_LOGE(AAFwkTag::APPMGR, "Get app running status module object is nullptr.");
7278         return;
7279     }
7280     appRunningStatusModule_->NotifyAppRunningStatusEvent(bundle, uid, runningStatus);
7281 }
7282 
7283 void AppMgrServiceInner::SendAppLaunchEvent(const std::shared_ptr<AppRunningRecord> &appRecord)
7284 {
7285     if (!appRecord) {
7286         TAG_LOGE(AAFwkTag::APPMGR, "appRecord is null");
7287         return;
7288     }
7289     AAFwk::EventInfo eventInfo;
7290     auto applicationInfo = appRecord->GetApplicationInfo();
7291     if (!applicationInfo) {
7292         TAG_LOGE(AAFwkTag::APPMGR, "applicationInfo is nullptr");
7293     } else {
7294         eventInfo.bundleName = applicationInfo->name;
7295         eventInfo.versionName = applicationInfo->versionName;
7296         eventInfo.versionCode = applicationInfo->versionCode;
7297     }
7298     if (appRecord->GetPriorityObject() != nullptr) {
7299         eventInfo.pid = appRecord->GetPriorityObject()->GetPid();
7300     }
7301     eventInfo.processName = appRecord->GetProcessName();
7302     int32_t callerPid = appRecord->GetCallerPid() == -1 ?
7303         IPCSkeleton::GetCallingPid() : appRecord->GetCallerPid();
7304     auto callerRecord = GetAppRunningRecordByPid(callerPid);
7305     if (callerRecord != nullptr) {
7306         eventInfo.callerBundleName = callerRecord->GetBundleName();
7307         eventInfo.callerUid = callerRecord->GetUid();
7308         eventInfo.callerState = static_cast<int32_t>(callerRecord->GetState());
7309         auto callerApplicationInfo = callerRecord->GetApplicationInfo();
7310         if (callerApplicationInfo != nullptr) {
7311             eventInfo.callerVersionName = callerApplicationInfo->versionName;
7312             eventInfo.callerVersionCode = callerApplicationInfo->versionCode;
7313         }
7314     }
7315     AAFwk::EventReport::SendAppLaunchEvent(AAFwk::EventName::APP_LAUNCH, eventInfo);
7316 }
7317 
7318 bool AppMgrServiceInner::IsFinalAppProcessByBundleName(const std::string &bundleName)
7319 {
7320     if (appRunningManager_ == nullptr) {
7321         TAG_LOGE(AAFwkTag::APPMGR, "App running manager is nullptr.");
7322         return false;
7323     }
7324 
7325     auto name = bundleName;
7326     if (bundleName.empty()) {
7327         auto callingPid = IPCSkeleton::GetCallingPid();
7328         auto appRecord = appRunningManager_->GetAppRunningRecordByPid(callingPid);
7329         if (appRecord == nullptr) {
7330             TAG_LOGE(AAFwkTag::APPMGR, "Get app running record is nullptr.");
7331             return false;
7332         }
7333         name = appRecord->GetBundleName();
7334     }
7335 
7336     auto count = appRunningManager_->GetAllAppRunningRecordCountByBundleName(name);
7337     TAG_LOGD(AAFwkTag::APPMGR, "Get application %{public}s process list size[%{public}d].", name.c_str(), count);
7338     return count == 1;
7339 }
7340 
7341 void AppMgrServiceInner::ParseServiceExtMultiProcessWhiteList()
7342 {
7343     auto serviceExtMultiProcessWhiteList =
7344         OHOS::system::GetParameter(SERVICE_EXT_MULTI_PROCESS_WHITE_LIST, "");
7345     if (serviceExtMultiProcessWhiteList.empty()) {
7346         TAG_LOGW(AAFwkTag::APPMGR, "Service extension multi process white list is empty.");
7347         return;
7348     }
7349     SplitStr(serviceExtMultiProcessWhiteList, ";", serviceExtensionWhiteList_);
7350 }
7351 
7352 void AppMgrServiceInner::ClearProcessByToken(sptr<IRemoteObject> token)
7353 {
7354     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
7355     if (token == nullptr) {
7356         TAG_LOGE(AAFwkTag::APPMGR, "token is null");
7357         return;
7358     }
7359 
7360     std::shared_ptr<AppRunningRecord> appRecord = nullptr;
7361     {
7362         std::lock_guard lock(exceptionLock_);
7363         appRecord = GetAppRunningRecordByAbilityToken(token);
7364         if (appRecord == nullptr) {
7365             TAG_LOGI(AAFwkTag::APPMGR, "app record is not exist for ability token");
7366             return;
7367         }
7368         appRecord->SetApplicationClient(nullptr);
7369         auto recordId = appRecord->GetRecordId();
7370         if (appRunningManager_ == nullptr) {
7371             TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
7372             return;
7373         }
7374         appRunningManager_->RemoveAppRunningRecordById(recordId);
7375     }
7376     ClearData(appRecord);
7377 }
7378 
7379 void AppMgrServiceInner::ClearData(std::shared_ptr<AppRunningRecord> appRecord)
7380 {
7381     if (appRecord == nullptr) {
7382         TAG_LOGW(AAFwkTag::APPMGR, "app record is nullptr.");
7383         return;
7384     }
7385     ClearAppRunningData(appRecord, false);
7386     if (!GetAppRunningStateByBundleName(appRecord->GetBundleName())) {
7387         RemoveRunningSharedBundleList(appRecord->GetBundleName());
7388     }
7389 }
7390 
7391 int32_t AppMgrServiceInner::RegisterRenderStateObserver(const sptr<IRenderStateObserver> &observer)
7392 {
7393     if (observer == nullptr) {
7394         TAG_LOGE(AAFwkTag::APPMGR, "observer is nullptr.");
7395         return ERR_INVALID_VALUE;
7396     }
7397     return DelayedSingleton<RenderStateObserverManager>::GetInstance()->RegisterRenderStateObserver(observer);
7398 }
7399 
7400 int32_t AppMgrServiceInner::UnregisterRenderStateObserver(const sptr<IRenderStateObserver> &observer)
7401 {
7402     if (observer == nullptr) {
7403         TAG_LOGE(AAFwkTag::APPMGR, "observer is nullptr.");
7404         return ERR_INVALID_VALUE;
7405     }
7406     return DelayedSingleton<RenderStateObserverManager>::GetInstance()->UnregisterRenderStateObserver(observer);
7407 }
7408 
7409 void AppMgrServiceInner::SetAppAssertionPauseState(bool flag)
7410 {
7411     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
7412     TAG_LOGD(AAFwkTag::APPMGR, "called");
7413     if (!system::GetBoolParameter(PRODUCT_ASSERT_FAULT_DIALOG_ENABLED, false)) {
7414         TAG_LOGE(AAFwkTag::APPMGR, "Product of assert fault dialog is not enabled.");
7415         return;
7416     }
7417     if (!system::GetBoolParameter(DEVELOPER_MODE_STATE, false)) {
7418         TAG_LOGE(AAFwkTag::APPMGR, "Developer Mode is false.");
7419         return;
7420     }
7421 
7422     auto callerPid = IPCSkeleton::GetCallingPid();
7423     auto appRecord = GetAppRunningRecordByPid(callerPid);
7424     if (appRecord == nullptr) {
7425         TAG_LOGE(AAFwkTag::APPMGR, "No such appRecord pid is %{public}d.", callerPid);
7426         return;
7427     }
7428     appRecord->SetAssertionPauseFlag(flag);
7429     auto isDebugStart = appRecord->IsDebugApp() || appRecord->IsAttachDebug();
7430     if (!isDebugStart) {
7431         std::vector<AppDebugInfo> debugInfos;
7432         debugInfos.emplace_back(MakeAppDebugInfo(appRecord, flag));
7433         flag ? appDebugManager_->StartDebug(debugInfos) : appDebugManager_->StopDebug(debugInfos);
7434     }
7435 
7436     NotifyAbilitysAssertDebugChange(appRecord, flag);
7437 }
7438 
7439 int32_t AppMgrServiceInner::UpdateRenderState(pid_t renderPid, int32_t state)
7440 {
7441     int32_t hostPid = IPCSkeleton::GetCallingPid();
7442     auto appRecord = GetAppRunningRecordByPid(hostPid);
7443     if (!appRecord) {
7444         TAG_LOGE(AAFwkTag::APPMGR, "No such appRecord, hostPid:%{public}d", hostPid);
7445         return ERR_INVALID_VALUE;
7446     }
7447 
7448     auto renderRecord = appRecord->GetRenderRecordByPid(renderPid);
7449     if (renderRecord == nullptr) {
7450         TAG_LOGE(AAFwkTag::APPMGR, "renderPid:%{pubclic}d not exist.", renderPid);
7451         return ERR_INVALID_VALUE;
7452     }
7453     renderRecord->SetState(state);
7454     return DelayedSingleton<RenderStateObserverManager>::GetInstance()->OnRenderStateChanged(
7455         renderRecord, state);
7456 }
7457 
7458 int32_t AppMgrServiceInner::SignRestartAppFlag(int32_t uid)
7459 {
7460     TAG_LOGD(AAFwkTag::APPMGR, "call.");
7461     if (!appRunningManager_) {
7462         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
7463         return ERR_NO_INIT;
7464     }
7465     return appRunningManager_->SignRestartAppFlag(uid);
7466 }
7467 
7468 int32_t AppMgrServiceInner::GetAppIndexByPid(pid_t pid, int32_t &appIndex) const
7469 {
7470     auto appRecord = GetAppRunningRecordByPid(pid);
7471     if (appRecord == nullptr) {
7472         TAG_LOGE(AAFwkTag::APPMGR, "no appRecord, pid:%{public}d", pid);
7473         return ERR_INVALID_VALUE;
7474     }
7475     appIndex = appRecord->GetAppIndex();
7476     return ERR_OK;
7477 }
7478 
7479 int32_t AppMgrServiceInner::GetAppRunningUniqueIdByPid(pid_t pid, std::string &appRunningUniqueId)
7480 {
7481     TAG_LOGD(AAFwkTag::APPMGR, "call.");
7482     if (!appRunningManager_) {
7483         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
7484         return ERR_NO_INIT;
7485     }
7486     return appRunningManager_->GetAppRunningUniqueIdByPid(pid, appRunningUniqueId);
7487 }
7488 
7489 bool AppMgrServiceInner::NotifyMemMgrPriorityChanged(const std::shared_ptr<AppRunningRecord> appRecord)
7490 {
7491     if (!appRecord) {
7492         TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
7493         return false;
7494     }
7495     auto priorityObject = appRecord->GetPriorityObject();
7496     if (!priorityObject) {
7497         TAG_LOGE(AAFwkTag::APPMGR, "priorityObject is nullptr.");
7498         return false;
7499     }
7500     int32_t pid = priorityObject->GetPid();
7501     int32_t uid = appRecord->GetUid();
7502     TAG_LOGI(AAFwkTag::APPMGR, "NotifyMemMgrPriorityChanged, pid:%{public}d, uid:%{public}d", pid, uid);
7503 
7504     Memory::MemMgrProcessStateInfo info;
7505     info.pid_ = pid;
7506     info.uid_ = uid;
7507     info.reason_ = Memory::ProcPriorityUpdateReason::START_ABILITY;
7508     int32_t result = ERR_OK;
7509     {
7510         HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
7511         result = Memory::MemMgrClient::GetInstance().NotifyProcessStateChangedAsync(info);
7512     }
7513     if (result != ERR_OK) {
7514         TAG_LOGE(AAFwkTag::APPMGR, "NotifyPriorityChangedSync error, result:%{public}d.", result);
7515         return false;
7516     }
7517     return true;
7518 }
7519 
7520 int32_t AppMgrServiceInner::GetAllUIExtensionRootHostPid(pid_t pid, std::vector<pid_t> &hostPids)
7521 {
7522     if (!appRunningManager_) {
7523         TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr.");
7524         return ERR_NO_INIT;
7525     }
7526 
7527     CHECK_CALLER_IS_SYSTEM_APP;
7528     if (!AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm()) {
7529         TAG_LOGE(AAFwkTag::APPMGR, "Permission deny.");
7530         return ERR_PERMISSION_DENIED;
7531     }
7532 
7533     return appRunningManager_->GetAllUIExtensionRootHostPid(pid, hostPids);
7534 }
7535 
7536 int32_t AppMgrServiceInner::GetAllUIExtensionProviderPid(pid_t hostPid, std::vector<pid_t> &providerPids)
7537 {
7538     if (!appRunningManager_) {
7539         TAG_LOGE(AAFwkTag::APPMGR, "app running manager is nullptr.");
7540         return ERR_NO_INIT;
7541     }
7542 
7543     CHECK_CALLER_IS_SYSTEM_APP;
7544     if (!AAFwk::PermissionVerification::GetInstance()->VerifyRunningInfoPerm()) {
7545         TAG_LOGE(AAFwkTag::APPMGR, "Permission deny.");
7546         return ERR_PERMISSION_DENIED;
7547     }
7548 
7549     return appRunningManager_->GetAllUIExtensionProviderPid(hostPid, providerPids);
7550 }
7551 
7552 int32_t AppMgrServiceInner::NotifyMemorySizeStateChanged(bool isMemorySizeSufficent)
7553 {
7554     TAG_LOGI(AAFwkTag::APPMGR, "NotifyMemorySizeStateChanged, isMemorySizeSufficent: %{public}d",
7555         isMemorySizeSufficent);
7556     bool isMemmgrCall = AAFwk::PermissionVerification::GetInstance()->CheckSpecificSystemAbilityAccessPermission(
7557         MEMMGR_PROC_NAME);
7558     bool isSupportCall = OHOS::system::GetBoolParameter(SUPPORT_CALL_NOTIFY_MEMORY_CHANGED, false);
7559     if (!isMemmgrCall && !isSupportCall) {
7560         TAG_LOGE(AAFwkTag::APPMGR, "callerToken not %{public}s", MEMMGR_PROC_NAME);
7561         return ERR_PERMISSION_DENIED;
7562     }
7563 
7564     if (!isMemorySizeSufficent) {
7565         auto ret = ExitResidentProcessManager::GetInstance().HandleMemorySizeInSufficent();
7566         if (ret != ERR_OK) {
7567             TAG_LOGE(AAFwkTag::APPMGR, "HandleMemorySizeInSufficent failed, ret is %{public}d.", ret);
7568         }
7569         return ret;
7570     }
7571     std::vector<ExitResidentProcessInfo> exitProcessInfos;
7572     auto ret = ExitResidentProcessManager::GetInstance().HandleMemorySizeSufficient(exitProcessInfos);
7573     if (ret != ERR_OK) {
7574         TAG_LOGE(AAFwkTag::APPMGR, "HandleMemorySizeSufficient fail, ret: %{public}d", ret);
7575         return ret;
7576     }
7577     auto StartExitKeepAliveProcessTask = [exitProcessInfos, innerServicerWeak = weak_from_this()]() {
7578         auto innerServicer = innerServicerWeak.lock();
7579         if (!innerServicer) {
7580             TAG_LOGE(AAFwkTag::APPMGR, "get AppMgrServiceInner failed");
7581             return;
7582         }
7583         std::vector<AppExecFwk::BundleInfo> exitBundleInfos;
7584         ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(exitProcessInfos, exitBundleInfos);
7585 
7586         innerServicer->NotifyStartResidentProcess(exitBundleInfos);
7587     };
7588     taskHandler_->SubmitTask(StartExitKeepAliveProcessTask, "startexitkeepaliveprocess");
7589     return ERR_OK;
7590 }
7591 
7592 bool AppMgrServiceInner::IsMemorySizeSufficent()
7593 {
7594     return ExitResidentProcessManager::GetInstance().IsMemorySizeSufficent();
7595 }
7596 
7597 void AppMgrServiceInner::NotifyAppPreCache(int32_t pid, int32_t userId)
7598 {
7599     std::lock_guard lock(appStateCallbacksLock_);
7600     for (const auto &item : appStateCallbacks_) {
7601         if (item.callback != nullptr) {
7602             item.callback->NotifyAppPreCache(pid, userId);
7603         }
7604     }
7605 }
7606 
7607 void AppMgrServiceInner::NotifyStartResidentProcess(std::vector<AppExecFwk::BundleInfo> &bundleInfos)
7608 {
7609     std::lock_guard lock(appStateCallbacksLock_);
7610     for (const auto &item : appStateCallbacks_) {
7611         if (item.callback != nullptr) {
7612             item.callback->NotifyStartResidentProcess(bundleInfos);
7613         }
7614     }
7615 }
7616 
7617 void AppMgrServiceInner::SetKeepAliveEnableState(const std::string &bundleName, bool enable, int32_t uid)
7618 {
7619     TAG_LOGD(AAFwkTag::APPMGR, "called");
7620     if (bundleName.empty()) {
7621         TAG_LOGE(AAFwkTag::APPMGR, "Bundle name is empty.");
7622         return;
7623     }
7624 
7625     if (appRunningManager_ == nullptr) {
7626         TAG_LOGE(AAFwkTag::APPMGR, "App running manager error.");
7627         return;
7628     }
7629 
7630     auto callerUid = IPCSkeleton::GetCallingUid();
7631     if (callerUid != FOUNDATION_UID) {
7632         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
7633         return;
7634     }
7635 
7636     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
7637         const auto &appRecord = item.second;
7638         if (appRecord != nullptr && appRecord->GetBundleName() == bundleName &&
7639             (uid == 0 || appRecord->GetUid() == uid)) {
7640             TAG_LOGD(AAFwkTag::APPMGR, "%{public}s update state: %{public}d",
7641                 bundleName.c_str(), static_cast<int32_t>(enable));
7642             appRecord->SetKeepAliveEnableState(enable);
7643         }
7644     }
7645 }
7646 
7647 int32_t AppMgrServiceInner::SetSupportedProcessCacheSelf(bool isSupport)
7648 {
7649     TAG_LOGI(AAFwkTag::APPMGR, "called");
7650     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
7651     if (!appRunningManager_) {
7652         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
7653         return ERR_NO_INIT;
7654     }
7655 
7656     auto callerPid = IPCSkeleton::GetCallingPid();
7657     auto appRecord = GetAppRunningRecordByPid(callerPid);
7658     if (!appRecord) {
7659         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, callerPid:%{public}d", callerPid);
7660         return ERR_INVALID_VALUE;
7661     }
7662 
7663     if (!DelayedSingleton<CacheProcessManager>::GetInstance()->QueryEnableProcessCache()) {
7664         TAG_LOGE(AAFwkTag::APPMGR, "process cache feature is disabled.");
7665         return AAFwk::ERR_CAPABILITY_NOT_SUPPORT;
7666     }
7667     appRecord->SetSupportedProcessCache(isSupport);
7668     return ERR_OK;
7669 }
7670 
7671 int32_t AppMgrServiceInner::SetSupportedProcessCache(int32_t pid, bool isSupport)
7672 {
7673     TAG_LOGI(AAFwkTag::APPMGR, "called");
7674     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
7675     if (!appRunningManager_) {
7676         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
7677         return ERR_NO_INIT;
7678     }
7679 
7680     auto appRecord = GetAppRunningRecordByPid(pid);
7681     if (!appRecord) {
7682         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord, pid:%{public}d", pid);
7683         return ERR_INVALID_VALUE;
7684     }
7685 
7686     appRecord->SetEnableProcessCache(isSupport);
7687     return ERR_OK;
7688 }
7689 
7690 void AppMgrServiceInner::OnAppCacheStateChanged(const std::shared_ptr<AppRunningRecord> &appRecord,
7691     ApplicationState state)
7692 {
7693     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
7694     if (!appRecord) {
7695         TAG_LOGE(AAFwkTag::APPMGR, "OnAppCacheStateChanged come, app record is null");
7696         return;
7697     }
7698 
7699     if (appRecord->GetPriorityObject() == nullptr) {
7700         TAG_LOGE(AAFwkTag::APPMGR, "OnAppCacheStateChanged come, appRecord's priorityobject is null");
7701         return;
7702     }
7703 
7704     TAG_LOGD(AAFwkTag::APPMGR, "OnAppCacheStateChanged begin, bundleName is %{public}s, pid:%{public}d",
7705         appRecord->GetBundleName().c_str(), appRecord->GetPriorityObject()->GetPid());
7706 
7707     DelayedSingleton<AppStateObserverManager>::GetInstance()->OnAppCacheStateChanged(appRecord, state);
7708 }
7709 
7710 bool AppMgrServiceInner::IsAppProcessesAllCached(const std::string &bundleName, int32_t uid,
7711     const std::set<std::shared_ptr<AppRunningRecord>> &cachedSet)
7712 {
7713     if (!appRunningManager_) {
7714         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is nullptr");
7715         return false;
7716     }
7717     return appRunningManager_->IsAppProcessesAllCached(bundleName, uid, cachedSet);
7718 }
7719 
7720 int32_t AppMgrServiceInner::CheckCallingIsUserTestModeInner(const pid_t pid, bool &isUserTest)
7721 {
7722     if (!IsSceneBoardCall()) {
7723         TAG_LOGE(AAFwkTag::APPMGR, "this is not called by SceneBoard.");
7724         return AAFwk::CHECK_PERMISSION_FAILED;
7725     }
7726     if (pid <= 0) {
7727         TAG_LOGE(AAFwkTag::APPMGR, "hht-invalid pid:%{public}d", pid);
7728         return ERR_INVALID_VALUE;
7729     }
7730     auto appRecord = GetAppRunningRecordByPid(pid);
7731     if (!appRecord) {
7732         TAG_LOGE(AAFwkTag::APPMGR, "hht-no such appRecord");
7733         return ERR_INVALID_VALUE;
7734     }
7735     if (appRecord->GetUserTestInfo() == nullptr) {
7736         TAG_LOGE(AAFwkTag::APPMGR, "hht-no such user test info.");
7737         return ERR_INVALID_VALUE;
7738     }
7739     isUserTest = true;
7740     return ERR_OK;
7741 }
7742 
7743 bool AppMgrServiceInner::IsSceneBoardCall() {
7744     if (remoteClientManager_ == nullptr) {
7745         TAG_LOGE(AAFwkTag::APPMGR, "The remoteClientManager_ is nullptr.");
7746         return false;
7747     }
7748     auto bundleMgrHelper = remoteClientManager_->GetBundleManagerHelper();
7749     if (bundleMgrHelper != nullptr) {
7750         int32_t callingUid = IPCSkeleton::GetCallingUid();
7751         std::string callerBundleName;
7752         IN_PROCESS_CALL(bundleMgrHelper->GetNameForUid(callingUid, callerBundleName));
7753         return callerBundleName == SCENE_BOARD_BUNDLE_NAME;
7754     }
7755     return false;
7756 }
7757 
7758 int32_t AppMgrServiceInner::StartNativeChildProcess(const pid_t hostPid, const std::string &libName,
7759     int32_t childProcessCount, const sptr<IRemoteObject> &callback)
7760 {
7761     TAG_LOGI(AAFwkTag::APPMGR, "StartNativeChildProcess, hostPid:%{public}d", hostPid);
7762     if (hostPid <= 0 || libName.empty() || !callback) {
7763         TAG_LOGE(AAFwkTag::APPMGR, "Invalid param: hostPid:%{public}d libName:%{private}s",
7764             hostPid, libName.c_str());
7765         return ERR_INVALID_VALUE;
7766     }
7767 
7768     int32_t errCode = StartChildProcessPreCheck(hostPid, CHILD_PROCESS_TYPE_NATIVE);
7769     if (errCode != ERR_OK) {
7770         return errCode;
7771     }
7772 
7773     if (UserRecordManager::GetInstance().IsLogoutUser(GetUserIdByUid(IPCSkeleton::GetCallingUid()))) {
7774         TAG_LOGE(AAFwkTag::APPMGR, "disable start process in logout user");
7775         return ERR_INVALID_OPERATION;
7776     }
7777 
7778     auto appRecord = GetAppRunningRecordByPid(hostPid);
7779     if (!appRecord) {
7780         TAG_LOGI(AAFwkTag::APPMGR, "Get app runnning record(hostPid:%{public}d) failed.", hostPid);
7781         return ERR_INVALID_OPERATION;
7782     }
7783 
7784     if (!AAFwk::AppUtils::GetInstance().IsSupportNativeChildProcess() &&
7785         !AAFwk::AppUtils::GetInstance().IsAllowNativeChildProcess(appRecord->GetAppIdentifier())) {
7786         TAG_LOGE(AAFwkTag::APPMGR, "unSupport native child process");
7787         return AAFwk::ERR_NOT_SUPPORT_NATIVE_CHILD_PROCESS;
7788     }
7789 
7790     std::lock_guard<std::mutex> lock(childProcessRecordMapMutex_);
7791     auto childRecordMap = appRecord->GetChildProcessRecordMap();
7792     auto count = count_if(childRecordMap.begin(), childRecordMap.end(), [] (const auto &pair) -> bool {
7793         return pair.second->GetChildProcessType() == CHILD_PROCESS_TYPE_NATIVE;
7794     });
7795 
7796     if (count >= PC_MAX_CHILD_PROCESS_NUM) {
7797         TAG_LOGI(AAFwkTag::APPMGR, "The number of native child process reached the limit (hostPid:%{public}d)",
7798             hostPid);
7799         return ERR_OVERFLOW;
7800     }
7801 
7802     pid_t dummyChildPid = 0;
7803     auto nativeChildRecord = ChildProcessRecord::CreateNativeChildProcessRecord(
7804         hostPid, libName, appRecord, callback, childProcessCount, false);
7805     ChildProcessArgs args;
7806     ChildProcessOptions options;
7807     return StartChildProcessImpl(nativeChildRecord, appRecord, dummyChildPid, args, options);
7808 }
7809 
7810 void AppMgrServiceInner::CacheLoadAbilityTask(const LoadAbilityTaskFunc& func)
7811 {
7812     std::lock_guard lock(loadTaskListMutex_);
7813     loadAbilityTaskFuncList_.emplace_back(func);
7814 }
7815 
7816 void AppMgrServiceInner::SubmitCacheLoadAbilityTask()
7817 {
7818     std::lock_guard lock(loadTaskListMutex_);
7819     std::weak_ptr<AAFwk::TaskHandlerWrap> taskHandler = taskHandler_;
7820     for_each(loadAbilityTaskFuncList_.begin(), loadAbilityTaskFuncList_.end(),
7821         [taskHandler](LoadAbilityTaskFunc loadAbilityFunc) {
7822             auto LoadAbilityhandler = taskHandler.lock();
7823             if (LoadAbilityhandler != nullptr && loadAbilityFunc) {
7824                 LoadAbilityhandler->SubmitTask(loadAbilityFunc, "loadAbilityFunc");
7825             }
7826         });
7827     loadAbilityTaskFuncList_.clear();
7828 }
7829 
7830 bool AppMgrServiceInner::GetSceneBoardAttachFlag() const
7831 {
7832     return sceneBoardAttachFlag_;
7833 }
7834 
7835 void AppMgrServiceInner::SetSceneBoardAttachFlag(bool flag)
7836 {
7837     sceneBoardAttachFlag_ = flag;
7838 }
7839 
7840 void AppMgrServiceInner::AttachedToStatusBar(const sptr<IRemoteObject> &token)
7841 {
7842     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
7843     auto appRecord = GetAppRunningRecordByAbilityToken(token);
7844     if (appRecord == nullptr) {
7845         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord is nullptr");
7846         return;
7847     }
7848     appRecord->SetAttachedToStatusBar(true);
7849 }
7850 
7851 int32_t AppMgrServiceInner::NotifyProcessDependedOnWeb()
7852 {
7853     int32_t pid = IPCSkeleton::GetCallingPid();
7854     auto appRecord = GetAppRunningRecordByPid(pid);
7855     if (appRecord == nullptr) {
7856         TAG_LOGE(AAFwkTag::APPMGR, "no such appRecord");
7857         return ERR_INVALID_VALUE;
7858     }
7859     TAG_LOGD(AAFwkTag::APPMGR, "call");
7860     appRecord->SetIsDependedOnArkWeb(true);
7861     return ERR_OK;
7862 }
7863 
7864 void AppMgrServiceInner::KillProcessDependedOnWeb()
7865 {
7866     TAG_LOGI(AAFwkTag::APPMGR, "call");
7867     CHECK_POINTER_AND_RETURN_LOG(appRunningManager_, "appRunningManager_ is nullptr");
7868     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
7869         const auto &appRecord = item.second;
7870         if (!appRecord || !appRecord->GetSpawned() ||
7871             !appRecord->GetPriorityObject() || !appRecord->IsDependedOnArkWeb()) {
7872             continue;
7873         }
7874 
7875         std::string bundleName = appRecord->GetBundleName();
7876         pid_t pid = appRecord->GetPriorityObject()->GetPid();
7877         if (appRecord->IsKeepAliveApp()) {
7878             ExitResidentProcessManager::GetInstance().RecordExitResidentBundleDependedOnWeb(bundleName,
7879                 appRecord->GetUid());
7880         }
7881         KillProcessByPid(pid, "KillProcessDependedOnWeb");
7882     }
7883 }
7884 
7885 void AppMgrServiceInner::RestartResidentProcessDependedOnWeb()
7886 {
7887     TAG_LOGD(AAFwkTag::APPMGR, "call");
7888     std::vector<ExitResidentProcessInfo> bundleNames;
7889     ExitResidentProcessManager::GetInstance().HandleExitResidentBundleDependedOnWeb(bundleNames);
7890     if (bundleNames.empty()) {
7891         TAG_LOGE(AAFwkTag::APPMGR, "exit resident bundle names is empty");
7892         return;
7893     }
7894 
7895     auto RestartResidentProcessDependedOnWebTask = [bundleNames, innerServicerWeak = weak_from_this()]() {
7896         auto innerServicer = innerServicerWeak.lock();
7897         CHECK_POINTER_AND_RETURN_LOG(innerServicer, "get AppMgrServiceInner failed");
7898         std::vector<AppExecFwk::BundleInfo> exitBundleInfos;
7899         ExitResidentProcessManager::GetInstance().QueryExitBundleInfos(bundleNames, exitBundleInfos);
7900 
7901         innerServicer->NotifyStartResidentProcess(exitBundleInfos);
7902     };
7903     taskHandler_->SubmitTask(RestartResidentProcessDependedOnWebTask, "RestartResidentProcessDependedOnWeb");
7904 }
7905 
7906 void AppMgrServiceInner::BlockProcessCacheByPids(const std::vector<int32_t>& pids)
7907 {
7908     for (const auto& pid : pids) {
7909         auto appRecord = GetAppRunningRecordByPid(pid);
7910         if (appRecord == nullptr) {
7911             TAG_LOGE(AAFwkTag::APPMGR, "null appRecord");
7912             continue;
7913         }
7914         appRecord->SetProcessCacheBlocked(true);
7915         DelayedSingleton<CacheProcessManager>::GetInstance()->OnAppProcessCacheBlocked(appRecord);
7916     }
7917 }
7918 
7919 bool AppMgrServiceInner::IsKilledForUpgradeWeb(const std::string &bundleName) const
7920 {
7921     auto callerUid = IPCSkeleton::GetCallingUid();
7922     if (callerUid != FOUNDATION_UID) {
7923         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
7924         return false;
7925     }
7926     return ExitResidentProcessManager::GetInstance().IsKilledForUpgradeWeb(bundleName);
7927 }
7928 
7929 bool AppMgrServiceInner::CleanAbilityByUserRequest(const sptr<IRemoteObject> &token)
7930 {
7931     TAG_LOGD(AAFwkTag::APPMGR, "call");
7932     if (!token) {
7933         TAG_LOGE(AAFwkTag::APPMGR, "token is invalid.");
7934         return false;
7935     }
7936 
7937     if (!appRunningManager_) {
7938         TAG_LOGE(AAFwkTag::APPMGR, "appRunningManager_ is invalid.");
7939         return false;
7940     }
7941 
7942     pid_t targetPid = 0;
7943     int32_t targetUid = 0;
7944     if (!appRunningManager_->HandleUserRequestClean(token, targetPid, targetUid)) {
7945         TAG_LOGW(AAFwkTag::APPMGR, "can not clean process now.");
7946         return false;
7947     }
7948 
7949     if (targetPid <= 0 || targetUid <= 0) {
7950         TAG_LOGE(AAFwkTag::APPMGR, "get pid or uid is invalid.pid:%{public}d, uid:%{public}d", targetPid, targetUid);
7951         return false;
7952     }
7953     TAG_LOGI(AAFwkTag::APPMGR, "all user request clean ability scheduled to bg, force kill pid:%{public}d", targetPid);
7954     willKillPidsNum_ += 1;
7955     int32_t delayTime = willKillPidsNum_ * KILL_PROCESS_BY_USER_INTERVAL + KILL_PROCESS_BY_USER_DELAY_BASE;
7956     TAG_LOGD(AAFwkTag::APPMGR, "delayTime:%{public}d", delayTime);
7957     auto delayKillTask = [targetPid, innerServicerWeak = weak_from_this()]() {
7958         auto self = innerServicerWeak.lock();
7959         CHECK_POINTER_AND_RETURN_LOG(self, "get AppMgrServiceInner failed");
7960         self->KillProcessByPid(targetPid, KILL_REASON_USER_REQUEST);
7961         self->DecreaseWillKillPidsNum();
7962         TAG_LOGD(AAFwkTag::APPMGR, "pid:%{public}d killed", targetPid);
7963     };
7964     delayKillTaskHandler_->SubmitTask(delayKillTask, "delayKillUIAbility", delayTime);
7965 
7966     return true;
7967 }
7968 
7969 void AppMgrServiceInner::CheckCleanAbilityByUserRequest(const std::shared_ptr<AppRunningRecord> &appRecord,
7970     const std::shared_ptr<AbilityRunningRecord> &abilityRecord, const AbilityState state)
7971 {
7972     if (!appRecord || !abilityRecord) {
7973         return;
7974     }
7975 
7976     if (state != AbilityState::ABILITY_STATE_BACKGROUND) {
7977         return;
7978     }
7979 
7980     if (abilityRecord->GetAbilityInfo() && abilityRecord->GetAbilityInfo()->type != AppExecFwk::AbilityType::PAGE) {
7981         return;
7982     }
7983 
7984     if (appRecord->IsKeepAliveApp()) {
7985         return;
7986     }
7987 
7988     if (!appRecord->IsAllAbilityReadyToCleanedByUserRequest()) {
7989         TAG_LOGD(AAFwkTag::APPMGR,
7990             "not ready to clean when user request. bundleName:%{public}s", appRecord->GetBundleName().c_str());
7991         return;
7992     }
7993     appRecord->SetUserRequestCleaning();
7994 
7995     pid_t pid = 0;
7996     if (appRecord->GetPriorityObject()) {
7997         pid = appRecord->GetPriorityObject()->GetPid();
7998     }
7999     TAG_LOGI(AAFwkTag::APPMGR, "all user request clean ability scheduled to bg, force kill, pid:%{public}d", pid);
8000     KillProcessByPid(pid, KILL_REASON_USER_REQUEST);
8001 }
8002 
8003 void AppMgrServiceInner::GetPidsByAccessTokenId(const uint32_t accessTokenId, std::vector<pid_t> &pids)
8004 {
8005     int32_t result = ERR_OK;
8006     std::vector<pid_t> foregroundPids;
8007     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
8008         const auto &appRecord = item.second;
8009         if (!appRecord->GetSpawned()) {
8010             continue;
8011         }
8012         auto applicationInfo = appRecord->GetApplicationInfo();
8013         if (!applicationInfo) {
8014             continue;
8015         }
8016         if (accessTokenId == applicationInfo->accessTokenId) {
8017             pid_t curPid = appRecord->GetPriorityObject()->GetPid();
8018             if (appRecord->GetState() == ApplicationState::APP_STATE_FOREGROUND) {
8019                 foregroundPids.push_back(curPid);
8020                 continue;
8021             }
8022             pids.push_back(curPid);
8023         }
8024     }
8025     for (pid_t foregroundPid : foregroundPids) {
8026         pids.push_back(foregroundPid);
8027     }
8028 }
8029 
8030 bool AppMgrServiceInner::IsProcessContainsOnlyUIAbility(const pid_t pid)
8031 {
8032     auto appRecord = GetAppRunningRecordByPid(pid);
8033     if (appRecord == nullptr) {
8034         return false;
8035     }
8036 
8037     auto abilityRecordList = appRecord->GetAbilities();
8038 
8039     for (auto it = abilityRecordList.begin(); it != abilityRecordList.end(); ++it) {
8040         if (it->second == nullptr) {
8041             return false;
8042         }
8043         auto abilityInfo = it->second->GetAbilityInfo();
8044         if (abilityInfo == nullptr) {
8045             return false;
8046         }
8047 
8048         bool isUIAbility = (abilityInfo->type == AppExecFwk::AbilityType::PAGE);
8049         if (!isUIAbility) {
8050             return false;
8051         }
8052     }
8053     return true;
8054 }
8055 
8056 bool AppMgrServiceInner::IsProcessAttached(sptr<IRemoteObject> token) const
8057 {
8058     HITRACE_METER_NAME(HITRACE_TAG_APP, __PRETTY_FUNCTION__);
8059     if (IPCSkeleton::GetCallingUid() != FOUNDATION_UID) {
8060         TAG_LOGE(AAFwkTag::APPMGR, "Not foundation call.");
8061         return false;
8062     }
8063     auto appRecord = GetAppRunningRecordByAbilityToken(token);
8064     if (appRecord == nullptr) {
8065         TAG_LOGE(AAFwkTag::APPMGR, "abilityRecord is nullptr");
8066         return false;
8067     }
8068     return appRecord->IsProcessAttached();
8069 }
8070 
8071 int32_t AppMgrServiceInner::GetSupportedProcessCachePids(const std::string &bundleName,
8072     std::vector<int32_t> &pidList)
8073 {
8074     auto cachePrcoMgr = DelayedSingleton<CacheProcessManager>::GetInstance();
8075     auto osAccountMgr = DelayedSingleton<OsAccountManagerWrapper>::GetInstance();
8076     if (cachePrcoMgr == nullptr || osAccountMgr == nullptr || appRunningManager_ == nullptr) {
8077         TAG_LOGE(AAFwkTag::APPMGR, "Inner manager is nullptr.");
8078         return AAFwk::INNER_ERR;
8079     }
8080     pidList.clear();
8081     int32_t callderUserId = -1;
8082     if (osAccountMgr->GetOsAccountLocalIdFromUid(IPCSkeleton::GetCallingUid(), callderUserId) != 0) {
8083         TAG_LOGE(AAFwkTag::APPMGR, "Get caller local id failed.");
8084         return AAFwk::INNER_ERR;
8085     }
8086     for (const auto &item : appRunningManager_->GetAppRunningRecordMap()) {
8087         auto appRecord = item.second;
8088         if (appRecord == nullptr) {
8089             continue;
8090         }
8091         int32_t procUserId = -1;
8092         if (appRecord->GetBundleName() == bundleName &&
8093             osAccountMgr->GetOsAccountLocalIdFromUid(appRecord->GetUid(), procUserId) == 0 &&
8094             procUserId == callderUserId && cachePrcoMgr->IsAppSupportProcessCache(appRecord) &&
8095             appRecord->GetPriorityObject() != nullptr) {
8096             pidList.push_back(appRecord->GetPriorityObject()->GetPid());
8097         }
8098     }
8099     return ERR_OK;
8100 }
8101 
8102 bool AppMgrServiceInner::IsSpecifiedModuleLoaded(const AAFwk::Want &want, const AbilityInfo &abilityInfo)
8103 {
8104     if (!CheckRemoteClient() || !appRunningManager_) {
8105         return false;
8106     }
8107     auto appInfo = std::make_shared<ApplicationInfo>(abilityInfo.applicationInfo);
8108     int32_t appIndex = 0;
8109     (void)AbilityRuntime::StartupUtil::GetAppIndex(want, appIndex);
8110     BundleInfo bundleInfo;
8111     HapModuleInfo hapModuleInfo;
8112     if (!GetBundleAndHapInfo(abilityInfo, appInfo, bundleInfo, hapModuleInfo, appIndex)) {
8113         return false;
8114     }
8115 
8116     auto abilityInfoPtr = std::make_shared<AbilityInfo>(abilityInfo);
8117     std::string processName;
8118     MakeProcessName(abilityInfoPtr, appInfo, hapModuleInfo, appIndex, "", processName);
8119 
8120     auto appRecord = appRunningManager_->CheckAppRunningRecordIsExist(appInfo->name, processName, appInfo->uid,
8121         bundleInfo, "");
8122     if (appRecord == nullptr) {
8123         return false;
8124     }
8125 
8126     auto moduleRecord = appRecord->GetModuleRecordByModuleName(appInfo->bundleName, hapModuleInfo.moduleName);
8127     if (moduleRecord == nullptr) {
8128         return false;
8129     }
8130     TAG_LOGD(AAFwkTag::APPMGR, "IsSpecifiedModuleLoaded state %{public}d", moduleRecord->GetModuleRecordState());
8131     return moduleRecord->IsLoaded();
8132 }
8133 
8134 void AppMgrServiceInner::SendAppSpawnUninstallDebugHapMsg(int32_t userId)
8135 {
8136     if (remoteClientManager_ == nullptr) {
8137         TAG_LOGE(AAFwkTag::APPMGR, "null remoteClientManager_");
8138         return;
8139     }
8140     auto spawnClient = remoteClientManager_->GetSpawnClient();
8141     if (spawnClient == nullptr) {
8142         TAG_LOGE(AAFwkTag::APPMGR, "null spawnClient");
8143         return;
8144     }
8145     auto errCode = spawnClient->SendAppSpawnUninstallDebugHapMsg(userId);
8146     if (FAILED(errCode)) {
8147         TAG_LOGE(AAFwkTag::APPMGR, "SendAppSpawnUninstallDebugHapMsg failed, errCode %{public}08x", errCode);
8148     }
8149 }
8150 } // namespace AppExecFwk
8151 }  // namespace OHOS
8152