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