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