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