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